Marcel van Lohuizen | 434c3a1 | 2018-12-10 15:37:18 +0100 | [diff] [blame] | 1 | // Copyright 2018 The CUE Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package str |
| 16 | |
| 17 | import ( |
| 18 | "path/filepath" |
| 19 | "strings" |
| 20 | ) |
| 21 | |
| 22 | // HasPath reports whether the slash-separated path s |
| 23 | // begins with the elements in prefix. |
| 24 | func HasPathPrefix(s, prefix string) bool { |
| 25 | if len(s) == len(prefix) { |
| 26 | return s == prefix |
| 27 | } |
| 28 | if prefix == "" { |
| 29 | return true |
| 30 | } |
| 31 | if len(s) > len(prefix) { |
| 32 | if prefix[len(prefix)-1] == '/' || s[len(prefix)] == '/' { |
| 33 | return s[:len(prefix)] == prefix |
| 34 | } |
| 35 | } |
| 36 | return false |
| 37 | } |
| 38 | |
| 39 | // HasFilePathPrefix reports whether the filesystem path s |
| 40 | // begins with the elements in prefix. |
| 41 | func HasFilePathPrefix(s, prefix string) bool { |
| 42 | sv := strings.ToUpper(filepath.VolumeName(s)) |
| 43 | pv := strings.ToUpper(filepath.VolumeName(prefix)) |
| 44 | s = s[len(sv):] |
| 45 | prefix = prefix[len(pv):] |
| 46 | switch { |
| 47 | default: |
| 48 | return false |
| 49 | case sv != pv: |
| 50 | return false |
| 51 | case len(s) == len(prefix): |
| 52 | return s == prefix |
| 53 | case prefix == "": |
| 54 | return true |
| 55 | case len(s) > len(prefix): |
| 56 | if prefix[len(prefix)-1] == filepath.Separator { |
| 57 | return strings.HasPrefix(s, prefix) |
| 58 | } |
| 59 | return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix |
| 60 | } |
| 61 | } |