blob: 4641f7470f551babbe8edb1938c21676e320f20d [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
7import re
8import sys
9
10from collections import defaultdict
11
12import git_common as git
13
agable@chromium.orgd629fb42014-10-01 09:40:10 +000014
luqui@chromium.org0b887622014-09-03 02:31:03 +000015FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): (.*)$')
16CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/-]+)@{#(\d+)}$')
17GIT_SVN_ID_PATTERN = re.compile('^([^\s@]+)@(\d+)')
18
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):
25 match = FOOTER_PATTERN.match(line)
26 if match:
27 return (match.group(1), match.group(2))
28 else:
29 return None
30
31
32def parse_footers(message):
33 """Parses a git commit message into a multimap of footers."""
34 footer_lines = []
35 for line in reversed(message.splitlines()):
36 if line == '' or line.isspace():
37 break
38 footer_lines.append(line)
39
40 footers = map(parse_footer, footer_lines)
41 if not all(footers):
42 return defaultdict(list)
43
44 footer_map = defaultdict(list)
45 for (k, v) in footers:
46 footer_map[normalize_name(k)].append(v.strip())
47
48 return footer_map
49
50
mmoss@chromium.orgf0e41522015-06-10 19:52:01 +000051def get_footer_svn_id(branch=None):
52 if not branch:
53 branch = git.root()
54 svn_id = None
55 message = git.run('log', '-1', '--format=%B', branch)
56 footers = parse_footers(message)
57 git_svn_id = get_unique(footers, 'git-svn-id')
58 if git_svn_id:
59 match = GIT_SVN_ID_PATTERN.match(git_svn_id)
60 if match:
61 svn_id = match.group(1)
62 return svn_id
63
64
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000065def get_footer_change_id(message):
66 """Returns a list of Gerrit's ChangeId from given commit message."""
67 return parse_footers(message).get(normalize_name('Change-Id'), [])
68
69
70def add_footer_change_id(message, change_id):
71 """Returns message with Change-ID footer in it.
72
73 Assumes that Change-Id is not yet in footers, which is then
74 inserted after any of these footers: Bug|Issue|Test|Feature.
75 """
76 assert 0 == len(get_footer_change_id(message))
77 change_id_line = 'Change-Id: %s' % change_id
78 # This code does the same as parse_footers, but keeps track of line
79 # numbers so that ChangeId is inserted in the right place.
80 lines = message.splitlines()
81 footer_lines = []
82 for line in reversed(lines):
83 if line == '' or line.isspace():
84 break
85 footer_lines.append(line)
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +000086 else:
87 # The whole description was consisting of footers,
88 # which means those aren't footers.
89 footer_lines = []
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000090 # footers order is from end to start of the message.
91 footers = map(parse_footer, footer_lines)
tandrii@chromium.org9fc50db2016-03-17 12:38:55 +000092 if not footers or not all(footers):
tandrii@chromium.org3c3c0342016-03-04 11:59:28 +000093 lines.append('')
94 lines.append(change_id_line)
95 else:
96 after = set(map(normalize_name, ['Bug', 'Issue', 'Test', 'Feature']))
97 for i, (key, _) in enumerate(footers):
98 if normalize_name(key) in after:
99 insert_at = len(lines) - i
100 break
101 else:
102 insert_at = len(lines) - len(footers)
103 lines.insert(insert_at, change_id_line)
104 return '\n'.join(lines)
105
106
luqui@chromium.org0b887622014-09-03 02:31:03 +0000107def get_unique(footers, key):
108 key = normalize_name(key)
109 values = footers[key]
110 assert len(values) <= 1, 'Multiple %s footers' % key
111 if values:
112 return values[0]
113 else:
114 return None
115
116
117def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000118 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000119
120 Returns:
121 A tuple of the branch and the position on that branch. For example,
122
123 Cr-Commit-Position: refs/heads/master@{#292272}
124
125 would give the return value ('refs/heads/master', 292272). If
126 Cr-Commit-Position is not defined, we try to infer the ref and position
127 from git-svn-id. The position number can be None if it was not inferrable.
128 """
129
130 position = get_unique(footers, 'Cr-Commit-Position')
131 if position:
132 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
133 assert match, 'Invalid Cr-Commit-Position value: %s' % position
134 return (match.group(1), match.group(2))
135
136 svn_commit = get_unique(footers, 'git-svn-id')
137 if svn_commit:
138 match = GIT_SVN_ID_PATTERN.match(svn_commit)
139 assert match, 'Invalid git-svn-id value: %s' % svn_commit
hinoka@chromium.org4593f472014-10-13 21:25:43 +0000140 # V8 has different semantics than Chromium.
141 if re.match(r'.*https?://v8\.googlecode\.com/svn/trunk',
142 match.group(1)):
143 return ('refs/heads/candidates', match.group(2))
144 if re.match(r'.*https?://v8\.googlecode\.com/svn/branches/bleeding_edge',
145 match.group(1)):
146 return ('refs/heads/master', match.group(2))
147
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000148 # Assume that any trunk svn revision will match the commit-position
149 # semantics.
iannucci@chromium.org0a17dab2014-09-09 23:07:36 +0000150 if re.match('.*/trunk.*$', match.group(1)):
luqui@chromium.org0b887622014-09-03 02:31:03 +0000151 return ('refs/heads/master', match.group(2))
iannucci@chromium.org74c44f62014-09-09 22:35:03 +0000152
153 # But for now only support faking branch-heads for chrome.
luqui@chromium.org0b887622014-09-03 02:31:03 +0000154 branch_match = re.match('.*/chrome/branches/([\w/-]+)/src$', match.group(1))
155 if branch_match:
156 # svn commit numbers do not map to branches.
157 return ('refs/branch-heads/%s' % branch_match.group(1), None)
158
159 raise ValueError('Unable to infer commit position from footers')
160
161
162def main(args):
163 parser = argparse.ArgumentParser(
164 formatter_class=argparse.ArgumentDefaultsHelpFormatter
165 )
166 parser.add_argument('ref')
167
168 g = parser.add_mutually_exclusive_group()
169 g.add_argument('--key', metavar='KEY',
170 help='Get all values for the given footer name, one per '
171 'line (case insensitive)')
172 g.add_argument('--position', action='store_true')
173 g.add_argument('--position-ref', action='store_true')
174 g.add_argument('--position-num', action='store_true')
175
176
177 opts = parser.parse_args(args)
178
179 message = git.run('log', '-1', '--format=%B', opts.ref)
180 footers = parse_footers(message)
181
182 if opts.key:
183 for v in footers.get(normalize_name(opts.key), []):
184 print v
185 elif opts.position:
186 pos = get_position(footers)
187 print '%s@{#%s}' % (pos[0], pos[1] or '?')
188 elif opts.position_ref:
189 print get_position(footers)[0]
190 elif opts.position_num:
191 pos = get_position(footers)
192 assert pos[1], 'No valid position for commit'
193 print pos[1]
194 else:
195 for k in footers.keys():
196 for v in footers[k]:
197 print '%s: %s' % (k, v)
sbc@chromium.org013731e2015-02-26 18:28:43 +0000198 return 0
luqui@chromium.org0b887622014-09-03 02:31:03 +0000199
200
201if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000202 try:
203 sys.exit(main(sys.argv[1:]))
204 except KeyboardInterrupt:
205 sys.stderr.write('interrupted\n')
206 sys.exit(1)