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