Search code examples
pythondulwich

How would I go about getting the full commit hash in Dulwich?


I would like to get the behavior of git show -s --format=%H in Dulwich; i.e. getting the full commit hash pointed to by HEAD. However, as it turns out the porcelain.show() function behaves pretty much like git show but doesn't seem to know any additional options like the Git CLI.

I am not surprised, given porcelain.describe() behaves similarly. But what alternative means do I have with Dulwich to see the full commit hash of HEAD?

For the abbreviated - albeit hardcoded to 7 characters (!) - hash I can use the aforementioned porcelain.describe().


Solution

  • By consulting the code for porcelain.describe() we can pull the pieces together.

    1. open_repo_closing offers a nice context manager for the dulwich.repo.BaseRepo class, with contextlib.closing behavior
    2. BaseRepo.head() contains the information as bytes

    A minimal implementation could look like this:

    def get_latest_hash(repo):
        from dulwich.porcelain import open_repo_closing
        with open_repo_closing(repo) as r:
            return r.head().decode("ascii")
    

    Simpler than I initially expected.