X-Git-Url: http://git.scottworley.com/git-cache/blobdiff_plain/bef7ce53ce70499b4f13985cc9d4b64e2d8aace4..4edcbae7ce1ecc1f6f1cea224f8b39da3453fb80:/git_cache.py?ds=sidebyside diff --git a/git_cache.py b/git_cache.py index d1923cd..c848161 100644 --- a/git_cache.py +++ b/git_cache.py @@ -8,9 +8,12 @@ import hashlib import logging import os import subprocess +import sys from typing import Tuple +import backoff + Path = str # eg: "/home/user/.cache/git-cache/v1" Repo = str # eg: "https://github.com/NixOS/nixpkgs.git" Ref = str # eg: "master" or "v1.0.0" @@ -35,6 +38,17 @@ def verify_ancestry(repo: Repo, ref: Ref, rev: Rev) -> None: rev, ref], check=True) +@backoff.on_exception( + backoff.expo, + subprocess.CalledProcessError, + max_time=lambda: int(os.environ.get('BACKOFF_MAX_TIME', '30'))) +def _git_fetch(cachedir: Path, repo: Repo, ref: Ref) -> None: + # We don't use --force here because we want to abort and freak out if forced + # updates are happening. + subprocess.run(['git', '-C', cachedir, 'fetch', repo, + '%s:%s' % (ref, ref)], check=True) + + def fetch(repo: Repo, ref: Ref) -> Tuple[Path, Rev]: cachedir = git_cachedir(repo) if not os.path.exists(cachedir): @@ -42,10 +56,7 @@ def fetch(repo: Repo, ref: Ref) -> Tuple[Path, Rev]: subprocess.run(['git', 'init', '--bare', cachedir], check=True) logging.debug('Fetching ref "%s" from %s', ref, repo) - # We don't use --force here because we want to abort and freak out if forced - # updates are happening. - subprocess.run(['git', '-C', cachedir, 'fetch', repo, - '%s:%s' % (ref, ref)], check=True) + _git_fetch(cachedir, repo, ref) with open(os.path.join(cachedir, 'refs', 'heads', ref)) as rev_file: rev = Rev(rev_file.read(999).strip()) @@ -77,3 +88,16 @@ def ensure_rev_available(repo: Repo, ref: Ref, rev: Rev) -> Path: subprocess.run(['git', '-C', cachedir, 'cat-file', '-e', rev], check=True) return cachedir + + +def _main() -> None: + if len(sys.argv) == 3: + print('{1} {0}'.format(*fetch(Repo(sys.argv[1]), Ref(sys.argv[2])))) + elif len(sys.argv) == 4: + print(ensure_rev_available( + Repo(sys.argv[1]), Ref(sys.argv[2]), Rev(sys.argv[3]))) + else: + usage = '''usage: git-cache repo ref [rev] +example: git-cache https://github.com/NixOS/nixpkgs.git master''' + print(usage, file=sys.stderr) + sys.exit(1)