1#!/usr/bin/env python3
2# coding: utf-8
3#
4# © 2021 Qualcomm Innovation Center, Inc. All rights reserved.
5#
6# SPDX-License-Identifier: BSD-3-Clause
7
8import argparse
9import subprocess
10import sys
11from datetime import datetime
12
13from genfile import GenFile
14
15
16def main():
17    args = argparse.ArgumentParser()
18
19    args.add_argument("-o", "--output", help="Output file (default: stdout)",
20                      default=None)
21    args.add_argument("-c", dest='commit', help="Use specified GIT revision",
22                      default="HEAD")
23    args.add_argument("-C", dest='path',
24                      help="Run GIT in the specified directory", default=None)
25    args.add_argument("-n", dest='now', action='store_true',
26                      help="Use now as timestamp")
27
28    options = args.parse_args()
29
30    cwd = options.path
31
32    ret = subprocess.run(['git', 'diff', options.commit, '--quiet'],
33                         cwd=cwd, stdout=subprocess.PIPE)
34    dirty = ret.returncode
35
36    ret = subprocess.run(['git', 'rev-parse', '--short', options.commit],
37                         cwd=cwd, stdout=subprocess.PIPE)
38    if ret.returncode:
39        raise Exception('git rev-parse failed\n', ret.stderr)
40
41    rev = ret.stdout.decode("utf-8").strip()
42
43    id = rev + ('-dirty' if dirty else '')
44    if options.now or dirty:
45        utcnow = datetime.utcnow()
46        utcnow = utcnow.replace(microsecond=0)
47        time = utcnow.isoformat(sep=' ')
48        time = time + ' UTC'
49    else:
50        ret = subprocess.run(['git', 'show', '-s', '--pretty=%cd',
51                              '--date=iso-local', options.commit],
52                             cwd=cwd, env={'TZ': 'UTC'},
53                             stdout=subprocess.PIPE)
54        if ret.returncode:
55            raise Exception('git rev-parse failed\n', ret.stderr)
56        time = ret.stdout.decode("utf-8").strip()
57        time = time.replace('+0000', 'UTC')
58
59    out = '// This file is automatically generated.\n'
60    out += '// Do not manually resolve conflicts! Contact ' \
61        'hypervisor.team for assistance.\n'
62    out += '#define HYP_GIT_VERSION {:s}\n'.format(id)
63    out += '#define HYP_BUILD_DATE \"{:s}\"\n'.format(time)
64
65    if options.output:
66        with GenFile(options.output, 'w', encoding='utf-8') as f:
67            f.write(out)
68    else:
69        sys.stdout.write(out)
70
71
72if __name__ == '__main__':
73    sys.exit(main())
74