@@ -38,8 +38,6 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
38
38
}
39
39
}
40
40
41
- var treeHash plumbing.Hash
42
-
43
41
if opts .Amend {
44
42
head , err := w .r .Head ()
45
43
if err != nil {
@@ -61,16 +59,34 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
61
59
return plumbing .ZeroHash , err
62
60
}
63
61
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
+
64
67
h := & buildTreeHelper {
65
68
fs : w .Filesystem ,
66
69
s : w .r .Storer ,
67
70
}
68
71
69
- treeHash , err = h .BuildTree (idx , opts )
72
+ treeHash , err : = h .BuildTree (idx , opts )
70
73
if err != nil {
71
74
return plumbing .ZeroHash , err
72
75
}
73
76
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
+
74
90
commit , err := w .buildCommitObject (msg , opts , treeHash )
75
91
if err != nil {
76
92
return plumbing .ZeroHash , err
@@ -175,10 +191,6 @@ type buildTreeHelper struct {
175
191
// BuildTree builds the tree objects and push its to the storer, the hash
176
192
// of the root tree is returned.
177
193
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
-
182
194
const rootNode = ""
183
195
h .trees = map [string ]* object.Tree {rootNode : {}}
184
196
h .entries = map [string ]* object.TreeEntry {}
0 commit comments