Skip to content

Commit

Permalink
Validate KO_CONFIG_PATH (#471)
Browse files Browse the repository at this point in the history
* Validate KO_CONFIG_PATH to avoid ignored options

* Remove dup
  • Loading branch information
tcnghia authored Feb 8, 2022
1 parent 1425e4b commit 3e5ee5b
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
13 changes: 11 additions & 2 deletions pkg/commands/options/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,23 @@ func (bo *BuildOptions) LoadConfig() error {
}
// If omitted, use this base image.
v.SetDefault("defaultBaseImage", configDefaultBaseImage)
v.SetConfigName(".ko") // .yaml is implicit
const configName = ".ko"

v.SetConfigName(configName) // .yaml is implicit
v.SetEnvPrefix("KO")
v.AutomaticEnv()

if override := os.Getenv("KO_CONFIG_PATH"); override != "" {
path := filepath.Join(override, configName+".yaml")
file, err := os.Stat(path)
if err != nil {
return fmt.Errorf("error looking for config file: %w", err)
}
if !file.Mode().IsRegular() {
return fmt.Errorf("config file %s is not a regular file", path)
}
v.AddConfigPath(override)
}

v.AddConfigPath(bo.WorkingDirectory)

if err := v.ReadInConfig(); err != nil {
Expand Down
40 changes: 40 additions & 0 deletions pkg/commands/options/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package options

import (
"os"
"strings"
"testing"

"github.com/google/ko/pkg/build"
Expand Down Expand Up @@ -97,3 +99,41 @@ func TestAddBuildOptionsSetsDefaultsForNonFlagOptions(t *testing.T) {
t.Error("expected Trimpath=true")
}
}

func TestOverrideConfigPath(t *testing.T) {
const envName = "KO_CONFIG_PATH"
bo := &BuildOptions{}
for _, tc := range []struct {
name string
koConfigPath string
err string
}{{
name: ".ko.yaml does not exist",
koConfigPath: "testdata",
err: "testdata/.ko.yaml: no such file or directory",
}, {
name: ".ko.yaml is dir",
koConfigPath: "testdata/bad-config",
err: "testdata/bad-config/.ko.yaml is not a regular file",
}, {
name: "good",
koConfigPath: "testdata/config",
}} {
t.Run(tc.name, func(t *testing.T) {
oldEnv := os.Getenv(envName)
defer os.Setenv(envName, oldEnv)

os.Setenv(envName, tc.koConfigPath)
err := bo.LoadConfig()
if err == nil {
if tc.err == "" {
return
}
t.Fatalf("expected error %q, saw nil", tc.err)
}
if !strings.Contains(err.Error(), tc.err) {
t.Errorf("expected error to contain %q, saw: %v", tc.err, err)
}
})
}
}
3 changes: 3 additions & 0 deletions pkg/commands/options/testdata/bad-config/.ko.yaml/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.# We just want to have a practically empty directory.
*
!.gitignore

0 comments on commit 3e5ee5b

Please sign in to comment.