/
displayname.go
64 lines (55 loc) · 1.3 KB
/
displayname.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package resolvers
import (
"fmt"
"path/filepath"
"strings"
)
type displayNameBuilder struct {
tree reversePathTree
separator string
}
func newDisplayNameBuilder(separator string) *displayNameBuilder {
return &displayNameBuilder{
tree: make(reversePathTree),
separator: separator,
}
}
type reversePathTree map[string]reversePathTree
func (b *displayNameBuilder) dump() {
b.tree.dump("")
}
func (tree reversePathTree) dump(prefix string) {
for name, child := range tree {
fmt.Printf("%s%q\n", prefix, name)
child.dump(prefix + " ")
}
}
func (b *displayNameBuilder) pathParts(path string) []string {
return strings.Split(filepath.Clean(path), b.separator)
}
func (b *displayNameBuilder) AddPath(path string) {
parts := b.pathParts(path)
tree := b.tree
for i := len(parts) - 1; i >= 0; i-- {
part := parts[i]
child := tree[part]
if child == nil {
child = make(reversePathTree)
tree[part] = child
}
tree = child
}
}
func (b *displayNameBuilder) GetDisplayName(path string) string {
parts := b.pathParts(path)
tree := b.tree
for i := len(parts) - 1; i >= 0; i-- {
part := parts[i]
child := tree[part]
if len(child) <= 1 {
return strings.Join(parts[i:], b.separator)
}
}
// Fallback, but shouldn't be reachable if builder is properly initialized.
return path
}