github.com/bir3/gocompiler@v0.3.205/src/cmd/gocmd/internal/str/path.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package str 6 7 import ( 8 "path/filepath" 9 "strings" 10 ) 11 12 // HasPathPrefix reports whether the slash-separated path s 13 // begins with the elements in prefix. 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 // HasFilePathPrefix reports whether the filesystem path s 30 // begins with the elements in prefix. 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 // TrimFilePathPrefix returns s without the leading path elements in prefix. 54 // If s does not start with prefix (HasFilePathPrefix with the same arguments 55 // returns false), TrimFilePathPrefix returns s. If s equals prefix, 56 // TrimFilePathPrefix returns "". 57 func TrimFilePathPrefix(s, prefix string) string { 58 if !HasFilePathPrefix(s, prefix) { 59 return s 60 } 61 trimmed := s[len(prefix):] 62 if len(trimmed) == 0 || trimmed[0] != filepath.Separator { 63 // Prefix either is equal to s, or ends with a separator 64 // (for example, if it is exactly "/"). 65 return trimmed 66 } 67 return trimmed[1:] 68 } 69 70 // QuoteGlob returns s with all Glob metacharacters quoted. 71 // We don't try to handle backslash here, as that can appear in a 72 // file path on Windows. 73 func QuoteGlob(s string) string { 74 if !strings.ContainsAny(s, `*?[]`) { 75 return s 76 } 77 var sb strings.Builder 78 for _, c := range s { 79 switch c { 80 case '*', '?', '[', ']': 81 sb.WriteByte('\\') 82 } 83 sb.WriteRune(c) 84 } 85 return sb.String() 86 }