feat: identify the running code by source hash

This commit is contained in:
imSp4rky
2026-07-30 16:38:11 -06:00
parent 72b8ab7027
commit c14277e6dc
9 changed files with 134 additions and 83 deletions
+44 -15
View File
@@ -1,24 +1,53 @@
import subprocess
import hashlib
import os
from pathlib import Path
from typing import Callable, Optional
__version__ = "5.3.0"
_PKG = Path(__file__).parent.parent
# Framework code only. Services are user-swappable, so they are not part of the identity.
_CODE_DIRS = ("core", "commands", "utils", "vaults")
def _git_commit() -> str:
root = Path(__file__).parents[2]
if not (root / ".git").exists():
return ""
def _raise(error: OSError) -> None:
raise error
def code_files() -> list[str]:
"""Framework source paths relative to the package root, in a platform-stable order."""
rels = ["__main__.py"]
for name in _CODE_DIRS:
for root, dirs, files in os.walk(_PKG / name, onerror=_raise):
dirs[:] = [d for d in dirs if d != "__pycache__"]
rel = os.path.relpath(root, _PKG)
rels.extend(os.path.join(rel, f).replace(os.sep, "/") for f in files if f.endswith(".py"))
return sorted(rels)
def code_hash(
files: Optional[list[str]] = None,
read: Optional[Callable[[str], bytes]] = None,
) -> str:
"""
md5 of the framework source. Identifies the running code, not the release it claims to be.
Pass `files` and `read` to digest a different byte source, such as blobs from git history
(see tools/resolve_code_hash.py). Returns "" when the source cannot be read.
"""
if read is None:
def read(rel: str) -> bytes:
return (_PKG / rel).read_bytes()
digest = hashlib.md5(usedforsecurity=False)
try:
proc = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
cwd=root,
capture_output=True,
text=True,
timeout=2,
)
except (OSError, subprocess.SubprocessError):
for rel in code_files() if files is None else files:
digest.update(rel.encode())
digest.update(read(rel))
except OSError:
return ""
return proc.stdout.strip() if proc.returncode == 0 else ""
return digest.hexdigest()
__commit__ = _git_commit()
__code_hash__ = code_hash()[:7]
+2 -2
View File
@@ -10,7 +10,7 @@ from rich.padding import Padding
from rich.text import Text
from urllib3.exceptions import InsecureRequestWarning
from unshackle.core import __commit__, __version__
from unshackle.core import __code_hash__, __version__
from unshackle.core.commands import Commands
from unshackle.core.config import config
from unshackle.core.console import ComfyRichHandler, console
@@ -63,7 +63,7 @@ def main(version: bool, debug: bool) -> None:
r" ▀▀▀ ▀▀ █▪ ▀▀▀▀ ▀▀▀ · ▀ ▀ ·▀▀▀ ·▀ ▀.▀▀▀ ▀▀▀ ",
style="ascii.art",
),
f"v [repr.number]{__version__}[/]{f' ({__commit__})' if __commit__ else ''}"
f"v [repr.number]{__version__}[/]{f' ({__code_hash__})' if __code_hash__ else ''}"
f" - © 2025-{datetime.now().year} - github.com/unshackle-dl/unshackle",
),
(1, 11, 1, 10),
+4 -4
View File
@@ -8,7 +8,7 @@ import click
from aiohttp import web
from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
from unshackle.core import __commit__, __version__
from unshackle.core import __code_hash__, __version__
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
from unshackle.core.api.handlers import (
cancel_download_job_handler,
@@ -105,10 +105,10 @@ async def health(request: web.Request) -> web.Response:
version:
type: string
example: "2.0.0"
commit:
code_hash:
type: string
nullable: true
example: "a24c9b9"
example: "1d22a1e"
update_check:
type: object
properties:
@@ -133,7 +133,7 @@ async def health(request: web.Request) -> web.Response:
update_info = {"update_available": None, "current_version": __version__, "latest_version": None}
return web.json_response(
{"status": "ok", "version": __version__, "commit": __commit__ or None, "update_check": update_info}
{"status": "ok", "version": __version__, "code_hash": __code_hash__ or None, "update_check": update_info}
)
+2 -2
View File
@@ -787,7 +787,7 @@ class DebugLogger:
"""Log the start of a new session with environment information."""
import platform
from unshackle.core import __commit__, __version__
from unshackle.core import __code_hash__, __version__
self.log(
level="INFO",
@@ -795,7 +795,7 @@ class DebugLogger:
message="Debug logging session started",
context={
"unshackle_version": __version__,
"unshackle_commit": __commit__ or None,
"unshackle_code_hash": __code_hash__ or None,
"python_version": sys.version,
"platform": platform.platform(),
"platform_system": platform.system(),