From de74ccde5609c1bdbbf55c1abbd6714f503debdc Mon Sep 17 00:00:00 2001 From: Jon Johnson Date: Wed, 11 Dec 2019 10:59:24 -0800 Subject: [PATCH] Add entrypoint to PATH This makes it easier to invoke the binary when using a debug container. E.g. you could invoke `ko` instead of `/ko-app/ko`. --- pkg/build/gobuild.go | 23 +++++++++++++++++++++++ pkg/build/gobuild_test.go | 20 +++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/pkg/build/gobuild.go b/pkg/build/gobuild.go index 2c7aa10b2e..f08681077a 100644 --- a/pkg/build/gobuild.go +++ b/pkg/build/gobuild.go @@ -21,6 +21,7 @@ import ( "context" "encoding/json" "errors" + "fmt" gb "go/build" "io" "io/ioutil" @@ -450,6 +451,7 @@ func (gb *gobuild) Build(ctx context.Context, s string) (v1.Image, error) { cfg = cfg.DeepCopy() cfg.Config.Entrypoint = []string{appPath} + updatePath(cfg, appPath) cfg.Config.Env = append(cfg.Config.Env, "KO_DATA_PATH="+kodataRoot) cfg.Author = "github.com/google/ko" @@ -464,3 +466,24 @@ func (gb *gobuild) Build(ctx context.Context, s string) (v1.Image, error) { } return image, nil } + +// Append appPath to the PATH environment variable, if it exists. Otherwise, +// set the PATH environment variable to appPath. +func updatePath(cf *v1.ConfigFile, appPath string) { + for i, env := range cf.Config.Env { + parts := strings.SplitN(env, "=", 2) + if len(parts) != 2 { + // Expect environment variables to be in the form KEY=VALUE, so this is unexpected. + continue + } + key, value := parts[0], parts[1] + if key == "PATH" { + value = fmt.Sprintf("%s:%s", value, appPath) + cf.Config.Env[i] = "PATH=" + value + return + } + } + + // If we get here, we never saw PATH. + cf.Config.Env = append(cf.Config.Env, "PATH="+appPath) +} diff --git a/pkg/build/gobuild_test.go b/pkg/build/gobuild_test.go index 9888e7050c..55fe51b606 100644 --- a/pkg/build/gobuild_test.go +++ b/pkg/build/gobuild_test.go @@ -21,6 +21,7 @@ import ( "io/ioutil" "path" "path/filepath" + "strings" "testing" "time" @@ -336,7 +337,24 @@ func TestGoBuild(t *testing.T) { } } if !found { - t.Error("Didn't find expected file in tarball.") + t.Error("Didn't find KO_DATA_PATH.") + } + }) + + // Check that PATH contains the produced binary. + t.Run("check PATH env var", func(t *testing.T) { + cfg, err := img.ConfigFile() + if err != nil { + t.Errorf("ConfigFile() = %v", err) + } + found := false + for _, entry := range cfg.Config.Env { + if strings.HasPrefix(entry, "PATH=") && strings.Contains(entry, "/ko-app/test") { + found = true + } + } + if !found { + t.Error("Didn't find entrypoint in PATH.") } })