diff --git a/pkg/build/gobuild.go b/pkg/build/gobuild.go index 5db012771e..0ad585c368 100644 --- a/pkg/build/gobuild.go +++ b/pkg/build/gobuild.go @@ -261,6 +261,15 @@ func build(ctx context.Context, ip string, dir string, platform v1.Platform, con } if dir := os.Getenv("KOCACHE"); dir != "" { + dirInfo, err := os.Stat(dir) + if os.IsNotExist(err) { + if err := os.MkdirAll(dir, os.ModePerm); err != nil && !os.IsExist(err) { + return "", fmt.Errorf("could not create KOCACHE dir %s: %w", dir, err) + } + } else if !dirInfo.IsDir() { + return "", fmt.Errorf("KOCACHE should be a directory, %s is not a directory", dir) + } + // TODO(#264): if KOCACHE is unset, default to filepath.Join(os.TempDir(), "ko"). tmpDir = filepath.Join(dir, "bin", ip, platform.String()) if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil { diff --git a/pkg/build/gobuild_test.go b/pkg/build/gobuild_test.go index 2fbe3eded1..63511b7ae2 100644 --- a/pkg/build/gobuild_test.go +++ b/pkg/build/gobuild_test.go @@ -23,9 +23,11 @@ import ( "fmt" "io" "io/ioutil" + "os" "path" "path/filepath" "runtime" + "strconv" "strings" "testing" "time" @@ -772,6 +774,42 @@ func TestGoBuild(t *testing.T) { }) } +func TestGoBuildWithKOCACHE(t *testing.T) { + now := time.Now() // current local time + sec := now.Unix() + koCacheDir := t.TempDir() + t.Setenv("KOCACHE", filepath.Join(koCacheDir, strconv.FormatInt(sec, 10))) + baseLayers := int64(3) + base, err := random.Image(1024, baseLayers) + if err != nil { + t.Fatalf("random.Image() = %v", err) + } + importpath := "github.com/google/ko" + + creationTime := v1.Time{Time: time.Unix(5000, 0)} + ng, err := NewGo( + context.Background(), + "", + WithCreationTime(creationTime), + WithBaseImages(func(context.Context, string) (name.Reference, Result, error) { return baseRef, base, nil }), + ) + if err != nil { + t.Fatalf("NewGo() = %v", err) + } + + _, err = ng.Build(context.Background(), StrictScheme+filepath.Join(importpath, "test")) + if err != nil { + t.Fatalf("Build() = %v", err) + } + + t.Run("check KOCACHE exists", func(t *testing.T) { + _, err := os.Stat(koCacheDir) + if os.IsNotExist(err) { + t.Fatalf("KOCACHE directory %s should be exists= %v", koCacheDir, err) + } + }) +} + func TestGoBuildWithoutSBOM(t *testing.T) { baseLayers := int64(3) base, err := random.Image(1024, baseLayers)