Add BuildWithEnvironment() to gexec
diff --git a/gexec/build.go b/gexec/build.go index 220c8c4..e798900 100644 --- a/gexec/build.go +++ b/gexec/build.go
@@ -28,6 +28,18 @@ } /* +BuildWithEnvironment is identical to Build but allows you to specify env vars to be set at build time. +*/ +func BuildWithEnvironment(packagePath string, env map[string]string, args ...string) (compiledPath string, err error) { + for key, val := range env { + os.Setenv(key, val) + defer os.Unsetenv(key) + } + + return BuildIn(os.Getenv("GOPATH"), packagePath, args...) +} + +/* BuildIn is identical to Build but allows you to specify a custom $GOPATH (the first argument). */ func BuildIn(gopath string, packagePath string, args ...string) (compiledPath string, err error) {
diff --git a/gexec/build_test.go b/gexec/build_test.go index 7bd62fe..a2f1ccd 100644 --- a/gexec/build_test.go +++ b/gexec/build_test.go
@@ -1,14 +1,16 @@ package gexec_test import ( + "os" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) -var _ = Describe(".Build", func() { - var packagePath = "./_fixture/firefly" +var packagePath = "./_fixture/firefly" +var _ = Describe(".Build", func() { Context("when there have been previous calls to Build", func() { BeforeEach(func() { _, err := gexec.Build(packagePath) @@ -35,3 +37,31 @@ }) }) }) + +var _ = Describe(".BuildWithEnvironment", func() { + var err error + + It("compiles the specified package with the specified env vars", func() { + env := map[string]string{ + "GOOS": "linux", + "GOARCH": "amd64", + } + + compiledPath, err := gexec.BuildWithEnvironment(packagePath, env) + Ω(err).ShouldNot(HaveOccurred()) + Ω(compiledPath).Should(BeAnExistingFile()) + }) + + It("returns the environment to a good state", func() { + knownGoodEnv := os.Environ() + + env := map[string]string{ + "THIS_ENV_VAR": "SHOULD_NOT_BE_SET", + } + + _, err = gexec.BuildWithEnvironment(packagePath, env) + Ω(err).ShouldNot(HaveOccurred()) + + Ω(os.Environ()).Should(Equal(knownGoodEnv)) + }) +})