1"""
2Generate the contents of the git_sha1.h file.
3"""
4
5import argparse
6import os
7import os.path
8import subprocess
9import sys
10
11
12def get_git_sha1():
13    """Try to get the git SHA1 with git rev-parse."""
14    git_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', '.git')
15    try:
16        git_sha1 = subprocess.check_output([
17            'git',
18            '--git-dir=' + git_dir,
19            'rev-parse',
20            'HEAD',
21        ], stderr=open(os.devnull, 'w')).decode("ascii")
22    except Exception:
23        # don't print anything if it fails
24        git_sha1 = ''
25    return git_sha1
26
27
28def write_if_different(contents):
29    """
30    Avoid touching the output file if it doesn't need modifications
31    Useful to avoid triggering rebuilds when nothing has changed.
32    """
33    if os.path.isfile(args.output):
34        with open(args.output, 'r') as file:
35            if file.read() == contents:
36                return
37    with open(args.output, 'w') as file:
38        file.write(contents)
39
40
41parser = argparse.ArgumentParser()
42parser.add_argument('--output', help='File to write the #define in',
43                    required=True)
44args = parser.parse_args()
45
46git_sha1 = os.environ.get('MESA_GIT_SHA1_OVERRIDE', get_git_sha1())[:10]
47if git_sha1:
48    write_if_different('#define MESA_GIT_SHA1 " (git-' + git_sha1 + ')"')
49else:
50    write_if_different('#define MESA_GIT_SHA1 ""')
51