101e04c3fSmrg"""
201e04c3fSmrgGenerate the contents of the git_sha1.h file.
301e04c3fSmrg"""
401e04c3fSmrg
501e04c3fSmrgimport argparse
601e04c3fSmrgimport os
701e04c3fSmrgimport os.path
801e04c3fSmrgimport subprocess
901e04c3fSmrgimport sys
1001e04c3fSmrg
1101e04c3fSmrg
1201e04c3fSmrgdef get_git_sha1():
1301e04c3fSmrg    """Try to get the git SHA1 with git rev-parse."""
1401e04c3fSmrg    git_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', '.git')
1501e04c3fSmrg    try:
1601e04c3fSmrg        git_sha1 = subprocess.check_output([
1701e04c3fSmrg            'git',
1801e04c3fSmrg            '--git-dir=' + git_dir,
1901e04c3fSmrg            'rev-parse',
2001e04c3fSmrg            'HEAD',
2101e04c3fSmrg        ], stderr=open(os.devnull, 'w')).decode("ascii")
227ec681f3Smrg    except Exception:
2301e04c3fSmrg        # don't print anything if it fails
2401e04c3fSmrg        git_sha1 = ''
2501e04c3fSmrg    return git_sha1
2601e04c3fSmrg
277ec681f3Smrg
2801e04c3fSmrgdef write_if_different(contents):
2901e04c3fSmrg    """
3001e04c3fSmrg    Avoid touching the output file if it doesn't need modifications
3101e04c3fSmrg    Useful to avoid triggering rebuilds when nothing has changed.
3201e04c3fSmrg    """
3301e04c3fSmrg    if os.path.isfile(args.output):
3401e04c3fSmrg        with open(args.output, 'r') as file:
3501e04c3fSmrg            if file.read() == contents:
3601e04c3fSmrg                return
3701e04c3fSmrg    with open(args.output, 'w') as file:
3801e04c3fSmrg        file.write(contents)
3901e04c3fSmrg
407ec681f3Smrg
4101e04c3fSmrgparser = argparse.ArgumentParser()
4201e04c3fSmrgparser.add_argument('--output', help='File to write the #define in',
4301e04c3fSmrg                    required=True)
4401e04c3fSmrgargs = parser.parse_args()
4501e04c3fSmrg
4601e04c3fSmrggit_sha1 = os.environ.get('MESA_GIT_SHA1_OVERRIDE', get_git_sha1())[:10]
4701e04c3fSmrgif git_sha1:
4801e04c3fSmrg    write_if_different('#define MESA_GIT_SHA1 " (git-' + git_sha1 + ')"')
4901e04c3fSmrgelse:
5001e04c3fSmrg    write_if_different('#define MESA_GIT_SHA1 ""')
51