github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/test/testutil/testutil_runfiles.go (about) 1 // Copyright 2018 The gVisor Authors. 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 package testutil 16 17 import ( 18 "fmt" 19 "os" 20 "path/filepath" 21 ) 22 23 // FindFile searchs for a file inside the test run environment. It returns the 24 // full path to the file. It fails if none or more than one file is found. 25 func FindFile(path string) (string, error) { 26 wd, err := os.Getwd() 27 if err != nil { 28 return "", err 29 } 30 31 // The test root is demarcated by a path element called "__main__". Search for 32 // it backwards from the working directory. 33 root := wd 34 for { 35 dir, name := filepath.Split(root) 36 if name == "__main__" { 37 break 38 } 39 if len(dir) == 0 { 40 return "", fmt.Errorf("directory __main__ not found in %q", wd) 41 } 42 // Remove ending slash to loop around. 43 root = dir[:len(dir)-1] 44 } 45 46 // Annoyingly, bazel adds the build type to the directory path for go 47 // binaries, but not for c++ binaries. We use two different patterns to 48 // to find our file. 49 patterns := []string{ 50 // Try the obvious path first. 51 filepath.Join(root, path), 52 // If it was a go binary, use a wildcard to match the build 53 // type. The pattern is: /test-path/__main__/directories/*/file. 54 filepath.Join(root, filepath.Dir(path), "*", filepath.Base(path)), 55 } 56 57 for _, p := range patterns { 58 matches, err := filepath.Glob(p) 59 if err != nil { 60 // "The only possible returned error is ErrBadPattern, 61 // when pattern is malformed." -godoc 62 return "", fmt.Errorf("error globbing %q: %v", p, err) 63 } 64 switch len(matches) { 65 case 0: 66 // Try the next pattern. 67 case 1: 68 // We found it. 69 return matches[0], nil 70 default: 71 return "", fmt.Errorf("more than one match found for %q: %s", path, matches) 72 } 73 } 74 return "", fmt.Errorf("file %q not found", path) 75 }