api.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # Copyright 2013 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import itertools
  5. import re
  6. from recipe_engine import recipe_api
  7. class GitApi(recipe_api.RecipeApi):
  8. _GIT_HASH_RE = re.compile('[0-9a-f]{40}', re.IGNORECASE)
  9. def __init__(self, *args, **kwargs):
  10. super(GitApi, self).__init__(*args, **kwargs)
  11. self.initialized_win_git = False
  12. def __call__(self, *args, **kwargs):
  13. """Return a git command step."""
  14. name = kwargs.pop('name', 'git '+args[0])
  15. infra_step = kwargs.pop('infra_step', True)
  16. if 'cwd' not in kwargs:
  17. kwargs.setdefault('cwd', self.m.path['checkout'])
  18. git_cmd = ['git']
  19. if self.m.platform.is_win:
  20. self.ensure_win_git_tooling()
  21. git_cmd = [self.package_repo_resource('git.bat')]
  22. options = kwargs.pop('git_config_options', {})
  23. for k, v in sorted(options.iteritems()):
  24. git_cmd.extend(['-c', '%s=%s' % (k, v)])
  25. can_fail_build = kwargs.pop('can_fail_build', True)
  26. try:
  27. return self.m.step(name, git_cmd + list(args), infra_step=infra_step,
  28. **kwargs)
  29. except self.m.step.StepFailure as f:
  30. if can_fail_build:
  31. raise
  32. else:
  33. return f.result
  34. def ensure_win_git_tooling(self):
  35. """Ensures that depot_tools/git.bat actually exists."""
  36. if not self.m.platform.is_win or self.initialized_win_git:
  37. return
  38. self.m.step(
  39. 'ensure git tooling on windows',
  40. [self.package_repo_resource('bootstrap', 'win', 'win_tools.bat')],
  41. infra_step=True,
  42. cwd=self.package_repo_resource())
  43. self.initialized_win_git = True
  44. def fetch_tags(self, remote_name=None, **kwargs):
  45. """Fetches all tags from the remote."""
  46. kwargs.setdefault('name', 'git fetch tags')
  47. remote_name = remote_name or 'origin'
  48. return self('fetch', remote_name, '--tags', **kwargs)
  49. def cat_file_at_commit(self, file_path, commit_hash, remote_name=None,
  50. **kwargs):
  51. """Outputs the contents of a file at a given revision."""
  52. self.fetch_tags(remote_name=remote_name, **kwargs)
  53. kwargs.setdefault('name', 'git cat-file %s:%s' % (commit_hash, file_path))
  54. return self('cat-file', 'blob', '%s:%s' % (commit_hash, file_path),
  55. **kwargs)
  56. def count_objects(self, previous_result=None, can_fail_build=False, **kwargs):
  57. """Returns `git count-objects` result as a dict.
  58. Args:
  59. previous_result (dict): the result of previous count_objects call.
  60. If passed, delta is reported in the log and step text.
  61. can_fail_build (bool): if True, may fail the build and/or raise an
  62. exception. Defaults to False.
  63. Returns:
  64. A dict of count-object values, or None if count-object run failed.
  65. """
  66. if previous_result:
  67. assert isinstance(previous_result, dict)
  68. assert all(isinstance(v, long) for v in previous_result.itervalues())
  69. assert 'size' in previous_result
  70. assert 'size-pack' in previous_result
  71. step_result = None
  72. try:
  73. step_result = self(
  74. 'count-objects', '-v', stdout=self.m.raw_io.output(),
  75. can_fail_build=can_fail_build, **kwargs)
  76. if not step_result.stdout:
  77. return None
  78. result = {}
  79. for line in step_result.stdout.splitlines():
  80. name, value = line.split(':', 1)
  81. result[name] = long(value.strip())
  82. def results_to_text(results):
  83. return [' %s: %s' % (k, v) for k, v in results.iteritems()]
  84. step_result.presentation.logs['result'] = results_to_text(result)
  85. if previous_result:
  86. delta = {
  87. key: value - previous_result[key]
  88. for key, value in result.iteritems()
  89. if key in previous_result}
  90. step_result.presentation.logs['delta'] = (
  91. ['before:'] + results_to_text(previous_result) +
  92. ['', 'after:'] + results_to_text(result) +
  93. ['', 'delta:'] + results_to_text(delta)
  94. )
  95. size_delta = (
  96. result['size'] + result['size-pack']
  97. - previous_result['size'] - previous_result['size-pack'])
  98. # size_delta is in KiB.
  99. step_result.presentation.step_text = (
  100. 'size delta: %+.2f MiB' % (size_delta / 1024.0))
  101. return result
  102. except Exception as ex:
  103. if step_result:
  104. step_result.presentation.logs['exception'] = ['%r' % ex]
  105. step_result.presentation.status = self.m.step.WARNING
  106. if can_fail_build:
  107. raise recipe_api.InfraFailure('count-objects failed: %s' % ex)
  108. return None
  109. def checkout(self, url, ref=None, dir_path=None, recursive=False,
  110. submodules=True, submodule_update_force=False,
  111. keep_paths=None, step_suffix=None,
  112. curl_trace_file=None, can_fail_build=True,
  113. set_got_revision=False, remote_name=None,
  114. display_fetch_size=None, file_name=None,
  115. submodule_update_recursive=True):
  116. """Returns an iterable of steps to perform a full git checkout.
  117. Args:
  118. url (str): url of remote repo to use as upstream
  119. ref (str): ref to fetch and check out
  120. dir_path (Path): optional directory to clone into
  121. recursive (bool): whether to recursively fetch submodules or not
  122. submodules (bool): whether to sync and update submodules or not
  123. submodule_update_force (bool): whether to update submodules with --force
  124. keep_paths (iterable of strings): paths to ignore during git-clean;
  125. paths are gitignore-style patterns relative to checkout_path.
  126. step_suffix (str): suffix to add to a each step name
  127. curl_trace_file (Path): if not None, dump GIT_CURL_VERBOSE=1 trace to that
  128. file. Useful for debugging git issue reproducible only on bots. It has
  129. a side effect of all stderr output of 'git fetch' going to that file.
  130. can_fail_build (bool): if False, ignore errors during fetch or checkout.
  131. set_got_revision (bool): if True, resolves HEAD and sets got_revision
  132. property.
  133. remote_name (str): name of the git remote to use
  134. display_fetch_size (bool): if True, run `git count-objects` before and
  135. after fetch and display delta. Adds two more steps. Defaults to False.
  136. file_name (str): optional path to a single file to checkout.
  137. submodule_update_recursive (bool): if True, updates submodules
  138. recursively.
  139. Returns: If the checkout was successful, this returns the commit hash of
  140. the checked-out-repo. Otherwise this returns None.
  141. """
  142. retVal = None
  143. # TODO(robertocn): Break this function and refactor calls to it.
  144. # The problem is that there are way too many unrealated use cases for
  145. # it, and the function's signature is getting unwieldy and its body
  146. # unreadable.
  147. display_fetch_size = display_fetch_size or False
  148. if not dir_path:
  149. dir_path = url.rsplit('/', 1)[-1]
  150. if dir_path.endswith('.git'): # ex: https://host/foobar.git
  151. dir_path = dir_path[:-len('.git')]
  152. # ex: ssh://host:repo/foobar/.git
  153. dir_path = dir_path or dir_path.rsplit('/', 1)[-1]
  154. dir_path = self.m.path['slave_build'].join(dir_path)
  155. if 'checkout' not in self.m.path:
  156. self.m.path['checkout'] = dir_path
  157. git_setup_args = ['--path', dir_path, '--url', url]
  158. if remote_name:
  159. git_setup_args += ['--remote', remote_name]
  160. else:
  161. remote_name = 'origin'
  162. if self.m.platform.is_win:
  163. self.ensure_win_git_tooling()
  164. git_setup_args += [
  165. '--git_cmd_path', self.package_repo_resource('git.bat')]
  166. step_suffix = '' if step_suffix is None else ' (%s)' % step_suffix
  167. self.m.python(
  168. 'git setup%s' % step_suffix,
  169. self.resource('git_setup.py'),
  170. git_setup_args)
  171. # There are five kinds of refs we can be handed:
  172. # 0) None. In this case, we default to properties['branch'].
  173. # 1) A 40-character SHA1 hash.
  174. # 2) A fully-qualifed arbitrary ref, e.g. 'refs/foo/bar/baz'.
  175. # 3) A fully qualified branch name, e.g. 'refs/heads/master'.
  176. # Chop off 'refs/heads' and now it matches case (4).
  177. # 4) A branch name, e.g. 'master'.
  178. # Note that 'FETCH_HEAD' can be many things (and therefore not a valid
  179. # checkout target) if many refs are fetched, but we only explicitly fetch
  180. # one ref here, so this is safe.
  181. fetch_args = []
  182. if not ref: # Case 0
  183. fetch_remote = remote_name
  184. fetch_ref = self.m.properties.get('branch') or 'master'
  185. checkout_ref = 'FETCH_HEAD'
  186. elif self._GIT_HASH_RE.match(ref): # Case 1.
  187. fetch_remote = remote_name
  188. fetch_ref = ''
  189. checkout_ref = ref
  190. elif ref.startswith('refs/heads/'): # Case 3.
  191. fetch_remote = remote_name
  192. fetch_ref = ref[len('refs/heads/'):]
  193. checkout_ref = 'FETCH_HEAD'
  194. else: # Cases 2 and 4.
  195. fetch_remote = remote_name
  196. fetch_ref = ref
  197. checkout_ref = 'FETCH_HEAD'
  198. fetch_args = [x for x in (fetch_remote, fetch_ref) if x]
  199. if recursive:
  200. fetch_args.append('--recurse-submodules')
  201. fetch_env = {}
  202. fetch_stderr = None
  203. if curl_trace_file:
  204. fetch_env['GIT_CURL_VERBOSE'] = '1'
  205. fetch_stderr = self.m.raw_io.output(leak_to=curl_trace_file)
  206. fetch_step_name = 'git fetch%s' % step_suffix
  207. if display_fetch_size:
  208. count_objects_before_fetch = self.count_objects(
  209. name='count-objects before %s' % fetch_step_name,
  210. cwd=dir_path,
  211. step_test_data=lambda: self.m.raw_io.test_api.stream_output(
  212. self.test_api.count_objects_output(1000)))
  213. self('retry', 'fetch', *fetch_args,
  214. cwd=dir_path,
  215. name=fetch_step_name,
  216. env=fetch_env,
  217. stderr=fetch_stderr,
  218. can_fail_build=can_fail_build)
  219. if display_fetch_size:
  220. self.count_objects(
  221. name='count-objects after %s' % fetch_step_name,
  222. cwd=dir_path,
  223. previous_result=count_objects_before_fetch,
  224. step_test_data=lambda: self.m.raw_io.test_api.stream_output(
  225. self.test_api.count_objects_output(2000)))
  226. if file_name:
  227. self('checkout', '-f', checkout_ref, '--', file_name,
  228. cwd=dir_path,
  229. name='git checkout%s' % step_suffix,
  230. can_fail_build=can_fail_build)
  231. else:
  232. self('checkout', '-f', checkout_ref,
  233. cwd=dir_path,
  234. name='git checkout%s' % step_suffix,
  235. can_fail_build=can_fail_build)
  236. rev_parse_step = self('rev-parse', 'HEAD',
  237. cwd=dir_path,
  238. name='read revision',
  239. stdout=self.m.raw_io.output(),
  240. can_fail_build=False,
  241. step_test_data=lambda:
  242. self.m.raw_io.test_api.stream_output('deadbeef'))
  243. if rev_parse_step.presentation.status == 'SUCCESS':
  244. sha = rev_parse_step.stdout.strip()
  245. retVal = sha
  246. rev_parse_step.presentation.step_text = "<br/>checked out %r<br/>" % sha
  247. if set_got_revision:
  248. rev_parse_step.presentation.properties['got_revision'] = sha
  249. clean_args = list(itertools.chain(
  250. *[('-e', path) for path in keep_paths or []]))
  251. self('clean', '-f', '-d', '-x', *clean_args,
  252. name='git clean%s' % step_suffix,
  253. cwd=dir_path,
  254. can_fail_build=can_fail_build)
  255. if submodules:
  256. self('submodule', 'sync',
  257. name='submodule sync%s' % step_suffix,
  258. cwd=dir_path,
  259. can_fail_build=can_fail_build)
  260. submodule_update = ['submodule', 'update', '--init']
  261. if submodule_update_recursive:
  262. submodule_update.append('--recursive')
  263. if submodule_update_force:
  264. submodule_update.append('--force')
  265. self(*submodule_update,
  266. name='submodule update%s' % step_suffix,
  267. cwd=dir_path,
  268. can_fail_build=can_fail_build)
  269. return retVal
  270. def get_timestamp(self, commit='HEAD', test_data=None, **kwargs):
  271. """Find and return the timestamp of the given commit."""
  272. step_test_data = None
  273. if test_data is not None:
  274. step_test_data = lambda: self.m.raw_io.test_api.stream_output(test_data)
  275. return self('show', commit, '--format=%at', '-s',
  276. stdout=self.m.raw_io.output(),
  277. step_test_data=step_test_data).stdout.rstrip()
  278. def rebase(self, name_prefix, branch, dir_path, remote_name=None,
  279. **kwargs):
  280. """Run rebase HEAD onto branch
  281. Args:
  282. name_prefix (str): a prefix used for the step names
  283. branch (str): a branch name or a hash to rebase onto
  284. dir_path (Path): directory to clone into
  285. remote_name (str): the remote name to rebase from if not origin
  286. """
  287. remote_name = remote_name or 'origin'
  288. try:
  289. self('rebase', '%s/master' % remote_name,
  290. name="%s rebase" % name_prefix, cwd=dir_path, **kwargs)
  291. except self.m.step.StepFailure:
  292. self('rebase', '--abort', name='%s rebase abort' % name_prefix,
  293. cwd=dir_path, **kwargs)
  294. raise
  295. def config_get(self, prop_name, **kwargs):
  296. """Returns: (str) The Git config output, or None if no output was generated.
  297. Args:
  298. prop_name: (str) The name of the config property to query.
  299. kwargs: Forwarded to '__call__'.
  300. """
  301. kwargs['name'] = kwargs.get('name', 'git config %s' % (prop_name,))
  302. result = self('config', '--get', prop_name, stdout=self.m.raw_io.output(),
  303. **kwargs)
  304. value = result.stdout
  305. if value:
  306. value = value.strip()
  307. result.presentation.step_text = value
  308. return value
  309. def get_remote_url(self, remote_name=None, **kwargs):
  310. """Returns: (str) The URL of the remote Git repository, or None.
  311. Args:
  312. remote_name: (str) The name of the remote to query, defaults to 'origin'.
  313. kwargs: Forwarded to '__call__'.
  314. """
  315. remote_name = remote_name or 'origin'
  316. return self.config_get('remote.%s.url' % (remote_name,), **kwargs)
  317. def bundle_create(self, bundle_path, rev_list_args=None, **kwargs):
  318. """Run 'git bundle create' on a Git repository.
  319. Args:
  320. bundle_path (Path): The path of the output bundle.
  321. refs (list): The list of refs to include in the bundle. If None, all
  322. refs in the Git checkout will be bundled.
  323. kwargs: Forwarded to '__call__'.
  324. """
  325. if not rev_list_args:
  326. rev_list_args = ['--all']
  327. self('bundle', 'create', bundle_path, *rev_list_args, **kwargs)