1// Copyright 2020 The Bazel Authors. All rights reserved. 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 15package bzltestutil 16 17// This package must have no deps beyond Go SDK. 18import ( 19 "fmt" 20 "os" 21 "path/filepath" 22 "runtime" 23) 24 25var ( 26 // Initialized by linker. 27 RunDir string 28 29 // Initial working directory. 30 testExecDir string 31) 32 33// This initializer runs before any user packages. 34func init() { 35 var err error 36 testExecDir, err = os.Getwd() 37 if err != nil { 38 panic(err) 39 } 40 41 // Check if we're being run by Bazel and change directories if so. 42 // TEST_SRCDIR and TEST_WORKSPACE are set by the Bazel test runner, so that makes a decent proxy. 43 testSrcDir, hasSrcDir := os.LookupEnv("TEST_SRCDIR") 44 testWorkspace, hasWorkspace := os.LookupEnv("TEST_WORKSPACE") 45 if hasSrcDir && hasWorkspace && RunDir != "" { 46 abs := RunDir 47 if !filepath.IsAbs(RunDir) { 48 abs = filepath.Join(testSrcDir, testWorkspace, RunDir) 49 } 50 err := os.Chdir(abs) 51 // Ignore the Chdir err when on Windows, since it might have have runfiles symlinks. 52 // https://github.com/bazelbuild/rules_go/pull/1721#issuecomment-422145904 53 if err != nil && runtime.GOOS != "windows" { 54 panic(fmt.Sprintf("could not change to test directory: %v", err)) 55 } 56 if err == nil { 57 os.Setenv("PWD", abs) 58 } 59 } 60} 61