-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalias.go
More file actions
81 lines (70 loc) · 2.24 KB
/
alias.go
File metadata and controls
81 lines (70 loc) · 2.24 KB
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
package figtree
import (
"fmt"
"strings"
)
// resolveName returns the canonical fig name for a given name or alias.
// Callers must hold tree.mu (read or write) before calling this.
func (tree *figTree) resolveName(name string) string {
name = strings.ToLower(name)
if canonical, exists := tree.aliases[name]; exists {
return canonical
}
return name
}
func (tree *figTree) Problems() []error {
tree.mu.RLock()
defer tree.mu.RUnlock()
return append([]error(nil), tree.problems...)
}
func (tree *figTree) WithAlias(name, alias string) Plant {
tree.mu.Lock()
defer tree.mu.Unlock()
name = strings.ToLower(name)
alias = strings.ToLower(alias)
// Guard: alias already registered
if existing, exists := tree.aliases[alias]; exists {
if existing != name {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: alias -%s already maps to -%s, cannot remap to -%s", alias, existing, name))
}
// idempotent: same alias→name pair is a no-op, not an error
return tree
}
// Guard: canonical fig must exist
if _, exists := tree.figs[name]; !exists {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: no fig named -%s", name))
return tree
}
// Guard: alias must not shadow an existing fig name
if _, exists := tree.figs[alias]; exists {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: alias -%s conflicts with existing fig name", alias))
return tree
}
// Guard: alias must not shadow an existing flag (covers both figs and
// any flags registered outside of figtree, e.g. via flagSet.Var directly)
if tree.flagSet.Lookup(alias) != nil {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: alias -%s conflicts with existing flag", alias))
return tree
}
// Guard: underlying value must be retrievable and correctly typed
ptr, ok := tree.values.Load(name)
if !ok {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: no value found for -%s", name))
return tree
}
value, ok := ptr.(*Value)
if !ok {
tree.problems = append(tree.problems,
fmt.Errorf("WithAlias: value for -%s is %T, expected *Value", name, ptr))
return tree
}
// All validations passed — register the alias
tree.aliases[alias] = name
tree.flagSet.Var(value, alias, "Alias of -"+name)
return tree
}