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