[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 1 | #!/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 | |
| 6 | import argparse |
[email protected] | 456ca7f | 2016-05-23 21:33:28 | [diff] [blame] | 7 | import json |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 8 | import re |
| 9 | import sys |
| 10 | |
| 11 | from collections import defaultdict |
| 12 | |
| 13 | import git_common as git |
| 14 | |
[email protected] | d629fb4 | 2014-10-01 09:40:10 | [diff] [blame] | 15 | |
Andrii Shyshkalov | 80cae42 | 2017-04-26 23:01:42 | [diff] [blame] | 16 | FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): *(.*)$') |
Andrii Shyshkalov | 49fe922 | 2016-12-15 10:05:06 | [diff] [blame] | 17 | CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/\-\.]+)@{#(\d+)}$') |
Aaron Gable | d9a6756 | 2018-01-03 23:56:08 | [diff] [blame] | 18 | FOOTER_KEY_BLACKLIST = set(['http', 'https']) |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 19 | |
[email protected] | d629fb4 | 2014-10-01 09:40:10 | [diff] [blame] | 20 | |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 21 | def normalize_name(header): |
| 22 | return '-'.join([ word.title() for word in header.strip().split('-') ]) |
| 23 | |
| 24 | |
| 25 | def parse_footer(line): |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 26 | """Returns footer's (key, value) if footer is valid, else None.""" |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 27 | match = FOOTER_PATTERN.match(line) |
Aaron Gable | d9a6756 | 2018-01-03 23:56:08 | [diff] [blame] | 28 | if match and match.group(1) not in FOOTER_KEY_BLACKLIST: |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 29 | return (match.group(1), match.group(2)) |
Aaron Gable | d9a6756 | 2018-01-03 23:56:08 | [diff] [blame] | 30 | return None |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 31 | |
| 32 | |
| 33 | def parse_footers(message): |
| 34 | """Parses a git commit message into a multimap of footers.""" |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 35 | _, _, 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 | |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 45 | def matches_footer_key(line, key): |
| 46 | """Returns whether line is a valid footer whose key matches a given one. |
| 47 | |
| 48 | Keys are compared in normalized form. |
| 49 | """ |
| 50 | r = parse_footer(line) |
| 51 | if r is None: |
Andrii Shyshkalov | 1a91c60 | 2017-05-11 12:35:56 | [diff] [blame] | 52 | return False |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 53 | return normalize_name(r[0]) == normalize_name(key) |
| 54 | |
| 55 | |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 56 | def split_footers(message): |
| 57 | """Returns (non_footer_lines, footer_lines, parsed footers). |
| 58 | |
| 59 | Guarantees that: |
Aaron Gable | 4be3187 | 2018-01-04 00:30:46 | [diff] [blame] | 60 | (non_footer_lines + footer_lines) ~= message.splitlines(), with at |
| 61 | most one new newline, if the last paragraph is text followed by footers. |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 62 | parsed_footers is parse_footer applied on each line of footer_lines. |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 63 | There could be fewer parsed_footers than footer lines if some lines in |
| 64 | last paragraph are malformed. |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 65 | """ |
| 66 | message_lines = list(message.splitlines()) |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 67 | footer_lines = [] |
Aaron Gable | 4be3187 | 2018-01-04 00:30:46 | [diff] [blame] | 68 | maybe_footer_lines = [] |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 69 | for line in reversed(message_lines): |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 70 | if line == '' or line.isspace(): |
| 71 | break |
Aaron Gable | 4be3187 | 2018-01-04 00:30:46 | [diff] [blame] | 72 | elif parse_footer(line): |
| 73 | footer_lines.extend(maybe_footer_lines) |
| 74 | maybe_footer_lines = [] |
| 75 | footer_lines.append(line) |
| 76 | else: |
| 77 | # We only want to include malformed lines if they are preceeded by |
| 78 | # well-formed lines. So keep them in holding until we see a well-formed |
| 79 | # line (case above). |
| 80 | maybe_footer_lines.append(line) |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 81 | else: |
| 82 | # The whole description was consisting of footers, |
| 83 | # which means those aren't footers. |
| 84 | footer_lines = [] |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 85 | |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 86 | footer_lines.reverse() |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 87 | footers = filter(None, map(parse_footer, footer_lines)) |
| 88 | if not footers: |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 89 | return message_lines, [], [] |
Aaron Gable | 4be3187 | 2018-01-04 00:30:46 | [diff] [blame] | 90 | if maybe_footer_lines: |
| 91 | # If some malformed lines were left over, add a newline to split them |
| 92 | # from the well-formed ones. |
| 93 | return message_lines[:-len(footer_lines)] + [''], footer_lines, footers |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 94 | return message_lines[:-len(footer_lines)], footer_lines, footers |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 95 | |
| 96 | |
[email protected] | 3c3c034 | 2016-03-04 11:59:28 | [diff] [blame] | 97 | def get_footer_change_id(message): |
| 98 | """Returns a list of Gerrit's ChangeId from given commit message.""" |
| 99 | return parse_footers(message).get(normalize_name('Change-Id'), []) |
| 100 | |
| 101 | |
| 102 | def add_footer_change_id(message, change_id): |
| 103 | """Returns message with Change-ID footer in it. |
| 104 | |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 105 | Assumes that Change-Id is not yet in footers, which is then inserted at |
| 106 | earliest footer line which is after all of these footers: |
| 107 | Bug|Issue|Test|Feature. |
[email protected] | 3c3c034 | 2016-03-04 11:59:28 | [diff] [blame] | 108 | """ |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 109 | assert 'Change-Id' not in parse_footers(message) |
| 110 | return add_footer(message, 'Change-Id', change_id, |
| 111 | after_keys=['Bug', 'Issue', 'Test', 'Feature']) |
| 112 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 15:44:13 | [diff] [blame] | 113 | |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 114 | def add_footer(message, key, value, after_keys=None, before_keys=None): |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 115 | """Returns a message with given footer appended. |
| 116 | |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 117 | If after_keys and before_keys are both None (default), appends footer last. |
| 118 | If after_keys is provided and matches footers already present, inserts footer |
| 119 | as *early* as possible while still appearing after all provided keys, even |
| 120 | if doing so conflicts with before_keys. |
| 121 | If before_keys is provided, inserts footer as late as possible while still |
| 122 | appearing before all provided keys. |
| 123 | |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 124 | For example, given |
| 125 | message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ' |
| 126 | after_keys=['Bug', 'Issue'] |
| 127 | the new footer will be inserted between Bug and Verified-By existing footers. |
| 128 | """ |
| 129 | assert key == normalize_name(key), 'Use normalized key' |
| 130 | new_footer = '%s: %s' % (key, value) |
| 131 | |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 132 | top_lines, footer_lines, _ = split_footers(message) |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 133 | if not footer_lines: |
| 134 | if not top_lines or top_lines[-1] != '': |
| 135 | top_lines.append('') |
| 136 | footer_lines = [new_footer] |
[email protected] | 9fc50db | 2016-03-17 12:38:55 | [diff] [blame] | 137 | else: |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 138 | after_keys = set(map(normalize_name, after_keys or [])) |
| 139 | after_indices = [ |
| 140 | footer_lines.index(x) for x in footer_lines for k in after_keys |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 141 | if matches_footer_key(x, k)] |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 142 | before_keys = set(map(normalize_name, before_keys or [])) |
| 143 | before_indices = [ |
| 144 | footer_lines.index(x) for x in footer_lines for k in before_keys |
Andrii Shyshkalov | 04b51d6 | 2017-05-11 11:21:30 | [diff] [blame] | 145 | if matches_footer_key(x, k)] |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 146 | if after_indices: |
| 147 | # after_keys takes precedence, even if there's a conflict. |
| 148 | insert_idx = max(after_indices) + 1 |
| 149 | elif before_indices: |
| 150 | insert_idx = min(before_indices) |
[email protected] | 3c3c034 | 2016-03-04 11:59:28 | [diff] [blame] | 151 | else: |
Aaron Gable | c06db44 | 2017-04-27 00:29:49 | [diff] [blame] | 152 | insert_idx = len(footer_lines) |
| 153 | footer_lines.insert(insert_idx, new_footer) |
[email protected] | f2aa52b | 2016-06-03 12:58:20 | [diff] [blame] | 154 | return '\n'.join(top_lines + footer_lines) |
[email protected] | 3c3c034 | 2016-03-04 11:59:28 | [diff] [blame] | 155 | |
| 156 | |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 157 | def remove_footer(message, key): |
| 158 | """Returns a message with all instances of given footer removed.""" |
| 159 | key = normalize_name(key) |
| 160 | top_lines, footer_lines, _ = split_footers(message) |
| 161 | if not footer_lines: |
| 162 | return message |
Aaron Gable | b08ba65 | 2017-07-12 22:30:02 | [diff] [blame] | 163 | new_footer_lines = [] |
| 164 | for line in footer_lines: |
| 165 | try: |
| 166 | f = normalize_name(parse_footer(line)[0]) |
| 167 | if f != key: |
| 168 | new_footer_lines.append(line) |
| 169 | except TypeError: |
| 170 | # If the footer doesn't parse (i.e. is malformed), just let it carry over. |
| 171 | new_footer_lines.append(line) |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 172 | return '\n'.join(top_lines + new_footer_lines) |
| 173 | |
| 174 | |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 175 | def get_unique(footers, key): |
| 176 | key = normalize_name(key) |
| 177 | values = footers[key] |
| 178 | assert len(values) <= 1, 'Multiple %s footers' % key |
| 179 | if values: |
| 180 | return values[0] |
| 181 | else: |
| 182 | return None |
| 183 | |
| 184 | |
| 185 | def get_position(footers): |
[email protected] | 74c44f6 | 2014-09-09 22:35:03 | [diff] [blame] | 186 | """Get the commit position from the footers multimap using a heuristic. |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 187 | |
| 188 | Returns: |
| 189 | A tuple of the branch and the position on that branch. For example, |
| 190 | |
| 191 | Cr-Commit-Position: refs/heads/master@{#292272} |
| 192 | |
agable | 814b1ca | 2016-12-21 21:05:59 | [diff] [blame] | 193 | would give the return value ('refs/heads/master', 292272). |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 194 | """ |
| 195 | |
| 196 | position = get_unique(footers, 'Cr-Commit-Position') |
| 197 | if position: |
| 198 | match = CHROME_COMMIT_POSITION_PATTERN.match(position) |
| 199 | assert match, 'Invalid Cr-Commit-Position value: %s' % position |
| 200 | return (match.group(1), match.group(2)) |
| 201 | |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 202 | raise ValueError('Unable to infer commit position from footers') |
| 203 | |
| 204 | |
| 205 | def main(args): |
| 206 | parser = argparse.ArgumentParser( |
| 207 | formatter_class=argparse.ArgumentDefaultsHelpFormatter |
| 208 | ) |
Andrii Shyshkalov | 22a9cf5 | 2017-07-13 12:23:58 | [diff] [blame] | 209 | parser.add_argument('ref', nargs='?', help='Git ref to retrieve footers from.' |
| 210 | ' Omit to parse stdin.') |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 211 | |
| 212 | g = parser.add_mutually_exclusive_group() |
| 213 | g.add_argument('--key', metavar='KEY', |
| 214 | help='Get all values for the given footer name, one per ' |
| 215 | 'line (case insensitive)') |
| 216 | g.add_argument('--position', action='store_true') |
| 217 | g.add_argument('--position-ref', action='store_true') |
| 218 | g.add_argument('--position-num', action='store_true') |
Andrii Shyshkalov | 22a9cf5 | 2017-07-13 12:23:58 | [diff] [blame] | 219 | g.add_argument('--json', help='filename to dump JSON serialized footers to.') |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 220 | |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 221 | opts = parser.parse_args(args) |
| 222 | |
[email protected] | 456ca7f | 2016-05-23 21:33:28 | [diff] [blame] | 223 | if opts.ref: |
| 224 | message = git.run('log', '-1', '--format=%B', opts.ref) |
| 225 | else: |
Andrii Shyshkalov | 22a9cf5 | 2017-07-13 12:23:58 | [diff] [blame] | 226 | message = sys.stdin.read() |
[email protected] | 456ca7f | 2016-05-23 21:33:28 | [diff] [blame] | 227 | |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 228 | footers = parse_footers(message) |
| 229 | |
| 230 | if opts.key: |
| 231 | for v in footers.get(normalize_name(opts.key), []): |
| 232 | print v |
| 233 | elif opts.position: |
| 234 | pos = get_position(footers) |
| 235 | print '%s@{#%s}' % (pos[0], pos[1] or '?') |
| 236 | elif opts.position_ref: |
| 237 | print get_position(footers)[0] |
| 238 | elif opts.position_num: |
| 239 | pos = get_position(footers) |
| 240 | assert pos[1], 'No valid position for commit' |
| 241 | print pos[1] |
[email protected] | 456ca7f | 2016-05-23 21:33:28 | [diff] [blame] | 242 | elif opts.json: |
| 243 | with open(opts.json, 'w') as f: |
| 244 | json.dump(footers, f) |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 245 | else: |
| 246 | for k in footers.keys(): |
| 247 | for v in footers[k]: |
| 248 | print '%s: %s' % (k, v) |
[email protected] | 013731e | 2015-02-26 18:28:43 | [diff] [blame] | 249 | return 0 |
[email protected] | 0b88762 | 2014-09-03 02:31:03 | [diff] [blame] | 250 | |
| 251 | |
| 252 | if __name__ == '__main__': |
[email protected] | 013731e | 2015-02-26 18:28:43 | [diff] [blame] | 253 | try: |
| 254 | sys.exit(main(sys.argv[1:])) |
| 255 | except KeyboardInterrupt: |
| 256 | sys.stderr.write('interrupted\n') |
| 257 | sys.exit(1) |