From d70f4efcb1b39da445181220e9e721fab7ad8aa2 Mon Sep 17 00:00:00 2001 From: wanghao-SunSky Date: Tue, 1 Dec 2026 08:38:14 +0800 Subject: [PATCH] fix(prettylog): close each input file after processing --- cmd/prettylog/prettylog.go | 4 +- cmd/prettylog/prettylog_unix_test.go | 70 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 cmd/prettylog/prettylog_unix_test.go diff --git a/cmd/prettylog/prettylog.go b/cmd/prettylog/prettylog.go index 10d77994..f3dc1416 100644 --- a/cmd/prettylog/prettylog.go +++ b/cmd/prettylog/prettylog.go @@ -67,7 +67,9 @@ func main() { os.Exit(1) } - if err := processInput(reader, writer); err != nil { + err = processInput(reader, writer) + _ = reader.Close() + if err != nil { fmt.Printf("%s scan: %v", filename, err) os.Exit(1) } diff --git a/cmd/prettylog/prettylog_unix_test.go b/cmd/prettylog/prettylog_unix_test.go new file mode 100644 index 00000000..a6ad63f0 --- /dev/null +++ b/cmd/prettylog/prettylog_unix_test.go @@ -0,0 +1,70 @@ +//go:build darwin || linux + +package main + +import ( + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" +) + +func TestPrettylogFiles(t *testing.T) { + const childEnv = "PRETTYLOG_TEST_CHILD" + if os.Getenv(childEnv) == "1" { + limit := syscall.Rlimit{Cur: 32, Max: 32} + if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { + t.Fatal(err) + } + os.Args = append(os.Args[:1], flag.Args()...) + main() + os.Exit(0) + } + + dir := t.TempDir() + const fileCount = 48 + files := make([]string, fileCount) + messages := make([]string, fileCount) + for i := 0; i < fileCount; i++ { + messages[i] = fmt.Sprintf("entry-%02d", i) + files[i] = filepath.Join(dir, messages[i]+".jsonl") + line := fmt.Sprintf("{\"level\":\"info\",\"message\":%q}\n", messages[i]) + if err := os.WriteFile(files[i], []byte(line), 0600); err != nil { + t.Fatal(err) + } + } + + for _, tc := range []struct { + name string + count int + }{ + {name: "single_file", count: 1}, + {name: "many_files", count: fileCount}, + } { + t.Run(tc.name, func(t *testing.T) { + args := append([]string{"-test.run=^TestPrettylogFiles$", "--"}, files[:tc.count]...) + cmd := exec.Command(os.Args[0], args...) + // Prevent garbage collection from closing leaked files. + cmd.Env = append(os.Environ(), childEnv+"=1", "GOGC=off", "GOMEMLIMIT=off") + output, err := cmd.CombinedOutput() + got := string(output) + lineCount := strings.Count(got, "\n") + if err != nil { + t.Fatalf("prettylog: %v after writing %d of %d lines\n%s", err, lineCount, tc.count, got) + } + if lineCount != tc.count { + t.Fatalf("prettylog wrote %d lines, want %d\n%s", lineCount, tc.count, got) + } + for i, line := range strings.Split(strings.TrimSuffix(got, "\n"), "\n") { + if !strings.Contains(line, messages[i]) { + t.Errorf("line %d = %q, want message %q", i+1, line, messages[i]) + } + } + t.Logf("prettylog exited 0 and wrote %d lines", lineCount) + }) + } +}