-
Notifications
You must be signed in to change notification settings - Fork 31
/
path.go
156 lines (140 loc) · 2.26 KB
/
path.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main
import "strings"
type Path []string
func splitIntoPathInner(p Path, path string, state int) Path {
s := 0
i := 0
c := 0
for c >= 0 {
if i < len(path) {
c = int(path[i])
} else {
c = -1
}
switch state {
case 0:
if c == '/' {
i++
} else {
state = 1
s = i
}
case 1:
if c == '/' || c < 0 {
p = append(p, path[s:i])
state = 0
} else {
i++
}
}
}
return p
}
func SplitIntoPathAsAbs(path string) Path {
if path == "" {
return Path{}
}
return splitIntoPathInner(Path{""}, path, 0)
}
func SplitIntoPath(path string) Path {
if path == "" {
return Path{}
}
return splitIntoPathInner(Path{}, path, 1)
}
func (p Path) Canonicalize() Path {
retval := make(Path, 0, len(p))
for _, c := range p {
switch c {
case ".":
continue
case "..":
if len(retval) > 0 && retval[len(retval)-1] != "" {
retval = retval[:len(retval)-1]
}
default:
retval = append(retval, c)
}
}
return retval
}
func (p Path) IsEmpty() bool {
return len(p) == 0
}
func (p Path) IsRoot() bool {
return len(p) == 1 && p[0] == ""
}
func (p Path) IsAbs() bool {
return len(p) > 0 && p[0] == ""
}
func (p Path) Join(another Path) Path {
if len(another) > 0 && another[0] == "" {
return append(p, another[1:]...)
} else {
return append(p, another...)
}
}
func (p Path) String() string {
return strings.Join(p, "/")
}
func (p Path) IsPrefixed(another Path) bool {
if len(p) < len(another) {
return false
}
for i, c := range another {
if p[i] != c {
return false
}
}
return true
}
func (p Path) Prefix() Path {
if len(p) == 0 {
return p
} else if len(p) == 1 {
if p[0] == "" {
return Path{""}
} else {
return Path{}
}
} else {
return p[:len(p)-1]
}
}
func (p Path) BasePart() Path {
if len(p) == 0 {
return p
} else if len(p) == 1 {
if p[0] == "" {
return Path{""}
} else {
return Path{}
}
} else {
return p[len(p)-1:]
}
}
func (p Path) Base() string {
if len(p) == 0 {
return ""
} else if len(p) == 1 {
if p[0] == "" {
return "/"
} else {
return ""
}
} else {
return p[len(p)-1]
}
}
func (p Path) Equal(p2 Path) bool {
if len(p) != len(p2) {
return false
}
for i := 0; i < len(p); i++ {
if p[i] != p2[i] {
return false
}
}
return true
}