GetCommitInfo.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. import os
  3. import subprocess
  4. def git_get_commit_hash():
  5. try:
  6. return subprocess.check_output(
  7. ['git', 'rev-parse', '--short=8', 'HEAD']).decode('ascii').strip()
  8. except subprocess.CalledProcessError:
  9. return "00000000"
  10. def git_get_commit_count():
  11. try:
  12. return subprocess.check_output(
  13. ['git', 'rev-list', '--count', 'HEAD']).decode('ascii').strip()
  14. except subprocess.CalledProcessError:
  15. return 0
  16. def compose_commit_namespace(git_count, git_hash):
  17. return ('namespace {{\n'
  18. ' const uint32_t kGitCommitCount = {}u;\n'
  19. ' const char kGitCommitHash[] = "{}";\n'
  20. '}}\n').format(git_count, git_hash)
  21. def update(srcdir, commit_file):
  22. # Read the original commit info
  23. try:
  24. f = open(commit_file)
  25. prev_commit = f.read()
  26. f.close()
  27. except:
  28. prev_commit = ''
  29. prev_cwd = os.getcwd()
  30. os.chdir(srcdir)
  31. cur_commit = compose_commit_namespace(
  32. git_get_commit_count(), git_get_commit_hash())
  33. os.chdir(prev_cwd)
  34. # Update if different: avoid triggering rebuilding unnecessarily
  35. if cur_commit != prev_commit:
  36. with open(commit_file, 'w') as f:
  37. f.write(cur_commit)
  38. def main():
  39. import argparse
  40. parser = argparse.ArgumentParser(
  41. description='Generate file containing Git commit information')
  42. parser.add_argument('srcpath', metavar='<src-dir-path>', type=str,
  43. help='Path to the source code directory')
  44. parser.add_argument('dstpath', metavar='<dst-file-path>', type=str,
  45. help='Path to the generated file')
  46. args = parser.parse_args()
  47. update(args.srcpath, args.dstpath)
  48. if __name__ == '__main__':
  49. main()