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