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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
package refstore
import "strings"
type shortenRule struct {
prefix string
suffix string
}
var shortenRules = [...]shortenRule{
{prefix: "", suffix: ""},
{prefix: "refs/", suffix: ""},
{prefix: "refs/tags/", suffix: ""},
{prefix: "refs/heads/", suffix: ""},
{prefix: "refs/remotes/", suffix: ""},
{prefix: "refs/remotes/", suffix: "/HEAD"},
}
func (rule shortenRule) match(name string) (string, bool) {
if !strings.HasPrefix(name, rule.prefix) {
return "", false
}
if !strings.HasSuffix(name, rule.suffix) {
return "", false
}
short := strings.TrimPrefix(name, rule.prefix)
short = strings.TrimSuffix(short, rule.suffix)
if short == "" {
return "", false
}
if rule.prefix+short+rule.suffix != name {
return "", false
}
return short, true
}
func (rule shortenRule) render(short string) string {
return rule.prefix + short + rule.suffix
}
// ShortenName returns the shortest unambiguous shorthand for name among all.
//
// all must contain full reference names visible to the shortening scope.
func ShortenName(name string, all []string) string {
names := make(map[string]struct{}, len(all))
for _, full := range all {
if full == "" {
continue
}
names[full] = struct{}{}
}
for i := len(shortenRules) - 1; i > 0; i-- {
short, ok := shortenRules[i].match(name)
if !ok {
continue
}
ambiguous := false
for j := range shortenRules {
if j == i {
continue
}
full := shortenRules[j].render(short)
if _, found := names[full]; found {
ambiguous = true
break
}
}
if !ambiguous {
return short
}
}
return name
}
|