Skip to content

Commit 7fba141

Browse files
authored
Sort Git Tree Entries Correctly (#2838)
The Git tree entry sort oder is very particular. Tree entries are sorted as if tree entries (directories) had '/' appended to them. Git seems to rely on this order, causing errors if it is not followed.
1 parent 24faa46 commit 7fba141

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

porch/repository/pkg/git/draft.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,10 +215,7 @@ func storeTrees(store storer.EncodedObjectStorer, trees map[string]*object.Tree,
215215

216216
entries := tree.Entries
217217
sort.Slice(entries, func(i, j int) bool {
218-
if entries[i].Mode == entries[j].Mode {
219-
return entries[i].Name < entries[j].Name
220-
}
221-
return entries[i].Mode == filemode.Dir // Directories before files
218+
return entrySortKey(&entries[i]) < entrySortKey(&entries[j])
222219
})
223220

224221
// Store all child trees and get their hashes
@@ -252,6 +249,14 @@ func storeTrees(store storer.EncodedObjectStorer, trees map[string]*object.Tree,
252249
return treeHash, nil
253250
}
254251

252+
// Git sorts tree entries as though directories have '/' appended to them.
253+
func entrySortKey(e *object.TreeEntry) string {
254+
if e.Mode == filemode.Dir {
255+
return e.Name + "/"
256+
}
257+
return e.Name
258+
}
259+
255260
func storeCommit(store storer.EncodedObjectStorer, parent plumbing.Hash, tree plumbing.Hash, change *v1alpha1.Task) (plumbing.Hash, error) {
256261
now := time.Now()
257262
commit := &object.Commit{

0 commit comments

Comments
 (0)