github.com/afking/bazel-gazelle@v0.0.0-20180301150245-c02bc0f529e8/internal/common/path.go (about) 1 /* Copyright 2017 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 common 17 18 import "strings" 19 20 // PathHasPrefix returns whether the slash-separated path p has the given 21 // prefix. Unlike strings.HasPrefix, this function respects component 22 // boundaries, so "/home/foo" is not a prefix is "/home/foobar/baz". If the 23 // prefix is empty, this function always returns true. 24 func PathHasPrefix(p, prefix string) bool { 25 return prefix == "" || p == prefix || strings.HasPrefix(p, prefix+"/") 26 } 27 28 // PathTrimPrefix returns p without the provided prefix. If p doesn't start 29 // with prefix, it returns p unchanged. Unlike strings.HasPrefix, this function 30 // respects component boundaries (assuming slash-separated paths), so 31 // PathTrimPrefix("foo/bar", "foo") returns "baz". 32 func PathTrimPrefix(p, prefix string) string { 33 if prefix == "" { 34 return p 35 } 36 if prefix == p { 37 return "" 38 } 39 return strings.TrimPrefix(p, prefix+"/") 40 }