blob: 8e9aaff9bc2cb708c21fefea68c504919d6ff2ff [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.
51 """
52 message_lines = list(message.splitlines())
luqui@chromium.org0b887622014-09-03 02:31:03 +000053 footer_lines = []
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000054 for line in reversed(message_lines):
luqui@chromium.org0b887622014-09-03 02:31:03 +000055 if line == '' or line.isspace():
56 break
57 footer_lines.append(line)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000058 else:
59 # The whole description was consisting of footers,
60 # which means those aren't footers.
61 footer_lines = []
luqui@chromium.org0b887622014-09-03 02:31:03 +000062
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000063 footer_lines.reverse()
luqui@chromium.org0b887622014-09-03 02:31:03 +000064 footers = map(parse_footer, footer_lines)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000065 if not footer_lines or not all(footers):
66 return message_lines, [], []
67 return message_lines[:-len(footer_lines)], footer_lines, footers
luqui@chromium.org0b887622014-09-03 02:31:03 +000068
69
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000070def get_footer_change_id(message):
71 """Returns a list of Gerrit's ChangeId from given commit message."""
72 return parse_footers(message).get(normalize_name('Change-Id'), [])
73
74
75def add_footer_change_id(message, change_id):
76 """Returns message with Change-ID footer in it.
77
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000078 Assumes that Change-Id is not yet in footers, which is then inserted at
79 earliest footer line which is after all of these footers:
80 Bug|Issue|Test|Feature.
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000081 """
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000082 assert 'Change-Id' not in parse_footers(message)
83 return add_footer(message, 'Change-Id', change_id,
84 after_keys=['Bug', 'Issue', 'Test', 'Feature'])
85
Andrii Shyshkalov18975322017-01-25 16:44:13 +010086
Aaron Gablec06db442017-04-26 17:29:49 -070087def add_footer(message, key, value, after_keys=None, before_keys=None):
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000088 """Returns a message with given footer appended.
89
Aaron Gablec06db442017-04-26 17:29:49 -070090 If after_keys and before_keys are both None (default), appends footer last.
91 If after_keys is provided and matches footers already present, inserts footer
92 as *early* as possible while still appearing after all provided keys, even
93 if doing so conflicts with before_keys.
94 If before_keys is provided, inserts footer as late as possible while still
95 appearing before all provided keys.
96
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +000097 For example, given
98 message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
99 after_keys=['Bug', 'Issue']
100 the new footer will be inserted between Bug and Verified-By existing footers.
101 """
102 assert key == normalize_name(key), 'Use normalized key'
103 new_footer = '%s: %s' % (key, value)
104
Aaron Gablec06db442017-04-26 17:29:49 -0700105 top_lines, footer_lines, _ = split_footers(message)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000106 if not footer_lines:
107 if not top_lines or top_lines[-1] != '':
108 top_lines.append('')
109 footer_lines = [new_footer]
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +0000110 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700111 after_keys = set(map(normalize_name, after_keys or []))
112 after_indices = [
113 footer_lines.index(x) for x in footer_lines for k in after_keys
114 if normalize_name(parse_footer(x)[0]) == k]
115 before_keys = set(map(normalize_name, before_keys or []))
116 before_indices = [
117 footer_lines.index(x) for x in footer_lines for k in before_keys
118 if normalize_name(parse_footer(x)[0]) == k]
119 if after_indices:
120 # after_keys takes precedence, even if there's a conflict.
121 insert_idx = max(after_indices) + 1
122 elif before_indices:
123 insert_idx = min(before_indices)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000124 else:
Aaron Gablec06db442017-04-26 17:29:49 -0700125 insert_idx = len(footer_lines)
126 footer_lines.insert(insert_idx, new_footer)
tandrii@chromium.orgf2aa52b2016-06-03 12:58:20 +0000127 return '\n'.join(top_lines + footer_lines)
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +0000128
129
Aaron Gableb584c4f2017-04-26 16:28:08 -0700130def remove_footer(message, key):
131 """Returns a message with all instances of given footer removed."""
132 key = normalize_name(key)
133 top_lines, footer_lines, _ = split_footers(message)
134 if not footer_lines:
135 return message
136 new_footer_lines = [
137 l for l in footer_lines if normalize_name(parse_footer(l)[0]) != key]
138 return '\n'.join(top_lines + new_footer_lines)
139
140
luqui@chromium.org0b887622014-09-03 02:31:03 +0000141def get_unique(footers, key):
142 key = normalize_name(key)
143 values = footers[key]
144 assert len(values) <= 1, 'Multiple %s footers' % key
145 if values:
146 return values[0]
147 else:
148 return None
149
150
151def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000152 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000153
154 Returns:
155 A tuple of the branch and the position on that branch. For example,
156
157 Cr-Commit-Position: refs/heads/master@{#292272}
158
agable814b1ca2016-12-21 13:05:59 -0800159 would give the return value ('refs/heads/master', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000160 """
161
162 position = get_unique(footers, 'Cr-Commit-Position')
163 if position:
164 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
165 assert match, 'Invalid Cr-Commit-Position value: %s' % position
166 return (match.group(1), match.group(2))
167
luqui@chromium.org0b887622014-09-03 02:31:03 +0000168 raise ValueError('Unable to infer commit position from footers')
169
170
171def main(args):
172 parser = argparse.ArgumentParser(
173 formatter_class=argparse.ArgumentDefaultsHelpFormatter
174 )
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000175 parser.add_argument('ref', nargs='?', help="Git ref to retrieve footers from."
176 " Omit to parse stdin.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000177
178 g = parser.add_mutually_exclusive_group()
179 g.add_argument('--key', metavar='KEY',
180 help='Get all values for the given footer name, one per '
181 'line (case insensitive)')
182 g.add_argument('--position', action='store_true')
183 g.add_argument('--position-ref', action='store_true')
184 g.add_argument('--position-num', action='store_true')
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000185 g.add_argument('--json', help="filename to dump JSON serialized headers to.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000186
luqui@chromium.org0b887622014-09-03 02:31:03 +0000187 opts = parser.parse_args(args)
188
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000189 if opts.ref:
190 message = git.run('log', '-1', '--format=%B', opts.ref)
191 else:
192 message = '\n'.join(l for l in sys.stdin)
193
luqui@chromium.org0b887622014-09-03 02:31:03 +0000194 footers = parse_footers(message)
195
196 if opts.key:
197 for v in footers.get(normalize_name(opts.key), []):
198 print v
199 elif opts.position:
200 pos = get_position(footers)
201 print '%s@{#%s}' % (pos[0], pos[1] or '?')
202 elif opts.position_ref:
203 print get_position(footers)[0]
204 elif opts.position_num:
205 pos = get_position(footers)
206 assert pos[1], 'No valid position for commit'
207 print pos[1]
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000208 elif opts.json:
209 with open(opts.json, 'w') as f:
210 json.dump(footers, f)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000211 else:
212 for k in footers.keys():
213 for v in footers[k]:
214 print '%s: %s' % (k, v)
sbc@chromium.org013731e2015-02-26 18:28:43 +0000215 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000216
217
218if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000219 try:
220 sys.exit(main(sys.argv[1:]))
221 except KeyboardInterrupt:
222 sys.stderr.write('interrupted\n')
223 sys.exit(1)