filetime_from_git.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from pelican import signals, contents
  4. from pelican.utils import strftime, set_date_tzinfo
  5. from datetime import datetime
  6. from .git_wrapper import git_wrapper
  7. def datetime_from_timestamp(timestamp, content):
  8. """
  9. Helper function to add timezone information to datetime,
  10. so that datetime is comparable to other datetime objects in recent versions
  11. that now also have timezone information.
  12. """
  13. return set_date_tzinfo(
  14. datetime.fromtimestamp(timestamp),
  15. tz_name=content.settings.get('TIMEZONE', None))
  16. def filetime_from_git(content):
  17. if isinstance(content, contents.Static):
  18. return
  19. git = git_wrapper('.')
  20. tz_name = content.settings.get('TIMEZONE', None)
  21. gittime = content.metadata.get('gittime', 'yes').lower()
  22. gittime = gittime.replace("false", "no").replace("off", "no")
  23. if gittime == "no":
  24. return
  25. # 1. file is not managed by git
  26. # date: fs time
  27. # 2. file is staged, but has no commits
  28. # date: fs time
  29. # 3. file is managed, and clean
  30. # date: first commit time, update: last commit time or None
  31. # 4. file is managed, but dirty
  32. # date: first commit time, update: fs time
  33. path = content.source_path
  34. if git.is_file_managed_by_git(path):
  35. commits = git.get_commits(
  36. path, follow=content.settings.get('GIT_FILETIME_FOLLOW', False))
  37. if len(commits) == 0:
  38. # never commited, but staged
  39. content.date = datetime_from_timestamp(
  40. os.stat(path).st_ctime, content)
  41. else:
  42. # has commited
  43. content.date = git.get_commit_date(
  44. commits[-1], tz_name)
  45. if git.is_file_modified(path):
  46. # file has changed
  47. content.modified = datetime_from_timestamp(
  48. os.stat(path).st_ctime, content)
  49. else:
  50. # file is not changed
  51. if len(commits) > 1:
  52. content.modified = git.get_commit_date(
  53. commits[0], tz_name)
  54. else:
  55. # file is not managed by git
  56. content.date = datetime_from_timestamp(os.stat(path).st_ctime, content)
  57. if not hasattr(content, 'modified'):
  58. content.modified = content.date
  59. if hasattr(content, 'date'):
  60. content.locale_date = strftime(content.date, content.date_format)
  61. if hasattr(content, 'modified'):
  62. content.locale_modified = strftime(
  63. content.modified, content.date_format)
  64. def register():
  65. signals.content_object_init.connect(filetime_from_git)