Skip to content

Commit 354c605

Browse files
committed
Extract commit hash from git archive and local docker deployment
Signed-off-by: Keshav Priyadarshi <git@keshav.space>
1 parent 1936d9f commit 354c605

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

Dockerfile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,10 @@ COPY setup.cfg setup.py requirements.txt pyproject.toml /app/
2828
RUN pip install . -c requirements.txt
2929

3030
COPY . /app
31+
32+
# Store commit hash for docker deployment from local checkout.
33+
RUN if [ -d ".git" ]; then \
34+
GIT_COMMIT=$(git rev-parse --short HEAD) && \
35+
echo "VULNERABLECODE_GIT_COMMIT=\"$GIT_COMMIT\"" >> /app/vulnerablecode/settings.py; \
36+
rm -rf .git; \
37+
fi

vulnerablecode/__init__.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,36 @@ def get_git_describe_from_local_checkout():
3030
return git.Repo(".").git.describe(tags=True, always=True)
3131

3232

33+
def get_git_commit_from_version_file():
34+
"""
35+
Return the git commit from the ".VERSION" file.
36+
This will only provide a result when the codebase is an extracted git archive.
37+
"""
38+
version_file = ROOT_DIR / ".VERSION"
39+
if not version_file.exists():
40+
return
41+
42+
try:
43+
lines = version_file.read_text().splitlines()
44+
commit_line = lines[1]
45+
if not commit_line.startswith("commit=") or commit_line.startswith("commit=$Format"):
46+
return
47+
return commit_line.replace("commit=", "")
48+
except (UnicodeDecodeError):
49+
return
50+
51+
3352
def get_short_commit():
3453
"""
35-
Return the short commit hash from a Git describe string while removing
36-
any leading "g" character if present.
54+
Return the short commit hash from the .VERSION file or from `git describe`
55+
in a local checkout or docker deployment using a local checkout.
3756
"""
57+
from vulnerablecode import settings
58+
59+
if short_commit := get_git_commit_from_version_file():
60+
return short_commit
61+
if hasattr(settings, "VULNERABLECODE_GIT_COMMIT"):
62+
return settings.VULNERABLECODE_GIT_COMMIT
3863
if git_describe := get_git_describe_from_local_checkout():
3964
short_commit = git_describe.split("-")[-1]
4065
return short_commit.lstrip("g")

0 commit comments

Comments
 (0)