Skip to content

Commit

Permalink
Construct the git commit message manually
Browse files Browse the repository at this point in the history
Instead of relying on 'status --porcelain'. This way in the future we
can avoid committing certain files.
  • Loading branch information
vHanda committed May 15, 2022
1 parent 2adc0bd commit 17e0c50
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
42 changes: 35 additions & 7 deletions common/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion common/commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

0 comments on commit 17e0c50

Please sign in to comment.