diff --git a/README.md b/README.md index d0de362..85567da 100644 --- a/README.md +++ b/README.md @@ -141,9 +141,11 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Batman_002_p002.jpg → p003.jpg ... -Done — processed: 2 errors: 0 +Done — processed: 2 renamed: 0 errors: 0 ``` +Ctrl+C stops before the next page conversion or file, or at the `--update-cover` prompt, prints the summary headed `Interrupted` and exits 130. A comic it stops part-way is left as it was. A second Ctrl+C also kills the conversion in progress, as closing the terminal or SIGTERM does. From then on SIGTERM and (on Unix) SIGHUP are ignored, and a further Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. + --- ## mkv-audit diff --git a/cbz-fix/cbz_test.go b/cbz-fix/cbz_test.go index 4dbdb63..3060c21 100644 --- a/cbz-fix/cbz_test.go +++ b/cbz-fix/cbz_test.go @@ -159,7 +159,7 @@ func TestProcessCBZ_BasicRename(t *testing.T) { {"003.png", portrait}, }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -196,7 +196,7 @@ func TestProcessCBZ_BlankIsWhite(t *testing.T) { {"002.png", portrait}, }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -226,7 +226,7 @@ func TestProcessCBZ_DoublePageSkipped(t *testing.T) { {"003.png", portrait}, // first non-double page }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -277,7 +277,7 @@ func TestProcessCBZ_ComicInfoUpdated(t *testing.T) { {"ComicInfo.xml", []byte(ci)}, }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -312,7 +312,7 @@ func TestProcessCBZ_BackupCreated(t *testing.T) { {"002.png", portrait}, }) - if _, err := processCBZ(path, false, false, false, false, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, false, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -331,7 +331,7 @@ func TestProcessCBZ_DryRun(t *testing.T) { // Record original names. before := readCBZNames(t, path) - if _, err := processCBZ(path, true, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, true, false, false, true, false); err != nil { t.Fatalf("processCBZ dry-run: %v", err) } @@ -355,7 +355,7 @@ func TestProcessCBZ_Idempotent(t *testing.T) { before := readCBZNames(t, path) - skipped, err := processCBZ(path, false, false, false, true, false) + skipped, err := processCBZ(t.Context(), path, false, false, false, true, false) if err != nil { t.Fatalf("processCBZ: %v", err) } @@ -379,7 +379,7 @@ func TestProcessCBZ_ForceReprocesses(t *testing.T) { {"p002.png", portrait}, }) - skipped, err := processCBZ(path, false, false, false, true, true) // force + skipped, err := processCBZ(t.Context(), path, false, false, false, true, true) // force if err != nil { t.Fatalf("processCBZ: %v", err) } @@ -409,7 +409,7 @@ func TestProcessCBZ_ForceAddsMissingBlank(t *testing.T) { {"p002.png", portrait}, }) - skipped, err := processCBZ(path, false, false, false, true, true) // force + skipped, err := processCBZ(t.Context(), path, false, false, false, true, true) // force if err != nil { t.Fatalf("processCBZ: %v", err) } @@ -434,7 +434,7 @@ func TestProcessCBZ_ForceRespectsNoBlank(t *testing.T) { {"p002.png", portrait}, }) - if _, err := processCBZ(path, false, false, true, true, true); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, true, true, true); err != nil { t.Fatalf("processCBZ: %v", err) } if names := readCBZNames(t, path); containsEntry(names, "p003.png") { @@ -1104,7 +1104,7 @@ func TestProcessCBZ_KFXOrdering(t *testing.T) { // HTML chain: img_c → img_a → img_b (all portrait → blank inserted after cover). path := makeKFXCBZ(t, []string{"img_c", "img_a", "img_b"}) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } @@ -1160,7 +1160,7 @@ func TestProcessCBZ_NeedsFixing(t *testing.T) { {"002.png", portrait}, }) - skipped, err := processCBZ(path, true, false, false, true, false) // dry-run + skipped, err := processCBZ(t.Context(), path, true, false, false, true, false) // dry-run if err != nil { t.Fatalf("processCBZ: %v", err) } @@ -1178,7 +1178,7 @@ func TestProcessCBZ_SubdirImages(t *testing.T) { {"Comic Name/003.png", portrait}, }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } diff --git a/cbz-fix/command.go b/cbz-fix/command.go new file mode 100644 index 0000000..ea86194 --- /dev/null +++ b/cbz-fix/command.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "os/exec" +) + +// killKey keys the kill context a ctx carries for command: cancelling ctx lets +// command's processes finish, and cancelling the kill context kills them. +type killKey struct{} + +// killContext is the kill context ctx carries, or one never cancelled. +func killContext(ctx context.Context) context.Context { + if kill, ok := ctx.Value(killKey{}).(context.Context); ok { + return kill + } + return context.WithoutCancel(ctx) +} + +// command returns a Cmd for name that the terminal's Ctrl+C doesn't reach +// (isolate). Only ctx's kill context kills it: ctx's own cancellation and +// deadline never do. +func command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(killContext(ctx), name, args...) + isolate(cmd) + return cmd +} + +// commandErr is err from running a command, or the kill context's error once +// that is cancelled: any failure is then reported as the kill, its likely cause. +func commandErr(ctx context.Context, err error) error { + if killErr := killContext(ctx).Err(); err != nil && killErr != nil { + return killErr + } + return err +} diff --git a/cbz-fix/command_other.go b/cbz-fix/command_other.go new file mode 100644 index 0000000..9a732d4 --- /dev/null +++ b/cbz-fix/command_other.go @@ -0,0 +1,17 @@ +//go:build !unix && !windows + +package main + +import ( + "os" + "os/exec" +) + +// isolate does nothing where there are no process groups. +func isolate(*exec.Cmd) {} + +// quitSignals is empty: without isolate, children get the same signals. +var quitSignals []os.Signal + +// pipeSignals is empty: there is no SIGPIPE to catch. +var pipeSignals []os.Signal diff --git a/cbz-fix/command_test.go b/cbz-fix/command_test.go new file mode 100644 index 0000000..a03abc7 --- /dev/null +++ b/cbz-fix/command_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "strings" + "testing" + "time" +) + +const ( + // helperEnv names the helperModes entry a child started by these tests runs. + helperEnv = "CBZFIX_TEST_HELPER" + // readyEnv names a file the helper creates once ready, for a child whose + // stdout the test can't read. + readyEnv = "CBZFIX_TEST_READY" +) + +// helperModes are the children the command tests start: the test binary run +// with helperEnv set, which TestMain hands to the mode instead of the tests. +// Those startHelper runs say "ready" first. +var helperModes = map[string]func(){ + // sleep sleeps for a minute or until killed. + "sleep": func() { ready(); time.Sleep(time.Minute) }, +} + +// ready prints "ready", and creates the file readyEnv names, if any. +func ready() { + fmt.Println("ready") + if path := os.Getenv(readyEnv); path != "" { + if err := os.WriteFile(path, nil, 0o600); err != nil { + fmt.Fprintln(os.Stderr, "write ready file:", err) + os.Exit(1) + } + } +} + +func TestMain(m *testing.M) { + if mode := os.Getenv(helperEnv); mode != "" { + helper, ok := helperModes[mode] + if !ok { + fmt.Fprintln(os.Stderr, "unknown helper mode", mode) + os.Exit(2) + } + helper() + os.Exit(0) + } + os.Exit(m.Run()) +} + +// startHelper runs the helper mode through command and waits for it to say +// "ready", returning its stdout and a channel that gets commandErr's verdict +// once it ends. Cleanup kills it, so a failed test leaves nothing running, and +// logs its stderr if the test failed. +func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (*bufio.Reader, <-chan error) { + t.Helper() + cmd := command(ctx, os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+mode) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = w, &stderr + result := make(chan error, 1) + finished := make(chan struct{}) + go func() { + result <- commandErr(ctx, cmd.Run()) + w.Close() // EOF for a reader still waiting on a helper that never spoke + close(finished) + }() + t.Cleanup(func() { + kill() + <-finished + r.Close() + if t.Failed() && stderr.Len() > 0 { + t.Logf("helper stderr:\n%s", stderr.String()) + } + }) + out := bufio.NewReader(r) + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q, want ready", line) + } + return out, result +} + +// readLine reads one line from the helper, failing the test on EOF. +func readLine(t *testing.T, r *bufio.Reader) string { + t.Helper() + line, err := r.ReadString('\n') + if err != nil { + t.Fatalf("helper said %q, then %v", line, err) + } + return strings.TrimSpace(line) +} + +// wantKilled waits for startHelper's verdict, which must be the kill. +func wantKilled(t *testing.T, result <-chan error) { + t.Helper() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Errorf("commandErr = %v, want context.Canceled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("child still running after the kill") + } +} + +// wantRunning fails the test if the helper ends within a short wait. +func wantRunning(t *testing.T, result <-chan error) { + t.Helper() + select { + case err := <-result: + t.Fatalf("child ended after the first interrupt: %v", err) + case <-time.After(300 * time.Millisecond): + } +} + +// Without an interrupt context, command's processes are never killed. +func TestKillContext_DefaultNeverCancels(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := killContext(ctx).Err(); err != nil { + t.Errorf("killContext of a cancelled plain context: %v", err) + } +} + +// commandErr reports a failure as the kill only once the kill context, not +// ctx, is cancelled, and never turns a success into an error. +func TestCommandErr(t *testing.T) { + failed := errors.New("exit status 1") + cases := []struct { + name string + stop, kill bool + in, want error + }{ + {"running", false, false, failed, failed}, + {"stopped", true, false, failed, failed}, + {"killed", true, true, failed, context.Canceled}, + {"killed but succeeded", true, true, nil, nil}, + } + for _, tc := range cases { + ctx, stop, kill := newInterruptContext() + if tc.stop { + stop() + } + if tc.kill { + kill() + } + if got := commandErr(ctx, tc.in); !errors.Is(got, tc.want) || (tc.want == nil) != (got == nil) { + t.Errorf("%s: commandErr = %v, want %v", tc.name, got, tc.want) + } + stop() + kill() + } +} + +// A child outlives the first interrupt and is killed by the second, which +// commandErr reports as the interrupt. +func TestCommand_SecondInterruptKillsChild(t *testing.T) { + ctx, stop, kill := newInterruptContext() + _, result := startHelper(ctx, t, kill, "sleep") + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} diff --git a/cbz-fix/command_unix.go b/cbz-fix/command_unix.go new file mode 100644 index 0000000..8402c3b --- /dev/null +++ b/cbz-fix/command_unix.go @@ -0,0 +1,33 @@ +//go:build unix + +package main + +import ( + "errors" + "os" + "os/exec" + "syscall" +) + +// isolate starts cmd in its own process group, so the terminal's SIGINT +// doesn't reach it. Cancelling cmd sends the group SIGTERM, which ImageMagick +// catches to remove its temp files. +func isolate(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } +} + +// quitSignals would end cbz-fix by default without reaching its isolated +// children, so it catches them and kills the children itself. +var quitSignals = []os.Signal{syscall.SIGTERM, syscall.SIGHUP} + +// pipeSignals is SIGPIPE, which ends cbz-fix on a write to a broken stdout or +// stderr unless caught. Caught (not ignored, which magick would inherit), the +// write fails instead. +var pipeSignals = []os.Signal{syscall.SIGPIPE} diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go new file mode 100644 index 0000000..c0e2492 --- /dev/null +++ b/cbz-fix/command_unix_test.go @@ -0,0 +1,322 @@ +//go:build unix + +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func init() { + // group starts a sleeping grandchild in its process group and prints the + // grandchild's pid, then sleeps. + helperModes["group"] = func() { + gc := exec.CommandContext(context.Background(), os.Args[0]) + gc.Env = append(os.Environ(), helperEnv+"=sleep") + if err := gc.Start(); err != nil { + fmt.Fprintln(os.Stderr, "start grandchild:", err) + os.Exit(1) + } + ready() + fmt.Println(gc.Process.Pid) + time.Sleep(time.Minute) + } + // term says "term" when it gets SIGTERM, then exits. + helperModes["term"] = func() { + terms := make(chan os.Signal, 1) + signal.Notify(terms, syscall.SIGTERM) + ready() + select { + case <-terms: + fmt.Println("term") + case <-time.After(time.Minute): + } + } + + // The modes below run interruptContext and signal themselves. + helperModes["int3"] = func() { + ctx := interruptContext() + raise(syscall.SIGINT) + waitFor(ctx, "stopped") + raise(syscall.SIGINT) + waitFor(killContext(ctx), "killed") + interruptUntilDead() + } + helperModes["hup"] = func() { quitTwice(syscall.SIGHUP) } // a closed terminal + helperModes["sigterm"] = func() { quitTwice(syscall.SIGTERM) } + // The broken-pipe modes run with stdout and stderr on a broken pipe. + // Before a stop, a write ends the process by SIGPIPE as usual. + helperModes["broken-pipe-idle"] = func() { + interruptContext() + // The ready file shows the death below isn't TestMain's write about an + // unknown mode, which a broken pipe ends the same way. + if err := os.WriteFile(os.Getenv(readyEnv), nil, 0o600); err != nil { + failHelper("write ready file:", err) + } + fmt.Println("x") + failHelper("survived a write to a broken pipe") + } + // After Ctrl+C, the notice's and the summary's writes fail instead. + helperModes["broken-pipe"] = func() { + ctx := interruptContext() + raise(syscall.SIGINT) + waitFor(ctx, "stopped") + time.Sleep(100 * time.Millisecond) // the notice's write + fmt.Println("summary") + } + // nohup: an ignored hangup doesn't stop cbz-fix. + helperModes["ignored-hup"] = func() { + signal.Ignore(syscall.SIGHUP) + ctx := interruptContext() + raise(syscall.SIGHUP) + sayStopped(ctx) + } + // A background job in a script: with SIGINT ignored, no other signal + // becomes an interrupt, since notify doesn't Notify an empty list (which + // would relay every signal). + helperModes["ignored-int"] = func() { + signal.Ignore(syscall.SIGINT) + ctx := interruptContext() + raise(syscall.SIGWINCH) + sayStopped(ctx) + } +} + +// diagEnv names a file a helper reports its failure to instead of stderr, for +// a child whose stderr is a broken pipe. +const diagEnv = "CBZFIX_TEST_DIAG" + +// failHelper reports a helper's failure and exits 1. +func failHelper(msg ...any) { + w := os.Stderr + if path := os.Getenv(diagEnv); path != "" { + if f, err := os.Create(path); err == nil { + w = f + } + } + fmt.Fprintln(w, msg...) + os.Exit(1) +} + +func raise(sig syscall.Signal) { + if err := syscall.Kill(os.Getpid(), sig); err != nil { + failHelper("kill:", err) + } +} + +// waitFor prints done once ctx is cancelled, or exits if it takes too long. +func waitFor(ctx context.Context, done string) { + select { + case <-ctx.Done(): + fmt.Println(done) + case <-time.After(5 * time.Second): + failHelper("timed out before:", done) + } +} + +// quitTwice sends sig, then repeats it once the kill is requested (a closed +// terminal sends SIGHUP twice), and checks the repeats are absorbed and Ctrl+C +// then quits. Repeating checks that restore, which runs just after the kill, +// leaves the quit signals caught. +func quitTwice(sig syscall.Signal) { + ctx := interruptContext() + raise(sig) + waitFor(killContext(ctx), "stopped and killed") + for range 5 { + raise(sig) + time.Sleep(50 * time.Millisecond) + } + fmt.Println("absorbed") + interruptUntilDead() +} + +// interruptUntilDead sends Ctrl+C until one gets the default handling. +func interruptUntilDead() { + for range 100 { + raise(syscall.SIGINT) + time.Sleep(50 * time.Millisecond) + } + fmt.Println("survived Ctrl+C") +} + +// sayStopped says whether ctx is cancelled after a short wait. +func sayStopped(ctx context.Context) { + select { + case <-ctx.Done(): + fmt.Println("stopped") + case <-time.After(500 * time.Millisecond): + fmt.Println("kept running") + } +} + +// The signal sequences interruptContext handles, run in a child that signals +// itself: three Ctrl+Cs (the third quits), a quit (a second is absorbed, and +// Ctrl+C then quits), and signals the process started out ignoring. +func TestInterruptContext(t *testing.T) { + cases := []struct { + mode, want string + diesBy syscall.Signal // 0: exits normally + needs []syscall.Signal + }{ + {"int3", "stopped\nkilled", syscall.SIGINT, []syscall.Signal{syscall.SIGINT}}, + {"hup", "stopped and killed\nabsorbed", syscall.SIGINT, []syscall.Signal{syscall.SIGHUP, syscall.SIGINT}}, + {"sigterm", "stopped and killed\nabsorbed", syscall.SIGINT, []syscall.Signal{syscall.SIGINT}}, + {"ignored-hup", "kept running", 0, nil}, + {"ignored-int", "kept running", 0, nil}, + } + for _, tc := range cases { + t.Run(tc.mode, func(t *testing.T) { + for _, sig := range tc.needs { + if signal.Ignored(sig) { + t.Skipf("%v is ignored here (nohup, or a background job?), so the child inherits that", sig) + } + } + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+tc.mode) + out, err := cmd.Output() + if cmd.ProcessState == nil { + t.Fatalf("start: %v", err) + } + var stderr []byte + if ee, ok := errors.AsType[*exec.ExitError](err); ok { + stderr = ee.Stderr + } + if got := strings.TrimSpace(string(out)); got != tc.want { + t.Errorf("said %q, want %q (stderr %q)", got, tc.want, stderr) + } + ws, _ := cmd.ProcessState.Sys().(syscall.WaitStatus) + if tc.diesBy == 0 && err != nil { + t.Errorf("exited with %v, want success (stderr %q)", err, stderr) + } + if tc.diesBy != 0 && (!ws.Signaled() || ws.Signal() != tc.diesBy) { + t.Errorf("ended with %v, want death by %v (stderr %q)", err, tc.diesBy, stderr) + } + }) + } +} + +// Output to a broken pipe ends cbz-fix by SIGPIPE as usual (`cbz-fix | head`) +// until Ctrl+C. After it, which in `cbz-fix 2>&1 | tee log` ends tee too, the +// notice's and the summary's writes fail instead, so cbz-fix finishes stopping. +func TestInterruptContext_BrokenPipe(t *testing.T) { + cases := []struct { + mode string + diesBy syscall.Signal // 0: exits normally + needs []syscall.Signal + }{ + {"broken-pipe-idle", syscall.SIGPIPE, nil}, + {"broken-pipe", 0, []syscall.Signal{syscall.SIGINT}}, + } + for _, tc := range cases { + t.Run(tc.mode, func(t *testing.T) { + for _, sig := range tc.needs { + if signal.Ignored(sig) { + t.Skipf("%v is ignored here, so the child inherits that", sig) + } + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + r.Close() + defer w.Close() + dir := t.TempDir() + diag, readyFile := filepath.Join(dir, "diag"), filepath.Join(dir, "ready") + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+tc.mode, diagEnv+"="+diag, readyEnv+"="+readyFile) + cmd.Stdout, cmd.Stderr = w, w + err = cmd.Run() + if cmd.ProcessState == nil { + t.Fatalf("start: %v", err) + } + said, _ := os.ReadFile(diag) + if _, statErr := os.Stat(readyFile); tc.mode == "broken-pipe-idle" && statErr != nil { + t.Errorf("helper never reached its write (ended with %v)", err) + } + ws, _ := cmd.ProcessState.Sys().(syscall.WaitStatus) + if tc.diesBy == 0 && err != nil { + t.Errorf("ended with %v, want success (helper said %q)", err, said) + } + if tc.diesBy != 0 && (!ws.Signaled() || ws.Signal() != tc.diesBy) { + t.Errorf("ended with %v, want death by %v (helper said %q)", err, tc.diesBy, said) + } + }) + } +} + +// command starts children in their own process group, so the terminal's +// SIGINT doesn't reach them. +func TestCommand_OwnProcessGroup(t *testing.T) { + cmd := command(t.Context(), "magick") + if cmd.SysProcAttr == nil || !cmd.SysProcAttr.Setpgid { + t.Errorf("SysProcAttr = %+v, want Setpgid", cmd.SysProcAttr) + } +} + +// The kill reaches the child's whole process group, not just the child. +func TestCommand_KillReachesProcessGroup(t *testing.T) { + ctx, stop, kill := newInterruptContext() + out, result := startHelper(ctx, t, kill, "group") + pidLine := readLine(t, out) + pid, err := strconv.Atoi(pidLine) + if err != nil { + t.Fatalf("helper said %q", pidLine) + } + + stop() + kill() + wantKilled(t, result) + for deadline := time.Now().Add(5 * time.Second); running(pid); time.Sleep(20 * time.Millisecond) { + if time.Now().After(deadline) { + _ = syscall.Kill(pid, syscall.SIGKILL) + t.Fatal("grandchild survived the kill") + } + } +} + +// The kill is SIGTERM, which ImageMagick catches to remove its temp files. +func TestCommand_KillIsSIGTERM(t *testing.T) { + ctx, stop, kill := newInterruptContext() + out, result := startHelper(ctx, t, kill, "term") + + stop() + kill() + if line := readLine(t, out); line != "term" { + t.Errorf("helper said %q, want term", line) + } + wantKilled(t, result) +} + +// Cancel maps a child that has already exited to os.ErrProcessDone, which +// exec doesn't report as an error. +func TestCommand_CancelAfterExit(t *testing.T) { + cmd := command(t.Context(), os.Args[0], "-test.run=^$") + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + if err := cmd.Cancel(); !errors.Is(err, os.ErrProcessDone) { + t.Errorf("Cancel = %v, want os.ErrProcessDone", err) + } +} + +// running reports whether pid exists and isn't a zombie waiting to be reaped. +func running(pid int) bool { + if syscall.Kill(pid, 0) != nil { + return false + } + stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return true // no /proc: trust kill + } + return !strings.Contains(string(stat), ") Z ") +} diff --git a/cbz-fix/command_windows.go b/cbz-fix/command_windows.go new file mode 100644 index 0000000..8ef716a --- /dev/null +++ b/cbz-fix/command_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +package main + +import ( + "os" + "os/exec" + "syscall" +) + +// createNoWindow is CREATE_NO_WINDOW, which syscall doesn't define. +const createNoWindow = 0x08000000 + +// isolate gives cmd a hidden console of its own, so Ctrl+C and Ctrl+Break at +// ours don't reach it. Cancelling cmd kills it, which can leave magick's +// spooled input in %TEMP%. +func isolate(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow} +} + +// quitSignals would end cbz-fix by default without reaching its isolated +// children, so it catches them and kills the children itself. Go reports a +// closed console, logoff or shutdown as SIGTERM. +var quitSignals = []os.Signal{syscall.SIGTERM} + +// pipeSignals is empty: a write to a broken pipe fails without a signal. +var pipeSignals []os.Signal diff --git a/cbz-fix/command_windows_test.go b/cbz-fix/command_windows_test.go new file mode 100644 index 0000000..bd5cca1 --- /dev/null +++ b/cbz-fix/command_windows_test.go @@ -0,0 +1,27 @@ +//go:build windows + +package main + +import ( + "os" + "slices" + "syscall" + "testing" +) + +// command starts children in a hidden console of their own, so no Ctrl+C or +// Ctrl+Break at ours reaches them. +func TestCommand_NoConsole(t *testing.T) { + attr := command(t.Context(), "magick").SysProcAttr + if attr == nil || attr.CreationFlags&createNoWindow == 0 { + t.Errorf("SysProcAttr = %+v, want CREATE_NO_WINDOW", attr) + } +} + +// A closed console, logoff or shutdown arrives as SIGTERM, which must be caught +// so cbz-fix kills magick before it ends. +func TestQuitSignals_SIGTERM(t *testing.T) { + if !slices.Contains(quitSignals, os.Signal(syscall.SIGTERM)) { + t.Errorf("quitSignals = %v, want SIGTERM", quitSignals) + } +} diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index 21bcb37..bfeebdc 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -3,6 +3,7 @@ package main import ( "archive/zip" "bytes" + "context" "encoding/binary" "errors" "fmt" @@ -11,8 +12,9 @@ import ( "strings" ) -// magickBin is the ImageMagick v7 CLI used to convert non-JPEG/PNG pages. -const magickBin = "magick" +// magickBin is the ImageMagick v7 CLI used to convert non-JPEG/PNG pages. It +// is a variable so tests can substitute a stand-in. +var magickBin = "magick" // convertImage converts arbitrary image bytes into a white-flattened PNG. // It is a package-level variable so tests can substitute a stub that does not @@ -29,7 +31,7 @@ var convertImage = magickToPNG // // The input format is named explicitly: left to guess, ImageMagick also reads // SVG and similar formats that can pull in local files or URLs. -func magickToPNG(src []byte) ([]byte, error) { +func magickToPNG(ctx context.Context, src []byte) ([]byte, error) { coder := imageCoder(src) if coder == "" { return nil, errUnrecognisedFormat @@ -37,12 +39,12 @@ func magickToPNG(src []byte) ([]byte, error) { if _, err := exec.LookPath(magickBin); err != nil { return nil, fmt.Errorf("ImageMagick %q not found on PATH: %w", magickBin, err) } - cmd := exec.Command(magickBin, magickArgs(coder)...) + cmd := command(ctx, magickBin, magickArgs(coder)...) cmd.Stdin = bytes.NewReader(src) var out, stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr - if err := cmd.Run(); err != nil { + if err := commandErr(ctx, cmd.Run()); err != nil { if msg := strings.TrimSpace(stderr.String()); msg != "" { return nil, fmt.Errorf("magick: %w: %s", err, msg) } diff --git a/cbz-fix/convert_coder_test.go b/cbz-fix/convert_coder_test.go index db55b78..71e5e0f 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestImageCoder(t *testing.T) { @@ -69,7 +70,7 @@ func TestProcessCBZ_RejectsSVGDisguisedAsPage(t *testing.T) { t.Fatal(err) } - _, err = processCBZ(path, false, false, false, true, false) + _, err = processCBZ(t.Context(), path, false, false, false, true, false) if err == nil || !strings.Contains(err.Error(), "unrecognised image format") { t.Fatalf("processCBZ error = %v, want unrecognised image format", err) } @@ -86,14 +87,14 @@ func TestMagickToPNG_RealFormats(t *testing.T) { } for _, format := range []string{"gif", "webp", "bmp", "tiff", "jxl", "avif", "heic", "jp2", "j2k"} { t.Run(format, func(t *testing.T) { - src, err := exec.Command(magickBin, "-size", "8x6", "xc:red", format+":-").Output() + src, err := exec.CommandContext(t.Context(), magickBin, "-size", "8x6", "xc:red", format+":-").Output() if err != nil || len(src) == 0 { t.Skipf("this ImageMagick can't encode %s: %v", format, err) } if got := imageCoder(src); got != format { t.Fatalf("imageCoder = %q, want %q", got, format) } - out, err := magickToPNG(src) + out, err := magickToPNG(t.Context(), src) if err != nil { t.Fatalf("magickToPNG: %v", err) } @@ -120,19 +121,72 @@ func TestMagickArgsNameCoder(t *testing.T) { // A dry run rejects an unconvertible page too, rather than previewing it as // converted to PNG. func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { - restore := convertImage - convertImage = func(src []byte) ([]byte, error) { - t.Error("convertImage called in dry-run") - return portrait, nil - } - defer func() { convertImage = restore }() + forbidConvert(t) path := makeCBZ(t, []zipEntry{ {"001.webp", []byte(``)}, {"002.png", portrait}, }) - _, err := processCBZ(path, true, false, false, true, false) + _, err := processCBZ(t.Context(), path, true, false, false, true, false) if err == nil || !strings.Contains(err.Error(), "unrecognised image format") { t.Fatalf("processCBZ dry-run error = %v, want unrecognised image format", err) } } + +// tinyGIF is a 1×1 GIF, a page magickToPNG accepts. +var tinyGIF = []byte("GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;") + +// magickToPNG lets magick finish after one interrupt. +func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { + if _, err := exec.LookPath(magickBin); err != nil { + t.Skip("ImageMagick not installed") + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + stop() + out, err := magickToPNG(ctx, tinyGIF) + if err != nil { + t.Fatalf("magickToPNG: %v", err) + } + if _, err := png.Decode(bytes.NewReader(out)); err != nil { + t.Errorf("output is not a PNG: %v", err) + } +} + +// magick outlives the first interrupt, the second kills it, and magickToPNG +// reports the interrupt rather than magick's exit status. A sleeping helper +// stands in for magick. +func TestMagickToPNG_KilledIsTheInterrupt(t *testing.T) { + bin := magickBin + magickBin = os.Args[0] + t.Cleanup(func() { magickBin = bin }) + readyFile := filepath.Join(t.TempDir(), "ready") + t.Setenv(helperEnv, "sleep") + t.Setenv(readyEnv, readyFile) + + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { + _, err := magickToPNG(ctx, tinyGIF) + result <- err + }() + for deadline := time.Now().Add(10 * time.Second); ; { + if _, err := os.Stat(readyFile); err == nil { + break + } + select { + case err := <-result: + t.Fatalf("magickToPNG ended before the helper was ready: %v", err) + case <-time.After(20 * time.Millisecond): + } + if time.Now().After(deadline) { + t.Fatal("helper never started") + } + } + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} diff --git a/cbz-fix/convert_test.go b/cbz-fix/convert_test.go index 7fe7d21..c539882 100644 --- a/cbz-fix/convert_test.go +++ b/cbz-fix/convert_test.go @@ -2,10 +2,28 @@ package main import ( "bytes" + "context" "image" "testing" ) +// stubConvert swaps convertImage for the test's duration. +func stubConvert(t *testing.T, f func(context.Context, []byte) ([]byte, error)) { + t.Helper() + restore := convertImage + convertImage = f + t.Cleanup(func() { convertImage = restore }) +} + +// forbidConvert fails the test if convertImage is called. +func forbidConvert(t *testing.T) { + t.Helper() + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + t.Error("convertImage called") + return portrait, nil + }) +} + // fakeNonImage returns bytes that are neither a JPEG nor a PNG (a stand-in for // a WebP/BMP/etc. page). Only the leading signature is inspected during // detection, so the payload can be arbitrary. @@ -37,13 +55,11 @@ func TestIsJPEGorPNG(t *testing.T) { // other than JPEG/PNG are converted to PNG (via the stubbed converter), // renamed with a .png extension, and that the originals are dropped. func TestProcessCBZ_ConvertsNonJPEGPNG(t *testing.T) { - restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + stubConvert(t, func(context.Context, []byte) ([]byte, error) { calls++ return portrait, nil // 100x200 PNG - } - defer func() { convertImage = restore }() + }) path := makeCBZ(t, []zipEntry{ {"001.webp", fakeNonImage()}, // cover, needs conversion @@ -51,7 +67,7 @@ func TestProcessCBZ_ConvertsNonJPEGPNG(t *testing.T) { {"003.png", portrait}, // already PNG, raw-copied }) - if _, err := processCBZ(path, false, false, false, true, false); err != nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err != nil { t.Fatalf("processCBZ: %v", err) } if calls != 2 { @@ -88,13 +104,11 @@ func TestProcessCBZ_ConvertsNonJPEGPNG(t *testing.T) { // TestProcessCBZ_ConvertDryRunSkipsMagick verifies that --dry-run detects pages // needing conversion but never invokes the converter and leaves the file alone. func TestProcessCBZ_ConvertDryRunSkipsMagick(t *testing.T) { - restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + stubConvert(t, func(context.Context, []byte) ([]byte, error) { calls++ return portrait, nil - } - defer func() { convertImage = restore }() + }) path := makeCBZ(t, []zipEntry{ {"001.webp", fakeNonImage()}, @@ -102,7 +116,7 @@ func TestProcessCBZ_ConvertDryRunSkipsMagick(t *testing.T) { }) before := readCBZNames(t, path) - skipped, err := processCBZ(path, true, false, false, true, false) // dry-run + skipped, err := processCBZ(t.Context(), path, true, false, false, true, false) // dry-run if err != nil { t.Fatalf("processCBZ dry-run: %v", err) } @@ -122,13 +136,11 @@ func TestProcessCBZ_ConvertDryRunSkipsMagick(t *testing.T) { // run). --force reprocesses it, converting the leftover page to PNG without // adding a second blank. func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { - restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + stubConvert(t, func(context.Context, []byte) ([]byte, error) { calls++ return portrait, nil - } - defer func() { convertImage = restore }() + }) path := makeCBZ(t, []zipEntry{ {"cover.png", portrait}, @@ -137,7 +149,7 @@ func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { }) // Without --force it would be skipped. - skipped, err := processCBZ(path, false, false, false, true, false) + skipped, err := processCBZ(t.Context(), path, false, false, false, true, false) if err != nil { t.Fatalf("processCBZ (no force): %v", err) } @@ -149,7 +161,7 @@ func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { } // With --force the leftover page is converted; no second blank is added. - skipped, err = processCBZ(path, false, false, false, true, true) + skipped, err = processCBZ(t.Context(), path, false, false, false, true, true) if err != nil { t.Fatalf("processCBZ (force): %v", err) } @@ -177,18 +189,16 @@ func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { // TestProcessCBZ_ConvertError propagates a converter failure as a fatal error // so the file is left untouched. func TestProcessCBZ_ConvertError(t *testing.T) { - restore := convertImage - convertImage = func(src []byte) ([]byte, error) { + stubConvert(t, func(context.Context, []byte) ([]byte, error) { return nil, errConvert - } - defer func() { convertImage = restore }() + }) path := makeCBZ(t, []zipEntry{ {"001.webp", fakeNonImage()}, {"002.png", portrait}, }) - if _, err := processCBZ(path, false, false, false, true, false); err == nil { + if _, err := processCBZ(t.Context(), path, false, false, false, true, false); err == nil { t.Fatal("expected error when conversion fails, got nil") } } diff --git a/cbz-fix/interrupt.go b/cbz-fix/interrupt.go new file mode 100644 index 0000000..19e748c --- /dev/null +++ b/cbz-fix/interrupt.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "os/signal" + "slices" +) + +// interruptContext returns a context the first Ctrl+C cancels, so run stops +// before the next conversion or file. The second also kills any conversion in +// progress (see command), and a third Ctrl+C quits at once. A quit signal does +// the first two at once, after which Ctrl+C quits at once. +// +// Only the interrupts get their default handling back, so once the children +// are killed further quit signals are absorbed: a closed terminal sends a +// second SIGHUP, which would otherwise end cbz-fix before its children were +// killed. From the first stop or quit, cbz-fix also catches pipeSignals, so a +// pipe reader that the same Ctrl+C ended can't end it. +func interruptContext() context.Context { + ctx, cancel, kill := newInterruptContext() + interrupts := make(chan os.Signal, 2) + quits := make(chan os.Signal, 1) + notify(interrupts, os.Interrupt) + notify(quits, quitSignals...) + stop := func() { + notify(make(chan os.Signal, 1), pipeSignals...) + cancel() + } + go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { signal.Stop(interrupts) }) + return ctx +} + +// notify relays sigs to c, except those the process started out ignoring, +// such as SIGHUP under nohup: Notify would stop them being ignored. Go reports +// that only for SIGHUP and SIGINT. +func notify(c chan<- os.Signal, sigs ...os.Signal) { + sigs = slices.DeleteFunc(slices.Clone(sigs), signal.Ignored) + if len(sigs) > 0 { // Notify with no signals relays them all + signal.Notify(c, sigs...) + } +} + +// newInterruptContext returns ctx, stop, which cancels it, and kill, which +// cancels the kill context ctx carries for command. +func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) { + killCtx, kill := context.WithCancel(context.Background()) + ctx, stop = context.WithCancel(context.WithValue(context.Background(), killKey{}, killCtx)) + return ctx, stop, kill +} + +// watchSignals calls stop on the first interrupt, and kill then restore on the +// second, so a third Ctrl+C gets the default handling. A quit calls all three. +// restore releases only the interrupts; quits stay caught. +func watchSignals(w io.Writer, interrupts, quits <-chan os.Signal, stop, kill, restore func()) { + select { + case <-interrupts: + stop() + fmt.Fprintln(w, "\ninterrupted: stopping before the next conversion or file (Ctrl+C again to stop sooner)") + case <-quits: + stop() + kill() + restore() + return + } + select { + case <-interrupts: + case <-quits: + } + kill() + restore() + fmt.Fprintln(w, "\ninterrupted: stopping any conversion in progress (Ctrl+C again to quit at once)") +} diff --git a/cbz-fix/interrupt_test.go b/cbz-fix/interrupt_test.go new file mode 100644 index 0000000..f551ab6 --- /dev/null +++ b/cbz-fix/interrupt_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "os" + "strings" + "testing" + "time" +) + +// watchSignalsOn runs watchSignals, sending it "interrupt" or "quit" for each +// of sends, and returns the stop/kill/restore calls it made and its notices. +func watchSignalsOn(t *testing.T, sends ...string) (calls, notices string) { + t.Helper() + interrupts, quits := make(chan os.Signal), make(chan os.Signal) + var w strings.Builder + var got []string + record := func(name string) func() { return func() { got = append(got, name) } } + done := make(chan struct{}) + go func() { + watchSignals(&w, interrupts, quits, record("stop"), record("kill"), record("restore")) + close(done) + }() + for _, s := range sends { + ch := interrupts + if s == "quit" { + ch = quits + } + select { + case ch <- os.Interrupt: + case <-done: + t.Fatalf("watchSignals returned before %s", s) + } + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("watchSignals still running") + } + return strings.Join(got, " "), w.String() +} + +func TestWatchSignals(t *testing.T) { + cases := []struct { + sends []string + wantCalls string + notices int + }{ + // kill comes before restore, so the kill is requested before a third + // Ctrl+C gets the default handling. + {[]string{"interrupt", "interrupt"}, "stop kill restore", 2}, + // A quit calls restore too, so a Ctrl+C after it quits at once. + {[]string{"quit"}, "stop kill restore", 0}, + {[]string{"interrupt", "quit"}, "stop kill restore", 2}, + } + for _, tc := range cases { + calls, notices := watchSignalsOn(t, tc.sends...) + if calls != tc.wantCalls { + t.Errorf("%v: calls %q, want %q", tc.sends, calls, tc.wantCalls) + } + if n := strings.Count(notices, "interrupted:"); n != tc.notices { + t.Errorf("%v: %d notices, want %d: %q", tc.sends, n, tc.notices, notices) + } + } +} + +// The first stop leaves the kill context running; kill cancels it. +func TestNewInterruptContext(t *testing.T) { + ctx, stop, kill := newInterruptContext() + killCtx := killContext(ctx) + stop() + if ctx.Err() == nil || killCtx.Err() != nil { + t.Fatalf("after stop: ctx %v, kill context %v; want ctx cancelled only", ctx.Err(), killCtx.Err()) + } + kill() + if killCtx.Err() == nil { + t.Error("kill left the kill context running") + } +} diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 6e5fc69..e3a1023 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -2,21 +2,36 @@ package main import ( "bufio" + "context" + "errors" "flag" "fmt" + "io" "os" "path/filepath" "strings" + "time" ) +// options are the command-line switches run acts on. +type options struct { + check, dryRun, verbose, noBlank, backup, force, updateCover bool +} + +// tally counts run's outcomes for the closing summary. +type tally struct { + needsFix, renamed, errCount int +} + func main() { - check := flag.Bool("check", false, "list files that need processing and exit 1 if any found") - dryRun := flag.Bool("dry-run", false, "preview changes without modifying files") - verbose := flag.Bool("verbose", false, "print each file rename") - noBlank := flag.Bool("no-blank", false, "skip blank page insertion") - backup := flag.Bool("backup", false, "create a .bak file before overwriting") - force := flag.Bool("force", false, "reprocess files that already look processed (adds the blank page only if one is missing)") - updateCover := flag.Bool("update-cover", false, "replace cover.* in each CBZ with a larger cover.jpg from the same directory") + var o options + flag.BoolVar(&o.check, "check", false, "list files that need processing and exit 1 if any found") + flag.BoolVar(&o.dryRun, "dry-run", false, "preview changes without modifying files") + flag.BoolVar(&o.verbose, "verbose", false, "print each file rename") + flag.BoolVar(&o.noBlank, "no-blank", false, "skip blank page insertion") + flag.BoolVar(&o.backup, "backup", false, "create a .bak file before overwriting") + flag.BoolVar(&o.force, "force", false, "reprocess files that already look processed (adds the blank page only if one is missing)") + flag.BoolVar(&o.updateCover, "update-cover", false, "replace cover.* in each CBZ with a larger cover.jpg from the same directory") flag.Parse() dir := "." @@ -24,26 +39,106 @@ func main() { dir = flag.Arg(0) } - // --check implies dry-run - impliedDryRun := *dryRun || *check + ctx := interruptContext() + t, err := run(ctx, dir, o, newPrompt(ctx, os.Stdin, os.Stdout)) + os.Exit(finish(os.Stdout, os.Stderr, o, t, err)) +} - // Build a prompt function once; used only in --update-cover mode. - stdinReader := bufio.NewReader(os.Stdin) - prompt := func(q string) (bool, error) { - fmt.Print(q) - line, err := stdinReader.ReadString('\n') - if err != nil { +// finish prints run's closing summary and returns the exit code. +func finish(stdout, stderr io.Writer, o options, t tally, err error) int { + switch { + case errors.Is(err, context.Canceled): + printSummary(stdout, "Interrupted", o, t) + return 130 + case err != nil: + fmt.Fprintf(stderr, "walk error: %v\n", err) + printSummary(stdout, "Stopped", o, t) + return 1 + } + printSummary(stdout, "Done", o, t) + if o.check && (t.needsFix > 0 || t.renamed > 0 || t.errCount > 0) { + return 1 + } + return 0 +} + +// eofGrace is how long a prompt that read EOF waits for the interrupt that +// may have caused it. +const eofGrace = 250 * time.Millisecond + +// newPrompt returns --update-cover's y/n prompt, writing questions to w and +// reading answers from r. Once ctx is cancelled it returns ctx's error without +// waiting for an answer. A read that ends in EOF first waits up to eofGrace +// for ctx to be cancelled. +func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bool, error) { + br := bufio.NewReader(r) + type answer struct { + line string + err error + } + return func(q string) (bool, error) { + if err := ctx.Err(); err != nil { return false, err } - s := strings.ToLower(strings.TrimSpace(line)) + fmt.Fprint(w, q) + // The read can't be cancelled, so it runs on its own; after an + // interrupt it is left blocked, and nothing reads stdin again. + c := make(chan answer, 1) + go func() { + line, err := br.ReadString('\n') + c <- answer{line, err} + }() + var a answer + select { + case <-ctx.Done(): + return false, ctx.Err() + case a = <-c: + } + // On Windows a Ctrl+C at the prompt ends the read with EOF, which can + // arrive before the signal does, so any EOF waits briefly for it. + if errors.Is(a.err, io.EOF) { + select { + case <-ctx.Done(): + case <-time.After(eofGrace): + } + } + if err := ctx.Err(); err != nil { + return false, err + } + if a.err != nil { + return false, fmt.Errorf("read answer from stdin: %w", a.err) + } + s := strings.ToLower(strings.TrimSpace(a.line)) return s == "y" || s == "yes", nil } +} - var needsFix, renamed, errCount int +// printSummary writes the closing counts, headed by label. +func printSummary(w io.Writer, label string, o options, t tally) { + switch { + case o.check: + fmt.Fprintf(w, "\n%s — needs fixing: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + case o.dryRun: + fmt.Fprintf(w, "\n%s — would process: %d would rename: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + default: + fmt.Fprintf(w, "\n%s — processed: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + } +} + +// run processes every .cbz under dir. Once ctx is cancelled it stops before +// the next page conversion or walk entry and returns ctx's error. +func run(ctx context.Context, dir string, o options, prompt func(q string) (bool, error)) (tally, error) { + // --check implies dry-run + impliedDryRun := o.dryRun || o.check + + var t tally err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { if err != nil { return err } + if ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } if d.IsDir() { if isHiddenDir(d.Name(), path) { return filepath.SkipDir @@ -60,7 +155,7 @@ func main() { if sniffErr != nil { fmt.Printf("%s\n", path) fmt.Fprintf(os.Stderr, " ERROR: %v\n", sniffErr) - errCount++ + t.errCount++ return nil } if mis != nil { @@ -68,63 +163,58 @@ func main() { newPath := strings.TrimSuffix(path, filepath.Ext(path)) + mis.correctExt if impliedDryRun { fmt.Printf(" is a %s archive, not a zip; would rename to %s (not processed)\n", mis.format, filepath.Base(newPath)) - renamed++ + t.renamed++ return nil } if _, statErr := os.Stat(newPath); statErr == nil { fmt.Fprintf(os.Stderr, " ERROR: is a %s archive but %s already exists; leaving as-is\n", mis.format, filepath.Base(newPath)) - errCount++ + t.errCount++ return nil } if renErr := os.Rename(path, newPath); renErr != nil { fmt.Fprintf(os.Stderr, " ERROR: rename to %s: %v\n", filepath.Base(newPath), renErr) - errCount++ + t.errCount++ return nil } fmt.Printf(" is a %s archive, not a zip; renamed to %s (not processed)\n", mis.format, filepath.Base(newPath)) - renamed++ + t.renamed++ return nil } - if !*check { + if !o.check { fmt.Printf("%s\n", path) } var skipped bool var processErr error - if *updateCover { - skipped, processErr = updateCoverCBZ(path, impliedDryRun, *verbose, !*backup, prompt) + if o.updateCover { + skipped, processErr = updateCoverCBZ(path, impliedDryRun, o.verbose, !o.backup, prompt) } else { - skipped, processErr = processCBZ(path, impliedDryRun, *verbose, *noBlank, !*backup, *force) + skipped, processErr = processCBZ(ctx, path, impliedDryRun, o.verbose, o.noBlank, !o.backup, o.force) } if processErr != nil { - if *check { + // A file the interrupt stopped part-way has not failed: it is left as it was. + if errors.Is(processErr, context.Canceled) { + if !o.check { + fmt.Println(" interrupted; left unchanged") + } + return processErr + } + if o.check { fmt.Printf("%s\n", path) } fmt.Fprintf(os.Stderr, " ERROR: %v\n", processErr) - errCount++ + t.errCount++ } else if !skipped { - needsFix++ - if *check { + t.needsFix++ + if o.check { fmt.Printf("%s\n", path) } } return nil }) - if err != nil { - fmt.Fprintf(os.Stderr, "walk error: %v\n", err) - os.Exit(1) - } - - switch { - case *check: - fmt.Printf("\nDone — needs fixing: %d renamed: %d errors: %d\n", needsFix, renamed, errCount) - if needsFix > 0 || renamed > 0 || errCount > 0 { - os.Exit(1) - } - case *dryRun: - fmt.Printf("\nDone — would process: %d would rename: %d errors: %d\n", needsFix, renamed, errCount) - default: - fmt.Printf("\nDone — processed: %d renamed: %d errors: %d\n", needsFix, renamed, errCount) + if err == nil { // a cancel after the last walk entry's check + err = ctx.Err() } + return t, err } diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go new file mode 100644 index 0000000..98527a1 --- /dev/null +++ b/cbz-fix/main_test.go @@ -0,0 +1,409 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// cbzDir puts a.cbz holding firstPages and b.cbz holding secondPages into one +// directory, returning the directory and the two paths in walk order. +func cbzDir(t *testing.T, firstPages, secondPages []zipEntry) (dir, first, second string) { + t.Helper() + dir = t.TempDir() + first, second = filepath.Join(dir, "a.cbz"), filepath.Join(dir, "b.cbz") + for path, pages := range map[string][]zipEntry{first: firstPages, second: secondPages} { + if err := os.Rename(makeCBZ(t, pages), path); err != nil { + t.Fatal(err) + } + } + return dir, first, second +} + +// onePage and twoPages need one and two conversions respectively. +var ( + onePage = []zipEntry{{"001.webp", fakeNonImage()}, {"002.png", portrait}} + twoPages = []zipEntry{{"001.webp", fakeNonImage()}, {"002.webp", fakeNonImage()}, {"003.png", portrait}} +) + +func readFile(t *testing.T, path string) []byte { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return b +} + +func noPrompt(string) (bool, error) { return false, nil } + +// cancelOnConvert returns a context and a converter that cancels it on its +// first call, then returns res and err; calls counts its calls. +func cancelOnConvert(t *testing.T, res []byte, err error) (ctx context.Context, calls *int) { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + calls = new(int) + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + *calls++ + cancel() + return res, err + }) + return ctx, calls +} + +// An interrupt stops at the next page: the file it is in is left as it was and +// not counted as an error, and no later file is touched. +func TestRun_InterruptStopsBetweenPages(t *testing.T) { + dir, first, second := cbzDir(t, twoPages, twoPages) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + ctx, calls := cancelOnConvert(t, portrait, nil) + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{}) { + t.Errorf("tally = %+v, want zero", got) + } + if *calls != 1 { + t.Errorf("convertImage called %d times, want 1", *calls) + } + if !bytes.Equal(readFile(t, first), firstBefore) { + t.Error("file stopped part-way was rewritten") + } + if !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("file after the interrupt was processed") + } +} + +// An interrupt during a file's last conversion lets that file finish, then +// stops the walk before the next one. The next one needs no conversion, so +// only the walk's own check can stop it. +func TestRun_InterruptStopsBeforeNextFile(t *testing.T) { + dir, first, second := cbzDir(t, onePage, []zipEntry{{"001.png", portrait}, {"002.png", portrait}}) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + ctx, _ := cancelOnConvert(t, portrait, nil) + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{needsFix: 1}) { + t.Errorf("tally = %+v, want needsFix 1", got) + } + if bytes.Equal(readFile(t, first), firstBefore) { + t.Error("file in progress at the interrupt was not finished") + } + if !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("file after the interrupt was processed") + } +} + +// An interrupt during the only file still reports the interrupt. +func TestRun_InterruptOnLastFile(t *testing.T) { + dir := filepath.Dir(makeCBZ(t, onePage)) + ctx, _ := cancelOnConvert(t, portrait, nil) + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{needsFix: 1}) { + t.Errorf("tally = %+v, want needsFix 1", got) + } +} + +// A real failure that coincides with the interrupt is still counted. +func TestRun_FailureDuringInterruptIsCounted(t *testing.T) { + dir, _, second := cbzDir(t, onePage, onePage) + secondBefore := readFile(t, second) + ctx, _ := cancelOnConvert(t, nil, errUnrecognisedFormat) + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{errCount: 1}) { + t.Errorf("tally = %+v, want errCount 1", got) + } + if !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("file after the interrupt was processed") + } +} + +// A conversion the second Ctrl+C killed fails with the interrupt, wrapped by +// magickToPNG and processCBZ: its comic is left unchanged and not counted. +func TestRun_KilledConversionIsTheInterrupt(t *testing.T) { + dir, first, second := cbzDir(t, onePage, onePage) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + ctx, _ := cancelOnConvert(t, nil, fmt.Errorf("magick: %w: killed", context.Canceled)) + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{}) { + t.Errorf("tally = %+v, want zero", got) + } + if !bytes.Equal(readFile(t, first), firstBefore) || !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("a comic was rewritten after the kill") + } +} + +// A context cancelled before the walk processes nothing. +func TestRun_CancelledBeforeStart(t *testing.T) { + dir, _, _ := cbzDir(t, onePage, onePage) + forbidConvert(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + got, err := run(ctx, dir, options{}, noPrompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{}) { + t.Errorf("tally = %+v, want zero", got) + } +} + +// --check and --dry-run count both files without converting or rewriting either. +func TestRun_CheckAndDryRunLeaveFiles(t *testing.T) { + for name, o := range map[string]options{"check": {check: true}, "dry-run": {dryRun: true}} { + t.Run(name, func(t *testing.T) { + dir, first, second := cbzDir(t, onePage, onePage) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + forbidConvert(t) + + got, err := run(t.Context(), dir, o, noPrompt) + if err != nil { + t.Fatalf("run: %v", err) + } + if got != (tally{needsFix: 2}) { + t.Errorf("tally = %+v, want needsFix 2", got) + } + if !bytes.Equal(readFile(t, first), firstBefore) || !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("a dry run rewrote a file") + } + }) + } +} + +// The same run with no interrupt converts both files, so the interrupt tests +// stop because of the cancel and not because of their stubs. +func TestRun_ProcessesEveryFile(t *testing.T) { + dir, _, _ := cbzDir(t, twoPages, twoPages) + stubConvert(t, func(context.Context, []byte) ([]byte, error) { return portrait, nil }) + + got, err := run(t.Context(), dir, options{}, noPrompt) + if err != nil { + t.Fatalf("run: %v", err) + } + if got != (tally{needsFix: 2}) { + t.Errorf("tally = %+v, want needsFix 2", got) + } +} + +// A .cbz that is really a RAR is renamed to .cbr. --check counts it as renamed +// but leaves it, and an existing .cbr leaves it in place, counted as an error. +func TestRun_RenamesMisnamedArchive(t *testing.T) { + rar := []byte("Rar!\x1a\x07\x00rest") + cases := []struct { + name string + o options + existing bool + want tally + wantExt string + }{ + {"rename", options{}, false, tally{renamed: 1}, ".cbr"}, + {"check", options{check: true}, false, tally{renamed: 1}, ".cbz"}, + {"target exists", options{}, true, tally{errCount: 1}, ".cbz"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "x.cbz"), rar, 0o644); err != nil { + t.Fatal(err) + } + if tc.existing { + if err := os.WriteFile(filepath.Join(dir, "x.cbr"), nil, 0o644); err != nil { + t.Fatal(err) + } + } + + got, err := run(t.Context(), dir, tc.o, noPrompt) + if err != nil { + t.Fatalf("run: %v", err) + } + if got != tc.want { + t.Errorf("tally = %+v, want %+v", got, tc.want) + } + if b, err := os.ReadFile(filepath.Join(dir, "x"+tc.wantExt)); err != nil || !bytes.Equal(b, rar) { + t.Errorf("archive not at x%s: %v", tc.wantExt, err) + } + }) + } +} + +func TestPrintSummary(t *testing.T) { + tl := tally{needsFix: 3, renamed: 1, errCount: 2} + cases := []struct { + label string + o options + want string + }{ + {"Done", options{}, "\nDone — processed: 3 renamed: 1 errors: 2\n"}, + {"Interrupted", options{dryRun: true}, "\nInterrupted — would process: 3 would rename: 1 errors: 2\n"}, + {"Done", options{check: true, dryRun: true}, "\nDone — needs fixing: 3 renamed: 1 errors: 2\n"}, + } + for _, tc := range cases { + var b strings.Builder + printSummary(&b, tc.label, tc.o, tl) + if b.String() != tc.want { + t.Errorf("printSummary(%q, %+v) = %q, want %q", tc.label, tc.o, b.String(), tc.want) + } + } +} + +// An interrupt at --update-cover's prompt leaves that comic as it was and +// prompts for no later one. +func TestRun_InterruptAtCoverPrompt(t *testing.T) { + // Each comic's cover is 100×200 and cover.jpg is 150×100, so both prompt. + covered := []zipEntry{{"cover.png", makePNG(100, 200)}, {"p001.png", makePNG(100, 200)}} + dir, first, second := cbzDir(t, covered, covered) + if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), makePNG(150, 100), 0o644); err != nil { + t.Fatal(err) + } + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + prompts := 0 + prompt := func(string) (bool, error) { + prompts++ + return false, context.Canceled + } + + got, err := run(t.Context(), dir, options{updateCover: true}, prompt) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run error = %v, want context.Canceled", err) + } + if got != (tally{}) { + t.Errorf("tally = %+v, want zero", got) + } + if prompts != 1 { + t.Errorf("prompted %d times, want 1", prompts) + } + if !bytes.Equal(readFile(t, first), firstBefore) || !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("a comic was rewritten after the interrupt") + } +} + +func TestFinish(t *testing.T) { + walkErr := errors.New("boom") + cases := []struct { + name string + o options + counts tally + err error + wantCode int + wantLabel string + }{ + {"done", options{}, tally{needsFix: 1, errCount: 1}, nil, 0, "Done"}, + {"check clean", options{check: true}, tally{}, nil, 0, "Done"}, + {"check needs fixing", options{check: true}, tally{needsFix: 1}, nil, 1, "Done"}, + {"check renamed", options{check: true}, tally{renamed: 1}, nil, 1, "Done"}, + {"check errors", options{check: true}, tally{errCount: 1}, nil, 1, "Done"}, + {"interrupted", options{}, tally{}, fmt.Errorf("walk: %w", context.Canceled), 130, "Interrupted"}, + {"walk error", options{}, tally{needsFix: 1}, walkErr, 1, "Stopped"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var stdout, stderr strings.Builder + if code := finish(&stdout, &stderr, tc.o, tc.counts, tc.err); code != tc.wantCode { + t.Errorf("exit code = %d, want %d", code, tc.wantCode) + } + if !strings.HasPrefix(stdout.String(), "\n"+tc.wantLabel+" — ") { + t.Errorf("summary = %q, want it headed %q", stdout.String(), tc.wantLabel) + } + if strings.Contains(stderr.String(), "walk error: boom") != (tc.wantLabel == "Stopped") { + t.Errorf("stderr = %q", stderr.String()) + } + }) + } +} + +func TestNewPrompt_Answers(t *testing.T) { + cases := []struct { + input string + want bool + }{{"y\n", true}, {" YES \r\n", true}, {"n\n", false}, {"\n", false}, {"maybe\n", false}} + for _, tc := range cases { + var w strings.Builder + got, err := newPrompt(t.Context(), strings.NewReader(tc.input), &w)("replace? ") + if err != nil || got != tc.want { + t.Errorf("answer %q = %v, %v; want %v", tc.input, got, err, tc.want) + } + if w.String() != "replace? " { + t.Errorf("question written as %q", w.String()) + } + } +} + +// EOF with no interrupt is a read error, wrapped so the message says what failed. +func TestNewPrompt_EOF(t *testing.T) { + _, err := newPrompt(t.Context(), strings.NewReader(""), io.Discard)("q") + if !errors.Is(err, io.EOF) || !strings.Contains(err.Error(), "read answer from stdin") { + t.Errorf("error = %v, want a wrapped io.EOF", err) + } +} + +// An interrupt stops a prompt that is waiting for an answer. +func TestNewPrompt_InterruptWhileWaiting(t *testing.T) { + r, w := io.Pipe() + t.Cleanup(func() { w.Close() }) + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(50*time.Millisecond, cancel) + + if _, err := newPrompt(ctx, r, io.Discard)("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } +} + +// An EOF that beats the interrupt it came from (Windows' Ctrl+C) is still +// reported as the interrupt. +func TestNewPrompt_EOFBeforeInterrupt(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(eofGrace/5, cancel) + + if _, err := newPrompt(ctx, strings.NewReader(""), io.Discard)("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } +} + +// A prompt after the interrupt asks nothing. +func TestNewPrompt_InterruptBeforeQuestion(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var w strings.Builder + if _, err := newPrompt(ctx, strings.NewReader("y\n"), &w)("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } + if w.Len() != 0 { + t.Errorf("question written as %q after the interrupt", w.String()) + } +} + +// A walk error is reported as one even after an interrupt. +func TestRun_WalkErrorAfterInterrupt(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := run(ctx, filepath.Join(t.TempDir(), "missing"), options{}, noPrompt); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("run error = %v, want the missing directory's", err) + } +} diff --git a/cbz-fix/processor.go b/cbz-fix/processor.go index d624141..82c6bb1 100644 --- a/cbz-fix/processor.go +++ b/cbz-fix/processor.go @@ -3,6 +3,7 @@ package main import ( "archive/zip" "bytes" + "context" "fmt" "hash/crc32" "image" @@ -55,7 +56,7 @@ type pageInfo struct { // (e.g. to convert leftover non-PNG pages). A blank page is still inserted for // those files unless one is already there, so a file first processed with // --no-blank can be fixed up later. -func processCBZ(path string, dryRun, verbose, noBlank, noBackup, force bool) (skipped bool, err error) { +func processCBZ(ctx context.Context, path string, dryRun, verbose, noBlank, noBackup, force bool) (skipped bool, err error) { zr, err := zip.OpenReader(path) if err != nil { return false, fmt.Errorf("open: %w", err) @@ -161,12 +162,17 @@ func processCBZ(path string, dryRun, verbose, noBlank, noBackup, force bool) (sk if dryRun { continue } + // An interrupt stops before the next conversion; a second one also kills magick. + if err := ctx.Err(); err != nil { + zr.Close() + return false, err + } data, err := readZipEntry(f) if err != nil { zr.Close() return false, fmt.Errorf("read %s: %w", f.Name, err) } - png, err := convertImage(data) + png, err := convertImage(ctx, data) if err != nil { zr.Close() return false, fmt.Errorf("convert %s to PNG: %w", f.Name, err)