소스 검색

refactor(lazygit): move custom command logic to Python script

Joe 1 년 전
부모
커밋
5aee2f0244
4개의 변경된 파일118개의 추가작업 그리고 11개의 파일을 삭제
  1. 13 11
      .config/lazygit/config.yml
  2. 1 0
      .scripts/.gitignore
  3. 21 0
      .scripts/lazygit_add_conventional_commit.py
  4. 83 0
      .scripts/lazygit_modify_commit_date.py

+ 13 - 11
.config/lazygit/config.yml

@@ -25,10 +25,7 @@ customCommands:
   - key: "<c-c>"
     context: "files"
     description: "Create a conventional commit"
-    command: |
-      git commit --allow-empty \
-      -m "$(python3 -c "from sys import argv; output = argv[1]; output += ('(' + argv[2].lower().replace(' ', '-') + ')' if len(argv[2]) > 0 else ''); output += ('' if len(argv[3]) <= 0 or argv[3].lower() == 'no' else '!'); output += ': ' + argv[4]; print(output);" "{{.Form.Type}}" "{{.Form.Scope}}" "{{.Form.Breaking}}" "{{.Form.Subject}}" )" \
-      -m "$(python3 -c "from sys import argv; print('BREAKING CHANGE: ' + argv[-1] if len(argv[-1]) > 0 and argv[-1].lower() not in ['no', 'yes'] else '');" "{{.Form.Breaking}}")"
+    command: /usr/bin/env python3 $HOME/.scripts/lazygit_add_conventional_commit.py "{{.Form.Type}}" "{{.Form.Scope}}" "{{.Form.Breaking}}" "{{.Form.Subject}}" "{{.Form.Breaking}}"
     prompts:
       - type: "menu"
         key: "Type"
@@ -106,13 +103,18 @@ customCommands:
   - key: "<c-a>"
     context: "commits"
     description: "Modify author date and commit date"
-    command: |
-      export GIT_SEQUENCE_EDITOR="python3 -c \"from sys import argv; from re import sub, MULTILINE; path = argv[-1]; file = open(path, 'r'); content = sub('^pick ', 'edit ', file.read(), 1, flags=MULTILINE); file.close(); file = open(path, 'w'); file.write(content); file.close();\"";
-      git rebase --interactive --autostash --keep-empty --no-autosquash --rebase-merges {{.SelectedLocalCommit.Sha}}~;
-      export GIT_COMMITTER_DATE="{{.Form.Timestamp}}";
-      git commit --allow-empty --only --no-edit --amend --date="{{.Form.Timestamp}}";
-      git rebase --continue
+    command: /usr/bin/env python3 $HOME/.scripts/lazygit_modify_commit_date.py commit "{{.SelectedLocalCommit.Sha}}" "{{.Form.Commit}}" "{{.Form.Timestamp}}"
     prompts:
+      - type: "menu"
+        title: "Commit"
+        key: "Commit"
+        options:
+          - name: "Selected"
+            description: "The selected commit"
+            value: "selected"
+          - name: "Following"
+            description: "Selected and subsequent commits"
+            value: "following"
       - type: "menuFromCommand"
         title: "Select Timestamp"
         key: "InitialValue"
@@ -129,4 +131,4 @@ customCommands:
       - type: "confirm"
         title: "Confirm"
         body: |
-          Set author and commit dates for commit "{{.SelectedLocalCommit.Name}}" ({{.SelectedLocalCommit.Sha}}) to "{{.Form.Timestamp}}"?'
+          Set author and commit dates for {{.Form.Commit}} commit "{{.SelectedLocalCommit.Name}}" ({{.SelectedLocalCommit.Sha}}) to "{{.Form.Timestamp}}"?'

+ 1 - 0
.scripts/.gitignore

@@ -3,3 +3,4 @@
 !.gitignore
 # ...except for these:
 !**/*.zsh
+!**/*.py

+ 21 - 0
.scripts/lazygit_add_conventional_commit.py

@@ -0,0 +1,21 @@
+#!/usr/bin/env python3
+from logging import NOTSET, basicConfig, debug
+from subprocess import check_output
+from sys import argv
+
+if __name__ == "__main__":
+    basicConfig(level=NOTSET)
+    debug(f"Called with parameters {argv}")
+    _, form_type, form_scope, form_breaking, form_subject, form_breaking = tuple(argv)
+    is_breaking = False if form_breaking.lower() == "no" else True
+    message = form_type
+    message += (
+        "(" + form_scope.lower().replace(" ", "-") + ")"
+        if len(form_subject) > 0
+        else ""
+    )
+    message += "!" if is_breaking else ""
+    message += ": " + form_subject
+    if is_breaking and form_breaking.lower() != "yes":
+        message += "\n\nBREAKING CHANGE: " + form_breaking
+    check_output(["git", "commit", "--allow-empty", "-m", message])

+ 83 - 0
.scripts/lazygit_modify_commit_date.py

@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+from logging import NOTSET, basicConfig, debug
+from subprocess import check_output
+from sys import argv
+from re import sub, MULTILINE
+
+
+def run(args: list[str], env: dict):
+    return check_output(args, env=env)
+
+
+if __name__ == "__main__":
+    basicConfig(level=NOTSET)
+    debug(f"Called with parameters {argv}")
+    if argv[1] == "commit":
+        _, _, form_commit, form_following, form_timestamp = tuple(argv)
+        if form_following == "following":
+            commits = (
+                commit
+                for commit in check_output(["git", "rev-list", form_commit + "^..HEAD"])
+                .decode("utf-8")
+                .split("\n")
+                if len(commit) > 1
+            )
+        else:
+            commits = [form_commit]
+        for commit in commits:
+            previous_data = [
+                run(["git", "log", "-1", f'--pretty="%{attribute}"', commit], {})
+                for attribute in ["an", "ae", "cn", "ce"]
+            ]
+            author_name, author_email, committer_name, committer_email = tuple(
+                previous_data
+            )
+            env = {
+                "GIT_SEQUENCE_EDITOR": f"/usr/bin/env python3 {__file__}",
+                "GIT_COMMITTER_DATE": form_timestamp,
+                "GIT_AUTHOR_NAME": author_name,
+                "GIT_AUTHOR_EMAIL": author_email,
+                "GIT_COMMITTER_NAME": committer_name,
+                "GIT_COMMITTER_EMAIL": committer_email,
+            }
+            run(
+                [
+                    "git",
+                    "rebase",
+                    "--interactive",
+                    "--autostash",
+                    "--keep-empty",
+                    "--no-autosquash",
+                    "--rebase-merges",
+                    f"{commit}~",
+                ],
+                env,
+            )
+            run(
+                [
+                    "git",
+                    "commit",
+                    "--allow-empty",
+                    "--only",
+                    "--no-edit",
+                    "--amend",
+                    f'--date="{form_timestamp}"',
+                ],
+                env,
+            )
+            run(
+                [
+                    "git",
+                    "rebase",
+                    "--continue",
+                ],
+                env,
+            )
+    else:
+        path = argv[-1]
+        file = open(path, "r")
+        content = sub("^pick ", "edit ", file.read(), 1, flags=MULTILINE)
+        file.close()
+        file = open(path, "w")
+        file.write(content)
+        file.close()