aboutsummaryrefslogtreecommitdiffstats
path: root/worktree_commit.go
diff options
context:
space:
mode:
authorPaulo Gomes <pjbgf@linux.com>2022-12-03 16:34:35 +0000
committerPaulo Gomes <pjbgf@linux.com>2022-12-03 16:34:35 +0000
commita513415283c4628259c016587858fe56d7b0fa13 (patch)
treec39b970b1403d10693795ad6d61dd1ea59db4a2d /worktree_commit.go
parent3e07c5030b4e3b2fcbcb461f9f6b23212f978335 (diff)
downloadgo-git-a513415283c4628259c016587858fe56d7b0fa13.tar.gz
Return error instead of creating empty commits
BuildTree now returns an ErrEmptyCommit error, when there are no changes to be committed. This can be opted-out via CommitOptions.AllowEmptyCommits. This is a breaking change which enables applications to detect when empty commits are to be created. Some instances in which this can occur is when the fs (e.g. `billy/osfs`) make changes to the underlying files, causing a conflict between what the previous Git worktree state was, and the current state. Changes to the fs implementations are orthogonal to this, and will be dealt with separately. The new behaviour aligns with the Git CLI, in which empty commits returns the error message: 'nothing to commit, working tree clean'. Signed-off-by: Paulo Gomes <pjbgf@linux.com>
Diffstat (limited to 'worktree_commit.go')
-rw-r--r--worktree_commit.go15
1 files changed, 13 insertions, 2 deletions
diff --git a/worktree_commit.go b/worktree_commit.go
index dc79569..e927721 100644
--- a/worktree_commit.go
+++ b/worktree_commit.go
@@ -2,6 +2,7 @@ package git
import (
"bytes"
+ "errors"
"path"
"sort"
"strings"
@@ -16,6 +17,12 @@ import (
"github.com/go-git/go-billy/v5"
)
+var (
+ // ErrEmptyCommit occurs when a commit is attempted using a clean
+ // working tree, with no changes to be committed.
+ ErrEmptyCommit = errors.New("cannot create empty commit: clean working tree")
+)
+
// Commit stores the current contents of the index in a new commit along with
// a log message from the user describing the changes.
func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error) {
@@ -39,7 +46,7 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
s: w.r.Storer,
}
- tree, err := h.BuildTree(idx)
+ tree, err := h.BuildTree(idx, opts)
if err != nil {
return plumbing.ZeroHash, err
}
@@ -145,7 +152,11 @@ type buildTreeHelper struct {
// BuildTree builds the tree objects and push its to the storer, the hash
// of the root tree is returned.
-func (h *buildTreeHelper) BuildTree(idx *index.Index) (plumbing.Hash, error) {
+func (h *buildTreeHelper) BuildTree(idx *index.Index, opts *CommitOptions) (plumbing.Hash, error) {
+ if len(idx.Entries) == 0 && (opts == nil || !opts.AllowEmptyCommits) {
+ return plumbing.ZeroHash, ErrEmptyCommit
+ }
+
const rootNode = ""
h.trees = map[string]*object.Tree{rootNode: {}}
h.entries = map[string]*object.TreeEntry{}