Created
October 25, 2022 13:53
-
-
Save exoosh/5d0a015e01c1488e0520d9ca38d063b7 to your computer and use it in GitHub Desktop.
Use Dulwich to retrieve the full commit hash and dirty state of a Git work tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# vim: set autoindent smartindent softtabstop=4 tabstop=4 shiftwidth=4 expandtab: | |
import functools | |
import os | |
from contextlib import suppress | |
from dulwich import porcelain | |
from dulwich.errors import NotGitRepository | |
__version__ = "0.1.2" | |
@functools.cache | |
def get_version(repo=None): | |
repo = repo or os.getcwd() | |
with suppress(NotGitRepository): | |
revid = None | |
with porcelain.open_repo_closing(repo) as r: | |
revid = r.head().decode("ascii") | |
status = porcelain.status(repo=repo, untracked_files="no") | |
dirtymark = "+" if status.staged["add"] or status.staged["delete"] or status.staged["modify"] or status.unstaged else "" | |
return f"{__version__}~git:{revid}{dirtymark}" | |
return __version__ | |
if __name__ == "__main__": | |
print(get_version()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Goal here is to "enrich" the hardcoded version number with information from the Git repo and a dirty marker for the work tree.