From 6dc06b61bbb0b4584e830a069fe5e10447dddcf5 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:42:04 -0600 Subject: [PATCH 1/5] chore(docker): bump build image to golang 1.27.2 Pin the Dockerfile builder to golang:1.27.2 to match the go directive in go.mod, and add a test that fails when the two drift apart. govulncheck -show verbose reports one module-level finding, GO-2026-5932 (golang.org/x/crypto v0.57.0, openpgp package, no fixed version). No reachable vulnerabilities are found. --- Dockerfile | 2 +- toolchain_test.go | 102 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 toolchain_test.go diff --git a/Dockerfile b/Dockerfile index 5275d08..9cc3fb0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.0 AS binary +FROM golang:1.27.2 AS binary WORKDIR /go/src/github.com/jwilder/dockerize COPY *.go go.* /go/src/github.com/jwilder/dockerize/ diff --git a/toolchain_test.go b/toolchain_test.go new file mode 100644 index 0000000..e0908f6 --- /dev/null +++ b/toolchain_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "os" + "regexp" + "strings" + "testing" +) + +var ( + goModToolchainRe = regexp.MustCompile(`(?m)^\s*toolchain\s+go(\S+)`) + goModGoRe = regexp.MustCompile(`(?m)^\s*go\s+(\S+)`) + dockerfileGoRe = regexp.MustCompile(`(?im)^\s*FROM\s+golang:([^\s-]+)`) +) + +// goModVersion returns the toolchain directive from go.mod content if present, +// otherwise the go directive. +func goModVersion(content string) (string, bool) { + if m := goModToolchainRe.FindStringSubmatch(content); m != nil { + return m[1], true + } + if m := goModGoRe.FindStringSubmatch(content); m != nil { + return m[1], true + } + return "", false +} + +// dockerfileGoVersion returns the version part of the first golang image tag +// in the Dockerfile content, dropping any suffix such as "-alpine". +func dockerfileGoVersion(content string) (string, bool) { + if m := dockerfileGoRe.FindStringSubmatch(content); m != nil { + return m[1], true + } + return "", false +} + +func TestDockerfileGoVersionMatchesGoMod(t *testing.T) { + goMod, err := os.ReadFile("go.mod") + if err != nil { + t.Fatalf("reading go.mod: %v", err) + } + dockerfile, err := os.ReadFile("Dockerfile") + if err != nil { + t.Fatalf("reading Dockerfile: %v", err) + } + + modVersion, ok := goModVersion(string(goMod)) + if !ok { + t.Fatal("no go or toolchain directive found in go.mod") + } + imageVersion, ok := dockerfileGoVersion(string(dockerfile)) + if !ok { + t.Fatal("no FROM golang: line found in Dockerfile") + } + if modVersion != imageVersion { + t.Errorf("Dockerfile uses golang:%s but go.mod requires %s", imageVersion, modVersion) + } +} + +func TestGoModVersion(t *testing.T) { + tests := []struct { + name string + content string + want string + wantOK bool + }{ + {"go directive", "module x\n\ngo 1.27.2\n", "1.27.2", true}, + {"toolchain overrides go", "module x\n\ngo 1.27.0\ntoolchain go1.27.2\n", "1.27.2", true}, + {"no directive", "module x\n", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, ok := goModVersion(tt.content) + if ok != tt.wantOK || got != tt.want { + t.Errorf("goModVersion() = %q, %v; want %q, %v", got, ok, tt.want, tt.wantOK) + } + }) + } +} + +func TestDockerfileGoVersion(t *testing.T) { + tests := []struct { + name string + content string + want string + wantOK bool + }{ + {"plain tag", "FROM golang:1.27.2 AS binary\n", "1.27.2", true}, + {"alpine suffix", "FROM golang:1.27.2-alpine AS binary\n", "1.27.2", true}, + {"lowercase keyword", "from golang:1.27.2\n", "1.27.2", true}, + {"no golang image", "FROM gcr.io/distroless/static:nonroot\n", "", false}, + {"golang mentioned mid-line", "# uses golang:1.27.2\n", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, ok := dockerfileGoVersion(strings.TrimSpace(tt.content)) + if ok != tt.wantOK || got != tt.want { + t.Errorf("dockerfileGoVersion() = %q, %v; want %q, %v", got, ok, tt.want, tt.wantOK) + } + }) + } +} From 1f8cbf5f6778bcba631e82d1b4ac608bdb718985 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:04:46 -0600 Subject: [PATCH 2/5] refactor: use errors.AsType for exit code extraction Replace the var-and-errors.As pattern with the generic errors.AsType in the exit code paths and tests, and cover an ExitError wrapped with %w. --- e2e/e2e_test.go | 3 +-- exec.go | 3 +-- exec_error_test.go | 15 +++++++++++++-- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index 7b4a4c0..c1e5d74 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -84,8 +84,7 @@ func TestExitCodePassthrough(t *testing.T) { if err == nil { t.Fatalf("expected non-zero exit") } - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { + if exitErr, ok := errors.AsType[*exec.ExitError](err); ok { if exitErr.ExitCode() != tt.exitCode { t.Fatalf("expected exit code %d, got %d", tt.exitCode, exitErr.ExitCode()) } diff --git a/exec.go b/exec.go index a2f5bb7..26c05c3 100644 --- a/exec.go +++ b/exec.go @@ -53,8 +53,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ... } else { log.Printf("Command exited with error: %s\n", err) - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { + if exitErr, ok := errors.AsType[*exec.ExitError](err); ok { if status, ok := exitErr.Sys().(syscall.WaitStatus); ok { os.Exit(status.ExitStatus()) } diff --git a/exec_error_test.go b/exec_error_test.go index be65473..f096121 100644 --- a/exec_error_test.go +++ b/exec_error_test.go @@ -2,6 +2,7 @@ package main import ( "errors" + "fmt" "os/exec" "syscall" "testing" @@ -13,8 +14,7 @@ func extractExitCode(err error) int { return 0 } - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { + if exitErr, ok := errors.AsType[*exec.ExitError](err); ok { if status, ok := exitErr.Sys().(syscall.WaitStatus); ok { return status.ExitStatus() } @@ -37,6 +37,17 @@ func TestExtractExitCode_FromExitError(t *testing.T) { } } +func TestExtractExitCode_FromWrappedExitError(t *testing.T) { + cmd := exec.Command("sh", "-c", "exit 3") + exitErr := cmd.Run() + + err := fmt.Errorf("run: %w", exitErr) + code := extractExitCode(err) + if code != 3 { + t.Fatalf("expected exit code 3, got %d", code) + } +} + func TestExtractExitCode_FromGenericError(t *testing.T) { err := errors.New("some generic error") From 25765cd77aa776cfe29f3a6190e6b3cd7cd29e6d Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:08:11 -0600 Subject: [PATCH 3/5] refactor: use sync.WaitGroup.Go for wait and signal goroutines --- exec.go | 7 ++----- main.go | 18 ++++++------------ 2 files changed, 8 insertions(+), 17 deletions(-) diff --git a/exec.go b/exec.go index 26c05c3..18d78e9 100644 --- a/exec.go +++ b/exec.go @@ -30,10 +30,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ... signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) waitDone := make(chan struct{}) - wg.Add(1) - go func() { - defer wg.Done() - + wg.Go(func() { select { case sig := <-sigs: log.Printf("Received signal: %s\n", sig) @@ -42,7 +39,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ... case <-ctx.Done(): // exit when context is done } - }() + }) err = process.Wait() close(waitDone) diff --git a/main.go b/main.go index 14b4994..593e549 100644 --- a/main.go +++ b/main.go @@ -138,9 +138,7 @@ func waitForDependencies() { } func waitForFile(u url.URL) { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { ticker := time.NewTicker(waitRetryInterval) defer ticker.Stop() var err error @@ -158,17 +156,15 @@ func waitForFile(u url.URL) { log.Printf("Problem with check file %s exist: %v. Sleeping %s\n", u.String(), err.Error(), waitRetryInterval) } } - }() + }) } func waitForHTTP(u url.URL) { - wg.Add(1) - go func() { + wg.Go(func() { client := &http.Client{ Timeout: waitTimeoutFlag, } - defer wg.Done() for { req, err := http.NewRequest("GET", u.String(), nil) if err != nil { @@ -195,13 +191,11 @@ func waitForHTTP(u url.URL) { time.Sleep(waitRetryInterval) } } - }() + }) } func waitForSocket(scheme, addr string, timeout time.Duration) { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { conn, err := dialTimeout(scheme, addr, timeout) if err != nil { @@ -214,7 +208,7 @@ func waitForSocket(scheme, addr string, timeout time.Duration) { return } } - }() + }) } func usage() { From 78fdfa19b952977090c6332c0c3901fce6c5afa5 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:08:11 -0600 Subject: [PATCH 4/5] test: cover waitForFile returning after the file appears late --- main_test.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/main_test.go b/main_test.go index 1b4feda..9ed5349 100644 --- a/main_test.go +++ b/main_test.go @@ -408,6 +408,37 @@ func TestWaitForSocketConnectsToTCPServer(t *testing.T) { assert.Contains(t, logs.String(), "Connected to tcp://"+ln.Addr().String()) } +func TestWaitForFileReturnsWhenFileCreatedAfterDelay(t *testing.T) { + readyFile := filepath.Join(t.TempDir(), "ready.txt") + + oldRetry := waitRetryInterval + wg = sync.WaitGroup{} + waitRetryInterval = 10 * time.Millisecond + defer func() { + wg = sync.WaitGroup{} + waitRetryInterval = oldRetry + }() + + go func() { + time.Sleep(200 * time.Millisecond) + _ = os.WriteFile(readyFile, []byte("ready"), 0o644) + }() + + waitForFile(url.URL{Scheme: "file", Path: readyFile}) + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for file to be created") + } +} + func TestWaitForDependenciesWaitsForFileAndHTTP(t *testing.T) { tmpDir := t.TempDir() readyFile := filepath.Join(tmpDir, "ready.txt") From ff335d3b6ad34b272a321491deee4a0179585ab5 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:11:48 -0600 Subject: [PATCH 5/5] refactor(template): merge sprig and dockerize funcs with maps.Copy Move the func map merge into templateFuncMap so it can be tested, and copy dockerize's functions over sprig's with maps.Copy. Add a test that every dockerize function, including those that shadow sprig names, is the one in the merged map. --- template.go | 15 ++++++++++----- template_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/template.go b/template.go index 614e877..b5ab97a 100644 --- a/template.go +++ b/template.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "log" + "maps" "net/url" "os" "path/filepath" @@ -126,7 +127,9 @@ func loop(args ...int) (<-chan int, error) { return c, nil } -func generateFile(templatePath, destPath string) bool { +// templateFuncMap returns sprig's functions with dockerize's own functions +// merged over them, so a dockerize function wins when both define the same name. +func templateFuncMap() template.FuncMap { templateMap := template.FuncMap{ "contains": contains, "exists": exists, @@ -144,10 +147,12 @@ func generateFile(templatePath, destPath string) bool { } combinedFuncMap := sprig.TxtFuncMap() - for k, v := range templateMap { - combinedFuncMap[k] = v - } - tmpl := template.New(filepath.Base(templatePath)).Funcs(combinedFuncMap) + maps.Copy(combinedFuncMap, templateMap) + return combinedFuncMap +} + +func generateFile(templatePath, destPath string) bool { + tmpl := template.New(filepath.Base(templatePath)).Funcs(templateFuncMap()) if len(delims) > 0 { tmpl = tmpl.Delims(delims[0], delims[1]) diff --git a/template_test.go b/template_test.go index c42e350..6bebc84 100644 --- a/template_test.go +++ b/template_test.go @@ -3,6 +3,8 @@ package main import ( "os" "path/filepath" + "reflect" + "strconv" "strings" "syscall" "testing" @@ -319,3 +321,32 @@ func TestGenerateFileWritesFullContentAndKeepsMode(t *testing.T) { } } } + +func TestTemplateFuncMapDockerizeOverridesSprig(t *testing.T) { + merged := templateFuncMap() + + dockerizeFuncs := map[string]any{ + "contains": contains, + "exists": exists, + "split": strings.Split, + "replace": strings.Replace, + "default": defaultValue, + "parseUrl": parseUrl, + "atoi": strconv.Atoi, + "add": add, + "isTrue": isTrue, + "lower": strings.ToLower, + "upper": strings.ToUpper, + "jsonQuery": jsonQuery, + "loop": loop, + } + for name, fn := range dockerizeFuncs { + got, ok := merged[name] + if !ok { + t.Fatalf("%s missing from merged func map", name) + } + if reflect.ValueOf(got).Pointer() != reflect.ValueOf(fn).Pointer() { + t.Errorf("%s: merged map does not hold dockerize's function", name) + } + } +}