github.com/wolfd/bazel-gazelle@v0.14.0/internal/pathtools/path.go (about) 1 /* Copyright 2018 The Bazel Authors. All rights reserved. 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 16 package pathtools 17 18 import ( 19 "path" 20 "path/filepath" 21 "strings" 22 ) 23 24 // HasPrefix returns whether the slash-separated path p has the given 25 // prefix. Unlike strings.HasPrefix, this function respects component 26 // boundaries, so "/home/foo" is not a prefix is "/home/foobar/baz". If the 27 // prefix is empty, this function always returns true. 28 func HasPrefix(p, prefix string) bool { 29 return prefix == "" || p == prefix || strings.HasPrefix(p, prefix+"/") 30 } 31 32 // TrimPrefix returns p without the provided prefix. If p doesn't start 33 // with prefix, it returns p unchanged. Unlike strings.HasPrefix, this function 34 // respects component boundaries (assuming slash-separated paths), so 35 // TrimPrefix("foo/bar", "foo") returns "baz". 36 func TrimPrefix(p, prefix string) string { 37 if prefix == "" { 38 return p 39 } 40 if prefix == p { 41 return "" 42 } 43 return strings.TrimPrefix(p, prefix+"/") 44 } 45 46 // RelBaseName returns the base name for rel, a slash-separated path relative 47 // to the repository root. If rel is empty, RelBaseName returns the base name 48 // of prefix. If prefix is empty, RelBaseName returns the base name of root, 49 // the absolute file path of the repository root directory. If that's empty 50 // to, then RelBaseName returns "root". 51 func RelBaseName(rel, prefix, root string) string { 52 base := path.Base(rel) 53 if base == "." || base == "/" { 54 base = path.Base(prefix) 55 } 56 if base == "." || base == "/" { 57 base = filepath.Base(root) 58 } 59 if base == "." || base == "/" { 60 base = "root" 61 } 62 return base 63 }