1
2
3
4
5 package str
6
7 import (
8 "path/filepath"
9 "strings"
10 )
11
12
13
14 func HasPathPrefix(s, prefix string) bool {
15 if len(s) == len(prefix) {
16 return s == prefix
17 }
18 if prefix == "" {
19 return true
20 }
21 if len(s) > len(prefix) {
22 if prefix[len(prefix)-1] == '/' || s[len(prefix)] == '/' {
23 return s[:len(prefix)] == prefix
24 }
25 }
26 return false
27 }
28
29
30
31 func HasFilePathPrefix(s, prefix string) bool {
32 sv := strings.ToUpper(filepath.VolumeName(s))
33 pv := strings.ToUpper(filepath.VolumeName(prefix))
34 s = s[len(sv):]
35 prefix = prefix[len(pv):]
36 switch {
37 default:
38 return false
39 case sv != pv:
40 return false
41 case len(s) == len(prefix):
42 return s == prefix
43 case prefix == "":
44 return true
45 case len(s) > len(prefix):
46 if prefix[len(prefix)-1] == filepath.Separator {
47 return strings.HasPrefix(s, prefix)
48 }
49 return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix
50 }
51 }
52
53
54
55
56
57 func TrimFilePathPrefix(s, prefix string) string {
58 if !HasFilePathPrefix(s, prefix) {
59 return s
60 }
61 if len(s) == len(prefix) {
62 return ""
63 }
64 return s[len(prefix)+1:]
65 }
66
View as plain text