7fb5c9907353a536f9137a303942dcf77afc0a22
[mesa.git] / bin / git_sha1_gen.py
1 """
2 Generate the contents of the git_sha1.h file.
3 """
4
5
6 import argparse
7 import os
8 import os.path
9 import subprocess
10 import sys
11
12
13 def get_git_sha1():
14 """Try to get the git SHA1 with git rev-parse."""
15 git_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', '.git')
16 try:
17 git_sha1 = subprocess.check_output([
18 'git',
19 '--git-dir=' + git_dir,
20 'rev-parse',
21 'HEAD',
22 ], stderr=open(os.devnull, 'w')).decode("ascii")
23 except:
24 # don't print anything if it fails
25 git_sha1 = ''
26 return git_sha1
27
28 def 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 parser = argparse.ArgumentParser()
41 parser.add_argument('--output', help='File to write the #define in',
42 required=True)
43 args = parser.parse_args()
44
45 git_sha1 = os.environ.get('MESA_GIT_SHA1_OVERRIDE', get_git_sha1())[:10]
46 if git_sha1:
47 write_if_different('#define MESA_GIT_SHA1 " (git-' + git_sha1 + ')"')
48 else:
49 write_if_different('#define MESA_GIT_SHA1 ""')