blob: b70b248f0d7aa7e4c19c49d20b7d5336ab085e3b [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
luqui@chromium.org0b887622014-09-03 02:31:03 +00002# Copyright 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import argparse
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +00007import json
luqui@chromium.org0b887622014-09-03 02:31:03 +00008import re
9import sys
10
11from collections import defaultdict
12
13import git_common as git
14
Andrii Shyshkalov80cae422017-04-27 01:01:42 +020015FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): *(.*)$')
Andrii Shyshkalov49fe9222016-12-15 11:05:06 +010016CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/\-\.]+)@{#(\d+)}$')
Ayu Ishii09858612020-06-26 18:00:52 +000017FOOTER_KEY_BLOCKLIST = set(['http', 'https'])
luqui@chromium.org0b887622014-09-03 02:31:03 +000018
agable@chromium.orgd629fb42014-10-01 09:40:10 +000019
luqui@chromium.org0b887622014-09-03 02:31:03 +000020def normalize_name(header):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000021 return '-'.join([word.title() for word in header.strip().split('-')])
luqui@chromium.org0b887622014-09-03 02:31:03 +000022
23
24def parse_footer(line):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000025 """Returns footer's (key, value) if footer is valid, else None."""
26 match = FOOTER_PATTERN.match(line)
27 if match and match.group(1) not in FOOTER_KEY_BLOCKLIST:
28 return (match.group(1), match.group(2))
29 return None
luqui@chromium.org0b887622014-09-03 02:31:03 +000030
31
32def parse_footers(message):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000033 """Parses a git commit message into a multimap of footers."""
34 _, _, parsed_footers = split_footers(message)
35 footer_map = defaultdict(list)
36 if parsed_footers:
37 # Read footers from bottom to top, because latter takes precedense,
38 # and we want it to be first in the multimap value.
39 for (k, v) in reversed(parsed_footers):
40 footer_map[normalize_name(k)].append(v.strip())
41 return footer_map
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000042
43
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020044def matches_footer_key(line, key):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000045 """Returns whether line is a valid footer whose key matches a given one.
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020046
47 Keys are compared in normalized form.
48 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000049 r = parse_footer(line)
50 if r is None:
51 return False
52 return normalize_name(r[0]) == normalize_name(key)
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020053
54
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000055def split_footers(message):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000056 """Returns (non_footer_lines, footer_lines, parsed footers).
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000057
58 Guarantees that:
Aaron Gable4be31872018-01-03 16:30:46 -080059 (non_footer_lines + footer_lines) ~= message.splitlines(), with at
60 most one new newline, if the last paragraph is text followed by footers.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000061 parsed_footers is parse_footer applied on each line of footer_lines.
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020062 There could be fewer parsed_footers than footer lines if some lines in
63 last paragraph are malformed.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000064 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000065 message_lines = list(message.rstrip().splitlines())
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000066 footer_lines = []
Mike Frysinger124bb8e2023-09-06 05:48:55 +000067 maybe_footer_lines = []
68 for line in reversed(message_lines):
69 if line == '' or line.isspace():
70 break
luqui@chromium.org0b887622014-09-03 02:31:03 +000071
Mike Frysinger124bb8e2023-09-06 05:48:55 +000072 if parse_footer(line):
73 footer_lines.extend(maybe_footer_lines)
74 maybe_footer_lines = []
75 footer_lines.append(line)
76 else:
77 # We only want to include malformed lines if they are preceded by
78 # well-formed lines. So keep them in holding until we see a
79 # well-formed line (case above).
80 maybe_footer_lines.append(line)
81 else:
82 # The whole description was consisting of footers,
83 # which means those aren't footers.
84 footer_lines = []
85
86 footer_lines.reverse()
87 footers = [footer for footer in map(parse_footer, footer_lines) if footer]
88 if not footers:
89 return message_lines, [], []
90 if maybe_footer_lines:
91 # If some malformed lines were left over, add a newline to split them
92 # from the well-formed ones.
93 return message_lines[:-len(footer_lines)] + [''], footer_lines, footers
94 return message_lines[:-len(footer_lines)], footer_lines, footers
luqui@chromium.org0b887622014-09-03 02:31:03 +000095
96
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000097def get_footer_change_id(message):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000098 """Returns a list of Gerrit's ChangeId from given commit message."""
99 return parse_footers(message).get(normalize_name('Change-Id'), [])
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000100
101
102def add_footer_change_id(message, change_id):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000103 """Returns message with Change-ID footer in it.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000104
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000105 Assumes that Change-Id is not yet in footers, which is then inserted at
106 earliest footer line which is after all of these footers:
107 Bug|Issue|Test|Feature.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000108 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000109 assert 'Change-Id' not in parse_footers(message)
110 return add_footer(message,
111 'Change-Id',
112 change_id,
113 after_keys=['Bug', 'Issue', 'Test', 'Feature'])
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000114
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100115
Aaron Gablec06db442017-04-26 17:29:49 -0700116def add_footer(message, key, value, after_keys=None, before_keys=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000117 """Returns a message with given footer appended.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000118
Aaron Gablec06db442017-04-26 17:29:49 -0700119 If after_keys and before_keys are both None (default), appends footer last.
120 If after_keys is provided and matches footers already present, inserts footer
121 as *early* as possible while still appearing after all provided keys, even
122 if doing so conflicts with before_keys.
123 If before_keys is provided, inserts footer as late as possible while still
124 appearing before all provided keys.
125
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000126 For example, given
127 message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
128 after_keys=['Bug', 'Issue']
129 the new footer will be inserted between Bug and Verified-By existing footers.
130 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000131 assert key == normalize_name(key), 'Use normalized key'
132 new_footer = '%s: %s' % (key, value)
133 if not FOOTER_PATTERN.match(new_footer):
134 raise ValueError('Invalid footer %r' % new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000135
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000136 top_lines, footer_lines, _ = split_footers(message)
137 if not footer_lines:
138 if not top_lines or top_lines[-1] != '':
139 top_lines.append('')
140 footer_lines = [new_footer]
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000141 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000142 after_keys = set(map(normalize_name, after_keys or []))
143 after_indices = [
144 footer_lines.index(x) for x in footer_lines for k in after_keys
145 if matches_footer_key(x, k)
146 ]
147 before_keys = set(map(normalize_name, before_keys or []))
148 before_indices = [
149 footer_lines.index(x) for x in footer_lines for k in before_keys
150 if matches_footer_key(x, k)
151 ]
152 if after_indices:
153 # after_keys takes precedence, even if there's a conflict.
154 insert_idx = max(after_indices) + 1
155 elif before_indices:
156 insert_idx = min(before_indices)
157 else:
158 insert_idx = len(footer_lines)
159 footer_lines.insert(insert_idx, new_footer)
160 return '\n'.join(top_lines + footer_lines)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000161
162
Aaron Gableb584c4f2017-04-26 16:28:08 -0700163def remove_footer(message, key):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000164 """Returns a message with all instances of given footer removed."""
165 key = normalize_name(key)
166 top_lines, footer_lines, _ = split_footers(message)
167 if not footer_lines:
168 return message
169 new_footer_lines = []
170 for line in footer_lines:
171 try:
172 f = normalize_name(parse_footer(line)[0])
173 if f != key:
174 new_footer_lines.append(line)
175 except TypeError:
176 # If the footer doesn't parse (i.e. is malformed), just let it carry
177 # over.
178 new_footer_lines.append(line)
179 return '\n'.join(top_lines + new_footer_lines)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700180
181
luqui@chromium.org0b887622014-09-03 02:31:03 +0000182def get_unique(footers, key):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000183 key = normalize_name(key)
184 values = footers[key]
185 assert len(values) <= 1, 'Multiple %s footers' % key
186 if values:
187 return values[0]
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000188
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000189 return None
luqui@chromium.org0b887622014-09-03 02:31:03 +0000190
191
192def get_position(footers):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000193 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000194
195 Returns:
196 A tuple of the branch and the position on that branch. For example,
197
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000198 Cr-Commit-Position: refs/heads/main@{#292272}
luqui@chromium.org0b887622014-09-03 02:31:03 +0000199
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000200 would give the return value ('refs/heads/main', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000201 """
202
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000203 position = get_unique(footers, 'Cr-Commit-Position')
204 if position:
205 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
206 assert match, 'Invalid Cr-Commit-Position value: %s' % position
207 return (match.group(1), match.group(2))
luqui@chromium.org0b887622014-09-03 02:31:03 +0000208
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000209 raise ValueError('Unable to infer commit position from footers')
luqui@chromium.org0b887622014-09-03 02:31:03 +0000210
211
212def main(args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000213 parser = argparse.ArgumentParser(
214 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
215 parser.add_argument('ref',
216 nargs='?',
217 help='Git ref to retrieve footers from.'
218 ' Omit to parse stdin.')
luqui@chromium.org0b887622014-09-03 02:31:03 +0000219
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000220 g = parser.add_mutually_exclusive_group()
221 g.add_argument('--key',
222 metavar='KEY',
223 help='Get all values for the given footer name, one per '
224 'line (case insensitive)')
225 g.add_argument('--position', action='store_true')
226 g.add_argument('--position-ref', action='store_true')
227 g.add_argument('--position-num', action='store_true')
228 g.add_argument('--json',
229 help='filename to dump JSON serialized footers to.')
luqui@chromium.org0b887622014-09-03 02:31:03 +0000230
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000231 opts = parser.parse_args(args)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000232
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000233 if opts.ref:
234 message = git.run('log', '-1', '--format=%B', opts.ref)
235 else:
236 message = sys.stdin.read()
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000237
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000238 footers = parse_footers(message)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000239
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000240 if opts.key:
241 for v in footers.get(normalize_name(opts.key), []):
242 print(v)
243 elif opts.position:
244 pos = get_position(footers)
245 print('%s@{#%s}' % (pos[0], pos[1] or '?'))
246 elif opts.position_ref:
247 print(get_position(footers)[0])
248 elif opts.position_num:
249 pos = get_position(footers)
250 assert pos[1], 'No valid position for commit'
251 print(pos[1])
252 elif opts.json:
253 with open(opts.json, 'w') as f:
254 json.dump(footers, f)
255 else:
256 for k in footers.keys():
257 for v in footers[k]:
258 print('%s: %s' % (k, v))
259 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000260
261
262if __name__ == '__main__':
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000263 try:
264 sys.exit(main(sys.argv[1:]))
265 except KeyboardInterrupt:
266 sys.stderr.write('interrupted\n')
267 sys.exit(1)