2 Copyright 2018 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
30 // IsGoSrcPath validate if given path is of path $GOPATH/src.
31 func IsGoSrcPath(filePath string) bool {
32 for _, gopath := range getGoPaths() {
33 goSrc := path.Join(gopath, "src")
34 if filePath == goSrc {
42 // IsUnderGoSrcPath validate if given path is under path $GOPATH/src.
43 func IsUnderGoSrcPath(filePath string) bool {
44 for _, gopath := range getGoPaths() {
45 goSrc := path.Join(gopath, "src")
46 if strings.HasPrefix(filepath.Dir(filePath), goSrc) {
54 // DirToGoPkg returns the Gopkg for the given directory if it exists
55 // under a GOPATH otherwise returns error. For example,
56 // /Users/x/go/src/github.com/y/z ==> github.com/y/z
57 func DirToGoPkg(dir string) (pkg string, err error) {
58 goPaths := getGoPaths()
59 for _, gopath := range goPaths {
60 goSrc := path.Join(gopath, "src")
61 if !strings.HasPrefix(dir, goSrc) {
64 pkg, err := filepath.Rel(goSrc, dir)
70 return "", fmt.Errorf("dir '%s' does not exist under any GOPATH %v", dir, goPaths)
73 func getGoPaths() []string {
74 gopaths := os.Getenv("GOPATH")
75 if len(gopaths) == 0 {
76 gopaths = gobuild.Default.GOPATH
78 return filepath.SplitList(gopaths)
81 // PathHasProjectFile validate if PROJECT file exists under the path.
82 func PathHasProjectFile(filePath string) bool {
83 if _, err := os.Stat(path.Join(filePath, "PROJECT")); os.IsNotExist(err) {
90 // GetDomainFromProject get domain information from the PROJECT file under the path.
91 func GetDomainFromProject(rootPath string) string {
92 return GetFieldFromProject("domain", rootPath)
95 // GetRepoFromProject get domain information from the PROJECT file under the path.
96 func GetRepoFromProject(rootPath string) string {
97 return GetFieldFromProject("repo", rootPath)
100 // GetFieldFromProject get field information from the PROJECT file under the path.
101 func GetFieldFromProject(fieldKey string, rootPath string) string {
104 file, err := os.Open(path.Join(rootPath, "PROJECT"))
109 if err := file.Close(); err != nil {
114 scanner := bufio.NewScanner(file)
116 if strings.HasPrefix(scanner.Text(), fmt.Sprintf("%s:", fieldKey)) {
117 fieldInfo := strings.Split(scanner.Text(), ":")
118 if len(fieldInfo) != 2 {
119 log.Fatalf("Unexpected %s info: %s", fieldKey, scanner.Text())
121 fieldVal = strings.Replace(fieldInfo[1], " ", "", -1)
125 if len(fieldVal) == 0 {
126 log.Fatalf("%s/PROJECT file is missing value for '%s'", rootPath, fieldKey)