git_number.py 9.4 KB

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