blob: fd77c9d25f3f85a71e76357374f618efb24b92ca [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
luqui@chromium.org0b887622014-09-03 02:31:03 +0000130def get_unique(footers, key):
131 key = normalize_name(key)
132 values = footers[key]
133 assert len(values) <= 1, 'Multiple %s footers' % key
134 if values:
135 return values[0]
136 else:
137 return None
138
139
140def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000141 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000142
143 Returns:
144 A tuple of the branch and the position on that branch. For example,
145
146 Cr-Commit-Position: refs/heads/master@{#292272}
147
agable814b1ca2016-12-21 13:05:59 -0800148 would give the return value ('refs/heads/master', 292272).
luqui@chromium.org0b887622014-09-03 02:31:03 +0000149 """
150
151 position = get_unique(footers, 'Cr-Commit-Position')
152 if position:
153 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
154 assert match, 'Invalid Cr-Commit-Position value: %s' % position
155 return (match.group(1), match.group(2))
156
luqui@chromium.org0b887622014-09-03 02:31:03 +0000157 raise ValueError('Unable to infer commit position from footers')
158
159
160def main(args):
161 parser = argparse.ArgumentParser(
162 formatter_class=argparse.ArgumentDefaultsHelpFormatter
163 )
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000164 parser.add_argument('ref', nargs='?', help="Git ref to retrieve footers from."
165 " Omit to parse stdin.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000166
167 g = parser.add_mutually_exclusive_group()
168 g.add_argument('--key', metavar='KEY',
169 help='Get all values for the given footer name, one per '
170 'line (case insensitive)')
171 g.add_argument('--position', action='store_true')
172 g.add_argument('--position-ref', action='store_true')
173 g.add_argument('--position-num', action='store_true')
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000174 g.add_argument('--json', help="filename to dump JSON serialized headers to.")
luqui@chromium.org0b887622014-09-03 02:31:03 +0000175
luqui@chromium.org0b887622014-09-03 02:31:03 +0000176 opts = parser.parse_args(args)
177
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000178 if opts.ref:
179 message = git.run('log', '-1', '--format=%B', opts.ref)
180 else:
181 message = '\n'.join(l for l in sys.stdin)
182
luqui@chromium.org0b887622014-09-03 02:31:03 +0000183 footers = parse_footers(message)
184
185 if opts.key:
186 for v in footers.get(normalize_name(opts.key), []):
187 print v
188 elif opts.position:
189 pos = get_position(footers)
190 print '%s@{#%s}' % (pos[0], pos[1] or '?')
191 elif opts.position_ref:
192 print get_position(footers)[0]
193 elif opts.position_num:
194 pos = get_position(footers)
195 assert pos[1], 'No valid position for commit'
196 print pos[1]
martiniss@chromium.org456ca7f2016-05-23 21:33:28 +0000197 elif opts.json:
198 with open(opts.json, 'w') as f:
199 json.dump(footers, f)
luqui@chromium.org0b887622014-09-03 02:31:03 +0000200 else:
201 for k in footers.keys():
202 for v in footers[k]:
203 print '%s: %s' % (k, v)
sbc@chromium.org013731e2015-02-26 18:28:43 +0000204 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000205
206
207if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000208 try:
209 sys.exit(main(sys.argv[1:]))
210 except KeyboardInterrupt:
211 sys.stderr.write('interrupted\n')
212 sys.exit(1)