Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 13 additions & 13 deletions cbz-fix/cbz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand All @@ -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)
}

Expand All @@ -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)
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand All @@ -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") {
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}

Expand Down
36 changes: 36 additions & 0 deletions cbz-fix/command.go
Original file line number Diff line number Diff line change
@@ -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
}
17 changes: 17 additions & 0 deletions cbz-fix/command_other.go
Original file line number Diff line number Diff line change
@@ -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
173 changes: 173 additions & 0 deletions cbz-fix/command_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
33 changes: 33 additions & 0 deletions cbz-fix/command_unix.go
Original file line number Diff line number Diff line change
@@ -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}
Loading