gn build: Merge r372706
[llvm-complete.git] / utils / gn / build / write_vcsrevision.py
blob5bdca23e76485c156cd3cbba78464fe98ce9cdd5
1 #!/usr/bin/env python
3 """Gets the current revision and writes it to VCSRevision.h."""
5 from __future__ import print_function
7 import argparse
8 import os
9 import subprocess
10 import sys
13 THIS_DIR = os.path.abspath(os.path.dirname(__file__))
14 LLVM_DIR = os.path.dirname(os.path.dirname(os.path.dirname(THIS_DIR)))
17 def which(program):
18 # distutils.spawn.which() doesn't find .bat files,
19 # https://bugs.python.org/issue2200
20 for path in os.environ["PATH"].split(os.pathsep):
21 candidate = os.path.join(path, program)
22 if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
23 return candidate
24 return None
27 def main():
28 parser = argparse.ArgumentParser(description=__doc__)
29 parser.add_argument('-d', '--depfile',
30 help='if set, writes a depfile that causes this script '
31 'to re-run each time the current revision changes')
32 parser.add_argument('vcs_header', help='path to the output file to write')
33 args = parser.parse_args()
35 if os.path.isdir(os.path.join(LLVM_DIR, '.svn')):
36 print('SVN support not implemented', file=sys.stderr)
37 return 1
38 if os.path.exists(os.path.join(LLVM_DIR, '.git')):
39 print('non-mono-repo git support not implemented', file=sys.stderr)
40 return 1
42 git, use_shell = which('git'), False
43 if not git:
44 git = which('git.exe')
45 if not git:
46 git = which('git.bat')
47 use_shell = True
49 git_dir = subprocess.check_output([git, 'rev-parse', '--git-dir'],
50 cwd=LLVM_DIR, shell=use_shell).decode().strip()
51 if not os.path.isdir(git_dir):
52 print('.git dir not found at "%s"' % git_dir, file=sys.stderr)
53 return 1
55 rev = subprocess.check_output([git, 'rev-parse', '--short', 'HEAD'],
56 cwd=git_dir, shell=use_shell).decode().strip()
57 # FIXME: add pizzas such as the svn revision read off a git note?
58 vcsrevision_contents = '#define LLVM_REVISION "git-%s"\n' % rev
60 # If the output already exists and is identical to what we'd write,
61 # return to not perturb the existing file's timestamp.
62 if os.path.exists(args.vcs_header) and \
63 open(args.vcs_header).read() == vcsrevision_contents:
64 return 0
66 # http://neugierig.org/software/blog/2014/11/binary-revisions.html
67 if args.depfile:
68 build_dir = os.getcwd()
69 with open(args.depfile, 'w') as depfile:
70 depfile.write('%s: %s\n' % (
71 args.vcs_header,
72 os.path.relpath(os.path.join(git_dir, 'logs', 'HEAD'),
73 build_dir)))
74 open(args.vcs_header, 'w').write(vcsrevision_contents)
77 if __name__ == '__main__':
78 sys.exit(main())