[#2583] Extra Guarding Around Git Commands

This commit is contained in:
David Sangrey committed 2026-01-27 23:09:45 -05:00
1 parent 2ea4382958
commit 90701d9edb
3 files changed
+38 -62

No files matched your search

+13 -20
View File
@@ -402,26 +402,19 @@ if __name__ == '__main__': # noqa: C901
logger.trace('Truncating plain logfile')
sys.stdout.seek(0)
sys.stdout.truncate()
git_branch = ""
try:
git_cmd = subprocess.Popen('git branch --show-current'.split(),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
out, err = git_cmd.communicate()
git_branch = out.decode().strip()
except Exception:
pass
if (
git_branch == 'develop'
or (
git_branch == '' and '-alpha0' in str(appversion())
)
):
print("You're running in a DEVELOPMENT branch build. You might encounter bugs!")
else:
# Potential Git Repo?
if os.path.exists(".git"):
try:
git_branch = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
stderr=subprocess.DEVNULL,
encoding='utf-8'
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
git_branch = None # type: ignore
if git_branch == "develop" or (git_branch is not None and '-alpha0' in str(appversion())):
print("You're running in a DEVELOPMENT branch build. You might encounter bugs!")
# See EDMCLogging.py docs.
+16 -19
View File
@@ -89,35 +89,32 @@ def git_shorthash_from_head() -> str | None:
:return: str | None: None if we couldn't determine the short hash.
"""
if getattr(sys, 'frozen', False) or not os.path.exists(".git"):
return None
try:
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
["git", "describe", "--always", "--dirty=.DIRTY", "--exclude=*", "--abbrev=7"],
capture_output=True,
text=True,
check=True,
encoding='utf-8'
)
shorthash = result.stdout.strip()
if not re.fullmatch(r"[0-9a-f]{7,}(\.DIRTY)?", shorthash):
logger.error(f"'{shorthash}' is not a valid git short hash format.")
return None
# Log stderr if git had complaints but still exited 0
if result.stderr:
logger.warning(f"Git stderr: {result.stderr.strip()}")
return shorthash
except (subprocess.CalledProcessError, FileNotFoundError) as e:
logger.info(f"Couldn't run git command for short hash: {e!r}")
logger.info(f"Could not retrieve git hash: {e!r}")
return None
if not re.fullmatch(r"[0-9a-f]{7,}", shorthash):
logger.error(
f"'{shorthash}' doesn't look like a valid git short hash, forcing to None"
)
return None
with contextlib.suppress(Exception):
diff_result = subprocess.run(
["git", "diff", "--stat", "HEAD"], capture_output=True, check=True
)
if diff_result.stdout:
shorthash += ".DIRTY"
if diff_result.stderr:
logger.warning(f"Data from git on stderr:\n{diff_result.stderr.decode()}")
return shorthash
def appversion() -> semantic_version.Version:
"""
+9 -23
View File
@@ -26,11 +26,15 @@ class TestGitFunctions:
assert git_shorthash_from_head() == "a1b2c3d"
@patch("subprocess.run")
def test_git_shorthash_dirty(self, mock_run):
mock_run.side_effect = [
MagicMock(stdout="a1b2c3d\n", stderr=None),
MagicMock(stdout=" file.py | 1 +", stderr=None),
]
@patch("os.path.exists")
def test_git_shorthash_dirty(self, mock_exists, mock_run):
mock_exists.return_value = True
# Simulate the single call to git describe --dirty
mock_run.return_value = MagicMock(
stdout="a1b2c3d.DIRTY\n",
stderr="",
returncode=0
)
assert git_shorthash_from_head() == "a1b2c3d.DIRTY"
@patch("subprocess.run")
@@ -44,24 +48,6 @@ class TestAppVersion:
# Reset cached version before each test
config._cached_version = None
@patch.object(sys, "frozen", True, create=True)
@patch("sys.path", ["/app/library.zip"])
def test_appversion_frozen(self):
with patch("builtins.open", mock_open(read_data="frozenhash")):
with patch("pathlib.Path.parent", new_callable=MagicMock) as mock_parent:
# Bypass Path logic complexity
mock_parent.return_value.__truediv__.return_value = MagicMock()
ver = appversion()
# _static_appversion is "6.1.1" in source
assert str(ver) == "6.1.1+frozenhash"
def test_appversion_nobuild(self):
with patch(
"config.appversion", return_value=semantic_version.Version("6.1.1+deadbeef")
):
assert str(appversion_nobuild()) == "6.1.1"
class TestConfigClass: