Skip to content

Commit 9befd54

Browse files
committed
update
1 parent 72b8208 commit 9befd54

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

file.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ func HasPathSeperatorSuffix(ppath string) bool {
118118
}
119119

120120
var pathSeperatorRegex = regexp.MustCompile(`(\\|/)`)
121+
var winPathSeperatorRegex = regexp.MustCompile(`[\\]+`)
121122

122123
func GetPathSeperator(ppath string) string {
123124
matches := pathSeperatorRegex.FindAllStringSubmatch(ppath, 1)
@@ -127,6 +128,53 @@ func GetPathSeperator(ppath string) string {
127128
return ``
128129
}
129130

131+
func RealPath(fullPath string) string {
132+
if len(fullPath) == 0 {
133+
return fullPath
134+
}
135+
var root string
136+
var pathSeperator string
137+
if strings.HasPrefix(fullPath, `/`) {
138+
pathSeperator = `/`
139+
} else {
140+
pathSeperator = GetPathSeperator(fullPath)
141+
if pathSeperator == `/` {
142+
fullPath = `/` + fullPath
143+
} else {
144+
cleanedFullPath := winPathSeperatorRegex.ReplaceAllString(fullPath, `\`)
145+
parts := strings.SplitN(cleanedFullPath, `\`, 2)
146+
if !strings.HasSuffix(parts[0], `:`) {
147+
if len(parts[0]) > 0 {
148+
parts[0] = `c:\` + parts[0]
149+
} else {
150+
parts[0] = `c:`
151+
}
152+
}
153+
root = parts[0] + `\`
154+
if len(parts) != 2 {
155+
return fullPath
156+
}
157+
fullPath = parts[1]
158+
}
159+
}
160+
parts := pathSeperatorRegex.Split(fullPath, -1)
161+
result := make([]string, 0, len(parts))
162+
for _, part := range parts {
163+
if part == `.` {
164+
continue
165+
}
166+
if part == `..` {
167+
if len(result) <= 1 {
168+
continue
169+
}
170+
result = result[0 : len(result)-1]
171+
continue
172+
}
173+
result = append(result, part)
174+
}
175+
return root + strings.Join(result, pathSeperator)
176+
}
177+
130178
func SplitFileDirAndName(ppath string) (dir string, name string) {
131179
if len(ppath) == 0 {
132180
return

file_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,26 @@ func TestSplitFileDirAndName(t *testing.T) {
7575
sep = GetPathSeperator(`dfefe\ffefe`)
7676
assert.Equal(t, `\`, sep)
7777
}
78+
79+
func TestRealPath(t *testing.T) {
80+
ppath := RealPath(`/abc/../dd.txt`)
81+
assert.Equal(t, `/dd.txt`, ppath)
82+
83+
ppath = RealPath(`/../dd.txt`)
84+
assert.Equal(t, `/dd.txt`, ppath)
85+
86+
ppath = RealPath(`c:\..\dd.txt`)
87+
assert.Equal(t, `c:\dd.txt`, ppath)
88+
ppath = RealPath(`c:\\..\\dd.txt`)
89+
assert.Equal(t, `c:\dd.txt`, ppath)
90+
91+
ppath = RealPath(`\\dd.txt`)
92+
assert.Equal(t, `c:\dd.txt`, ppath)
93+
ppath = RealPath(`a\b\dd.txt`)
94+
assert.Equal(t, `c:\a\b\dd.txt`, ppath)
95+
ppath = RealPath(`dd.txt`)
96+
assert.Equal(t, `dd.txt`, ppath)
97+
98+
ppath = RealPath(`c:\a\b\c\..`)
99+
assert.Equal(t, `c:\a\b`, ppath)
100+
}

0 commit comments

Comments
 (0)