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
34 __all__ = ("get_git_version")
36 from subprocess import Popen, PIPE
39 def call_git_describe(abbrev=4):
41 p = Popen(['git', 'describe', '--abbrev=%d' % abbrev],
42 stdout=PIPE, stderr=PIPE)
44 line = p.stdout.readlines()[0]
51 def read_release_version():
53 f = open("RELEASE-VERSION", "r")
56 version = f.readlines()[0]
57 return version.strip()
66 def write_release_version(version):
67 f = open("RELEASE-VERSION", "w")
68 f.write("%s\n" % version)
72 def get_git_version(abbrev=4):
73 # Read in the version that's currently in RELEASE-VERSION.
75 release_version = read_release_version()
77 # First try to get the current version using “git describe”.
79 version = call_git_describe(abbrev)
81 # If that doesn't work, fall back on the value that's in
85 version = release_version
87 # If we still don't have anything, that's an error.
90 raise ValueError("Cannot find the version number!")
92 # If the current version is different from what's in the
93 # RELEASE-VERSION file, update the file to be current.
95 if version != release_version:
96 write_release_version(version)
98 # Finally, return the current version.
103 if __name__ == "__main__":
104 print get_git_version()