git_number.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #!/usr/bin/env vpython3
  2. # Copyright 2013 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. """Usage: %prog [options] [<commitref>]*
  6. If no <commitref>'s are supplied, it defaults to HEAD.
  7. Calculates the generation number for one or more commits in a git repo.
  8. Generation number of a commit C with parents P is defined as:
  9. generation_number(C, []) = 0
  10. generation_number(C, P) = max(map(generation_number, P)) + 1
  11. This number can be used to order commits relative to each other, as long as for
  12. any pair of the commits, one is an ancestor of the other.
  13. Since calculating the generation number of a commit requires walking that
  14. commit's entire history, this script caches all calculated data inside the git
  15. repo that it operates on in the ref 'refs/number/commits'.
  16. """
  17. import binascii
  18. import collections
  19. import logging
  20. import optparse
  21. import os
  22. import struct
  23. import sys
  24. import tempfile
  25. import git_common as git
  26. import subprocess2
  27. CHUNK_FMT = '!20sL'
  28. CHUNK_SIZE = struct.calcsize(CHUNK_FMT)
  29. DIRTY_TREES = collections.defaultdict(int)
  30. REF = 'refs/number/commits'
  31. AUTHOR_NAME = 'git-number'
  32. AUTHOR_EMAIL = 'chrome-infrastructure-team@google.com'
  33. # Number of bytes to use for the prefix on our internal number structure.
  34. # 0 is slow to deserialize. 2 creates way too much bookkeeping overhead (would
  35. # need to reimplement cache data structures to be a bit more sophisticated than
  36. # dicts. 1 seems to be just right.
  37. PREFIX_LEN = 1
  38. # Set this to 'threads' to gather coverage data while testing.
  39. POOL_KIND = 'procs'
  40. def pathlify(hash_prefix):
  41. """Converts a binary object hash prefix into a posix path, one folder per
  42. byte.
  43. >>> pathlify('\xDE\xAD')
  44. 'de/ad'
  45. """
  46. return '/'.join('%02x' % b for b in hash_prefix)
  47. @git.memoize_one(threadsafe=False)
  48. def get_number_tree(prefix_bytes):
  49. """Returns a dictionary of the git-number registry specified by
  50. |prefix_bytes|.
  51. This is in the form of {<full binary ref>: <gen num> ...}
  52. >>> get_number_tree('\x83\xb4')
  53. {'\x83\xb4\xe3\xe4W\xf9J*\x8f/c\x16\xecD\xd1\x04\x8b\xa9qz': 169, ...}
  54. """
  55. ref = '%s:%s' % (REF, pathlify(prefix_bytes))
  56. try:
  57. raw = git.run('cat-file', 'blob', ref, autostrip=False, decode=False)
  58. return dict(
  59. struct.unpack_from(CHUNK_FMT, raw, i * CHUNK_SIZE)
  60. for i in range(len(raw) // CHUNK_SIZE))
  61. except subprocess2.CalledProcessError:
  62. return {}
  63. @git.memoize_one(threadsafe=False)
  64. def get_num(commit_hash):
  65. """Returns the generation number for a commit.
  66. Returns None if the generation number for this commit hasn't been calculated
  67. yet (see load_generation_numbers()).
  68. """
  69. return get_number_tree(commit_hash[:PREFIX_LEN]).get(commit_hash)
  70. def clear_caches(on_disk=False):
  71. """Clears in-process caches for e.g. unit testing."""
  72. get_number_tree.clear()
  73. get_num.clear()
  74. if on_disk:
  75. git.run('update-ref', '-d', REF)
  76. def intern_number_tree(tree):
  77. """Transforms a number tree (in the form returned by |get_number_tree|) into
  78. a git blob.
  79. Returns the git blob id as hex-encoded string.
  80. >>> d = {'\x83\xb4\xe3\xe4W\xf9J*\x8f/c\x16\xecD\xd1\x04\x8b\xa9qz': 169}
  81. >>> intern_number_tree(d)
  82. 'c552317aa95ca8c3f6aae3357a4be299fbcb25ce'
  83. """
  84. with tempfile.TemporaryFile() as f:
  85. for k, v in sorted(tree.items()):
  86. f.write(struct.pack(CHUNK_FMT, k, v))
  87. f.seek(0)
  88. return git.intern_f(f)
  89. def leaf_map_fn(pre_tree):
  90. """Converts a prefix and number tree into a git index line."""
  91. pre, tree = pre_tree
  92. return '100644 blob %s\t%s\0' % (intern_number_tree(tree), pathlify(pre))
  93. def finalize(targets):
  94. """Saves all cache data to the git repository.
  95. After calculating the generation number for |targets|, call finalize() to
  96. save all the work to the git repository.
  97. This in particular saves the trees referred to by DIRTY_TREES.
  98. """
  99. if not DIRTY_TREES:
  100. return
  101. msg = 'git-number Added %s numbers' % sum(DIRTY_TREES.values())
  102. idx = os.path.join(git.run('rev-parse', '--git-dir'), 'number.idx')
  103. env = os.environ.copy()
  104. env['GIT_INDEX_FILE'] = str(idx)
  105. progress_message = 'Finalizing: (%%(count)d/%d)' % len(DIRTY_TREES)
  106. with git.ProgressPrinter(progress_message) as inc:
  107. git.run('read-tree', REF, env=env)
  108. prefixes_trees = ((p, get_number_tree(p)) for p in sorted(DIRTY_TREES))
  109. updater = subprocess2.Popen(
  110. ['git', 'update-index', '-z', '--index-info'],
  111. stdin=subprocess2.PIPE,
  112. env=env)
  113. with git.ScopedPool(kind=POOL_KIND) as leaf_pool:
  114. for item in leaf_pool.imap(leaf_map_fn, prefixes_trees):
  115. updater.stdin.write(item.encode())
  116. inc()
  117. updater.stdin.close()
  118. updater.wait()
  119. assert updater.returncode == 0
  120. tree_id = git.run('write-tree', env=env)
  121. commit_cmd = [
  122. # Git user.name and/or user.email may not be configured, so
  123. # specifying them explicitly. They are not used, but required by
  124. # Git.
  125. '-c',
  126. 'user.name=%s' % AUTHOR_NAME,
  127. '-c',
  128. 'user.email=%s' % AUTHOR_EMAIL,
  129. 'commit-tree',
  130. '-m',
  131. msg,
  132. '-p'
  133. ] + git.hash_multi(REF)
  134. for t in targets:
  135. commit_cmd.extend(['-p', binascii.hexlify(t).decode()])
  136. commit_cmd.append(tree_id)
  137. commit_hash = git.run(*commit_cmd)
  138. git.run('update-ref', REF, commit_hash)
  139. DIRTY_TREES.clear()
  140. def preload_tree(prefix):
  141. """Returns the prefix and parsed tree object for the specified prefix."""
  142. return prefix, get_number_tree(prefix)
  143. def all_prefixes(depth=PREFIX_LEN):
  144. prefixes = [bytes([i]) for i in range(255)]
  145. for x in prefixes:
  146. # This isn't covered because PREFIX_LEN currently == 1
  147. if depth > 1: # pragma: no cover
  148. for r in all_prefixes(depth - 1):
  149. yield x + r
  150. else:
  151. yield x
  152. def load_generation_numbers(targets):
  153. """Populates the caches of get_num and get_number_tree so they contain
  154. the results for |targets|.
  155. Loads cached numbers from disk, and calculates missing numbers if one or
  156. more of |targets| is newer than the cached calculations.
  157. Args:
  158. targets - An iterable of binary-encoded full git commit hashes.
  159. """
  160. # In case they pass us a generator, listify targets.
  161. targets = list(targets)
  162. if all(get_num(t) is not None for t in targets):
  163. return
  164. if git.tree(REF) is None:
  165. empty = git.mktree({})
  166. commit_hash = git.run(
  167. # Git user.name and/or user.email may not be configured, so
  168. # specifying them explicitly. They are not used, but required by
  169. # Git.
  170. '-c',
  171. 'user.name=%s' % AUTHOR_NAME,
  172. '-c',
  173. 'user.email=%s' % AUTHOR_EMAIL,
  174. 'commit-tree',
  175. '-m',
  176. 'Initial commit from git-number',
  177. empty)
  178. git.run('update-ref', REF, commit_hash)
  179. with git.ScopedPool(kind=POOL_KIND) as pool:
  180. preload_iter = pool.imap_unordered(preload_tree, all_prefixes())
  181. rev_list = []
  182. with git.ProgressPrinter('Loading commits: %(count)d') as inc:
  183. # Curiously, buffering the list into memory seems to be the fastest
  184. # approach in python (as opposed to iterating over the lines in the
  185. # stdout as they're produced). GIL strikes again :/
  186. cmd = [
  187. 'rev-list',
  188. '--topo-order',
  189. '--parents',
  190. '--reverse',
  191. '^' + REF,
  192. ] + [binascii.hexlify(target).decode() for target in targets]
  193. for line in git.run(*cmd).splitlines():
  194. tokens = [binascii.unhexlify(token) for token in line.split()]
  195. rev_list.append((tokens[0], tokens[1:]))
  196. inc()
  197. get_number_tree.update(preload_iter)
  198. with git.ProgressPrinter('Counting: %%(count)d/%d' % len(rev_list)) as inc:
  199. for commit_hash, pars in rev_list:
  200. num = max(map(get_num, pars)) + 1 if pars else 0
  201. prefix = commit_hash[:PREFIX_LEN]
  202. get_number_tree(prefix)[commit_hash] = num
  203. DIRTY_TREES[prefix] += 1
  204. get_num.set(commit_hash, num)
  205. inc()
  206. def main(): # pragma: no cover
  207. parser = optparse.OptionParser(usage=sys.modules[__name__].__doc__)
  208. parser.add_option('--no-cache',
  209. action='store_true',
  210. help='Do not actually cache anything we calculate.')
  211. parser.add_option('--reset',
  212. action='store_true',
  213. help='Reset the generation number cache and quit.')
  214. parser.add_option('-v',
  215. '--verbose',
  216. action='count',
  217. default=0,
  218. help='Be verbose. Use more times for more verbosity.')
  219. opts, args = parser.parse_args()
  220. levels = [logging.ERROR, logging.INFO, logging.DEBUG]
  221. logging.basicConfig(level=levels[min(opts.verbose, len(levels) - 1)])
  222. # 'git number' should only be used on bots.
  223. if os.getenv('CHROME_HEADLESS') != '1':
  224. logging.error(
  225. "'git-number' is an infrastructure tool that is only "
  226. "intended to be used internally by bots. Developers should "
  227. "use the 'Cr-Commit-Position' value in the commit's message.")
  228. return 1
  229. if opts.reset:
  230. clear_caches(on_disk=True)
  231. return
  232. try:
  233. targets = git.parse_commitrefs(*(args or ['HEAD']))
  234. except git.BadCommitRefException as e:
  235. parser.error(e)
  236. load_generation_numbers(targets)
  237. if not opts.no_cache:
  238. finalize(targets)
  239. print('\n'.join(map(str, map(get_num, targets))))
  240. return 0
  241. if __name__ == '__main__': # pragma: no cover
  242. try:
  243. sys.exit(main())
  244. except KeyboardInterrupt:
  245. sys.stderr.write('interrupted\n')
  246. sys.exit(1)