2

Are there any easy ways to grab the git repository (on GitHub) version hash with Python code? I want to use this to handle versioning of 'dev' releases of my software on github.

tMC
  • 18,105
  • 14
  • 62
  • 98
Christopher Dorian
  • 2,163
  • 5
  • 21
  • 25

4 Answers4

9
def git_version():
    from subprocess import Popen, PIPE
    gitproc = Popen(['git', 'rev-parse','HEAD'], stdout = PIPE)
    (stdout, _) = gitproc.communicate()
    return stdout.strip()
deddu
  • 855
  • 12
  • 16
1

Like this ?

import subprocess
ref = subprocess.check_output("""
    git 2>/dev/null show-ref | awk '/refs\/heads\/master/{print $1}'
""", shell=True)
print ref

Adapt it if you have something else than master

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Via python. run the `git` command via `Popen` and parse the output in python. – tMC Oct 10 '12 at 19:27
  • No need to pipe it to awk. Just read `stdout` from the `Popen` object and parse the text in Python. Python is very good as string handling! – tMC Oct 10 '12 at 19:31
  • Sorry, had to go with tMC's answer. check_output is from 2.7, I'de like backwards compatibility for now. – Christopher Dorian Oct 10 '12 at 23:40
1
from subprocess import Popen, PIPE

gitproc = Popen(['git', 'show-ref'], stdout = PIPE)
(stdout, stderr) = gitproc.communicate()

for row in stdout.split('\n'):
    if row.find('HEAD') != -1:
        hash = row.split()[0]
        break

print hash
tMC
  • 18,105
  • 14
  • 62
  • 98
-1

You can also use the GitHub API for this.

Zarkonnen
  • 22,200
  • 14
  • 65
  • 81