From c1132b49314d96788d6467f64e567faa31e8e063 Mon Sep 17 00:00:00 2001 From: Dmitry Vyukov Date: Thu, 21 Oct 2021 19:12:24 +0200 Subject: pkg/osutil: slightly relaxed Abs check Currently Abs captures pwd in init function and checks that it's not changing over program execution. However, in some test environments (bazel) we need to chdir in test init function because the test process is started in a wrong dir. This causes the check in Abs to fail. Query the pwd lazily on the first Abs call. This does not change behavior for Abs users, but allows to change pwd in other init functions. --- pkg/osutil/osutil.go | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'pkg') diff --git a/pkg/osutil/osutil.go b/pkg/osutil/osutil.go index ae8ebc2fb..cbace37c6 100644 --- a/pkg/osutil/osutil.go +++ b/pkg/osutil/osutil.go @@ -11,6 +11,7 @@ import ( "os/exec" "path/filepath" "strings" + "sync" "syscall" "time" ) @@ -285,17 +286,19 @@ func ListDir(dir string) ([]string, error) { return f.Readdirnames(-1) } -var wd string - -func init() { - var err error - wd, err = os.Getwd() - if err != nil { - panic(fmt.Sprintf("failed to get wd: %v", err)) - } -} +var ( + wd string + wdOnce sync.Once +) func Abs(path string) string { + wdOnce.Do(func() { + var err error + wd, err = os.Getwd() + if err != nil { + panic(fmt.Sprintf("failed to get wd: %v", err)) + } + }) if wd1, err := os.Getwd(); err == nil && wd1 != wd { panic(fmt.Sprintf("wd changed: %q -> %q", wd, wd1)) } -- cgit mrf-deployment