From e38773f3fbdbd82f3b7ad51b2c1b0a5fd2a2c7c2 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:09:36 -0600 Subject: [PATCH 1/9] fix(tail): handle t.Stop and write errors in tailFile Log a t.Stop error from the deferred cleanup. Stop tailing a file when a line cannot be written to the destination, since a broken destination will not recover. tailFile now takes an io.Writer so it can be tested with a failing writer. --- tail.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tail.go b/tail.go index 3f09856b..c70864ae 100644 --- a/tail.go +++ b/tail.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "io" "log" "os" "time" @@ -10,7 +11,7 @@ import ( "github.com/hpcloud/tail" ) -func tailFile(ctx context.Context, file string, poll bool, dest *os.File) { +func tailFile(ctx context.Context, file string, poll bool, dest io.Writer) { defer wg.Done() var isPipe bool @@ -37,7 +38,9 @@ func tailFile(ctx context.Context, file string, poll bool, dest *os.File) { } defer func() { - t.Stop() + if err := t.Stop(); err != nil { + log.Printf("Warning: unable to stop tailing %s: %s", file, err) + } t.Cleanup() }() @@ -62,7 +65,11 @@ func tailFile(ctx context.Context, file string, poll bool, dest *os.File) { } return } else { - fmt.Fprintln(dest, line.Text) + if _, err := fmt.Fprintln(dest, line.Text); err != nil { + // a broken destination won't recover, so stop tailing this file + log.Printf("unable to write tailed line from %s: %s", file, err) + return + } errCount = 0 // Zero the error count } } From 2f64e2483aa69df5e97361aea42a979025d37b79 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:09:36 -0600 Subject: [PATCH 2/9] test(tail): cover write errors and fix errcheck hits Add a test that tails into a writer that always fails and checks that tailFile returns and logs the write error. Check the Close and Write errors that errcheck flagged. --- tail_test.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/tail_test.go b/tail_test.go index 6468bcce..5987d857 100644 --- a/tail_test.go +++ b/tail_test.go @@ -2,7 +2,10 @@ package main import ( "bufio" + "bytes" "context" + "errors" + "log" "os" "path/filepath" "strings" @@ -23,7 +26,11 @@ func TestTailFileWritesAppendedLines(t *testing.T) { if err != nil { t.Fatalf("create dest file: %v", err) } - defer dest.Close() + defer func() { + if err := dest.Close(); err != nil { + t.Errorf("close dest file: %v", err) + } + }() ctx, cancel := context.WithCancel(context.Background()) wg.Add(1) @@ -36,7 +43,7 @@ func TestTailFileWritesAppendedLines(t *testing.T) { t.Fatalf("open source for append: %v", err) } if _, err := f.WriteString(line + "\n"); err != nil { - f.Close() + _ = f.Close() t.Fatalf("append source line: %v", err) } if err := f.Close(); err != nil { @@ -134,3 +141,61 @@ func TestTailFileStopsWhenContextCanceled(t *testing.T) { t.Fatalf("expected no tailed output, got %q", string(got)) } } + +// errWriter is an io.Writer whose every Write fails. +type errWriter struct { + err error +} + +func (w errWriter) Write(p []byte) (int, error) { + return 0, w.err +} + +func TestTailFileStopsOnWriteError(t *testing.T) { + tailDir := t.TempDir() + sourcePath := filepath.Join(tailDir, "source.log") + + if err := os.WriteFile(sourcePath, []byte{}, 0o644); err != nil { + t.Fatalf("write source file: %v", err) + } + + var logBuf bytes.Buffer + prevOutput := log.Writer() + log.SetOutput(&logBuf) + t.Cleanup(func() { log.SetOutput(prevOutput) }) + + writeErr := errors.New("destination is closed") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + wg.Add(1) + go tailFile(ctx, sourcePath, true, errWriter{err: writeErr}) + + time.Sleep(200 * time.Millisecond) + f, err := os.OpenFile(sourcePath, os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + t.Fatalf("open source for append: %v", err) + } + if _, err := f.WriteString("line\n"); err != nil { + _ = f.Close() + t.Fatalf("append source line: %v", err) + } + if err := f.Close(); err != nil { + t.Fatalf("close source file: %v", err) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("tailFile did not return after a write error") + } + + if got := logBuf.String(); !strings.Contains(got, "unable to write tailed line from") || !strings.Contains(got, writeErr.Error()) { + t.Fatalf("expected write error in log output, got %q", got) + } +} From 1909e5e423e1ffb932000daf1e534eb86bb8473c Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:09:50 -0600 Subject: [PATCH 3/9] test(e2e): handle errors from file writes, listeners and cleanup Setup writes and directory creation now fail the test through small helpers, and best-effort teardown is explicit about ignoring errors. --- e2e/e2e_test.go | 74 ++++++++++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 29 deletions(-) diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index dded3099..7b4a4c01 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -25,7 +25,7 @@ func TestMain(m *testing.M) { if err != nil { log.Fatalf("failed to create temp dir: %v", err) } - defer os.RemoveAll(tmpDir) + defer func() { _ = os.RemoveAll(tmpDir) }() dockerizeBin = filepath.Join(tmpDir, "dockerize") @@ -103,7 +103,7 @@ func TestTemplateBasic(t *testing.T) { tmplFile := filepath.Join(dir, "test.tmpl") destFile := filepath.Join(dir, "output.conf") - os.WriteFile(tmplFile, []byte(`server {{ .Env.TEST_HOST }}:{{ .Env.TEST_PORT }}`), 0644) + writeFile(t, tmplFile, []byte(`server {{ .Env.TEST_HOST }}:{{ .Env.TEST_PORT }}`)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = append(os.Environ(), "TEST_HOST=localhost", "TEST_PORT=8080") @@ -122,7 +122,7 @@ func TestTemplateBasic(t *testing.T) { func TestTemplateToStdout(t *testing.T) { dir := t.TempDir() tmplFile := filepath.Join(dir, "hello.tmpl") - os.WriteFile(tmplFile, []byte(`hello {{ .Env.NAME }}`), 0644) + writeFile(t, tmplFile, []byte(`hello {{ .Env.NAME }}`)) cmd := exec.Command(dockerizeBin, "-template", tmplFile) cmd.Env = append(os.Environ(), "NAME=world") @@ -141,7 +141,7 @@ func TestTemplateCustomDelims(t *testing.T) { tmplFile := filepath.Join(dir, "custom.tmpl") destFile := filepath.Join(dir, "output.txt") - os.WriteFile(tmplFile, []byte(`value=<% .Env.MY_VAR %>`), 0644) + writeFile(t, tmplFile, []byte(`value=<% .Env.MY_VAR %>`)) cmd := exec.Command(dockerizeBin, "-delims", "<%:%>", "-template", tmplFile+":"+destFile) cmd.Env = append(os.Environ(), "MY_VAR=custom_delims_work") @@ -161,8 +161,8 @@ func TestTemplateNoOverwrite(t *testing.T) { tmplFile := filepath.Join(dir, "tmpl.tmpl") destFile := filepath.Join(dir, "dest.txt") - os.WriteFile(tmplFile, []byte(`new content`), 0644) - os.WriteFile(destFile, []byte(`original content`), 0644) + writeFile(t, tmplFile, []byte(`new content`)) + writeFile(t, destFile, []byte(`original content`)) cmd := exec.Command(dockerizeBin, "-no-overwrite", "-template", tmplFile+":"+destFile) out, err := cmd.CombinedOutput() @@ -180,11 +180,11 @@ func TestTemplateDirectory(t *testing.T) { dir := t.TempDir() tmplDir := filepath.Join(dir, "templates") destDir := filepath.Join(dir, "output") - os.MkdirAll(tmplDir, 0755) - os.MkdirAll(destDir, 0755) + mkdirAll(t, tmplDir) + mkdirAll(t, destDir) - os.WriteFile(filepath.Join(tmplDir, "a.conf"), []byte(`a={{ .Env.A }}`), 0644) - os.WriteFile(filepath.Join(tmplDir, "b.conf"), []byte(`b={{ .Env.B }}`), 0644) + writeFile(t, filepath.Join(tmplDir, "a.conf"), []byte(`a={{ .Env.A }}`)) + writeFile(t, filepath.Join(tmplDir, "b.conf"), []byte(`b={{ .Env.B }}`)) cmd := exec.Command(dockerizeBin, "-template", tmplDir+":"+destDir) cmd.Env = append(os.Environ(), "A=alpha", "B=beta") @@ -209,7 +209,7 @@ func TestTemplateSprigFunctions(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `{{ .Env.GREETING | upper }}_{{ " padded " | trimAll " " }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = append(os.Environ(), "GREETING=hello") @@ -230,7 +230,7 @@ func TestStdoutTail(t *testing.T) { dir := t.TempDir() logFile := filepath.Join(dir, "app.log") - os.WriteFile(logFile, []byte("line1\nline2\n"), 0644) + writeFile(t, logFile, []byte("line1\nline2\n")) cmd := exec.Command(dockerizeBin, "-stdout", logFile, "-poll", "sh", "-c", "sleep 0.5") out, err := cmd.CombinedOutput() @@ -247,7 +247,7 @@ func TestStdoutTail(t *testing.T) { func TestStderrTail(t *testing.T) { dir := t.TempDir() logFile := filepath.Join(dir, "error.log") - os.WriteFile(logFile, []byte("err1\nerr2\n"), 0644) + writeFile(t, logFile, []byte("err1\nerr2\n")) cmd := exec.Command(dockerizeBin, "-stderr", logFile, "-poll", "sh", "-c", "sleep 0.5") var stderr bytes.Buffer @@ -270,7 +270,7 @@ func TestWaitTCP(t *testing.T) { if err != nil { t.Fatalf("failed to listen: %v", err) } - defer ln.Close() + t.Cleanup(func() { _ = ln.Close() }) addr := ln.Addr().String() @@ -349,7 +349,7 @@ func TestWaitFile(t *testing.T) { go func() { time.Sleep(1 * time.Second) - os.WriteFile(waitFile, []byte("ok"), 0644) + _ = os.WriteFile(waitFile, []byte("ok"), 0644) }() cmd := exec.Command(dockerizeBin, "-wait", "file://"+waitFile, "-timeout", "5s", "echo", "file-ready") @@ -372,8 +372,8 @@ func TestWaitMultiple(t *testing.T) { if err != nil { t.Fatalf("failed to listen: %v", err) } - defer ln1.Close() - defer ln2.Close() + t.Cleanup(func() { _ = ln1.Close() }) + t.Cleanup(func() { _ = ln2.Close() }) cmd := exec.Command(dockerizeBin, "-wait", "tcp://"+ln1.Addr().String(), @@ -476,7 +476,7 @@ func TestTemplateEnvContext(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `host={{ .Env.DB_HOST }} port={{ .Env.DB_PORT }} pass={{ .Env.DB_PASS }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = append(os.Environ(), "DB_HOST=pg.local", "DB_PORT=5432", "DB_PASS=p@ss=w0rd!") @@ -499,7 +499,7 @@ func TestTemplateEnvRange(t *testing.T) { // Range over .Env filtering by prefix tmpl := `{{ range $k, $v := .Env }}{{ if hasPrefix "MYAPP_" $k }}{{ $k }}={{ $v }}` + "\n" + `{{ end }}{{ end }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = []string{"MYAPP_HOST=web1", "MYAPP_PORT=9090", "OTHER_VAR=ignore"} @@ -523,7 +523,7 @@ func TestTemplateEnvMissing(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `before[{{ .Env.DEFINITELY_NOT_SET }}]after` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) // Deliberately don't set DEFINITELY_NOT_SET @@ -547,7 +547,7 @@ func TestTemplateFuncDefault(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `port={{ default .Env.PORT "3000" }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) // Test with PORT unset — should use default cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) @@ -580,7 +580,7 @@ func TestTemplateFuncContains(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `{{ if contains .Env "SECRET" }}has-secret{{ else }}no-secret{{ end }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) // With SECRET set cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) @@ -610,7 +610,7 @@ func TestTemplateFuncContains(t *testing.T) { func TestTemplateFuncExists(t *testing.T) { dir := t.TempDir() existingFile := filepath.Join(dir, "present.conf") - os.WriteFile(existingFile, []byte("x"), 0644) + writeFile(t, existingFile, []byte("x")) tmplFile := filepath.Join(dir, "exists.tmpl") destFile := filepath.Join(dir, "out.txt") @@ -618,7 +618,7 @@ func TestTemplateFuncExists(t *testing.T) { // exists returns (bool, error) — use with index or assign tmpl := fmt.Sprintf(`{{ $e := exists "%s" }}{{ $m := exists "%s/absent.conf" }}{{ $e }}-{{ $m }}`, existingFile, dir) - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = os.Environ() @@ -643,7 +643,7 @@ replaced={{ replace .Env.GREETING "hello" "hi" 1 }} lower={{ lower .Env.UPPER }} upper={{ upper .Env.LOWER }} sum={{ add (atoi .Env.A) (atoi .Env.B) }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = []string{"CSV=one,two,three", "GREETING=hello world", "UPPER=LOUD", "LOWER=quiet", "A=10", "B=32"} @@ -665,7 +665,7 @@ func TestTemplateFuncParseUrl(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `{{ $u := parseUrl .Env.DATABASE_URL }}host={{ $u.Host }} scheme={{ $u.Scheme }} path={{ $u.Path }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = []string{"DATABASE_URL=postgres://db.example.com:5432/mydb"} @@ -687,7 +687,7 @@ func TestTemplateFuncIsTrue(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `{{ if isTrue .Env.ENABLED }}on{{ else }}off{{ end }}-{{ if isTrue .Env.DISABLED }}on{{ else }}off{{ end }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) tests := []struct { enabled string @@ -723,7 +723,7 @@ func TestTemplateFuncJsonQuery(t *testing.T) { destFile := filepath.Join(dir, "out.txt") tmpl := `name={{ jsonQuery .Env.CONFIG "name" }} version={{ jsonQuery .Env.CONFIG "version" }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) jsonVal := `{"name":"myapp","version":"1.2.3"}` cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) @@ -749,7 +749,7 @@ func TestTemplateFuncLoop(t *testing.T) { tmpl := `a={{ range $i := loop 3 }}{{ $i }}{{ end }} b={{ range $i := loop 2 5 }}{{ $i }}{{ end }} c={{ range $i := loop 0 10 3 }}{{ $i }}{{ end }}` - os.WriteFile(tmplFile, []byte(tmpl), 0644) + writeFile(t, tmplFile, []byte(tmpl)) cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile) cmd.Env = []string{"HOME=/tmp"} @@ -764,3 +764,19 @@ c={{ range $i := loop 0 10 3 }}{{ $i }}{{ end }}` t.Fatalf("expected:\n%s\ngot:\n%s", expected, string(got)) } } + +// writeFile writes data to name, failing the test if it cannot be written. +func writeFile(t *testing.T, name string, data []byte) { + t.Helper() + if err := os.WriteFile(name, data, 0644); err != nil { + t.Fatalf("failed to write %s: %v", name, err) + } +} + +// mkdirAll creates path and any missing parents, failing the test on error. +func mkdirAll(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(path, 0755); err != nil { + t.Fatalf("failed to create %s: %v", path, err) + } +} From 1db1ed1a57034494163a2eb11dad2714cfcedb01 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:10:02 -0600 Subject: [PATCH 4/9] fix(exec): log signal and kill errors other than process already done --- exec.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/exec.go b/exec.go index b4401207..a2f5bb7e 100644 --- a/exec.go +++ b/exec.go @@ -67,11 +67,15 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ... } func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-chan struct{}) { - process.Process.Signal(sig) // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command? + // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command? + if err := process.Process.Signal(sig); err != nil && !errors.Is(err, os.ErrProcessDone) { + log.Printf("Error sending signal to command: %s\n", err) + } if len(waitDone) == 0 { done := make(chan struct{}) go func() { - process.Wait() + // Only signals completion; the caller's own Wait reports the exit status. + _ = process.Wait() close(done) }() waitDone = []<-chan struct{}{done} @@ -81,6 +85,8 @@ func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-ch return case <-time.After(10 * time.Second): log.Println("Killing command due to timeout.") - process.Process.Kill() + if err := process.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) { + log.Printf("Error killing command: %s\n", err) + } } } From d77ab8c6f4fb37bda0c4611ef446be16d7072305 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:10:02 -0600 Subject: [PATCH 5/9] test(exec): cover signalling exited and live processes --- exec_signal_test.go | 62 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/exec_signal_test.go b/exec_signal_test.go index a104de6e..6098efd0 100644 --- a/exec_signal_test.go +++ b/exec_signal_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "context" + "log" "os" "os/exec" "strings" @@ -39,13 +40,14 @@ func TestRunCmdSignalShutdown(t *testing.T) { t.Fatalf("signal helper: %v", err) } - waitErrCh := make(chan error, 1) + waitDone := make(chan struct{}) go func() { - waitErrCh <- cmd.Wait() + _ = cmd.Wait() + close(waitDone) }() select { - case <-waitErrCh: + case <-waitDone: case <-time.After(20 * time.Second): _ = cmd.Process.Kill() t.Fatal("timed out waiting for helper to exit") @@ -55,3 +57,57 @@ func TestRunCmdSignalShutdown(t *testing.T) { t.Fatalf("unexpected data race reported: %s", stderr.String()) } } + +func TestSignalProcessWithTimeoutAlreadyExited(t *testing.T) { + cmd := exec.Command("true") + if err := cmd.Run(); err != nil { + t.Fatalf("run command: %v", err) + } + + var logBuf bytes.Buffer + prevOutput := log.Writer() + log.SetOutput(&logBuf) + defer log.SetOutput(prevOutput) + + done := make(chan struct{}) + go func() { + signalProcessWithTimeout(cmd, syscall.SIGTERM) + close(done) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("signalProcessWithTimeout did not return for an exited command") + } + + if logBuf.Len() != 0 { + t.Errorf("expected no log output, got: %q", logBuf.String()) + } +} + +func TestSignalProcessWithTimeoutStopsLiveProcess(t *testing.T) { + cmd := exec.Command("sleep", "30") + if err := cmd.Start(); err != nil { + t.Fatalf("start sleep: %v", err) + } + + waitDone := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(waitDone) + }() + + start := time.Now() + signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone) + if elapsed := time.Since(start); elapsed >= 10*time.Second { + t.Fatalf("signalProcessWithTimeout took %s, expected the signal to stop sleep before the timeout", elapsed) + } + + select { + case <-waitDone: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + t.Fatal("sleep was not stopped") + } +} From 5a76866ea568bb3432aeb6435d020b30729329c7 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 21:11:45 -0600 Subject: [PATCH 6/9] test: handle errors from Set, cleanup and close calls in main tests --- main_test.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/main_test.go b/main_test.go index e1a69822..1b4feda9 100644 --- a/main_test.go +++ b/main_test.go @@ -25,16 +25,24 @@ func TestMain(m *testing.M) { func TestSliceVarString(t *testing.T) { var sv sliceVar - sv.Set("test1") - sv.Set("test2") + if err := sv.Set("test1"); err != nil { + t.Fatal(err) + } + if err := sv.Set("test2"); err != nil { + t.Fatal(err) + } result := sv.String() assert.Equal(t, "test1,test2", result) } func TestHostFlagsVarString(t *testing.T) { var hf hostFlagsVar - hf.Set("host1") - hf.Set("host2") + if err := hf.Set("host1"); err != nil { + t.Fatal(err) + } + if err := hf.Set("host2"); err != nil { + t.Fatal(err) + } result := hf.String() assert.Equal(t, "[host1 host2]", result) } @@ -42,7 +50,7 @@ func TestHostFlagsVarString(t *testing.T) { func TestExists(t *testing.T) { tempFile, err := os.CreateTemp("", "test-exists") assert.NoError(t, err) - defer os.Remove(tempFile.Name()) + t.Cleanup(func() { _ = os.Remove(tempFile.Name()) }) existsResult, err := exists(tempFile.Name()) assert.NoError(t, err) @@ -319,7 +327,7 @@ func TestWaitForSocketUsesPassedTimeoutForDial(t *testing.T) { dialTimeout = func(network, address string, timeout time.Duration) (net.Conn, error) { timeoutArg <- timeout client, server := net.Pipe() - go server.Close() + go func() { _ = server.Close() }() return client, nil } @@ -348,7 +356,7 @@ func TestWaitForSocketUsesPassedTimeoutForDial(t *testing.T) { func TestWaitForSocketConnectsToTCPServer(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") assert.NoError(t, err) - defer ln.Close() + defer func() { _ = ln.Close() }() var logs bytes.Buffer oldLogWriter := log.Writer() @@ -373,7 +381,7 @@ func TestWaitForSocketConnectsToTCPServer(t *testing.T) { defer close(acceptDone) conn, err := ln.Accept() if err == nil { - conn.Close() + _ = conn.Close() } }() From 5cd54499f0381912b5560894632d9688dfba8eb7 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:01:31 -0600 Subject: [PATCH 7/9] fix(template): check the error from closing the destination file --- template.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/template.go b/template.go index ef1de97b..614e8772 100644 --- a/template.go +++ b/template.go @@ -168,7 +168,6 @@ func generateFile(templatePath, destPath string) bool { if err != nil { log.Fatalf("unable to create %s, error: %s", destPath, err) } - defer dest.Close() } err = tmpl.ExecuteTemplate(dest, filepath.Base(templatePath), &Context{}) @@ -185,6 +184,12 @@ func generateFile(templatePath, destPath string) bool { } } + if destPath != "" { + if err := dest.Close(); err != nil { + log.Fatalf("unable to close %s: %s", destPath, err) + } + } + return true } From b7ee1ce050c752cf3f4acb2aba62abc400f3cdaf Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:01:31 -0600 Subject: [PATCH 8/9] test(template): cover full output and file mode when writing to a file --- template_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/template_test.go b/template_test.go index 34b435c7..c42e350d 100644 --- a/template_test.go +++ b/template_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "strings" + "syscall" "testing" ) @@ -265,3 +266,56 @@ func TestGenerateDirRendersAllTemplates(t *testing.T) { } } } + +func TestGenerateFileWritesFullContentAndKeepsMode(t *testing.T) { + oldDelims := delims + oldNoOverwrite := noOverwriteFlag + defer func() { + delims = oldDelims + noOverwriteFlag = oldNoOverwrite + }() + + delims = nil + noOverwriteFlag = false + + tempDir := t.TempDir() + templatePath := filepath.Join(tempDir, "big.tmpl") + destPath := filepath.Join(tempDir, "big.out") + + templateContent := strings.Repeat("line {{ add 1 2 }} {{ upper \"abc\" }}\n", 5000) + if err := os.WriteFile(templatePath, []byte(templateContent), 0o644); err != nil { + t.Fatalf("write template: %v", err) + } + if err := os.WriteFile(destPath, []byte("stale"), 0o640); err != nil { + t.Fatalf("write existing destination: %v", err) + } + if err := os.Chmod(destPath, 0o640); err != nil { + t.Fatalf("chmod destination: %v", err) + } + + if ok := generateFile(templatePath, destPath); !ok { + t.Fatalf("generateFile returned false") + } + + got, err := os.ReadFile(destPath) + if err != nil { + t.Fatalf("read rendered file: %v", err) + } + want := strings.Repeat("line 3 ABC\n", 5000) + if string(got) != want { + t.Fatalf("rendered output mismatch: got %d bytes want %d bytes", len(got), len(want)) + } + + fi, err := os.Stat(destPath) + if err != nil { + t.Fatalf("stat rendered file: %v", err) + } + if mode := fi.Mode().Perm(); mode != 0o640 { + t.Fatalf("mode mismatch: got %o want %o", mode, 0o640) + } + if st, ok := fi.Sys().(*syscall.Stat_t); ok { + if int(st.Uid) != os.Getuid() || int(st.Gid) != os.Getgid() { + t.Fatalf("owner mismatch: got %d:%d want %d:%d", st.Uid, st.Gid, os.Getuid(), os.Getgid()) + } + } +} From 9dbc1c0c1b8ae9d520f01f667d879d2ba9302279 Mon Sep 17 00:00:00 2001 From: Jason Wilder Date: Fri, 16 Oct 2026 22:02:36 -0600 Subject: [PATCH 9/9] chore(lint): enable errcheck --- .golangci.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 62cfc4b3..242bb6a1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,10 +1,8 @@ version: "2" linters: - disable: - # TODO: Re-enable after fixing pre-existing unchecked error returns - - errcheck enable: + - errcheck - govet - ineffassign - staticcheck