Skip to content

Commit 66592e8

Browse files
committed
git: worktree_commit, Modify checking empty commit. Fixes go-git#723
1 parent 3f77e6f commit 66592e8

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

worktree_commit.go

+19-7
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
3838
}
3939
}
4040

41-
var treeHash plumbing.Hash
42-
4341
if opts.Amend {
4442
head, err := w.r.Head()
4543
if err != nil {
@@ -61,16 +59,34 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
6159
return plumbing.ZeroHash, err
6260
}
6361

62+
// First handle the case of the first commit in the repository being empty.
63+
if len(opts.Parents) == 0 && len(idx.Entries) == 0 && !opts.AllowEmptyCommits {
64+
return plumbing.ZeroHash, ErrEmptyCommit
65+
}
66+
6467
h := &buildTreeHelper{
6568
fs: w.Filesystem,
6669
s: w.r.Storer,
6770
}
6871

69-
treeHash, err = h.BuildTree(idx, opts)
72+
treeHash, err := h.BuildTree(idx, opts)
7073
if err != nil {
7174
return plumbing.ZeroHash, err
7275
}
7376

77+
previousTree := plumbing.ZeroHash
78+
if len(opts.Parents) > 0 {
79+
parentCommit, err := w.r.CommitObject(opts.Parents[0])
80+
if err != nil {
81+
return plumbing.ZeroHash, err
82+
}
83+
previousTree = parentCommit.TreeHash
84+
}
85+
86+
if treeHash == previousTree && !opts.AllowEmptyCommits {
87+
return plumbing.ZeroHash, ErrEmptyCommit
88+
}
89+
7490
commit, err := w.buildCommitObject(msg, opts, treeHash)
7591
if err != nil {
7692
return plumbing.ZeroHash, err
@@ -175,10 +191,6 @@ type buildTreeHelper struct {
175191
// BuildTree builds the tree objects and push its to the storer, the hash
176192
// of the root tree is returned.
177193
func (h *buildTreeHelper) BuildTree(idx *index.Index, opts *CommitOptions) (plumbing.Hash, error) {
178-
if len(idx.Entries) == 0 && (opts == nil || !opts.AllowEmptyCommits) {
179-
return plumbing.ZeroHash, ErrEmptyCommit
180-
}
181-
182194
const rootNode = ""
183195
h.trees = map[string]*object.Tree{rootNode: {}}
184196
h.entries = map[string]*object.TreeEntry{}

0 commit comments

Comments
 (0)