-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.go
45 lines (40 loc) · 1.38 KB
/
index.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package testmark
import (
"strings"
)
const HunkPathSeparator = "/"
// BuildDirIndex mutates the Document to set the DirEnt field.
//
// The order of ChildrenList in the DirEnt
// is determined by the order in which things are first seen in the Document's Hunk list.
// The "directories" can be implied,
// e.g. a Hunk with name="foo/bar" will cause the creation of a DirEnt with name "foo".
//
// No concept of path "cleaning" is applied. Paths like "." and ".." are not treated specially.
// A path containing repeated slashes is a fairly deranged thing to do, but also won't be rejected.
func (doc *Document) BuildDirIndex() {
doc.DirEnt = &DirEnt{}
for _, hunk := range doc.DataHunks {
doc.DirEnt.fill(strings.Split(hunk.Name, HunkPathSeparator), 0, hunk.Hunk)
}
}
func (dirent *DirEnt) fill(pathSegs []string, pathIdx int, hunk Hunk) {
if pathIdx >= len(pathSegs) {
dirent.Hunk = &hunk
return
}
if dirent.Children == nil {
dirent.Children = make(map[string]*DirEnt)
}
if next, exists := dirent.Children[pathSegs[pathIdx]]; exists {
next.fill(pathSegs, pathIdx+1, hunk)
return
}
l := len(dirent.ChildrenList)
dirent.ChildrenList = append(dirent.ChildrenList, &DirEnt{
Name: pathSegs[pathIdx],
Path: strings.Join(pathSegs[:pathIdx+1], HunkPathSeparator),
})
dirent.Children[pathSegs[pathIdx]] = dirent.ChildrenList[l]
dirent.ChildrenList[l].fill(pathSegs, pathIdx+1, hunk)
}