1 # -*- coding: utf-8 -*-
2 # Author: Douglas Creager <dcreager@dcreager.net>
3 # This file is placed into the public domain.
5 # Calculates the current version number. If possible, this is the
6 # output of “git describe”, modified to conform to the versioning
7 # scheme that setuptools uses. If “git describe” returns an error
8 # (most likely because we're in an unpacked copy of a release tarball,
9 # rather than in a git working copy), then we fall back on reading the
10 # contents of the RELEASE-VERSION file.
12 # To use this script, simply import it your setup.py file, and use the
13 # results of get_git_version() as your package version:
15 # from version import *
18 # version=get_git_version(),
24 # This will automatically update the RELEASE-VERSION file, if
25 # necessary. Note that the RELEASE-VERSION file should *not* be
26 # checked into git; please add it to your top-level .gitignore file.
28 # You'll probably want to distribute the RELEASE-VERSION file in your
29 # sdist tarballs; to do this, just create a MANIFEST.in file that
30 # contains the following line:
32 # include RELEASE-VERSION
33 from __future__ import print_function
35 __all__ = ("get_git_version")
37 from subprocess import Popen, PIPE
40 def call_git_describe(abbrev=4):
42 p = Popen(['git', 'describe', '--abbrev=%d' % abbrev],
43 stdout=PIPE, stderr=PIPE)
45 line = p.stdout.readlines()[0]
46 return line.strip().decode('utf-8')
52 def read_release_version():
54 f = open("RELEASE-VERSION", "rt")
57 version = f.readlines()[0]
58 return version.strip()
67 def write_release_version(version):
68 f = open("RELEASE-VERSION", "wt")
69 f.write("%s\n" % version)
73 def get_git_version(abbrev=4):
74 # Read in the version that's currently in RELEASE-VERSION.
76 release_version = read_release_version()
78 # First try to get the current version using “git describe”.
80 version = call_git_describe(abbrev)
82 # If that doesn't work, fall back on the value that's in
86 version = release_version
88 # If we still don't have anything, that's an error.
91 raise ValueError("Cannot find the version number!")
93 # If the current version is different from what's in the
94 # RELEASE-VERSION file, update the file to be current.
96 if version != release_version:
97 write_release_version(version)
99 # Finally, return the current version.
104 if __name__ == "__main__":
105 print(get_git_version())