Skip to content

Commit

Permalink
fix: make the git-info python hook more robust (#957)
Browse files Browse the repository at this point in the history
  • Loading branch information
melund authored Apr 25, 2024
1 parent 9c6cab6 commit 61daf96
Showing 1 changed file with 45 additions and 14 deletions.
59 changes: 45 additions & 14 deletions Body/AAUHuman/BodyModels/GenericBodyModel/git_info.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path
from dataclasses import dataclass
from typing import Tuple
import subprocess


@dataclass
Expand All @@ -13,27 +14,57 @@ class AMSContext:
call_location_file: str


def git_info(context, fpath: str) -> Tuple[str, str]:
"""Get the git head and commit of a file in the repository."""
import subprocess
from pathlib import Path
from typing import Tuple


def git_info(context: tuple, fpath: str) -> Tuple[str, str]:
"""
Get the git information of a repository.
Args:
context (tuple): The context of the function call.
fpath (str): The path to the git repository.
Returns:
Tuple[str, str]: A tuple containing the reference (branch or tag name) and the commit hash.
Raises:
subprocess.CalledProcessError: If the git command fails.
subprocess.TimeoutExpired: If the git command times out.
"""
context = AMSContext(*context)
gitfolder = Path(fpath)
if not gitfolder.is_absolute():
gitfolder = Path(context.call_location_file).parent.joinpath(gitfolder)

head_file = gitfolder / "HEAD"
orig_head_file = gitfolder / "ORIG_HEAD"
fetch_head_file = gitfolder / "FETCH_HEAD"
if not gitfolder.is_dir():
return "unknown", "unknown"

if orig_head_file.is_file():
hashref = orig_head_file.read_text(encoding="utf-8").strip()
elif fetch_head_file.is_file():
hashref = fetch_head_file.read_text(encoding="utf-8").strip().split("\t")[0]
else:
try:
subprocess.run(["git", "--version"], capture_output=True, timeout=1, check=True)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
return "unknown", "unknown"

basecmd = ["git", "-C", f"{gitfolder.absolute()}"]
try:
cmd = basecmd + ["rev-parse", "HEAD"]
hashref = subprocess.check_output(cmd, text=True, timeout=2).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
hashref = "unknown"

if head_file.is_file():
ref = head_file.read_text(encoding="utf-8").strip()
else:
ref = "unknown"
try:
cmd = basecmd + ["symbolic-ref", "-q", "--short", "HEAD"]
branch_name = subprocess.check_output(cmd, text=True, timeout=2).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
branch_name = None

try:
cmd = basecmd + ["describe", "--tags", "--always"]
tag_name = subprocess.check_output(cmd, text=True, timeout=2).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
tag_name = "unknown"

ref = branch_name or tag_name
return ref, hashref

0 comments on commit 61daf96

Please sign in to comment.