From 17e0c5039109d57e80b1895b5c820cdcd74d49ae Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Sun, 15 May 2022 02:28:52 +0200 Subject: [PATCH] Construct the git commit message manually Instead of relying on 'status --porcelain'. This way in the future we can avoid committing certain files. --- common/commit.go | 42 +++++++++++++++++++++++++++++++++++------- common/commit_test.go | 2 +- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/common/commit.go b/common/commit.go index 9d77901..e01497d 100644 --- a/common/commit.go +++ b/common/commit.go @@ -6,23 +6,51 @@ import ( "strings" "github.com/ztrue/tracerr" + git "gopkg.in/src-d/go-git.v4" ) func commit(repoPath string) error { - outb, err := GitCommand(repoPath, []string{"status", "--porcelain"}) + repo, err := git.PlainOpenWithOptions(repoPath, &git.PlainOpenOptions{DetectDotGit: true}) + if err != nil { + return tracerr.Wrap(err) + } - if err == nil { - if len(outb.Bytes()) == 0 { - return nil - } + w, err := repo.Worktree() + if err != nil { + return tracerr.Wrap(err) } - _, err = GitCommand(repoPath, []string{"add", "--all"}) + status, err := w.Status() if err != nil { return tracerr.Wrap(err) } - _, err = GitCommand(repoPath, []string{"commit", "-m", outb.String()}) + hasChanges := false + commitMsg := "" + for filePath, fileStatus := range status { + if fileStatus.Worktree == git.Unmodified && fileStatus.Staging == git.Unmodified { + continue + } + + hasChanges = true + _, err := w.Add(filePath) + if err != nil { + return tracerr.Wrap(err) + } + + if fileStatus.Worktree == git.Untracked && fileStatus.Staging == git.Untracked { + commitMsg += "?? " + } else { + commitMsg += " " + string(fileStatus.Worktree) + " " + } + commitMsg += filePath + "\n" + } + + if !hasChanges { + return nil + } + + _, err = GitCommand(repoPath, []string{"commit", "-m", commitMsg}) if err != nil { return tracerr.Wrap(err) } diff --git a/common/commit_test.go b/common/commit_test.go index e2c2bd4..db411fe 100644 --- a/common/commit_test.go +++ b/common/commit_test.go @@ -84,5 +84,5 @@ func Test_MultipleFileChange(t *testing.T) { err := commit(repoPath) assert.NilError(t, err) - HasHeadCommit(t, repoPath, "7058b6b292ee3d1382670334b5f29570a1117ef1", " M 1.md\n D dirA/2.md\n?? dirB/\n") + HasHeadCommit(t, repoPath, "7058b6b292ee3d1382670334b5f29570a1117ef1", " M 1.md\n D dirA/2.md\n?? dirB/3.md\n") }