git_footers.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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
  62. # well-formed 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,
  88. 'Change-Id',
  89. change_id,
  90. after_keys=['Bug', 'Issue', 'Test', 'Feature'])
  91. def add_footer(message, key, value, after_keys=None, before_keys=None):
  92. """Returns a message with given footer appended.
  93. If after_keys and before_keys are both None (default), appends footer last.
  94. If after_keys is provided and matches footers already present, inserts footer
  95. as *early* as possible while still appearing after all provided keys, even
  96. if doing so conflicts with before_keys.
  97. If before_keys is provided, inserts footer as late as possible while still
  98. appearing before all provided keys.
  99. For example, given
  100. message='Header.\n\nAdded: 2016\nBug: 123\nVerified-By: CQ'
  101. after_keys=['Bug', 'Issue']
  102. the new footer will be inserted between Bug and Verified-By existing footers.
  103. """
  104. assert key == normalize_name(key), 'Use normalized key'
  105. new_footer = '%s: %s' % (key, value)
  106. if not FOOTER_PATTERN.match(new_footer):
  107. raise ValueError('Invalid footer %r' % new_footer)
  108. top_lines, footer_lines, _ = split_footers(message)
  109. if not footer_lines:
  110. if not top_lines or top_lines[-1] != '':
  111. top_lines.append('')
  112. footer_lines = [new_footer]
  113. else:
  114. after_keys = set(map(normalize_name, after_keys or []))
  115. after_indices = [
  116. footer_lines.index(x) for x in footer_lines for k in after_keys
  117. if matches_footer_key(x, k)
  118. ]
  119. before_keys = set(map(normalize_name, before_keys or []))
  120. before_indices = [
  121. footer_lines.index(x) for x in footer_lines for k in before_keys
  122. if matches_footer_key(x, k)
  123. ]
  124. if after_indices:
  125. # after_keys takes precedence, even if there's a conflict.
  126. insert_idx = max(after_indices) + 1
  127. elif before_indices:
  128. insert_idx = min(before_indices)
  129. else:
  130. insert_idx = len(footer_lines)
  131. footer_lines.insert(insert_idx, new_footer)
  132. return '\n'.join(top_lines + footer_lines)
  133. def remove_footer(message, key):
  134. """Returns a message with all instances of given footer removed."""
  135. key = normalize_name(key)
  136. top_lines, footer_lines, _ = split_footers(message)
  137. if not footer_lines:
  138. return message
  139. new_footer_lines = []
  140. for line in footer_lines:
  141. try:
  142. f = normalize_name(parse_footer(line)[0])
  143. if f != key:
  144. new_footer_lines.append(line)
  145. except TypeError:
  146. # If the footer doesn't parse (i.e. is malformed), just let it carry
  147. # over.
  148. new_footer_lines.append(line)
  149. return '\n'.join(top_lines + new_footer_lines)
  150. def get_unique(footers, key):
  151. key = normalize_name(key)
  152. values = footers[key]
  153. assert len(values) <= 1, 'Multiple %s footers' % key
  154. if values:
  155. return values[0]
  156. return None
  157. def get_position(footers):
  158. """Get the commit position from the footers multimap using a heuristic.
  159. Returns:
  160. A tuple of the branch and the position on that branch. For example,
  161. Cr-Commit-Position: refs/heads/main@{#292272}
  162. would give the return value ('refs/heads/main', 292272).
  163. """
  164. position = get_unique(footers, 'Cr-Commit-Position')
  165. if position:
  166. match = CHROME_COMMIT_POSITION_PATTERN.match(position)
  167. assert match, 'Invalid Cr-Commit-Position value: %s' % position
  168. return (match.group(1), match.group(2))
  169. raise ValueError('Unable to infer commit position from footers')
  170. def main(args):
  171. parser = argparse.ArgumentParser(
  172. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  173. parser.add_argument('ref',
  174. nargs='?',
  175. help='Git ref to retrieve footers from.'
  176. ' Omit to parse stdin.')
  177. g = parser.add_mutually_exclusive_group()
  178. g.add_argument('--key',
  179. metavar='KEY',
  180. help='Get all values for the given footer name, one per '
  181. 'line (case insensitive)')
  182. g.add_argument('--position', action='store_true')
  183. g.add_argument('--position-ref', action='store_true')
  184. g.add_argument('--position-num', action='store_true')
  185. g.add_argument('--json',
  186. help='filename to dump JSON serialized footers to.')
  187. opts = parser.parse_args(args)
  188. if opts.ref:
  189. message = git.run('log', '-1', '--format=%B', opts.ref)
  190. else:
  191. message = sys.stdin.read()
  192. footers = parse_footers(message)
  193. if opts.key:
  194. for v in footers.get(normalize_name(opts.key), []):
  195. print(v)
  196. elif opts.position:
  197. pos = get_position(footers)
  198. print('%s@{#%s}' % (pos[0], pos[1] or '?'))
  199. elif opts.position_ref:
  200. print(get_position(footers)[0])
  201. elif opts.position_num:
  202. pos = get_position(footers)
  203. assert pos[1], 'No valid position for commit'
  204. print(pos[1])
  205. elif opts.json:
  206. with open(opts.json, 'w') as f:
  207. json.dump(footers, f)
  208. else:
  209. for k in footers.keys():
  210. for v in footers[k]:
  211. print('%s: %s' % (k, v))
  212. return 0
  213. if __name__ == '__main__':
  214. try:
  215. sys.exit(main(sys.argv[1:]))
  216. except KeyboardInterrupt:
  217. sys.stderr.write('interrupted\n')
  218. sys.exit(1)