path.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Copyright 2018 The Bazel Authors. All rights reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package pathtools
  13. import (
  14. "path"
  15. "path/filepath"
  16. "strings"
  17. )
  18. // HasPrefix returns whether the slash-separated path p has the given
  19. // prefix. Unlike strings.HasPrefix, this function respects component
  20. // boundaries, so "/home/foo" is not a prefix is "/home/foobar/baz". If the
  21. // prefix is empty, this function always returns true.
  22. func HasPrefix(p, prefix string) bool {
  23. return prefix == "" || p == prefix || strings.HasPrefix(p, prefix+"/")
  24. }
  25. // TrimPrefix returns p without the provided prefix. If p doesn't start
  26. // with prefix, it returns p unchanged. Unlike strings.HasPrefix, this function
  27. // respects component boundaries (assuming slash-separated paths), so
  28. // TrimPrefix("foo/bar", "foo") returns "baz".
  29. func TrimPrefix(p, prefix string) string {
  30. if prefix == "" {
  31. return p
  32. }
  33. if prefix == p {
  34. return ""
  35. }
  36. return strings.TrimPrefix(p, prefix+"/")
  37. }
  38. // RelBaseName returns the base name for rel, a slash-separated path relative
  39. // to the repository root. If rel is empty, RelBaseName returns the base name
  40. // of prefix. If prefix is empty, RelBaseName returns the base name of root,
  41. // the absolute file path of the repository root directory. If that's empty
  42. // to, then RelBaseName returns "root".
  43. func RelBaseName(rel, prefix, root string) string {
  44. base := path.Base(rel)
  45. if base == "." || base == "/" {
  46. base = path.Base(prefix)
  47. }
  48. if base == "." || base == "/" {
  49. base = filepath.Base(root)
  50. }
  51. if base == "." || base == "/" {
  52. base = "root"
  53. }
  54. return base
  55. }