0
0

lazygit_modify_commit_date.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. f'--date="{form_timestamp}"',
  61. ],
  62. env,
  63. )
  64. run(
  65. [
  66. "git",
  67. "rebase",
  68. "--continue",
  69. ],
  70. env,
  71. )
  72. else:
  73. path = argv[-1]
  74. file = open(path, "r")
  75. content = sub("^pick ", "edit ", file.read(), 1, flags=MULTILINE)
  76. file.close()
  77. file = open(path, "w")
  78. file.write(content)
  79. file.close()