refactor: move git repo handling to function

- move git repo update logic into a separate function
- add error handling for each step in the update process
- return early if any step in the update process fails
- call the new function in the main loop for each stack

🤖
This commit is contained in:
Sebastian Mark 2023-12-19 23:05:35 +01:00
parent 8388362701
commit 7ca3da52d9

64
dc-ops
View file

@ -40,6 +40,44 @@ def run_subprocess(command: str, workdir: str) -> bool:
return True return True
def update_git_repo(repo: str) -> bool:
"""update repo and check for new commits
Args:
repo (str): path to git repo
Returns:
bool: False if any step fails
"""
# create repo instance if it exists
try:
repo = Repo(stackdir)
except NoSuchPathError:
log.error("directory not found")
return False
# try to fetch latest changes
try:
repo.git.fetch()
except GitCommandError as e:
log.error(str(e))
return False
# check for new commits
if repo.rev_parse("HEAD") == repo.rev_parse(f"origin/{repo.active_branch}"):
log.info("no changes - skipping")
return False
# pull remote changes to local branch
try:
log.info(repo.git.pull())
except GitCommandError as e:
log.error(str(e))
return False
return True
# iterate all stacks # iterate all stacks
for stack in cfg["stacks"]: for stack in cfg["stacks"]:
# skip disabled stacks # skip disabled stacks
@ -50,30 +88,8 @@ for stack in cfg["stacks"]:
stackdir = stack["dir"] stackdir = stack["dir"]
log.info(f"* processing {stackdir}") log.info(f"* processing {stackdir}")
# create repo instance if it exists # update repo and check for new commits
try: if not update_git_repo(stackdir):
repo = Repo(stackdir)
except NoSuchPathError:
log.error("directory not found")
continue
# try to fetch latest changes
try:
repo.git.fetch()
except GitCommandError as e:
log.error(str(e))
continue
# check for new commits
if repo.rev_parse("HEAD") == repo.rev_parse(f"origin/{repo.active_branch}"):
log.info("no changes - skipping")
continue
# pull remote changes to local branch
try:
log.info(repo.git.pull())
except GitCommandError as e:
log.error(str(e))
continue continue
# run pre-command # run pre-command