Skip to content

Commit 335e38b

Browse files
committed
Don't commit when no changes
1 parent 985d029 commit 335e38b

File tree

2 files changed

+61
-2
lines changed

2 files changed

+61
-2
lines changed

vcs/vcs.go

+25-2
Original file line numberDiff line numberDiff line change
@@ -107,16 +107,39 @@ func (s *syncRepo) CommitFiles(prepFiles func() error, message string, paths ...
107107
return err
108108
}
109109
}
110+
111+
// relativize paths to repo root
110112
rootPath := tree.Filesystem.Root()
111-
for _, path := range paths {
112-
path, err := filepath.Rel(rootPath, path)
113+
for i := range paths {
114+
path, err := filepath.Rel(rootPath, paths[i])
113115
if err != nil {
114116
return err
115117
}
118+
paths[i] = path
119+
}
120+
121+
for _, path := range paths {
116122
if _, err = tree.Add(path); err != nil {
117123
return errors.Wrapf(err, "Failed to add %s to the git index", path)
118124
}
119125
}
126+
127+
repoStatus, err := tree.Status()
128+
if err != nil {
129+
return err
130+
}
131+
shouldCommit := false
132+
for _, path := range paths {
133+
status, ok := repoStatus[path]
134+
if ok && status.Staging != git.Unmodified {
135+
shouldCommit = true
136+
break
137+
}
138+
}
139+
if !shouldCommit {
140+
return nil
141+
}
142+
120143
_, err = tree.Commit(message, &git.CommitOptions{
121144
Author: sageAuthor(),
122145
})

vcs/vcs_test.go

+36
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,39 @@ func TestCommitFiles(t *testing.T) {
8686
require.NoError(t, err)
8787
assert.Equal(t, 2, getCount())
8888
}
89+
90+
func TestCommitNoChanges(t *testing.T) {
91+
cleanup := func() {
92+
require.NoError(t, os.RemoveAll("./testdb"))
93+
}
94+
cleanup()
95+
defer cleanup()
96+
97+
repoInt, err := Open("./testdb")
98+
require.NoError(t, err)
99+
require.IsType(t, &syncRepo{}, repoInt)
100+
repo := repoInt.(*syncRepo)
101+
102+
err = repo.CommitFiles(func() error {
103+
return ioutil.WriteFile("./testdb/some file.txt", []byte("hello world"), 0750)
104+
}, "add some file", "./testdb/some file.txt")
105+
require.NoError(t, err)
106+
107+
getCount := func() int {
108+
count := 0
109+
log, err := repo.repo.Log(&git.LogOptions{})
110+
require.NoError(t, err)
111+
112+
err = log.ForEach(func(*object.Commit) error {
113+
count++
114+
return nil
115+
})
116+
require.NoError(t, err)
117+
return count
118+
}
119+
assert.Equal(t, 1, getCount())
120+
121+
err = repo.CommitFiles(func() error { return nil }, "add same file", "./testdb/some file.txt")
122+
require.NoError(t, err)
123+
assert.Equal(t, 1, getCount(), "no commit should be made for unchanged file")
124+
}

0 commit comments

Comments
 (0)