Skip to content

Instantly share code, notes, and snippets.

@exoosh
Created October 25, 2022 13:53
Show Gist options
  • Save exoosh/5d0a015e01c1488e0520d9ca38d063b7 to your computer and use it in GitHub Desktop.
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
#!/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())
@exoosh
Copy link
Author

exoosh commented Oct 25, 2022

Goal here is to "enrich" the hardcoded version number with information from the Git repo and a dirty marker for the work tree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment