0
0

lazygit_modify_commit_date.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python3
  2. from logging import NOTSET, basicConfig, debug
  3. from subprocess import check_output
  4. from sys import argv
  5. from re import sub, MULTILINE
  6. def run(args: list[str], env: dict):
  7. return check_output(args, env=env)
  8. if __name__ == "__main__":
  9. basicConfig(level=NOTSET)
  10. debug(f"Called with parameters {argv}")
  11. if argv[1] == "commit":
  12. _, _, form_commit, form_following, form_timestamp = tuple(argv)
  13. if form_following == "following":
  14. commits = (
  15. commit
  16. for commit in check_output(["git", "rev-list", form_commit + "^..HEAD"])
  17. .decode("utf-8")
  18. .split("\n")
  19. if len(commit) > 1
  20. )
  21. else:
  22. commits = [form_commit]
  23. for commit in commits:
  24. previous_data = [
  25. run(["git", "log", "-1", f'--pretty="%{attribute}"', commit], {})
  26. for attribute in ["an", "ae", "cn", "ce"]
  27. ]
  28. author_name, author_email, committer_name, committer_email = tuple(
  29. previous_data
  30. )
  31. env = {
  32. "GIT_SEQUENCE_EDITOR": f"/usr/bin/env python3 {__file__}",
  33. "GIT_COMMITTER_DATE": form_timestamp,
  34. "GIT_AUTHOR_NAME": author_name,
  35. "GIT_AUTHOR_EMAIL": author_email,
  36. "GIT_COMMITTER_NAME": committer_name,
  37. "GIT_COMMITTER_EMAIL": committer_email,
  38. }
  39. run(
  40. [
  41. "git",
  42. "rebase",
  43. "--interactive",
  44. "--autostash",
  45. "--keep-empty",
  46. "--no-autosquash",
  47. "--rebase-merges",
  48. f"{commit}~",
  49. ],
  50. env,
  51. )
  52. run(
  53. [
  54. "git",
  55. "commit",
  56. "--allow-empty",
  57. "--only",
  58. "--no-edit",
  59. "--amend",
  60. "--no-verify",
  61. f'--date="{form_timestamp}"',
  62. ],
  63. env,
  64. )
  65. run(
  66. [
  67. "git",
  68. "rebase",
  69. "--continue",
  70. ],
  71. env,
  72. )
  73. else:
  74. path = argv[-1]
  75. file = open(path, "r")
  76. content = sub("^pick ", "edit ", file.read(), 1, flags=MULTILINE)
  77. file.close()
  78. file = open(path, "w")
  79. file.write(content)
  80. file.close()