blob: a973a1105f6ce41c9e28c2bc06d5f6cea95addb2 [file] [log] [blame]
luqui@chromium.org0b887622014-09-03 02:31:03 +00001#!/usr/bin/env python
2# 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+)}$')
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):
21 return '-'.join([ word.title() for word in header.strip().split('-') ])
22
23
24def parse_footer(line):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000025 """Returns footer's (key, value) if footer is valid, else None."""
luqui@chromium.org0b887622014-09-03 02:31:03 +000026 match = FOOTER_PATTERN.match(line)
27 if match:
28 return (match.group(1), match.group(2))
29 else:
30 return None
31
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:
60 (non_footer_lines + footer_lines) == message.splitlines().
61 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 """
65 message_lines = list(message.splitlines())
luqui@chromium.org0b887622014-09-03 02:31:03 +000066 footer_lines = []
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000067 for line in reversed(message_lines):
luqui@chromium.org0b887622014-09-03 02:31:03 +000068 if line == '' or line.isspace():
69 break
70 footer_lines.append(line)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000071 else:
72 # The whole description was consisting of footers,
73 # which means those aren't footers.
74 footer_lines = []
luqui@chromium.org0b887622014-09-03 02:31:03 +000075
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000076 footer_lines.reverse()
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +020077 footers = filter(None, map(parse_footer, footer_lines))
78 if not footers:
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000079 return message_lines, [], []
80 return message_lines[:-len(footer_lines)], footer_lines, footers
luqui@chromium.org0b887622014-09-03 02:31:03 +000081
82
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000083def get_footer_change_id(message):
84 """Returns a list of Gerrit's ChangeId from given commit message."""
85 return parse_footers(message).get(normalize_name('Change-Id'), [])
86
87
88def add_footer_change_id(message, change_id):
89 """Returns message with Change-ID footer in it.
90
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000091 Assumes that Change-Id is not yet in footers, which is then inserted at
92 earliest footer line which is after all of these footers:
93 Bug|Issue|Test|Feature.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000094 """
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000095 assert 'Change-Id' not in parse_footers(message)
96 return add_footer(message, 'Change-Id', change_id,
97 after_keys=['Bug', 'Issue', 'Test', 'Feature'])
98
Andrii Shyshkalov18975322017-01-25 16:44:13 +010099
Aaron Gablec06db442017-04-26 17:29:49 -0700100def add_footer(message, key, value, after_keys=None, before_keys=None):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000101 """Returns a message with given footer appended.
102
Aaron Gablec06db442017-04-26 17:29:49 -0700103 If after_keys and before_keys are both None (default), appends footer last.
104 If after_keys is provided and matches footers already present, inserts footer
105 as *early* as possible while still appearing after all provided keys, even
106 if doing so conflicts with before_keys.
107 If before_keys is provided, inserts footer as late as possible while still
108 appearing before all provided keys.
109
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000110 For example, given
111 message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
112 after_keys=['Bug', 'Issue']
113 the new footer will be inserted between Bug and Verified-By existing footers.
114 """
115 assert key == normalize_name(key), 'Use normalized key'
116 new_footer = '%s: %s' % (key, value)
117
Aaron Gablec06db442017-04-26 17:29:49 -0700118 top_lines, footer_lines, _ = split_footers(message)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000119 if not footer_lines:
120 if not top_lines or top_lines[-1] != '':
121 top_lines.append('')
122 footer_lines = [new_footer]
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +0000123 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700124 after_keys = set(map(normalize_name, after_keys or []))
125 after_indices = [
126 footer_lines.index(x) for x in footer_lines for k in after_keys
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +0200127 if matches_footer_key(x, k)]
Aaron Gablec06db442017-04-26 17:29:49 -0700128 before_keys = set(map(normalize_name, before_keys or []))
129 before_indices = [
130 footer_lines.index(x) for x in footer_lines for k in before_keys
Andrii Shyshkalov04b51d62017-05-11 13:21:30 +0200131 if matches_footer_key(x, k)]
Aaron Gablec06db442017-04-26 17:29:49 -0700132 if after_indices:
133 # after_keys takes precedence, even if there's a conflict.
134 insert_idx = max(after_indices) + 1
135 elif before_indices:
136 insert_idx = min(before_indices)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000137 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700138 insert_idx = len(footer_lines)
139 footer_lines.insert(insert_idx, new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000140 return '\n'.join(top_lines + footer_lines)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000141
142
Aaron Gableb584c4f2017-04-26 16:28:08 -0700143def remove_footer(message, key):
144 """Returns a message with all instances of given footer removed."""
145 key = normalize_name(key)
146 top_lines, footer_lines, _ = split_footers(message)
147 if not footer_lines:
148 return message
149 new_footer_lines = [
150 l for l in footer_lines if normalize_name(parse_footer(l)[0]) != key]
151 return '\n'.join(top_lines + new_footer_lines)
152
153
luqui@chromium.org0b887622014-09-03 02:31:03 +0000154def get_unique(footers, key):
155 key = normalize_name(key)
156 values = footers[key]
157 assert len(values) <= 1, 'Multiple %s footers' % key
158 if values:
159 return values[0]
160 else:
161 return None
162
163
164def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000165 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000166
167 Returns:
168 A tuple of the branch and the position on that branch. For example,
169
170 Cr-Commit-Position: refs/heads/master@{#292272}
171
agable814b1ca2016-12-21 13:05:59 -0800172 would give the return value ('refs/heads/master', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000173 """
174
175 position = get_unique(footers, 'Cr-Commit-Position')
176 if position:
177 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
178 assert match, 'Invalid Cr-Commit-Position value: %s' % position
179 return (match.group(1), match.group(2))
180
luqui@chromium.org0b887622014-09-03 02:31:03 +0000181 raise ValueError('Unable to infer commit position from footers')
182
183
184def main(args):
185 parser = argparse.ArgumentParser(
186 formatter_class=argparse.ArgumentDefaultsHelpFormatter
187 )
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000188 parser.add_argument('ref', nargs='?', help="Git ref to retrieve footers from."
189 " Omit to parse stdin.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000190
191 g = parser.add_mutually_exclusive_group()
192 g.add_argument('--key', metavar='KEY',
193 help='Get all values for the given footer name, one per '
194 'line (case insensitive)')
195 g.add_argument('--position', action='store_true')
196 g.add_argument('--position-ref', action='store_true')
197 g.add_argument('--position-num', action='store_true')
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000198 g.add_argument('--json', help="filename to dump JSON serialized headers to.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000199
luqui@chromium.org0b887622014-09-03 02:31:03 +0000200 opts = parser.parse_args(args)
201
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000202 if opts.ref:
203 message = git.run('log', '-1', '--format=%B', opts.ref)
204 else:
205 message = '\n'.join(l for l in sys.stdin)
206
luqui@chromium.org0b887622014-09-03 02:31:03 +0000207 footers = parse_footers(message)
208
209 if opts.key:
210 for v in footers.get(normalize_name(opts.key), []):
211 print v
212 elif opts.position:
213 pos = get_position(footers)
214 print '%s@{#%s}' % (pos[0], pos[1] or '?')
215 elif opts.position_ref:
216 print get_position(footers)[0]
217 elif opts.position_num:
218 pos = get_position(footers)
219 assert pos[1], 'No valid position for commit'
220 print pos[1]
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000221 elif opts.json:
222 with open(opts.json, 'w') as f:
223 json.dump(footers, f)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000224 else:
225 for k in footers.keys():
226 for v in footers[k]:
227 print '%s: %s' % (k, v)
sbc@chromium.org013731e2015-02-26 18:28:43 +0000228 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000229
230
231if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000232 try:
233 sys.exit(main(sys.argv[1:]))
234 except KeyboardInterrupt:
235 sys.stderr.write('interrupted\n')
236 sys.exit(1)