rev_info.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. import argparse
  3. import datetime
  4. import subprocess
  5. def git_short_rev():
  6. try:
  7. return subprocess.check_output([
  8. 'git',
  9. 'rev-parse',
  10. '--short',
  11. 'HEAD',
  12. ]).decode('utf-8').strip()
  13. except Exception:
  14. raise RuntimeError("Could not read git revision. Make sure you have git installed and you're working with a git clone of the repository.")
  15. def current_date():
  16. return datetime.date.today().strftime('%Y-%m-%d')
  17. def git_date(short=True):
  18. try:
  19. iso = subprocess.check_output([
  20. 'git',
  21. 'log',
  22. '-1',
  23. '--format=%ci',
  24. 'HEAD',
  25. ]).decode('utf-8').strip()
  26. if short:
  27. return iso.split(' ')[0]
  28. else:
  29. return iso
  30. except Exception:
  31. raise RuntimeError("Could not read git commit date. Make sure you have git installed and you're working with a git clone of the repository.")
  32. def git_release_version(search_prefix, fallback=None):
  33. try:
  34. tags = subprocess.check_output([
  35. 'git',
  36. 'tag',
  37. '--points-at',
  38. 'HEAD',
  39. ]).decode('utf-8').splitlines()
  40. for tag in tags:
  41. if tag.startswith(search_prefix):
  42. return tag[len(search_prefix):]
  43. return fallback
  44. except Exception:
  45. raise RuntimeError("Could not read git release tags. Make sure you have git installed and you're working with a git clone of the repository.")
  46. if __name__ == '__main__':
  47. parser = argparse.ArgumentParser()
  48. subparsers = parser.add_subparsers(required=True, dest='option')
  49. parser_git_short_rev = subparsers.add_parser('git_short_rev')
  50. parser_git_date = subparsers.add_parser('git_date')
  51. parser_git_date.add_argument('--short', action='store_true')
  52. parser_git_release_version = subparsers.add_parser('git_release_version')
  53. parser_git_release_version.add_argument('search_prefix')
  54. args = parser.parse_args()
  55. if args.option == 'git_short_rev':
  56. print(git_short_rev())
  57. elif args.option == 'git_date':
  58. print(git_date(short=args.short))
  59. elif args.option == 'git_release_version':
  60. print(git_release_version(args.search_prefix, fallback='v#.#'))
  61. else:
  62. raise RuntimeError('Unexpected option')