aboutsummaryrefslogtreecommitdiffstats
path: root/worktree_commit.go
diff options
context:
space:
mode:
Diffstat (limited to 'worktree_commit.go')
-rw-r--r--worktree_commit.go21
1 files changed, 16 insertions, 5 deletions
diff --git a/worktree_commit.go b/worktree_commit.go
index 86320d8..eaa21c3 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) {
@@ -37,14 +44,14 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
return plumbing.ZeroHash, err
}
- t, err := w.getTreeFromCommitHash(head.Hash())
+ t, err := w.r.getTreeFromCommitHash(head.Hash())
if err != nil {
return plumbing.ZeroHash, err
}
treeHash = t.Hash
opts.Parents = []plumbing.Hash{head.Hash()}
- }else {
+ } else {
idx, err := w.r.Storer.Index()
if err != nil {
return plumbing.ZeroHash, err
@@ -55,7 +62,7 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
s: w.r.Storer,
}
- treeHash, err = h.BuildTree(idx)
+ treeHash, err = h.BuildTree(idx, opts)
if err != nil {
return plumbing.ZeroHash, err
}
@@ -162,7 +169,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{}
@@ -252,4 +263,4 @@ func (h *buildTreeHelper) copyTreeToStorageRecursive(parent string, t *object.Tr
return hash, nil
}
return h.s.SetEncodedObject(o)
-}
+} \ No newline at end of file