OLD | NEW |
(Empty) | |
| 1 # Copyright 2016 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 |
| 5 import logging |
| 6 import os |
| 7 import sys |
| 8 |
| 9 from .third_party import subprocess42 |
| 10 |
| 11 |
| 12 class FetchError(Exception): |
| 13 pass |
| 14 |
| 15 |
| 16 class UncleanFilesystemError(FetchError): |
| 17 pass |
| 18 |
| 19 |
| 20 class FetchNotAllowedError(FetchError): |
| 21 pass |
| 22 |
| 23 |
| 24 def _run_git(checkout_dir, *args): |
| 25 if sys.platform.startswith(('win', 'cygwin')): |
| 26 cmd = ['git.bat'] |
| 27 else: |
| 28 cmd = ['git'] |
| 29 |
| 30 if checkout_dir is not None: |
| 31 cmd += ['-C', checkout_dir] |
| 32 cmd += list(args) |
| 33 |
| 34 logging.info('Running: %s', cmd) |
| 35 return subprocess42.check_output(cmd) |
| 36 |
| 37 |
| 38 def ensure_git_checkout(repo, revision, checkout_dir, allow_fetch): |
| 39 """Fetches given |repo| at |revision| to |checkout_dir| using git. |
| 40 |
| 41 Network operations are performed only if |allow_fetch| is True. |
| 42 """ |
| 43 logging.info('Freshening repository %s in %s', repo, checkout_dir) |
| 44 |
| 45 if not os.path.isdir(checkout_dir): |
| 46 if not allow_fetch: |
| 47 raise FetchNotAllowedError( |
| 48 'need to clone %s but fetch not allowed' % repo) |
| 49 _run_git(None, 'clone', '-q', repo, checkout_dir) |
| 50 elif not os.path.isdir(os.path.join(checkout_dir, '.git')): |
| 51 raise UncleanFilesystemError( |
| 52 '%s exists but is not a git repo' % checkout_dir) |
| 53 |
| 54 actual_origin = _run_git(checkout_dir, 'config', 'remote.origin.url').strip() |
| 55 if actual_origin != repo: |
| 56 raise UncleanFilesystemError( |
| 57 ('workdir %r exists but uses a different origin url %r ' |
| 58 'than requested %r') % (checkout_dir, actual_origin, repo)) |
| 59 |
| 60 try: |
| 61 _run_git(checkout_dir, 'rev-parse', '-q', '--verify', |
| 62 '%s^{commit}' % revision) |
| 63 except subprocess42.CalledProcessError: |
| 64 if not allow_fetch: |
| 65 raise FetchNotAllowedError( |
| 66 'need to fetch %s but fetch not allowed' % repo) |
| 67 _run_git(checkout_dir, 'fetch') |
| 68 _run_git(checkout_dir, 'reset', '-q', '--hard', revision) |
OLD | NEW |