GetCommitInfo.py 1.6 KB

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