1#!/usr/bin/env python
2# Copyright 2019 The SwiftShader Authors. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16# Generate commit.h with git commit hash.
17#
18
19import subprocess as sp
20import sys
21import os
22
23usage = """\
24Usage: commit_id.py check                 - check if git is present
25       commit_id.py gen <file_to_write>   - generate commit.h"""
26
27
28def grab_output(command, cwd):
29    return sp.Popen(command, stdout=sp.PIPE, shell=True, cwd=cwd).communicate()[0].strip()
30
31
32if len(sys.argv) < 2:
33    sys.exit(usage)
34
35operation = sys.argv[1]
36cwd = sys.path[0]
37
38if operation == 'check':
39    index_path = os.path.join(cwd, '.git', 'index')
40    if os.path.exists(index_path):
41        print("1")
42    else:
43        print("0")
44    sys.exit(0)
45
46if len(sys.argv) < 3 or operation != 'gen':
47    sys.exit(usage)
48
49output_file = sys.argv[2]
50commit_id_size = 12
51
52commit_id = 'invalid-hash'
53commit_date = 'invalid-date'
54
55try:
56    commit_id = grab_output('git rev-parse --short=%d HEAD' % commit_id_size, cwd)
57    commit_date = grab_output('git show -s --format=%ci HEAD', cwd)
58except:
59    pass
60
61hfile = open(output_file, 'w')
62
63hfile.write('#define SWIFTSHADER_COMMIT_HASH "%s"\n' % commit_id)
64hfile.write('#define SWIFTSHADER_COMMIT_HASH_SIZE %d\n' % commit_id_size)
65hfile.write('#define SWIFTSHADER_COMMIT_DATE "%s"\n' % commit_date)
66hfile.write('#define SWIFTSHADER_VERSION_STRING    \\\n'
67            'MACRO_STRINGIFY(MAJOR_VERSION) \".\"  \\\n'
68            'MACRO_STRINGIFY(MINOR_VERSION) \".\"  \\\n'
69            'MACRO_STRINGIFY(PATCH_VERSION) \".\"  \\\n'
70            'SWIFTSHADER_COMMIT_HASH\n')
71
72hfile.close()
73