git_footers.py 9.2 KB

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