blob: fe72e18a9f832da4d0b5a774bfd6e1d5c2fee243 [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
51def get_unique(footers, key):
52 key = normalize_name(key)
53 values = footers[key]
54 assert len(values) <= 1, 'Multiple %s footers' % key
55 if values:
56 return values[0]
57 else:
58 return None
59
60
61def get_position(footers):
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000062 """Get the commit position from the footers multimap using a heuristic.
luqui@chromium.org0b887622014-09-03 02:31:03 +000063
64 Returns:
65 A tuple of the branch and the position on that branch. For example,
66
67 Cr-Commit-Position: refs/heads/master@{#292272}
68
69 would give the return value ('refs/heads/master', 292272). If
70 Cr-Commit-Position is not defined, we try to infer the ref and position
71 from git-svn-id. The position number can be None if it was not inferrable.
72 """
73
74 position = get_unique(footers, 'Cr-Commit-Position')
75 if position:
76 match = CHROME_COMMIT_POSITION_PATTERN.match(position)
77 assert match, 'Invalid Cr-Commit-Position value: %s' % position
78 return (match.group(1), match.group(2))
79
80 svn_commit = get_unique(footers, 'git-svn-id')
81 if svn_commit:
82 match = GIT_SVN_ID_PATTERN.match(svn_commit)
83 assert match, 'Invalid git-svn-id value: %s' % svn_commit
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000084 # Assume that any trunk svn revision will match the commit-position
85 # semantics.
iannucci@chromium.org0a17dab2014-09-09 23:07:36 +000086 if re.match('.*/trunk.*$', match.group(1)):
luqui@chromium.org0b887622014-09-03 02:31:03 +000087 return ('refs/heads/master', match.group(2))
iannucci@chromium.org74c44f62014-09-09 22:35:03 +000088
89 # But for now only support faking branch-heads for chrome.
luqui@chromium.org0b887622014-09-03 02:31:03 +000090 branch_match = re.match('.*/chrome/branches/([\w/-]+)/src$', match.group(1))
91 if branch_match:
92 # svn commit numbers do not map to branches.
93 return ('refs/branch-heads/%s' % branch_match.group(1), None)
94
95 raise ValueError('Unable to infer commit position from footers')
96
97
98def main(args):
99 parser = argparse.ArgumentParser(
100 formatter_class=argparse.ArgumentDefaultsHelpFormatter
101 )
102 parser.add_argument('ref')
103
104 g = parser.add_mutually_exclusive_group()
105 g.add_argument('--key', metavar='KEY',
106 help='Get all values for the given footer name, one per '
107 'line (case insensitive)')
108 g.add_argument('--position', action='store_true')
109 g.add_argument('--position-ref', action='store_true')
110 g.add_argument('--position-num', action='store_true')
111
112
113 opts = parser.parse_args(args)
114
115 message = git.run('log', '-1', '--format=%B', opts.ref)
116 footers = parse_footers(message)
117
118 if opts.key:
119 for v in footers.get(normalize_name(opts.key), []):
120 print v
121 elif opts.position:
122 pos = get_position(footers)
123 print '%s@{#%s}' % (pos[0], pos[1] or '?')
124 elif opts.position_ref:
125 print get_position(footers)[0]
126 elif opts.position_num:
127 pos = get_position(footers)
128 assert pos[1], 'No valid position for commit'
129 print pos[1]
130 else:
131 for k in footers.keys():
132 for v in footers[k]:
133 print '%s: %s' % (k, v)
134
135
136if __name__ == '__main__':
137 sys.exit(main(sys.argv[1:]))