Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current git hash in a Python script

I would like to include the current git hash in the output of a Python script (as a the version number of the code that generated that output).

How can I access the current git hash in my Python script?

like image 969
Victor Avatar asked Oct 18 '22 06:10

Victor


People also ask

How do I see current commit hash?

# open the git config editor $ git config --global --edit # in the alias section, add ... [alias] lastcommit = rev-parse HEAD ... From here on, use git lastcommit to show the last commit's hash.

How do I get git hash from github?

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master ), or the "Issues" tab to see pull requests containing the commit.

What is git hash?

In its simplest form, git hash-object would take the content you handed to it and merely return the unique key that would be used to store it in your Git database. The -w option then tells the command to not simply return the key, but to write that object to the database.


1 Answers

No need to hack around getting data from the git command yourself. GitPython is a very nice way to do this and a lot of other git stuff. It even has "best effort" support for Windows.

After pip install gitpython you can do

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

Something to consider when using this library. The following is taken from gitpython.readthedocs.io

Leakage of System Resources

GitPython is not suited for long-running processes (like daemons) as it tends to leak system resources. It was written in a time where destructors (as implemented in the __del__ method) still ran deterministically.

In case you still want to use it in such a context, you will want to search the codebase for __del__ implementations and call these yourself when you see fit.

Another way assure proper cleanup of resources is to factor out GitPython into a separate process which can be dropped periodically

like image 285
kqw Avatar answered Oct 20 '22 18:10

kqw