github.com/stackb/rules_proto@v0.0.0-20240221195024-5428336c51f1/cmd/gazelle/wspace.go (about) 1 /* Copyright 2016 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 13 package main 14 15 // wspace provides functions to locate and modify a bazel WORKSPACE file. In 16 // gazelle this is an internal package. 17 18 import ( 19 "os" 20 "path/filepath" 21 "strings" 22 ) 23 24 var workspaceFiles = []string{"WORKSPACE.bazel", "WORKSPACE"} 25 26 // IsWORKSPACE checks whether path is a WORKSPACE or WORKSPACE.bazel file 27 func IsWORKSPACE(path string) bool { 28 base := filepath.Base(path) 29 for _, workspaceFile := range workspaceFiles { 30 if base == workspaceFile { 31 return true 32 } 33 } 34 return false 35 } 36 37 // FindWORKSPACEFile returns a path to a file in the provided root directory, 38 // either to an existing WORKSPACE or WORKSPACE.bazel file, or to root/WORKSPACE 39 // if neither exists. Note that this function does NOT recursively check parent directories. 40 func FindWORKSPACEFile(root string) string { 41 for _, workspaceFile := range workspaceFiles { 42 path := filepath.Join(root, workspaceFile) 43 if _, err := os.Stat(path); err == nil { 44 return path 45 } 46 } 47 return filepath.Join(root, "WORKSPACE") 48 } 49 50 // FindRepoRoot searches from the given dir and up for a directory containing a WORKSPACE file 51 // returning the directory containing it, or an error if none found in the tree. 52 func FindRepoRoot(dir string) (string, error) { 53 dir, err := filepath.Abs(dir) 54 if err != nil { 55 return "", err 56 } 57 58 for { 59 for _, workspaceFile := range workspaceFiles { 60 filepath := filepath.Join(dir, workspaceFile) 61 _, err = os.Stat(filepath) 62 if err == nil { 63 return dir, nil 64 } 65 if !os.IsNotExist(err) { 66 return "", err 67 } 68 } 69 if strings.HasSuffix(dir, string(os.PathSeparator)) { // stop at root dir 70 return "", os.ErrNotExist 71 } 72 dir = filepath.Dir(dir) 73 } 74 }