build.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. gobuild "go/build"
  16. "path"
  17. "path/filepath"
  18. "reflect"
  19. "strings"
  20. )
  21. type empty struct{}
  22. // CurrentPackage returns the go package of the current directory, or "" if it cannot
  23. // be derived from the GOPATH.
  24. func CurrentPackage() string {
  25. for _, root := range gobuild.Default.SrcDirs() {
  26. if pkg, ok := hasSubdir(root, "."); ok {
  27. return pkg
  28. }
  29. }
  30. return ""
  31. }
  32. func hasSubdir(root, dir string) (rel string, ok bool) {
  33. // ensure a tailing separator to properly compare on word-boundaries
  34. const sep = string(filepath.Separator)
  35. root = filepath.Clean(root)
  36. if !strings.HasSuffix(root, sep) {
  37. root += sep
  38. }
  39. // check whether root dir starts with root
  40. dir = filepath.Clean(dir)
  41. if !strings.HasPrefix(dir, root) {
  42. return "", false
  43. }
  44. // cut off root
  45. return filepath.ToSlash(dir[len(root):]), true
  46. }
  47. // BoilerplatePath uses the boilerplate in code-generator by calculating the relative path to it.
  48. func BoilerplatePath() string {
  49. return path.Join(reflect.TypeOf(empty{}).PkgPath(), "/../../hack/boilerplate.go.txt")
  50. }
  51. // Vendorless trims vendor prefix from a package path to make it canonical
  52. func Vendorless(p string) string {
  53. if pos := strings.LastIndex(p, "/vendor/"); pos != -1 {
  54. return p[pos+len("/vendor/"):]
  55. }
  56. return p
  57. }