utils.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. """Returns date of specific commit given a hash
  2. OR date of first commit result given a command"""
  3. __author__ = "Kristian Berg"
  4. __copyright__ = "Copyright (c) 2018 Axis Communications AB"
  5. __license__ = "MIT"
  6. from datetime import datetime
  7. import subprocess
  8. import re
  9. def datetime_of_commit(path, hashval=None, command=None):
  10. """Returns date of specific commit given a hash
  11. OR date of first commit result given a command"""
  12. # Check that either hash or command parameter has a value
  13. if hashval:
  14. command = ['git', 'show', '--quiet', '--date=iso', hashval]
  15. elif command:
  16. if command[0] != 'git':
  17. raise ValueError('Not a git command')
  18. elif '--date=iso' not in command:
  19. raise ValueError('Command needs to specify --date=iso')
  20. else:
  21. raise ValueError('Either hash or command parameter is needed')
  22. # Get date of commit
  23. res = subprocess.run(command, cwd=path, stdout=subprocess.PIPE)
  24. gitlog = res.stdout.decode('utf-8', errors='ignore')
  25. match = re.search('(?<=\nDate: )[0-9-+: ]+(?=\n)', gitlog).group(0)
  26. date = datetime.strptime(match, '%Y-%m-%d %H:%M:%S %z')
  27. return date