git_footers.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python3
  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. import argparse
  6. import json
  7. import re
  8. import sys
  9. from collections import defaultdict
  10. import git_common as git
  11. FOOTER_PATTERN = re.compile(r'^\s*([\w-]+): *(.*)$')
  12. CHROME_COMMIT_POSITION_PATTERN = re.compile(r'^([\w/\-\.]+)@{#(\d+)}$')
  13. FOOTER_KEY_BLOCKLIST = set(['http', 'https'])
  14. def normalize_name(header):
  15. return '-'.join([ word.title() for word in header.strip().split('-') ])
  16. def parse_footer(line):
  17. """Returns footer's (key, value) if footer is valid, else None."""
  18. match = FOOTER_PATTERN.match(line)
  19. if match and match.group(1) not in FOOTER_KEY_BLOCKLIST:
  20. return (match.group(1), match.group(2))
  21. return None
  22. def parse_footers(message):
  23. """Parses a git commit message into a multimap of footers."""
  24. _, _, parsed_footers = split_footers(message)
  25. footer_map = defaultdict(list)
  26. if parsed_footers:
  27. # Read footers from bottom to top, because latter takes precedense,
  28. # and we want it to be first in the multimap value.
  29. for (k, v) in reversed(parsed_footers):
  30. footer_map[normalize_name(k)].append(v.strip())
  31. return footer_map
  32. def matches_footer_key(line, key):
  33. """Returns whether line is a valid footer whose key matches a given one.
  34. Keys are compared in normalized form.
  35. """
  36. r = parse_footer(line)
  37. if r is None:
  38. return False
  39. return normalize_name(r[0]) == normalize_name(key)
  40. def split_footers(message):
  41. """Returns (non_footer_lines, footer_lines, parsed footers).
  42. Guarantees that:
  43. (non_footer_lines + footer_lines) ~= message.splitlines(), with at
  44. most one new newline, if the last paragraph is text followed by footers.
  45. parsed_footers is parse_footer applied on each line of footer_lines.
  46. There could be fewer parsed_footers than footer lines if some lines in
  47. last paragraph are malformed.
  48. """
  49. message_lines = list(message.rstrip().splitlines())
  50. footer_lines = []
  51. maybe_footer_lines = []
  52. for line in reversed(message_lines):
  53. if line == '' or line.isspace():
  54. break
  55. if parse_footer(line):
  56. footer_lines.extend(maybe_footer_lines)
  57. maybe_footer_lines = []
  58. footer_lines.append(line)
  59. else:
  60. # We only want to include malformed lines if they are preceded by
  61. # well-formed lines. So keep them in holding until we see a well-formed
  62. # line (case above).
  63. maybe_footer_lines.append(line)
  64. else:
  65. # The whole description was consisting of footers,
  66. # which means those aren't footers.
  67. footer_lines = []
  68. footer_lines.reverse()
  69. footers = [footer for footer in map(parse_footer, footer_lines) if footer]
  70. if not footers:
  71. return message_lines, [], []
  72. if maybe_footer_lines:
  73. # If some malformed lines were left over, add a newline to split them
  74. # from the well-formed ones.
  75. return message_lines[:-len(footer_lines)] + [''], footer_lines, footers
  76. return message_lines[:-len(footer_lines)], footer_lines, footers
  77. def get_footer_change_id(message):
  78. """Returns a list of Gerrit's ChangeId from given commit message."""
  79. return parse_footers(message).get(normalize_name('Change-Id'), [])
  80. def add_footer_change_id(message, change_id):
  81. """Returns message with Change-ID footer in it.
  82. Assumes that Change-Id is not yet in footers, which is then inserted at
  83. earliest footer line which is after all of these footers:
  84. Bug|Issue|Test|Feature.
  85. """
  86. assert 'Change-Id' not in parse_footers(message)
  87. return add_footer(message, 'Change-Id', change_id,
  88. after_keys=['Bug', 'Issue', 'Test', 'Feature'])
  89. def add_footer(message, key, value, after_keys=None, before_keys=None):
  90. """Returns a message with given footer appended.
  91. If after_keys and before_keys are both None (default), appends footer last.
  92. If after_keys is provided and matches footers already present, inserts footer
  93. as *early* as possible while still appearing after all provided keys, even
  94. if doing so conflicts with before_keys.
  95. If before_keys is provided, inserts footer as late as possible while still
  96. appearing before all provided keys.
  97. 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. if not FOOTER_PATTERN.match(new_footer):
  105. raise ValueError('Invalid footer %r' % new_footer)
  106. top_lines, footer_lines, _ = split_footers(message)
  107. if not footer_lines:
  108. if not top_lines or top_lines[-1] != '':
  109. top_lines.append('')
  110. footer_lines = [new_footer]
  111. else:
  112. after_keys = set(map(normalize_name, after_keys or []))
  113. after_indices = [
  114. footer_lines.index(x) for x in footer_lines for k in after_keys
  115. if matches_footer_key(x, k)]
  116. before_keys = set(map(normalize_name, before_keys or []))
  117. before_indices = [
  118. footer_lines.index(x) for x in footer_lines for k in before_keys
  119. if matches_footer_key(x, k)]
  120. if after_indices:
  121. # after_keys takes precedence, even if there's a conflict.
  122. insert_idx = max(after_indices) + 1
  123. elif before_indices:
  124. insert_idx = min(before_indices)
  125. else:
  126. insert_idx = len(footer_lines)
  127. footer_lines.insert(insert_idx, new_footer)
  128. return '\n'.join(top_lines + footer_lines)
  129. def remove_footer(message, key):
  130. """Returns a message with all instances of given footer removed."""
  131. key = normalize_name(key)
  132. top_lines, footer_lines, _ = split_footers(message)
  133. if not footer_lines:
  134. return message
  135. new_footer_lines = []
  136. for line in footer_lines:
  137. try:
  138. f = normalize_name(parse_footer(line)[0])
  139. if f != key:
  140. new_footer_lines.append(line)
  141. except TypeError:
  142. # If the footer doesn't parse (i.e. is malformed), just let it carry over.
  143. new_footer_lines.append(line)
  144. return '\n'.join(top_lines + new_footer_lines)
  145. def get_unique(footers, key):
  146. key = normalize_name(key)
  147. values = footers[key]
  148. assert len(values) <= 1, 'Multiple %s footers' % key
  149. if values:
  150. return values[0]
  151. return None
  152. def get_position(footers):
  153. """Get the commit position from the footers multimap using a heuristic.
  154. Returns:
  155. A tuple of the branch and the position on that branch. For example,
  156. Cr-Commit-Position: refs/heads/main@{#292272}
  157. would give the return value ('refs/heads/main', 292272).
  158. """
  159. position = get_unique(footers, 'Cr-Commit-Position')
  160. if position:
  161. match = CHROME_COMMIT_POSITION_PATTERN.match(position)
  162. assert match, 'Invalid Cr-Commit-Position value: %s' % position
  163. return (match.group(1), match.group(2))
  164. raise ValueError('Unable to infer commit position from footers')
  165. def main(args):
  166. parser = argparse.ArgumentParser(
  167. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  168. )
  169. parser.add_argument('ref', nargs='?', help='Git ref to retrieve footers from.'
  170. ' Omit to parse stdin.')
  171. g = parser.add_mutually_exclusive_group()
  172. g.add_argument('--key', metavar='KEY',
  173. help='Get all values for the given footer name, one per '
  174. 'line (case insensitive)')
  175. g.add_argument('--position', action='store_true')
  176. g.add_argument('--position-ref', action='store_true')
  177. g.add_argument('--position-num', action='store_true')
  178. g.add_argument('--json', help='filename to dump JSON serialized footers to.')
  179. opts = parser.parse_args(args)
  180. if opts.ref:
  181. message = git.run('log', '-1', '--format=%B', opts.ref)
  182. else:
  183. message = sys.stdin.read()
  184. footers = parse_footers(message)
  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])
  197. elif opts.json:
  198. with open(opts.json, 'w') as f:
  199. json.dump(footers, f)
  200. else:
  201. for k in footers.keys():
  202. for v in footers[k]:
  203. print('%s: %s' % (k, v))
  204. return 0
  205. if __name__ == '__main__':
  206. try:
  207. sys.exit(main(sys.argv[1:]))
  208. except KeyboardInterrupt:
  209. sys.stderr.write('interrupted\n')
  210. sys.exit(1)