Apply Upstream code (2021-03-15)
[platform/upstream/connectedhomeip.git] / scripts / setup / nrfconnect / update_ncs.py
1 #!/usr/bin/env python3
2
3 #
4 # Copyright (c) 2021 Project CHIP Authors
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 #     http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18
19 import argparse
20 import os
21 import subprocess
22 import sys
23
24 def get_repository_commit_sha(repository_location):
25     command = ['git', '-C', repository_location, 'rev-parse', 'HEAD']
26     process = subprocess.run(command, check=True, stdout=subprocess.PIPE)
27     return process.stdout.decode('ascii').strip()
28
29 def update_ncs(repository_location, revision):
30     # Fetch sdk-nrf to the desired revision.
31     command = ['git', '-C', repository_location, 'fetch']
32     subprocess.run(command, check=True)
33
34     # Checkout sdk-nrf to the desired revision.
35     command = ['git', '-C', repository_location, 'checkout', revision]
36     subprocess.run(command, check=True)
37
38     # Call west update command to update all projects and submodules used by sdk-nrf.
39     command = ['west', 'update', '-r']
40     subprocess.run(command, check=True)
41
42 def get_ncs_recommended_revision():
43     chip_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.normpath('../../..')))
44
45     # Read recommended revision saved in the .nrfconnect-recommended-revision file.
46     try:
47         with open(os.path.join(chip_root, 'config/nrfconnect/.nrfconnect-recommended-revision'), 'r') as f:
48             return f.readline().strip()
49     except:
50         raise RuntimeError("Encountered problem when trying to read .nrfconnect-recommended-revision file.")
51
52 def print_messages(messages : list, yellow_text :  bool):
53     # Add colour formatting if yellow text was set
54     if yellow_text:
55         messages = [f"\33[33m{message}\x1b[0m" for message in messages]
56
57     for message in messages:
58         print(message)
59
60 def print_check_revision_warning_message(current_revision, recommended_revision):
61     current_revision_message = f"WARNING: Your current NCS revision ({current_revision})"
62     recommended_revision_message = f"differs from the recommended ({recommended_revision})."
63     allowed_message = "Please be aware that it may lead to encountering unexpected problems."
64     update_message = "Consider updating NCS to the recommended revision, by calling:"
65     call_command_message = os.path.abspath(__file__) + " --update"
66
67     # Get the longest message lenght, to fit warning frame size.
68     longest_message_len = max([len(current_revision_message), len(recommended_revision_message), len(allowed_message), len(update_message), len(call_command_message)])
69
70     # To keep right frame shape the space characters are added to messages shorter than the longest one.
71     fmt = "# {:<%s}#" % (longest_message_len)
72
73     print_messages([(longest_message_len+3)*'#', fmt.format(current_revision_message), fmt.format(recommended_revision_message), fmt.format(''),
74                     fmt.format(allowed_message), fmt.format(update_message), fmt.format(call_command_message), (longest_message_len+3)*'#'], sys.stdout.isatty())
75
76 def main():
77
78     try:
79         zephyr_base = os.getenv("ZEPHYR_BASE")
80         if not zephyr_base:
81             raise RuntimeError("No ZEPHYR_BASE environment variable found, please set ZEPHYR_BASE to a zephyr repository path.")
82
83         parser = argparse.ArgumentParser(description='Script helping to update nRF Connect SDK to currently recommended revision.')
84         parser.add_argument("-c", "--check", help="Check if your current nRF Connect SDK revision is the same as recommended one.", action="store_true")
85         parser.add_argument("-u", "--update", help="Update your nRF Connect SDK to currently recommended revision.", action="store_true")
86         parser.add_argument("-q", "--quiet", help="Don't print any message if the check succeeds.", action="store_true")
87         args = parser.parse_args()
88
89         ncs_base = os.path.join(zephyr_base, '../nrf')
90         recommended_revision = get_ncs_recommended_revision()
91
92         if args.check:
93             if not args.quiet:
94                 print("Checking current nRF Connect SDK revision...")
95
96             current_revision = get_repository_commit_sha(ncs_base)
97
98             if current_revision != recommended_revision:
99                 print_check_revision_warning_message(current_revision, recommended_revision)
100                 sys.exit(1)
101
102             if not args.quiet:
103                 print("Your current version is up to date with the recommended one.")
104
105         if args.update:
106             print("Updating nRF Connect SDK to recommended revision...")
107             update_ncs(ncs_base, recommended_revision)
108
109     except (RuntimeError, subprocess.CalledProcessError) as e:
110         print(e)
111         sys.exit(1)
112
113 if __name__ == '__main__':
114     main()