aboutsummaryrefslogtreecommitdiff
path: root/scripts/buildversion.py
blob: b948134c409a6bf4715fbdc434e823ca4bd7c56f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# Generate version information for a program
#
# Copyright (C) 2015  Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys, os, subprocess, time, socket, optparse

VERSION_FORMAT = """
/* DO NOT EDIT!  This is an autogenerated file.  See scripts/buildversion.py. */
#define BUILD_VERSION "%s"
"""

# Obtain version info from "git" program
def git_version():
    if not os.path.exists('.git'):
        return ""
    params = "git describe --tags --long --dirty".split()
    try:
        ver = subprocess.check_output(params).decode().strip()
    except:
        return ""
    return ver

# Look for version in a ".version" file
def file_version():
    if not os.path.isfile('.version'):
        return ""
    try:
        f = open('.version', 'r')
        ver = f.readline().strip()
        f.close()
    except:
        return ""
    return ver

# Generate an output file with the version information
def write_version(outfile, version):
    sys.stdout.write("Version: %s\n" % (version,))
    f = open(outfile, 'w')
    f.write(VERSION_FORMAT % (version,))
    f.close()

def main():
    usage = "%prog [options] <outputheader.h>"
    opts = optparse.OptionParser(usage)
    opts.add_option("-e", "--extra", dest="extra", default="",
                    help="extra version string to append to version")

    options, args = opts.parse_args()
    if len(args) != 1:
        opts.error("Incorrect arguments")
    outfile = args[0]

    ver = git_version()
    if not ver:
        ver = file_version()
        if not ver:
            ver = "?"
    btime = time.strftime("%Y%m%d_%H%M%S")
    hostname = socket.gethostname()
    ver = "%s-%s-%s%s" % (ver, btime, hostname, options.extra)
    write_version(outfile, ver)

if __name__ == '__main__':
    main()