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