diff --git a/helper/subproc/self.go b/helper/subproc/self.go index 1f44cbce9..7f0709753 100644 --- a/helper/subproc/self.go +++ b/helper/subproc/self.go @@ -8,30 +8,31 @@ import ( "os" "os/exec" "strings" + "sync" ) var ( // executable is the executable of this process executable string + once sync.Once ) -func init() { - s, err := os.Executable() - if err != nil { - panic(fmt.Sprintf("failed to detect executable: %v", err)) - } - - // when running tests, we need to use the real nomad binary, - // and make sure you recompile between changes! - if strings.HasSuffix(s, ".test") { - if s, err = exec.LookPath("nomad"); err != nil { - panic(fmt.Sprintf("failed to find nomad binary: %v", err)) - } - } - executable = s -} - // Self returns the path to the executable of this process. func Self() string { + once.Do(func() { + s, err := os.Executable() + if err != nil { + panic(fmt.Sprintf("failed to detect executable: %v", err)) + } + + // when running tests, we need to use the real nomad binary, + // and make sure you recompile between changes! + if strings.HasSuffix(s, ".test") { + if s, err = exec.LookPath("nomad"); err != nil { + panic(fmt.Sprintf("failed to find nomad binary: %v", err)) + } + } + executable = s + }) return executable } diff --git a/helper/subproc/self_test.go b/helper/subproc/self_test.go new file mode 100644 index 000000000..98b45eb53 --- /dev/null +++ b/helper/subproc/self_test.go @@ -0,0 +1,15 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +package subproc + +import ( + "testing" + + "github.com/shoenig/test/must" +) + +func TestSelf(t *testing.T) { + value := Self() + must.NotEq(t, "", value) +}