blob: 31535c917cdfc4b2709fedae811287cfcb980edf [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
45def split_footers(message):
46 """Returns (non_footer_lines, footer_lines, parsed footers).
47
48 Guarantees that:
49 (non_footer_lines + footer_lines) == message.splitlines().
50 parsed_footers is parse_footer applied on each line of footer_lines.
Andrii Shyshkalov28a5d5d2017-05-10 19:37:18 +020051 There could be fewer parsed_footers than footer lines if some lines in
52 last paragraph are malformed.
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000053 """
54 message_lines = list(message.splitlines())
luqui@chromium.org0b887622014-09-03 02:31:03 +000055 footer_lines = []
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000056 for line in reversed(message_lines):
luqui@chromium.org0b887622014-09-03 02:31:03 +000057 if line == '' or line.isspace():
58 break
59 footer_lines.append(line)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000060 else:
61 # The whole description was consisting of footers,
62 # which means those aren't footers.
63 footer_lines = []
luqui@chromium.org0b887622014-09-03 02:31:03 +000064
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000065 footer_lines.reverse()
Andrii Shyshkalov28a5d5d2017-05-10 19:37:18 +020066 footers = filter(None, map(parse_footer, footer_lines))
67 if not footers:
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000068 return message_lines, [], []
69 return message_lines[:-len(footer_lines)], footer_lines, footers
luqui@chromium.org0b887622014-09-03 02:31:03 +000070
71
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000072def get_footer_change_id(message):
73 """Returns a list of Gerrit's ChangeId from given commit message."""
74 return parse_footers(message).get(normalize_name('Change-Id'), [])
75
76
77def add_footer_change_id(message, change_id):
78 """Returns message with Change-ID footer in it.
79
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000080 Assumes that Change-Id is not yet in footers, which is then inserted at
81 earliest footer line which is after all of these footers:
82 Bug|Issue|Test|Feature.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000083 """
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000084 assert 'Change-Id' not in parse_footers(message)
85 return add_footer(message, 'Change-Id', change_id,
86 after_keys=['Bug', 'Issue', 'Test', 'Feature'])
87
Andrii Shyshkalov18975322017-01-25 16:44:13 +010088
Aaron Gablec06db442017-04-26 17:29:49 -070089def add_footer(message, key, value, after_keys=None, before_keys=None):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000090 """Returns a message with given footer appended.
91
Aaron Gablec06db442017-04-26 17:29:49 -070092 If after_keys and before_keys are both None (default), appends footer last.
93 If after_keys is provided and matches footers already present, inserts footer
94 as *early* as possible while still appearing after all provided keys, even
95 if doing so conflicts with before_keys.
96 If before_keys is provided, inserts footer as late as possible while still
97 appearing before all provided keys.
98
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000099 For example, given
100 message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
101 after_keys=['Bug', 'Issue']
102 the new footer will be inserted between Bug and Verified-By existing footers.
103 """
104 assert key == normalize_name(key), 'Use normalized key'
105 new_footer = '%s: %s' % (key, value)
106
Aaron Gablec06db442017-04-26 17:29:49 -0700107 top_lines, footer_lines, _ = split_footers(message)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000108 if not footer_lines:
109 if not top_lines or top_lines[-1] != '':
110 top_lines.append('')
111 footer_lines = [new_footer]
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +0000112 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700113 after_keys = set(map(normalize_name, after_keys or []))
114 after_indices = [
115 footer_lines.index(x) for x in footer_lines for k in after_keys
116 if normalize_name(parse_footer(x)[0]) == k]
117 before_keys = set(map(normalize_name, before_keys or []))
118 before_indices = [
119 footer_lines.index(x) for x in footer_lines for k in before_keys
120 if normalize_name(parse_footer(x)[0]) == k]
121 if after_indices:
122 # after_keys takes precedence, even if there's a conflict.
123 insert_idx = max(after_indices) + 1
124 elif before_indices:
125 insert_idx = min(before_indices)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000126 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700127 insert_idx = len(footer_lines)
128 footer_lines.insert(insert_idx, new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000129 return '\n'.join(top_lines + footer_lines)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000130
131
Aaron Gableb584c4f2017-04-26 16:28:08 -0700132def remove_footer(message, key):
133 """Returns a message with all instances of given footer removed."""
134 key = normalize_name(key)
135 top_lines, footer_lines, _ = split_footers(message)
136 if not footer_lines:
137 return message
138 new_footer_lines = [
139 l for l in footer_lines if normalize_name(parse_footer(l)[0]) != key]
140 return '\n'.join(top_lines + new_footer_lines)
141
142
luqui@chromium.org0b887622014-09-03 02:31:03 +0000143def get_unique(footers, key):
144 key = normalize_name(key)
145 values = footers[key]
146 assert len(values) <= 1, 'Multiple %s footers' % key
147 if values:
148 return values[0]
149 else:
150 return None
151
152
153def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000154 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000155
156 Returns:
157 A tuple of the branch and the position on that branch. For example,
158
159 Cr-Commit-Position: refs/heads/master@{#292272}
160
agable814b1ca2016-12-21 13:05:59 -0800161 would give the return value ('refs/heads/master', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000162 """
163
164 position = get_unique(footers, 'Cr-Commit-Position')
165 if position:
166 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
167 assert match, 'Invalid Cr-Commit-Position value: %s' % position
168 return (match.group(1), match.group(2))
169
luqui@chromium.org0b887622014-09-03 02:31:03 +0000170 raise ValueError('Unable to infer commit position from footers')
171
172
173def main(args):
174 parser = argparse.ArgumentParser(
175 formatter_class=argparse.ArgumentDefaultsHelpFormatter
176 )
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000177 parser.add_argument('ref', nargs='?', help="Git ref to retrieve footers from."
178 " Omit to parse stdin.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000179
180 g = parser.add_mutually_exclusive_group()
181 g.add_argument('--key', metavar='KEY',
182 help='Get all values for the given footer name, one per '
183 'line (case insensitive)')
184 g.add_argument('--position', action='store_true')
185 g.add_argument('--position-ref', action='store_true')
186 g.add_argument('--position-num', action='store_true')
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000187 g.add_argument('--json', help="filename to dump JSON serialized headers to.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000188
luqui@chromium.org0b887622014-09-03 02:31:03 +0000189 opts = parser.parse_args(args)
190
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000191 if opts.ref:
192 message = git.run('log', '-1', '--format=%B', opts.ref)
193 else:
194 message = '\n'.join(l for l in sys.stdin)
195
luqui@chromium.org0b887622014-09-03 02:31:03 +0000196 footers = parse_footers(message)
197
198 if opts.key:
199 for v in footers.get(normalize_name(opts.key), []):
200 print v
201 elif opts.position:
202 pos = get_position(footers)
203 print '%s@{#%s}' % (pos[0], pos[1] or '?')
204 elif opts.position_ref:
205 print get_position(footers)[0]
206 elif opts.position_num:
207 pos = get_position(footers)
208 assert pos[1], 'No valid position for commit'
209 print pos[1]
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000210 elif opts.json:
211 with open(opts.json, 'w') as f:
212 json.dump(footers, f)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000213 else:
214 for k in footers.keys():
215 for v in footers[k]:
216 print '%s: %s' % (k, v)
sbc@chromium.org013731e2015-02-26 18:28:43 +0000217 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000218
219
220if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000221 try:
222 sys.exit(main(sys.argv[1:]))
223 except KeyboardInterrupt:
224 sys.stderr.write('interrupted\n')
225 sys.exit(1)