blob: b8c1db7d83945f6fc09223178792463852b869c7 [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
agable@chromium.orgd629fb42014-10-01 09:40:10 +000015
Andrii Shyshkalov80cae422017-04-27 01:01:42 +020016FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): *(.*)$')
Andrii Shyshkalov49fe9222016-12-15 11:05:06 +010017CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/\-\.]+)@{#(\d+)}$')
Ayu Ishii09858612020-06-26 18:00:52 +000018FOOTER_KEY_BLOCKLIST = set(['http', 'https'])
luqui@chromium.org0b887622014-09-03 02:31:03 +000019
agable@chromium.orgd629fb42014-10-01 09:40:10 +000020
luqui@chromium.org0b887622014-09-03 02:31:03 +000021def normalize_name(header):
22 return '-'.join([ word.title() for word in header.strip().split('-') ])
23
24
25def parse_footer(line):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000026 """Returns footer's (key, value) if footer is valid, else None."""
luqui@chromium.org0b887622014-09-03 02:31:03 +000027 match = FOOTER_PATTERN.match(line)
Ayu Ishii09858612020-06-26 18:00:52 +000028 if match and match.group(1) not in FOOTER_KEY_BLOCKLIST:
luqui@chromium.org0b887622014-09-03 02:31:03 +000029 return (match.group(1), match.group(2))
Aaron Gabled9a67562018-01-03 15:56:08 -080030 return None
luqui@chromium.org0b887622014-09-03 02:31:03 +000031
32
33def parse_footers(message):
34 """Parses a git commit message into a multimap of footers."""
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000035 _, _, parsed_footers = split_footers(message)
36 footer_map = defaultdict(list)
37 if parsed_footers:
38 # Read footers from bottom to top, because latter takes precedense,
39 # and we want it to be first in the multimap value.
40 for (k, v) in reversed(parsed_footers):
41 footer_map[normalize_name(k)].append(v.strip())
42 return footer_map
43
44
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020045def matches_footer_key(line, key):
46 """Returns whether line is a valid footer whose key matches a given one.
47
48 Keys are compared in normalized form.
49 """
50 r = parse_footer(line)
51 if r is None:
Andrii Shyshkalov1a91c602017-05-11 14:35:56 +020052 return False
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020053 return normalize_name(r[0]) == normalize_name(key)
54
55
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000056def split_footers(message):
57 """Returns (non_footer_lines, footer_lines, parsed footers).
58
59 Guarantees that:
Aaron Gable4be31872018-01-03 16:30:46 -080060 (non_footer_lines + footer_lines) ~= message.splitlines(), with at
61 most one new newline, if the last paragraph is text followed by footers.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000062 parsed_footers is parse_footer applied on each line of footer_lines.
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020063 There could be fewer parsed_footers than footer lines if some lines in
64 last paragraph are malformed.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000065 """
Shahbaz Youssefi407b5a52020-09-22 19:39:00 +000066 message_lines = list(message.rstrip().splitlines())
luqui@chromium.org0b887622014-09-03 02:31:03 +000067 footer_lines = []
Aaron Gable4be31872018-01-03 16:30:46 -080068 maybe_footer_lines = []
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000069 for line in reversed(message_lines):
luqui@chromium.org0b887622014-09-03 02:31:03 +000070 if line == '' or line.isspace():
71 break
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000072
73 if parse_footer(line):
Aaron Gable4be31872018-01-03 16:30:46 -080074 footer_lines.extend(maybe_footer_lines)
75 maybe_footer_lines = []
76 footer_lines.append(line)
77 else:
Quinten Yearsley925cedb2020-04-13 17:49:39 +000078 # We only want to include malformed lines if they are preceded by
Aaron Gable4be31872018-01-03 16:30:46 -080079 # well-formed lines. So keep them in holding until we see a well-formed
80 # line (case above).
81 maybe_footer_lines.append(line)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000082 else:
83 # The whole description was consisting of footers,
84 # which means those aren't footers.
85 footer_lines = []
luqui@chromium.org0b887622014-09-03 02:31:03 +000086
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000087 footer_lines.reverse()
Edward Lemur5da394f2019-10-03 21:57:25 +000088 footers = [footer for footer in map(parse_footer, footer_lines) if footer]
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020089 if not footers:
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000090 return message_lines, [], []
Aaron Gable4be31872018-01-03 16:30:46 -080091 if maybe_footer_lines:
92 # If some malformed lines were left over, add a newline to split them
93 # from the well-formed ones.
94 return message_lines[:-len(footer_lines)] + [''], footer_lines, footers
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000095 return message_lines[:-len(footer_lines)], footer_lines, footers
luqui@chromium.org0b887622014-09-03 02:31:03 +000096
97
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000098def get_footer_change_id(message):
99 """Returns a list of Gerrit's ChangeId from given commit message."""
100 return parse_footers(message).get(normalize_name('Change-Id'), [])
101
102
103def add_footer_change_id(message, change_id):
104 """Returns message with Change-ID footer in it.
105
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000106 Assumes that Change-Id is not yet in footers, which is then inserted at
107 earliest footer line which is after all of these footers:
108 Bug|Issue|Test|Feature.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000109 """
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000110 assert 'Change-Id' not in parse_footers(message)
111 return add_footer(message, 'Change-Id', change_id,
112 after_keys=['Bug', 'Issue', 'Test', 'Feature'])
113
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100114
Aaron Gablec06db442017-04-26 17:29:49 -0700115def add_footer(message, key, value, after_keys=None, before_keys=None):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000116 """Returns a message with given footer appended.
117
Aaron Gablec06db442017-04-26 17:29:49 -0700118 If after_keys and before_keys are both None (default), appends footer last.
119 If after_keys is provided and matches footers already present, inserts footer
120 as *early* as possible while still appearing after all provided keys, even
121 if doing so conflicts with before_keys.
122 If before_keys is provided, inserts footer as late as possible while still
123 appearing before all provided keys.
124
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000125 For example, given
126 message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
127 after_keys=['Bug', 'Issue']
128 the new footer will be inserted between Bug and Verified-By existing footers.
129 """
130 assert key == normalize_name(key), 'Use normalized key'
131 new_footer = '%s: %s' % (key, value)
Edward Lemur69bb8be2020-02-03 20:37:38 +0000132 if not FOOTER_PATTERN.match(new_footer):
133 raise ValueError('Invalid footer %r' % new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000134
Aaron Gablec06db442017-04-26 17:29:49 -0700135 top_lines, footer_lines, _ = split_footers(message)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000136 if not footer_lines:
137 if not top_lines or top_lines[-1] != '':
138 top_lines.append('')
139 footer_lines = [new_footer]
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +0000140 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700141 after_keys = set(map(normalize_name, after_keys or []))
142 after_indices = [
143 footer_lines.index(x) for x in footer_lines for k in after_keys
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +0200144 if matches_footer_key(x, k)]
Aaron Gablec06db442017-04-26 17:29:49 -0700145 before_keys = set(map(normalize_name, before_keys or []))
146 before_indices = [
147 footer_lines.index(x) for x in footer_lines for k in before_keys
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +0200148 if matches_footer_key(x, k)]
Aaron Gablec06db442017-04-26 17:29:49 -0700149 if after_indices:
150 # after_keys takes precedence, even if there's a conflict.
151 insert_idx = max(after_indices) + 1
152 elif before_indices:
153 insert_idx = min(before_indices)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000154 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700155 insert_idx = len(footer_lines)
156 footer_lines.insert(insert_idx, new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000157 return '\n'.join(top_lines + footer_lines)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000158
159
Aaron Gableb584c4f2017-04-26 16:28:08 -0700160def remove_footer(message, key):
161 """Returns a message with all instances of given footer removed."""
162 key = normalize_name(key)
163 top_lines, footer_lines, _ = split_footers(message)
164 if not footer_lines:
165 return message
Aaron Gableb08ba652017-07-12 15:30:02 -0700166 new_footer_lines = []
167 for line in footer_lines:
168 try:
169 f = normalize_name(parse_footer(line)[0])
170 if f != key:
171 new_footer_lines.append(line)
172 except TypeError:
173 # If the footer doesn't parse (i.e. is malformed), just let it carry over.
174 new_footer_lines.append(line)
Aaron Gableb584c4f2017-04-26 16:28:08 -0700175 return '\n'.join(top_lines + new_footer_lines)
176
177
luqui@chromium.org0b887622014-09-03 02:31:03 +0000178def get_unique(footers, key):
179 key = normalize_name(key)
180 values = footers[key]
181 assert len(values) <= 1, 'Multiple %s footers' % key
182 if values:
183 return values[0]
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000184
185 return None
luqui@chromium.org0b887622014-09-03 02:31:03 +0000186
187
188def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000189 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000190
191 Returns:
192 A tuple of the branch and the position on that branch. For example,
193
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000194 Cr-Commit-Position: refs/heads/main@{#292272}
luqui@chromium.org0b887622014-09-03 02:31:03 +0000195
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000196 would give the return value ('refs/heads/main', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000197 """
198
199 position = get_unique(footers, 'Cr-Commit-Position')
200 if position:
201 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
202 assert match, 'Invalid Cr-Commit-Position value: %s' % position
203 return (match.group(1), match.group(2))
204
luqui@chromium.org0b887622014-09-03 02:31:03 +0000205 raise ValueError('Unable to infer commit position from footers')
206
207
208def main(args):
209 parser = argparse.ArgumentParser(
210 formatter_class=argparse.ArgumentDefaultsHelpFormatter
211 )
Andrii Shyshkalov22a9cf52017-07-13 14:23:58 +0200212 parser.add_argument('ref', nargs='?', help='Git ref to retrieve footers from.'
213 ' Omit to parse stdin.')
luqui@chromium.org0b887622014-09-03 02:31:03 +0000214
215 g = parser.add_mutually_exclusive_group()
216 g.add_argument('--key', metavar='KEY',
217 help='Get all values for the given footer name, one per '
218 'line (case insensitive)')
219 g.add_argument('--position', action='store_true')
220 g.add_argument('--position-ref', action='store_true')
221 g.add_argument('--position-num', action='store_true')
Andrii Shyshkalov22a9cf52017-07-13 14:23:58 +0200222 g.add_argument('--json', help='filename to dump JSON serialized footers to.')
luqui@chromium.org0b887622014-09-03 02:31:03 +0000223
luqui@chromium.org0b887622014-09-03 02:31:03 +0000224 opts = parser.parse_args(args)
225
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000226 if opts.ref:
227 message = git.run('log', '-1', '--format=%B', opts.ref)
228 else:
Andrii Shyshkalov22a9cf52017-07-13 14:23:58 +0200229 message = sys.stdin.read()
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000230
luqui@chromium.org0b887622014-09-03 02:31:03 +0000231 footers = parse_footers(message)
232
233 if opts.key:
234 for v in footers.get(normalize_name(opts.key), []):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000235 print(v)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000236 elif opts.position:
237 pos = get_position(footers)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000238 print('%s@{#%s}' % (pos[0], pos[1] or '?'))
luqui@chromium.org0b887622014-09-03 02:31:03 +0000239 elif opts.position_ref:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000240 print(get_position(footers)[0])
luqui@chromium.org0b887622014-09-03 02:31:03 +0000241 elif opts.position_num:
242 pos = get_position(footers)
243 assert pos[1], 'No valid position for commit'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000244 print(pos[1])
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000245 elif opts.json:
246 with open(opts.json, 'w') as f:
247 json.dump(footers, f)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000248 else:
249 for k in footers.keys():
250 for v in footers[k]:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000251 print('%s: %s' % (k, v))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000252 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000253
254
255if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000256 try:
257 sys.exit(main(sys.argv[1:]))
258 except KeyboardInterrupt:
259 sys.stderr.write('interrupted\n')
260 sys.exit(1)