Debian Codegraph @

crt/aws-c-common/scripts/latest_submodules.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 import argparse
3 import os
4 import os.path
5 import re
6 import subprocess
7 import sys
8
9
10 def run(*args, check=True):
11 return subprocess.run(args, capture_output=True, check=check, universal_newlines=True)
12
13
14 def get_submodules():
15 """
16 Return list of submodules for current repo, sorted by name.
17
18 Each item looks like:
19 {
20 'name': 'aws-c-common',
21 'path': 'crt/aws-c-common',
22 'url': 'https://github.com/awslabs/aws-c-common.git',
23 }
24 """
25 if not os.path.exists('.gitmodules'):
26 sys.exit(f'No .gitmodules found in {os.getcwd()}')
27
28 submodules = []
29 start_pattern = re.compile(r'\[submodule')
30 path_pattern = re.compile(r'\s+path = (\S+)')
31 url_pattern = re.compile(r'\s+url = (\S+)')
32
33 current = None
34 with open('.gitmodules', 'r') as f:
35 for line in f.readlines():
36 m = start_pattern.match(line)
37 if m:
38 current = {}
39 submodules.append(current)
40 continue
41
42 m = path_pattern.match(line)
43 if m:
44 current['path'] = m.group(1)
45 current['name'] = os.path.basename(current['path'])
46 continue
47
48 m = url_pattern.match(line)
49 if m:
50 current['url'] = m.group(1)
51 continue
52
53 return sorted(submodules, key=lambda x: x['name'])
54
55
56 def get_release_tags(prefix='v'):
57 """
58 Return list of release tags for current repo, sorted high to low.
59
60 Each item looks like:
61 {
62 'commit': 'e18f041a0c8d17189f2eae2a32f16e0a7a3f0f1c',
63 'version': 'v0.5.18'
64 'num_tuple': (0,5,18),
65 }
66 """
67 git_output = run('git', 'ls-remote', '--tags').stdout
68 tags = []
69 for line in git_output.splitlines():
70 # line looks like: "e18f041a0c8d17189f2eae2a32f16e0a7a3f0f1c refs/tags/v0.5.18"
71 match = re.match(
72 r'([a-f0-9]+)\s+refs/tags/(' + prefix + r'([0-9]+)\.([0-9]+)\.([0-9]+))$', line)
73 if not match:
74 # skip malformed release tags
75 continue
76 tags.append({
77 'commit': match.group(1),
78 'version': match.group(2),
79 'num_tuple': (int(match.group(3)), int(match.group(4)), int(match.group(5))),
80 })
81
82 # sort highest version first
83 return sorted(tags, reverse=True, key=lambda tag: tag['num_tuple'])
84
85
86 def get_current_commit():
87 git_output = run('git', 'rev-parse', 'HEAD').stdout
88 return git_output.splitlines()[0]
89
90
91 def is_ancestor(ancestor, descendant):
92 """Return whether first commit is an ancestor to the second'"""
93 result = run('git', 'merge-base', '--is-ancestor',
94 ancestor, descendant, check=False)
95 return result.returncode == 0
96
97
98 def get_tag_for_commit(tags, commit):
99 for tag in tags:
100 if tag['commit'] == commit:
101 return tag
102 return None
103
104
105 def main():
106 parser = argparse.ArgumentParser(
107 description="Update submodules to latest tags")
108 parser.add_argument('ignore', nargs='*', help="submodules to ignore")
109 parser.add_argument('--dry-run', action='store_true',
110 help="print without actually updating")
111 args = parser.parse_args()
112
113 root_path = os.getcwd()
114 submodules = get_submodules()
115 name_pad = max([len(x['name']) for x in submodules])
116 for submodule in submodules:
117 name = submodule['name']
118
119 os.chdir(os.path.join(root_path, submodule['path']))
120
121 version_prefix = 'v'
122 # aws-crt-java uses FIPS releases of aws-lc
123 if name == 'aws-lc' and 'aws-crt-java' in root_path:
124 version_prefix = 'AWS-LC-FIPS-'
125
126 tags = get_release_tags(version_prefix)
127 current_commit = get_current_commit()
128 current_tag = get_tag_for_commit(tags, current_commit)
129 sync_from = current_tag['version'] if current_tag else current_commit
130
131 if name in args.ignore:
132 print(f"{name:<{name_pad}} {sync_from} (ignored)")
133 continue
134
135 latest_tag = tags[0]
136 sync_to = latest_tag['version']
137
138 # The only time we don't want to sync to the latest release is:
139 # The submodule is at some commit beyond the latest release,
140 # and the CRT team doesn't control this repo so can't just cut a new release
141 if sync_from != sync_to and current_tag is None:
142 if name in ['aws-lc', 's2n', 's2n-tls']:
143 # must fetch tags before we can check their ancestry
144 run('git', 'fetch', '--tags', '--prune', '--prune-tags', '--force')
145 if not is_ancestor(ancestor=current_commit, descendant=sync_to):
146 sync_to = sync_from
147
148 if sync_from == sync_to:
149 print(f"{name:<{name_pad}} {sync_from} ✓")
150 else:
151 print(f"{name:<{name_pad}} {sync_from} -> {sync_to}")
152 if not args.dry_run:
153 run('git', 'fetch', '--tags', '--prune', '--prune-tags', '--force')
154 run('git', 'checkout', sync_to)
155 run('git', 'submodule', 'update')
156
157
158 if __name__ == '__main__':
159 main()