-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkg.go
97 lines (81 loc) · 1.54 KB
/
pkg.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package util
import (
"strings"
"github.com/samber/lo"
)
type Pkg []string
func (p Pkg) Quoted(quote string) string {
return strings.Join(lo.Map(p, func(x string, _ int) string {
return quote + x + quote
}), ".")
}
func (p Pkg) StringWith(extra ...string) string {
return strings.Join(append(p, extra...), "::")
}
func (p Pkg) String() string {
return p.StringWith()
}
func (p Pkg) ToPath(extra ...string) string {
return strings.Join(append(p, extra...), "/")
}
func (p Pkg) Equals(other Pkg) bool {
if len(p) != len(other) {
return false
}
return p.StartsWith(other)
}
func (p Pkg) Trim(src Pkg) Pkg {
return lo.Reject(src, func(v string, idx int) bool {
return len(src) >= idx && src[idx] == v
})
}
func (p Pkg) Drop(n int) Pkg {
l := len(p) - n
if l < 0 {
l = 0
}
ret := make(Pkg, 0, l)
for idx := 0; idx < l; idx++ {
ret = append(ret, p[idx])
}
return ret
}
func (p Pkg) Last() string {
return p[len(p)-1]
}
func (p Pkg) Shift() Pkg {
ret := make(Pkg, 0, len(p)-1)
for i, s := range p {
if i == len(p)-1 {
break
}
ret = append(ret, s)
}
return ret
}
func (p Pkg) Push(name string) Pkg {
if strings.Contains(name, "/") {
return Pkg{"ERROR:contains-slash"}
}
return append(p, name)
}
func (p Pkg) With(key string) Pkg {
return append(append(Pkg{}, p...), key)
}
func (p Pkg) StartsWith(t Pkg) bool {
if len(p) < len(t) {
return false
}
for i, x := range t {
if p[i] != x {
return false
}
}
return true
}
func DefaultIfNil[T any](ptr *T, d T) T {
if ptr == nil {
return d
}
return *ptr
}