Factor out Git commands into the GitRepo class This reduces boilerplate code and improves readability. Change-Id: I3e95263c46633a0e76c1d6c0450ab0e09a5b533a
diff --git a/container-images/fetch-job/tools/fetch-job.py b/container-images/fetch-job/tools/fetch-job.py index 7eda19c..55267d5 100755 --- a/container-images/fetch-job/tools/fetch-job.py +++ b/container-images/fetch-job/tools/fetch-job.py
@@ -35,47 +35,28 @@ return int(value) -def git(git_dir, *args, timeout=None): - cmd = ["git", f"--git-dir={git_dir}"] + list(args) - subprocess.run(cmd, check=True, timeout=timeout) +class GitRepo: + def __init__(self, git_dir): + self.git_dir = git_dir + self.base = ["git", f"--git-dir={git_dir}"] + + def config(self, *args, check=True): + subprocess.run(self.base + ["config"] + list(args), check=check) + + def fetch(self, *args, timeout=None): + subprocess.run(self.base + ["fetch"] + list(args), check=True, timeout=timeout) + + def __str__(self): + return self.git_dir -def configure_remote(git_dir, remote_name, remote_url, refspec): - subprocess.run( - [ - "git", - f"--git-dir={git_dir}", - "config", - f"remote.{remote_name}.url", - remote_url, - ], - check=True, - ) - subprocess.run( - [ - "git", - f"--git-dir={git_dir}", - "config", - "unset", - "--all", - f"remote.{remote_name}.fetch", - ], - # exit code 5 means the key did not exist — that is fine on first run - check=False, - ) +def configure_remote(git_repo, remote_name, remote_url, refspec): + git_repo.config(f"remote.{remote_name}.url", remote_url) + # exit code 5 means the key did not exist — that is fine on first run + git_repo.config("unset", "--all", f"remote.{remote_name}.fetch", check=False) refspecs = refspec if isinstance(refspec, list) else [refspec] for spec in refspecs: - subprocess.run( - [ - "git", - f"--git-dir={git_dir}", - "config", - "--add", - f"remote.{remote_name}.fetch", - spec, - ], - check=True, - ) + git_repo.config("--add", f"remote.{remote_name}.fetch", spec) def process_remote(remote): @@ -90,18 +71,12 @@ remote_name=remote_name ) - remote_url = f"{server_url}/{remote_repo}" - git_dir = f"{GIT_HOME}/{local_repo}.git" + git_repo = GitRepo(f"{GIT_HOME}/{local_repo}.git") + configure_remote(git_repo, remote_name, f"{server_url}/{remote_repo}", refspec) - configure_remote(git_dir, remote_name, remote_url, refspec) - - print(f"Fetching {remote_repo} from {remote_name} into {git_dir}") + print(f"Fetching {remote_repo} from {remote_name} into {git_repo}") try: - subprocess.run( - ["git", f"--git-dir={git_dir}", "fetch", remote_name], - check=True, - timeout=timeout_seconds, - ) + git_repo.fetch(remote_name, timeout=timeout_seconds) except subprocess.TimeoutExpired: print( f"ERROR: fetch of {remote_repo} from {remote_name} timed out "