blob: 6e8136b35b0f89a2abf9da85b50ed044e5d0664a [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
14FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): (.*)$')
15CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/-]+)@{#(\d+)}$')
16GIT_SVN_ID_PATTERN = re.compile('^([^\s@]+)@(\d+)')
17
18def normalize_name(header):
19 return '-'.join([ word.title() for word in header.strip().split('-') ])
20
21
22def parse_footer(line):
23 match = FOOTER_PATTERN.match(line)
24 if match:
25 return (match.group(1), match.group(2))
26 else:
27 return None
28
29
30def parse_footers(message):
31 """Parses a git commit message into a multimap of footers."""
32 footer_lines = []
33 for line in reversed(message.splitlines()):
34 if line == '' or line.isspace():
35 break
36 footer_lines.append(line)
37
38 footers = map(parse_footer, footer_lines)
39 if not all(footers):
40 return defaultdict(list)
41
42 footer_map = defaultdict(list)
43 for (k, v) in footers:
44 footer_map[normalize_name(k)].append(v.strip())
45
46 return footer_map
47
48
49def get_unique(footers, key):
50 key = normalize_name(key)
51 values = footers[key]
52 assert len(values) <= 1, 'Multiple %s footers' % key
53 if values:
54 return values[0]
55 else:
56 return None
57
58
59def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000060 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +000061
62 Returns:
63 A tuple of the branch and the position on that branch. For example,
64
65 Cr-Commit-Position: refs/heads/master@{#292272}
66
67 would give the return value ('refs/heads/master', 292272). If
68 Cr-Commit-Position is not defined, we try to infer the ref and position
69 from git-svn-id. The position number can be None if it was not inferrable.
70 """
71
72 position = get_unique(footers, 'Cr-Commit-Position')
73 if position:
74 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
75 assert match, 'Invalid Cr-Commit-Position value: %s' % position
76 return (match.group(1), match.group(2))
77
78 svn_commit = get_unique(footers, 'git-svn-id')
79 if svn_commit:
80 match = GIT_SVN_ID_PATTERN.match(svn_commit)
81 assert match, 'Invalid git-svn-id value: %s' % svn_commit
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000082 # Assume that any trunk svn revision will match the commit-position
83 # semantics.
iannucci@chromium.org0a17dab2014-09-09 23:07:36 +000084 if re.match('.*/trunk.*$', match.group(1)):
luqui@chromium.org0b887622014-09-03 02:31:03 +000085 return ('refs/heads/master', match.group(2))
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000086
87 # But for now only support faking branch-heads for chrome.
luqui@chromium.org0b887622014-09-03 02:31:03 +000088 branch_match = re.match('.*/chrome/branches/([\w/-]+)/src$', match.group(1))
89 if branch_match:
90 # svn commit numbers do not map to branches.
91 return ('refs/branch-heads/%s' % branch_match.group(1), None)
92
93 raise ValueError('Unable to infer commit position from footers')
94
95
96def main(args):
97 parser = argparse.ArgumentParser(
98 formatter_class=argparse.ArgumentDefaultsHelpFormatter
99 )
100 parser.add_argument('ref')
101
102 g = parser.add_mutually_exclusive_group()
103 g.add_argument('--key', metavar='KEY',
104 help='Get all values for the given footer name, one per '
105 'line (case insensitive)')
106 g.add_argument('--position', action='store_true')
107 g.add_argument('--position-ref', action='store_true')
108 g.add_argument('--position-num', action='store_true')
109
110
111 opts = parser.parse_args(args)
112
113 message = git.run('log', '-1', '--format=%B', opts.ref)
114 footers = parse_footers(message)
115
116 if opts.key:
117 for v in footers.get(normalize_name(opts.key), []):
118 print v
119 elif opts.position:
120 pos = get_position(footers)
121 print '%s@{#%s}' % (pos[0], pos[1] or '?')
122 elif opts.position_ref:
123 print get_position(footers)[0]
124 elif opts.position_num:
125 pos = get_position(footers)
126 assert pos[1], 'No valid position for commit'
127 print pos[1]
128 else:
129 for k in footers.keys():
130 for v in footers[k]:
131 print '%s: %s' % (k, v)
132
133
134if __name__ == '__main__':
135 sys.exit(main(sys.argv[1:]))