From 2ec46a6dd24b913ad1e3074a0af23c7619331923 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 13:50:41 +1300 Subject: [PATCH 01/10] fix(cbz-fix): stop after the current file on Ctrl+C and pass the context to magick --- README.md | 2 + cbz-fix/cbz_test.go | 26 +++---- cbz-fix/convert.go | 8 ++- cbz-fix/convert_coder_test.go | 11 +-- cbz-fix/convert_test.go | 19 +++--- cbz-fix/main.go | 123 +++++++++++++++++++++++----------- cbz-fix/main_test.go | 102 ++++++++++++++++++++++++++++ cbz-fix/processor.go | 5 +- 8 files changed, 226 insertions(+), 70 deletions(-) create mode 100644 cbz-fix/main_test.go diff --git a/README.md b/README.md index d0de362..f671c14 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,8 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Done — processed: 2 errors: 0 ``` +Ctrl+C stops after the current file, leaving a file it cut short as it was, and exits 130. A second Ctrl+C quits at once. + --- ## 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/convert.go b/cbz-fix/convert.go index 21bcb37..f19c7da 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" @@ -29,7 +30,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 +38,15 @@ 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 := exec.CommandContext(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 ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } 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..7db5cf4 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "context" "image/png" "os" "os/exec" @@ -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) } @@ -121,7 +122,7 @@ func TestMagickArgsNameCoder(t *testing.T) { // converted to PNG. func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { restore := convertImage - convertImage = func(src []byte) ([]byte, error) { + convertImage = func(_ context.Context, src []byte) ([]byte, error) { t.Error("convertImage called in dry-run") return portrait, nil } @@ -131,7 +132,7 @@ func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { {"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) } diff --git a/cbz-fix/convert_test.go b/cbz-fix/convert_test.go index 7fe7d21..930570c 100644 --- a/cbz-fix/convert_test.go +++ b/cbz-fix/convert_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "context" "image" "testing" ) @@ -39,7 +40,7 @@ func TestIsJPEGorPNG(t *testing.T) { func TestProcessCBZ_ConvertsNonJPEGPNG(t *testing.T) { restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + convertImage = func(_ context.Context, src []byte) ([]byte, error) { calls++ return portrait, nil // 100x200 PNG } @@ -51,7 +52,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 { @@ -90,7 +91,7 @@ func TestProcessCBZ_ConvertsNonJPEGPNG(t *testing.T) { func TestProcessCBZ_ConvertDryRunSkipsMagick(t *testing.T) { restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + convertImage = func(_ context.Context, src []byte) ([]byte, error) { calls++ return portrait, nil } @@ -102,7 +103,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) } @@ -124,7 +125,7 @@ func TestProcessCBZ_ConvertDryRunSkipsMagick(t *testing.T) { func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { restore := convertImage var calls int - convertImage = func(src []byte) ([]byte, error) { + convertImage = func(_ context.Context, src []byte) ([]byte, error) { calls++ return portrait, nil } @@ -137,7 +138,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 +150,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) } @@ -178,7 +179,7 @@ func TestProcessCBZ_ForceConvertsLeftoverNonPNG(t *testing.T) { // so the file is left untouched. func TestProcessCBZ_ConvertError(t *testing.T) { restore := convertImage - convertImage = func(src []byte) ([]byte, error) { + convertImage = func(_ context.Context, src []byte) ([]byte, error) { return nil, errConvert } defer func() { convertImage = restore }() @@ -188,7 +189,7 @@ func TestProcessCBZ_ConvertError(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.Fatal("expected error when conversion fails, got nil") } } diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 6e5fc69..1b1be9d 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -2,21 +2,35 @@ package main import ( "bufio" + "context" + "errors" "flag" "fmt" "os" + "os/signal" "path/filepath" "strings" ) +// 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,8 +38,7 @@ func main() { dir = flag.Arg(0) } - // --check implies dry-run - impliedDryRun := *dryRun || *check + ctx := interruptContext() // Build a prompt function once; used only in --update-cover mode. stdinReader := bufio.NewReader(os.Stdin) @@ -39,8 +52,51 @@ func main() { return s == "y" || s == "yes", nil } - var needsFix, renamed, errCount int + t, err := run(ctx, dir, o, prompt) + if errors.Is(err, context.Canceled) { + fmt.Fprintln(os.Stderr, "interrupted") + os.Exit(130) + } + if err != nil { + fmt.Fprintf(os.Stderr, "walk error: %v\n", err) + os.Exit(1) + } + + switch { + case o.check: + fmt.Printf("\nDone — needs fixing: %d renamed: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) + if t.needsFix > 0 || t.renamed > 0 || t.errCount > 0 { + os.Exit(1) + } + case o.dryRun: + fmt.Printf("\nDone — would process: %d would rename: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) + default: + fmt.Printf("\nDone — processed: %d renamed: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) + } +} + +// interruptContext lasts the life of the process. The first Ctrl+C cancels it, +// so run stops after the file it is on; a second kills the process as usual. +func interruptContext() context.Context { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + context.AfterFunc(ctx, func() { + stop() + fmt.Fprintln(os.Stderr, "\ninterrupted: stopping after the current file (Ctrl+C again to quit now)") + }) + return ctx +} + +// run processes every .cbz under dir. Once ctx is cancelled it processes no +// further files 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 ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } if err != nil { return err } @@ -60,7 +116,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 +124,52 @@ 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 conversion the interrupt cut short is not a failure of this file. + if errors.Is(processErr, context.Canceled) { + 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) - } + return t, err } diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go new file mode 100644 index 0000000..e0e68e6 --- /dev/null +++ b/cbz-fix/main_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "testing" +) + +// cbzDir puts two CBZs that each need a page converted into one directory, +// returning the directory and the two paths in walk order. +func cbzDir(t *testing.T) (dir, first, second string) { + t.Helper() + dir = t.TempDir() + for _, name := range []string{"a.cbz", "b.cbz"} { + src := makeCBZ(t, []zipEntry{{"001.webp", fakeNonImage()}, {"002.png", portrait}}) + if err := os.Rename(src, filepath.Join(dir, name)); err != nil { + t.Fatal(err) + } + } + return dir, filepath.Join(dir, "a.cbz"), filepath.Join(dir, "b.cbz") +} + +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 } + +// An interrupt during a conversion stops the run: the file it cut short is +// left as it was and not counted as an error, and no later file is touched. +func TestRun_InterruptStopsAfterCurrentFile(t *testing.T) { + dir, first, second := cbzDir(t) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + restore := convertImage + var calls int + convertImage = func(ctx context.Context, _ []byte) ([]byte, error) { + calls++ + cancel() + return nil, ctx.Err() + } + defer func() { convertImage = restore }() + + 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("interrupted file was rewritten") + } + if !bytes.Equal(readFile(t, second), secondBefore) { + t.Error("file after the interrupt was processed") + } +} + +// The same run with no interrupt converts both files, so the test above +// stops because of the cancel and not because of its stub. +func TestRun_ProcessesEveryFile(t *testing.T) { + dir, _, _ := cbzDir(t) + restore := convertImage + convertImage = func(context.Context, []byte) ([]byte, error) { return portrait, nil } + defer func() { convertImage = restore }() + + 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 real magick run under a cancelled context reports the cancel, which run +// relies on to tell an interrupt from a failed conversion. +func TestMagickToPNG_Cancelled(t *testing.T) { + if _, err := exec.LookPath(magickBin); err != nil { + t.Skip("ImageMagick not installed") + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + gif := []byte("GIF89a\x01\x00\x01\x00\x00\x00\x00;") + if _, err := magickToPNG(ctx, gif); !errors.Is(err, context.Canceled) { + t.Fatalf("magickToPNG error = %v, want context.Canceled", err) + } +} diff --git a/cbz-fix/processor.go b/cbz-fix/processor.go index d624141..417e998 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) @@ -166,7 +167,7 @@ func processCBZ(path string, dryRun, verbose, noBlank, noBackup, force bool) (sk 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) From c5c66fb4d8f57f35f6666c0d1621e1cfc52fd776 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 13:59:58 +1300 Subject: [PATCH 02/10] fix(cbz-fix): recognise an interrupt in run, keep Ctrl+C from magick, print the partial summary --- README.md | 2 +- cbz-fix/convert.go | 4 +- cbz-fix/main.go | 39 +++++++------ cbz-fix/main_test.go | 107 ++++++++++++++++++++++++++++++----- cbz-fix/procgroup_other.go | 14 +++++ cbz-fix/procgroup_windows.go | 14 +++++ 6 files changed, 144 insertions(+), 36 deletions(-) create mode 100644 cbz-fix/procgroup_other.go create mode 100644 cbz-fix/procgroup_windows.go diff --git a/README.md b/README.md index f671c14..2d28548 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Done — processed: 2 errors: 0 ``` -Ctrl+C stops after the current file, leaving a file it cut short as it was, and exits 130. A second Ctrl+C quits at once. +Ctrl+C stops the run before the next file, prints the summary so far and exits 130. A file whose page conversion it interrupts is left as it was. A second Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` beside the comic being written. --- diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index f19c7da..f659f03 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -39,14 +39,12 @@ func magickToPNG(ctx context.Context, src []byte) ([]byte, error) { return nil, fmt.Errorf("ImageMagick %q not found on PATH: %w", magickBin, err) } cmd := exec.CommandContext(ctx, magickBin, magickArgs(coder)...) + ownProcessGroup(cmd) cmd.Stdin = bytes.NewReader(src) var out, stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr if err := cmd.Run(); err != nil { - if ctxErr := ctx.Err(); ctxErr != nil { - return nil, ctxErr - } if msg := strings.TrimSpace(stderr.String()); msg != "" { return nil, fmt.Errorf("magick: %w: %s", err, msg) } diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 1b1be9d..175f796 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -54,7 +54,7 @@ func main() { t, err := run(ctx, dir, o, prompt) if errors.Is(err, context.Canceled) { - fmt.Fprintln(os.Stderr, "interrupted") + printSummary("Interrupted", o, t) os.Exit(130) } if err != nil { @@ -62,41 +62,43 @@ func main() { os.Exit(1) } + printSummary("Done", o, t) + if o.check && (t.needsFix > 0 || t.renamed > 0 || t.errCount > 0) { + os.Exit(1) + } +} + +func printSummary(label string, o options, t tally) { switch { case o.check: - fmt.Printf("\nDone — needs fixing: %d renamed: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) - if t.needsFix > 0 || t.renamed > 0 || t.errCount > 0 { - os.Exit(1) - } + fmt.Printf("\n%s — needs fixing: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) case o.dryRun: - fmt.Printf("\nDone — would process: %d would rename: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) + fmt.Printf("\n%s — would process: %d would rename: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) default: - fmt.Printf("\nDone — processed: %d renamed: %d errors: %d\n", t.needsFix, t.renamed, t.errCount) + fmt.Printf("\n%s — processed: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) } } // interruptContext lasts the life of the process. The first Ctrl+C cancels it, -// so run stops after the file it is on; a second kills the process as usual. +// which abandons a conversion in progress and stops run before the next file; +// a second Ctrl+C then kills the process. func interruptContext() context.Context { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) context.AfterFunc(ctx, func() { stop() - fmt.Fprintln(os.Stderr, "\ninterrupted: stopping after the current file (Ctrl+C again to quit now)") + fmt.Fprintln(os.Stderr, "\ninterrupted: stopping (Ctrl+C again to quit now)") }) return ctx } -// run processes every .cbz under dir. Once ctx is cancelled it processes no -// further files and returns ctx's error. +// run processes every .cbz under dir. ctx is checked before each .cbz and +// during page conversion; once it is cancelled, run 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 ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr - } if err != nil { return err } @@ -109,6 +111,9 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool if !strings.EqualFold(filepath.Ext(path), ".cbz") { return nil } + if ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } // A .cbz that is really a RAR/7z/ACE/tar archive can't be processed as // a zip. Rename it to the correct comic extension and move on. @@ -154,9 +159,9 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool skipped, processErr = processCBZ(ctx, path, impliedDryRun, o.verbose, o.noBlank, !o.backup, o.force) } if processErr != nil { - // A conversion the interrupt cut short is not a failure of this file. - if errors.Is(processErr, context.Canceled) { - return processErr + // A file the interrupt cut short has not failed: it is left as it was. + if ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr } if o.check { fmt.Printf("%s\n", path) diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go index e0e68e6..42e13e4 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -35,22 +35,28 @@ func readFile(t *testing.T, path string) []byte { func noPrompt(string) (bool, error) { return false, nil } -// An interrupt during a conversion stops the run: the file it cut short is -// left as it was and not counted as an error, and no later file is touched. -func TestRun_InterruptStopsAfterCurrentFile(t *testing.T) { +// 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 }) +} + +// An interrupt during a conversion abandons that file, leaving it as it was +// and not counting it as an error, and touches no later file. +func TestRun_InterruptAbandonsCurrentFile(t *testing.T) { dir, first, second := cbzDir(t) firstBefore, secondBefore := readFile(t, first), readFile(t, second) ctx, cancel := context.WithCancel(t.Context()) defer cancel() - restore := convertImage var calls int - convertImage = func(ctx context.Context, _ []byte) ([]byte, error) { + stubConvert(t, func(ctx context.Context, _ []byte) ([]byte, error) { calls++ cancel() return nil, ctx.Err() - } - defer func() { convertImage = restore }() + }) got, err := run(ctx, dir, options{}, noPrompt) if !errors.Is(err, context.Canceled) { @@ -70,13 +76,83 @@ func TestRun_InterruptStopsAfterCurrentFile(t *testing.T) { } } -// The same run with no interrupt converts both files, so the test above -// stops because of the cancel and not because of its stub. +// An interrupt that lands after the current file's last conversion lets that +// file finish, then stops the walk before the next one. +func TestRun_InterruptStopsBeforeNextFile(t *testing.T) { + dir, first, second := cbzDir(t) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + cancel() + return 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") + } +} + +// A context cancelled before the walk processes nothing. +func TestRun_CancelledBeforeStart(t *testing.T) { + dir, _, _ := cbzDir(t) + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + t.Error("convertImage called after the cancel") + return portrait, nil + }) + 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) + firstBefore, secondBefore := readFile(t, first), readFile(t, second) + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + t.Error("convertImage called in a dry run") + return portrait, nil + }) + + 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) - restore := convertImage - convertImage = func(context.Context, []byte) ([]byte, error) { return portrait, nil } - defer func() { convertImage = restore }() + stubConvert(t, func(context.Context, []byte) ([]byte, error) { return portrait, nil }) got, err := run(t.Context(), dir, options{}, noPrompt) if err != nil { @@ -87,15 +163,16 @@ func TestRun_ProcessesEveryFile(t *testing.T) { } } -// A real magick run under a cancelled context reports the cancel, which run -// relies on to tell an interrupt from a failed conversion. +// magickToPNG runs magick under ctx: an already-cancelled one starts nothing +// and reports the cancel, where exec.Command would run magick. func TestMagickToPNG_Cancelled(t *testing.T) { if _, err := exec.LookPath(magickBin); err != nil { t.Skip("ImageMagick not installed") } ctx, cancel := context.WithCancel(t.Context()) cancel() - gif := []byte("GIF89a\x01\x00\x01\x00\x00\x00\x00;") + // A valid 1x1 GIF, which magick would convert if it ran. + gif := []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;") if _, err := magickToPNG(ctx, gif); !errors.Is(err, context.Canceled) { t.Fatalf("magickToPNG error = %v, want context.Canceled", err) } diff --git a/cbz-fix/procgroup_other.go b/cbz-fix/procgroup_other.go new file mode 100644 index 0000000..8e7d286 --- /dev/null +++ b/cbz-fix/procgroup_other.go @@ -0,0 +1,14 @@ +//go:build !windows + +package main + +import ( + "os/exec" + "syscall" +) + +// ownProcessGroup keeps the terminal's SIGINT from reaching cmd, so only the +// cancelled context stops it. +func ownProcessGroup(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} +} diff --git a/cbz-fix/procgroup_windows.go b/cbz-fix/procgroup_windows.go new file mode 100644 index 0000000..4f5eba4 --- /dev/null +++ b/cbz-fix/procgroup_windows.go @@ -0,0 +1,14 @@ +//go:build windows + +package main + +import ( + "os/exec" + "syscall" +) + +// ownProcessGroup keeps the console's Ctrl+C from reaching cmd, so only the +// cancelled context stops it. +func ownProcessGroup(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP} +} From 5b1cebe2ebda08d3195ec22c54b9a19cef7cfc11 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 14:19:19 +1300 Subject: [PATCH 03/10] fix(cbz-fix): let magick finish and stop between pages, so an interrupt kills no child and hides no failure --- README.md | 4 +- cbz-fix/command_other.go | 18 ++++ cbz-fix/command_windows.go | 18 ++++ cbz-fix/convert.go | 3 +- cbz-fix/convert_coder_test.go | 6 +- cbz-fix/convert_test.go | 24 ++--- cbz-fix/main.go | 40 ++++--- cbz-fix/main_test.go | 189 +++++++++++++++++++++++++++------- cbz-fix/processor.go | 5 + cbz-fix/procgroup_other.go | 14 --- cbz-fix/procgroup_windows.go | 14 --- 11 files changed, 230 insertions(+), 105 deletions(-) create mode 100644 cbz-fix/command_other.go create mode 100644 cbz-fix/command_windows.go delete mode 100644 cbz-fix/procgroup_other.go delete mode 100644 cbz-fix/procgroup_windows.go diff --git a/README.md b/README.md index 2d28548..106ba06 100644 --- a/README.md +++ b/README.md @@ -141,10 +141,10 @@ 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 the run before the next file, prints the summary so far and exits 130. A file whose page conversion it interrupts is left as it was. A second Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` beside the comic being written. +Ctrl+C stops at the next page or file, prints the summary headed `Interrupted` and exits 130. A comic it stops part-way is left as it was. A second Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. --- diff --git a/cbz-fix/command_other.go b/cbz-fix/command_other.go new file mode 100644 index 0000000..67e4a49 --- /dev/null +++ b/cbz-fix/command_other.go @@ -0,0 +1,18 @@ +//go:build !windows + +package main + +import ( + "context" + "os/exec" + "syscall" +) + +// command runs name to completion: in its own process group the terminal's +// SIGINT doesn't reach it, and ctx's cancel doesn't kill it (a killed magick +// leaves its spooled input in the temp dir). Callers check ctx between commands. +func command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(context.WithoutCancel(ctx), name, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + return cmd +} diff --git a/cbz-fix/command_windows.go b/cbz-fix/command_windows.go new file mode 100644 index 0000000..3b61809 --- /dev/null +++ b/cbz-fix/command_windows.go @@ -0,0 +1,18 @@ +//go:build windows + +package main + +import ( + "context" + "os/exec" + "syscall" +) + +// command runs name to completion: in its own process group the console's +// Ctrl+C doesn't reach it, and ctx's cancel doesn't kill it (a killed magick +// leaves its spooled input in %TEMP%). Callers check ctx between commands. +func command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(context.WithoutCancel(ctx), name, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP} + return cmd +} diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index f659f03..b994571 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -38,8 +38,7 @@ func magickToPNG(ctx context.Context, 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.CommandContext(ctx, magickBin, magickArgs(coder)...) - ownProcessGroup(cmd) + cmd := command(ctx, magickBin, magickArgs(coder)...) cmd.Stdin = bytes.NewReader(src) var out, stderr bytes.Buffer cmd.Stdout = &out diff --git a/cbz-fix/convert_coder_test.go b/cbz-fix/convert_coder_test.go index 7db5cf4..ab5375c 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -121,12 +121,10 @@ 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(_ context.Context, src []byte) ([]byte, error) { + stubConvert(t, func(context.Context, []byte) ([]byte, error) { t.Error("convertImage called in dry-run") return portrait, nil - } - defer func() { convertImage = restore }() + }) path := makeCBZ(t, []zipEntry{ {"001.webp", []byte(``)}, diff --git a/cbz-fix/convert_test.go b/cbz-fix/convert_test.go index 930570c..d6d9e75 100644 --- a/cbz-fix/convert_test.go +++ b/cbz-fix/convert_test.go @@ -38,13 +38,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(_ context.Context, 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 @@ -89,13 +87,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(_ context.Context, 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()}, @@ -123,13 +119,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(_ context.Context, 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}, @@ -178,11 +172,9 @@ 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(_ context.Context, 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()}, diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 175f796..7431162 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -6,6 +6,7 @@ import ( "errors" "flag" "fmt" + "io" "os" "os/signal" "path/filepath" @@ -46,6 +47,10 @@ func main() { fmt.Print(q) line, err := stdinReader.ReadString('\n') if err != nil { + // On Windows a Ctrl+C at the prompt ends the read with EOF. + if ctxErr := ctx.Err(); ctxErr != nil { + return false, ctxErr + } return false, err } s := strings.ToLower(strings.TrimSpace(line)) @@ -54,7 +59,7 @@ func main() { t, err := run(ctx, dir, o, prompt) if errors.Is(err, context.Canceled) { - printSummary("Interrupted", o, t) + printSummary(os.Stdout, "Interrupted", o, t) os.Exit(130) } if err != nil { @@ -62,26 +67,26 @@ func main() { os.Exit(1) } - printSummary("Done", o, t) + printSummary(os.Stdout, "Done", o, t) if o.check && (t.needsFix > 0 || t.renamed > 0 || t.errCount > 0) { os.Exit(1) } } -func printSummary(label string, o options, t tally) { +// printSummary writes the closing counts, headed by label. +func printSummary(w io.Writer, label string, o options, t tally) { switch { case o.check: - fmt.Printf("\n%s — needs fixing: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + fmt.Fprintf(w, "\n%s — needs fixing: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) case o.dryRun: - fmt.Printf("\n%s — would process: %d would rename: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + fmt.Fprintf(w, "\n%s — would process: %d would rename: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) default: - fmt.Printf("\n%s — processed: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) + fmt.Fprintf(w, "\n%s — processed: %d renamed: %d errors: %d\n", label, t.needsFix, t.renamed, t.errCount) } } // interruptContext lasts the life of the process. The first Ctrl+C cancels it, -// which abandons a conversion in progress and stops run before the next file; -// a second Ctrl+C then kills the process. +// and run stops at the next page or file; a second Ctrl+C kills the process. func interruptContext() context.Context { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) context.AfterFunc(ctx, func() { @@ -91,14 +96,17 @@ func interruptContext() context.Context { return ctx } -// run processes every .cbz under dir. ctx is checked before each .cbz and -// during page conversion; once it is cancelled, run returns ctx's error. +// run processes every .cbz under dir. If ctx is cancelled it stops at the next +// walk entry or page, and returns ctx's error even when nothing was left. 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 ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } if err != nil { return err } @@ -111,9 +119,6 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool if !strings.EqualFold(filepath.Ext(path), ".cbz") { return nil } - if ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr - } // A .cbz that is really a RAR/7z/ACE/tar archive can't be processed as // a zip. Rename it to the correct comic extension and move on. @@ -159,9 +164,9 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool skipped, processErr = processCBZ(ctx, path, impliedDryRun, o.verbose, o.noBlank, !o.backup, o.force) } if processErr != nil { - // A file the interrupt cut short has not failed: it is left as it was. - if ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr + // A file the interrupt stopped part-way has not failed: it is left as it was. + if errors.Is(processErr, context.Canceled) { + return processErr } if o.check { fmt.Printf("%s\n", path) @@ -176,5 +181,8 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool } return nil }) + if err == nil { + err = ctx.Err() + } return t, err } diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go index 42e13e4..6584f26 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -4,26 +4,33 @@ import ( "bytes" "context" "errors" + "image/png" "os" "os/exec" "path/filepath" + "strings" "testing" ) -// cbzDir puts two CBZs that each need a page converted into one directory, +// cbzDir puts a.cbz and b.cbz, each holding pages, into one directory, // returning the directory and the two paths in walk order. -func cbzDir(t *testing.T) (dir, first, second string) { +func cbzDir(t *testing.T, pages []zipEntry) (dir, first, second string) { t.Helper() dir = t.TempDir() for _, name := range []string{"a.cbz", "b.cbz"} { - src := makeCBZ(t, []zipEntry{{"001.webp", fakeNonImage()}, {"002.png", portrait}}) - if err := os.Rename(src, filepath.Join(dir, name)); err != nil { + if err := os.Rename(makeCBZ(t, pages), filepath.Join(dir, name)); err != nil { t.Fatal(err) } } return dir, filepath.Join(dir, "a.cbz"), filepath.Join(dir, "b.cbz") } +// 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) @@ -43,20 +50,27 @@ func stubConvert(t *testing.T, f func(context.Context, []byte) ([]byte, error)) t.Cleanup(func() { convertImage = restore }) } -// An interrupt during a conversion abandons that file, leaving it as it was -// and not counting it as an error, and touches no later file. -func TestRun_InterruptAbandonsCurrentFile(t *testing.T) { - dir, first, second := cbzDir(t) - firstBefore, secondBefore := readFile(t, first), readFile(t, second) - +// 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()) - defer cancel() - var calls int - stubConvert(t, func(ctx context.Context, _ []byte) ([]byte, error) { - calls++ + t.Cleanup(cancel) + calls = new(int) + stubConvert(t, func(context.Context, []byte) ([]byte, error) { + *calls++ cancel() - return nil, ctx.Err() + 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) + 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) { @@ -65,29 +79,23 @@ func TestRun_InterruptAbandonsCurrentFile(t *testing.T) { if got != (tally{}) { t.Errorf("tally = %+v, want zero", got) } - if calls != 1 { - t.Errorf("convertImage called %d times, want 1", calls) + if *calls != 1 { + t.Errorf("convertImage called %d times, want 1", *calls) } if !bytes.Equal(readFile(t, first), firstBefore) { - t.Error("interrupted file was rewritten") + 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 that lands after the current file's last conversion lets that -// file finish, then stops the walk before the next one. +// An interrupt during a file's last conversion lets that file finish, then +// stops the walk before the next one. func TestRun_InterruptStopsBeforeNextFile(t *testing.T) { - dir, first, second := cbzDir(t) + dir, first, second := cbzDir(t, onePage) firstBefore, secondBefore := readFile(t, first), readFile(t, second) - - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - stubConvert(t, func(context.Context, []byte) ([]byte, error) { - cancel() - return portrait, nil - }) + ctx, _ := cancelOnConvert(t, portrait, nil) got, err := run(ctx, dir, options{}, noPrompt) if !errors.Is(err, context.Canceled) { @@ -104,9 +112,44 @@ func TestRun_InterruptStopsBeforeNextFile(t *testing.T) { } } +// An interrupt during the only file still reports the interrupt. +func TestRun_InterruptOnLastFile(t *testing.T) { + dir := t.TempDir() + if err := os.Rename(makeCBZ(t, onePage), filepath.Join(dir, "a.cbz")); err != nil { + t.Fatal(err) + } + 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) + 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 context cancelled before the walk processes nothing. func TestRun_CancelledBeforeStart(t *testing.T) { - dir, _, _ := cbzDir(t) + dir, _, _ := cbzDir(t, onePage) stubConvert(t, func(context.Context, []byte) ([]byte, error) { t.Error("convertImage called after the cancel") return portrait, nil @@ -127,7 +170,7 @@ func TestRun_CancelledBeforeStart(t *testing.T) { 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) + dir, first, second := cbzDir(t, onePage) firstBefore, secondBefore := readFile(t, first), readFile(t, second) stubConvert(t, func(context.Context, []byte) ([]byte, error) { t.Error("convertImage called in a dry run") @@ -151,7 +194,7 @@ func TestRun_CheckAndDryRunLeaveFiles(t *testing.T) { // 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) + dir, _, _ := cbzDir(t, twoPages) stubConvert(t, func(context.Context, []byte) ([]byte, error) { return portrait, nil }) got, err := run(t.Context(), dir, options{}, noPrompt) @@ -163,17 +206,89 @@ func TestRun_ProcessesEveryFile(t *testing.T) { } } -// magickToPNG runs magick under ctx: an already-cancelled one starts nothing -// and reports the cancel, where exec.Command would run magick. -func TestMagickToPNG_Cancelled(t *testing.T) { +// A .cbz that is really a RAR is renamed to .cbr, counted as renamed even in +// --check (which then exits 1), and left alone when the .cbr already exists. +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) + } + } +} + +// magickToPNG lets magick finish under a cancelled context, since a killed +// magick leaves its spooled input behind; run stops between pages instead. +func TestMagickToPNG_FinishesAfterCancel(t *testing.T) { if _, err := exec.LookPath(magickBin); err != nil { t.Skip("ImageMagick not installed") } ctx, cancel := context.WithCancel(t.Context()) cancel() - // A valid 1x1 GIF, which magick would convert if it ran. gif := []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;") - if _, err := magickToPNG(ctx, gif); !errors.Is(err, context.Canceled) { - t.Fatalf("magickToPNG error = %v, want context.Canceled", err) + out, err := magickToPNG(ctx, gif) + 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) + } +} + +// command puts the child in its own process group, so the console's Ctrl+C +// reaches only cbz-fix. +func TestCommand_OwnProcessGroup(t *testing.T) { + if command(t.Context(), "magick").SysProcAttr == nil { + t.Error("command left SysProcAttr unset") } } diff --git a/cbz-fix/processor.go b/cbz-fix/processor.go index 417e998..5fe8be1 100644 --- a/cbz-fix/processor.go +++ b/cbz-fix/processor.go @@ -162,6 +162,11 @@ func processCBZ(ctx context.Context, path string, dryRun, verbose, noBlank, noBa if dryRun { continue } + // An interrupt stops between pages; magick finishes the page it is on. + if err := ctx.Err(); err != nil { + zr.Close() + return false, err + } data, err := readZipEntry(f) if err != nil { zr.Close() diff --git a/cbz-fix/procgroup_other.go b/cbz-fix/procgroup_other.go deleted file mode 100644 index 8e7d286..0000000 --- a/cbz-fix/procgroup_other.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows - -package main - -import ( - "os/exec" - "syscall" -) - -// ownProcessGroup keeps the terminal's SIGINT from reaching cmd, so only the -// cancelled context stops it. -func ownProcessGroup(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} -} diff --git a/cbz-fix/procgroup_windows.go b/cbz-fix/procgroup_windows.go deleted file mode 100644 index 4f5eba4..0000000 --- a/cbz-fix/procgroup_windows.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build windows - -package main - -import ( - "os/exec" - "syscall" -) - -// ownProcessGroup keeps the console's Ctrl+C from reaching cmd, so only the -// cancelled context stops it. -func ownProcessGroup(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP} -} From af8867a6d3d38c16c20c33dce7c6a2aff8134b30 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 14:54:15 +1300 Subject: [PATCH 04/10] fix(cbz-fix): let a second Ctrl+C kill the conversion, keep Ctrl+Break from magick, make the prompt interruptible --- README.md | 2 +- cbz-fix/command.go | 51 ++++++++ cbz-fix/command_other.go | 18 +-- cbz-fix/command_unix.go | 24 ++++ cbz-fix/command_unix_test.go | 17 +++ cbz-fix/command_windows.go | 15 +-- cbz-fix/command_windows_test.go | 14 ++ cbz-fix/convert.go | 2 +- cbz-fix/main.go | 138 +++++++++++++++----- cbz-fix/main_test.go | 225 ++++++++++++++++++++++++++++++-- 10 files changed, 434 insertions(+), 72 deletions(-) create mode 100644 cbz-fix/command.go create mode 100644 cbz-fix/command_unix.go create mode 100644 cbz-fix/command_unix_test.go create mode 100644 cbz-fix/command_windows_test.go diff --git a/README.md b/README.md index 106ba06..96a0974 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Done — processed: 2 renamed: 0 errors: 0 ``` -Ctrl+C stops at the next page or file, prints the summary headed `Interrupted` and exits 130. A comic it stops part-way is left as it was. A second Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. +Ctrl+C stops at the next page 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 stops the page being converted. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. --- diff --git a/cbz-fix/command.go b/cbz-fix/command.go new file mode 100644 index 0000000..c2553e5 --- /dev/null +++ b/cbz-fix/command.go @@ -0,0 +1,51 @@ +package main + +import ( + "context" + "os/exec" + "time" +) + +// childKey keys the context that command's children run under. +type childKey struct{} + +// withChildContext returns ctx carrying child, the context command's children +// run under: cancelling ctx alone lets them finish, cancelling child kills them. +func withChildContext(ctx, child context.Context) context.Context { + return context.WithValue(ctx, childKey{}, child) +} + +// childContext is the context withChildContext stored in ctx, or one that is +// never cancelled. +func childContext(ctx context.Context) context.Context { + if c, ok := ctx.Value(childKey{}).(context.Context); ok { + return c + } + return context.WithoutCancel(ctx) +} + +// childWaitDelay bounds Wait on a killed child whose pipes a grandchild holds. +const childWaitDelay = 5 * time.Second + +// command returns a Cmd for name that the console's Ctrl+C doesn't reach +// (isolate). It runs to completion unless ctx's child context is cancelled, +// which a second Ctrl+C does (interruptContext): a killed magick can leave its +// spooled input in the temp dir, so the first Ctrl+C lets it finish. +func command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(childContext(ctx), name, args...) + cmd.WaitDelay = childWaitDelay + isolate(cmd) + return cmd +} + +// runCommand runs cmd. A failure once ctx's child context is cancelled reports +// that context's error, since the child's exit status is then the kill's. +func runCommand(ctx context.Context, cmd *exec.Cmd) error { + err := cmd.Run() + if err != nil { + if ctxErr := childContext(ctx).Err(); ctxErr != nil { + return ctxErr + } + } + return err +} diff --git a/cbz-fix/command_other.go b/cbz-fix/command_other.go index 67e4a49..8c2f6ba 100644 --- a/cbz-fix/command_other.go +++ b/cbz-fix/command_other.go @@ -1,18 +1,8 @@ -//go:build !windows +//go:build !unix && !windows package main -import ( - "context" - "os/exec" - "syscall" -) +import "os/exec" -// command runs name to completion: in its own process group the terminal's -// SIGINT doesn't reach it, and ctx's cancel doesn't kill it (a killed magick -// leaves its spooled input in the temp dir). Callers check ctx between commands. -func command(ctx context.Context, name string, args ...string) *exec.Cmd { - cmd := exec.CommandContext(context.WithoutCancel(ctx), name, args...) - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - return cmd -} +// isolate does nothing where there are no process groups. +func isolate(*exec.Cmd) {} diff --git a/cbz-fix/command_unix.go b/cbz-fix/command_unix.go new file mode 100644 index 0000000..d97f83f --- /dev/null +++ b/cbz-fix/command_unix.go @@ -0,0 +1,24 @@ +//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; WaitDelay then kills it. +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 + } +} diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go new file mode 100644 index 0000000..bc9430e --- /dev/null +++ b/cbz-fix/command_unix_test.go @@ -0,0 +1,17 @@ +//go:build unix + +package main + +import "testing" + +// command starts children in their own process group, so the terminal's +// SIGINT doesn't reach them, and cancels them by signalling that group. +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) + } + if cmd.Cancel == nil { + t.Error("Cancel unset: a cancel would kill only the group leader") + } +} diff --git a/cbz-fix/command_windows.go b/cbz-fix/command_windows.go index 3b61809..9eb0332 100644 --- a/cbz-fix/command_windows.go +++ b/cbz-fix/command_windows.go @@ -3,16 +3,15 @@ package main import ( - "context" "os/exec" "syscall" ) -// command runs name to completion: in its own process group the console's -// Ctrl+C doesn't reach it, and ctx's cancel doesn't kill it (a killed magick -// leaves its spooled input in %TEMP%). Callers check ctx between commands. -func command(ctx context.Context, name string, args ...string) *exec.Cmd { - cmd := exec.CommandContext(context.WithoutCancel(ctx), name, args...) - cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP} - return cmd +// createNoWindow is CREATE_NO_WINDOW, which syscall doesn't define. +const createNoWindow = 0x08000000 + +// isolate starts cmd without a console, so neither Ctrl+C nor Ctrl+Break at +// the console reaches it (its stdio are pipes). Cancelling cmd kills it. +func isolate(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow} } diff --git a/cbz-fix/command_windows_test.go b/cbz-fix/command_windows_test.go new file mode 100644 index 0000000..090c563 --- /dev/null +++ b/cbz-fix/command_windows_test.go @@ -0,0 +1,14 @@ +//go:build windows + +package main + +import "testing" + +// command starts children without a console, so no Ctrl+C or Ctrl+Break +// 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) + } +} diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index b994571..8fa7d7a 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -43,7 +43,7 @@ func magickToPNG(ctx context.Context, src []byte) ([]byte, error) { var out, stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr - if err := cmd.Run(); err != nil { + if err := runCommand(ctx, cmd); err != nil { if msg := strings.TrimSpace(stderr.String()); msg != "" { return nil, fmt.Errorf("magick: %w: %s", err, msg) } diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 7431162..35d7250 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -11,6 +11,7 @@ import ( "os/signal" "path/filepath" "strings" + "time" ) // options are the command-line switches run acts on. @@ -40,36 +41,73 @@ func main() { } 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 { - // On Windows a Ctrl+C at the prompt ends the read with EOF. - if ctxErr := ctx.Err(); ctxErr != nil { - return false, ctxErr - } - return false, err - } - s := strings.ToLower(strings.TrimSpace(line)) - return s == "y" || s == "yes", nil - } - - t, err := run(ctx, dir, o, prompt) - if errors.Is(err, context.Canceled) { - printSummary(os.Stdout, "Interrupted", o, t) - os.Exit(130) +// 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 } - if err != nil { - fmt.Fprintf(os.Stderr, "walk error: %v\n", err) - os.Exit(1) + printSummary(stdout, "Done", o, t) + if o.check && (t.needsFix > 0 || t.renamed > 0 || t.errCount > 0) { + return 1 } + return 0 +} - printSummary(os.Stdout, "Done", o, t) - if o.check && (t.needsFix > 0 || t.renamed > 0 || t.errCount > 0) { - os.Exit(1) +// 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. +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) { + 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: + } + if ctxErr := ctx.Err(); ctxErr != nil { + return false, ctxErr + } + if a.err != nil { + // On Windows a Ctrl+C at the prompt ends the read with EOF, which + // can arrive before the signal does. Waiting for it is best-effort. + if errors.Is(a.err, io.EOF) { + select { + case <-ctx.Done(): + return false, ctx.Err() + case <-time.After(eofGrace): + } + } + return false, fmt.Errorf("read answer from stdin: %w", a.err) + } + s := strings.ToLower(strings.TrimSpace(a.line)) + return s == "y" || s == "yes", nil } } @@ -85,19 +123,46 @@ func printSummary(w io.Writer, label string, o options, t tally) { } } -// interruptContext lasts the life of the process. The first Ctrl+C cancels it, -// and run stops at the next page or file; a second Ctrl+C kills the process. +// interruptContext returns a context the first Ctrl+C cancels, so run stops +// at the next page or file. The second also kills the conversion in progress +// (see command), and the third quits at once. func interruptContext() context.Context { - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) - context.AfterFunc(ctx, func() { - stop() - fmt.Fprintln(os.Stderr, "\ninterrupted: stopping (Ctrl+C again to quit now)") - }) + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt) + ctx, interrupt := newInterruptContext(os.Stderr) + go func() { + <-sig + interrupt() + <-sig + signal.Stop(sig) + interrupt() + }() return ctx } -// run processes every .cbz under dir. If ctx is cancelled it stops at the next -// walk entry or page, and returns ctx's error even when nothing was left. +// newInterruptContext returns ctx and interrupt. interrupt's first call +// cancels ctx, and its second cancels ctx's child context, telling w each time. +// It is not safe for concurrent use. +func newInterruptContext(w io.Writer) (ctx context.Context, interrupt func()) { + child, kill := context.WithCancel(context.Background()) + ctx, stop := context.WithCancel(withChildContext(context.Background(), child)) + calls := 0 + return ctx, func() { + calls++ + switch calls { + case 1: + fmt.Fprintln(w, "\ninterrupted: stopping after the current page (Ctrl+C again to stop sooner)") + stop() + case 2: + fmt.Fprintln(w, "\ninterrupted: killing the conversion in progress (Ctrl+C again to quit at once)") + kill() + } + } +} + +// run processes every .cbz under dir. Once ctx is cancelled it stops at the +// next page or walk entry and returns ctx's error, also when the cancel came +// during the last file. 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 @@ -166,6 +231,9 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool if processErr != nil { // 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 { diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go index 6584f26..77c9262 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -1,15 +1,19 @@ package main import ( + "bufio" "bytes" "context" "errors" + "fmt" "image/png" + "io" "os" "os/exec" "path/filepath" "strings" "testing" + "time" ) // cbzDir puts a.cbz and b.cbz, each holding pages, into one directory, @@ -91,9 +95,13 @@ func TestRun_InterruptStopsBetweenPages(t *testing.T) { } // An interrupt during a file's last conversion lets that file finish, then -// stops the walk before the next one. +// 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) + if err := os.Rename(makeCBZ(t, []zipEntry{{"001.png", portrait}, {"002.png", portrait}}), second); err != nil { + t.Fatal(err) + } firstBefore, secondBefore := readFile(t, first), readFile(t, second) ctx, _ := cancelOnConvert(t, portrait, nil) @@ -206,8 +214,8 @@ func TestRun_ProcessesEveryFile(t *testing.T) { } } -// A .cbz that is really a RAR is renamed to .cbr, counted as renamed even in -// --check (which then exits 1), and left alone when the .cbr already exists. +// 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 { @@ -267,14 +275,166 @@ func TestPrintSummary(t *testing.T) { } } -// magickToPNG lets magick finish under a cancelled context, since a killed -// magick leaves its spooled input behind; run stops between pages instead. -func TestMagickToPNG_FinishesAfterCancel(t *testing.T) { - if _, err := exec.LookPath(magickBin); err != nil { - t.Skip("ImageMagick not installed") +// 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. + dir, first, second := cbzDir(t, []zipEntry{{"cover.png", makePNG(100, 200)}, {"p001.png", makePNG(100, 200)}}) + 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 + t 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.t, 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) } +} + +// An answer that arrives after the interrupt is not acted on. +func TestNewPrompt_AnswerAfterInterrupt(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) cancel() + if yes, err := newPrompt(ctx, strings.NewReader("y\n"), io.Discard)("q"); yes || !errors.Is(err, context.Canceled) { + t.Errorf("got %v, %v; want false, context.Canceled", yes, err) + } +} + +// The first interrupt cancels ctx but not its children; the second kills them. +func TestNewInterruptContext(t *testing.T) { + var w strings.Builder + ctx, interrupt := newInterruptContext(&w) + child := childContext(ctx) + + interrupt() + if ctx.Err() == nil || child.Err() != nil { + t.Fatalf("after one interrupt: ctx %v, child %v; want ctx cancelled only", ctx.Err(), child.Err()) + } + if !strings.Contains(w.String(), "stopping after the current page") { + t.Errorf("first notice = %q", w.String()) + } + interrupt() + if child.Err() == nil { + t.Fatal("second interrupt left the child context running") + } + if !strings.Contains(w.String(), "killing the conversion in progress") { + t.Errorf("second notice = %q", w.String()) + } +} + +// Without an interrupt context, children are never cancelled. +func TestChildContext_DefaultNeverCancels(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := childContext(ctx).Err(); err != nil { + t.Errorf("childContext of a cancelled plain context: %v", err) + } +} + +// magickToPNG lets magick finish after one interrupt, since a killed magick +// leaves its spooled input behind; run stops between pages instead. +func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { + if _, err := exec.LookPath(magickBin); err != nil { + t.Skip("ImageMagick not installed") + } + ctx, interrupt := newInterruptContext(io.Discard) + interrupt() gif := []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;") out, err := magickToPNG(ctx, gif) if err != nil { @@ -285,10 +445,49 @@ func TestMagickToPNG_FinishesAfterCancel(t *testing.T) { } } -// command puts the child in its own process group, so the console's Ctrl+C -// reaches only cbz-fix. -func TestCommand_OwnProcessGroup(t *testing.T) { - if command(t.Context(), "magick").SysProcAttr == nil { - t.Error("command left SysProcAttr unset") +// TestHelperProcess is the child for the command tests, not a test: it says +// it is ready, then sleeps until killed. +func TestHelperProcess(*testing.T) { + if os.Getenv("CBZFIX_TEST_HELPER") != "sleep" { + return + } + fmt.Println("ready") + time.Sleep(time.Minute) + os.Exit(0) +} + +// A child outlives the first interrupt and is killed by the second, which +// runCommand reports as the interrupt. +func TestRunCommand_SecondInterruptKillsChild(t *testing.T) { + ctx, interrupt := newInterruptContext(io.Discard) + cmd := command(ctx, os.Args[0], "-test.run=^TestHelperProcess$") + cmd.Env = append(os.Environ(), "CBZFIX_TEST_HELPER=sleep") + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { r.Close() }) + cmd.Stdout = w + done := make(chan error, 1) + go func() { done <- runCommand(ctx, cmd) }() + if line, err := bufio.NewReader(r).ReadString('\n'); err != nil || strings.TrimSpace(line) != "ready" { + t.Fatalf("helper said %q, %v", line, err) + } + w.Close() + + interrupt() + select { + case err := <-done: + t.Fatalf("child ended after the first interrupt: %v", err) + case <-time.After(300 * time.Millisecond): + } + interrupt() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Errorf("runCommand = %v, want context.Canceled", err) + } + case <-time.After(childWaitDelay + 5*time.Second): + t.Fatal("child still running after the second interrupt") } } From ec64891556ee7b418c7308931d47465e3101cac9 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Mon, 30 Nov 2026 23:31:32 +1300 Subject: [PATCH 05/10] fix(cbz-fix): kill magick on a closed console or SIGTERM, report a walk error after Ctrl+C, and shape command for the ports --- README.md | 2 +- cbz-fix/command.go | 45 +++--- cbz-fix/command_other.go | 8 +- cbz-fix/command_unix.go | 6 +- cbz-fix/command_unix_test.go | 58 +++++++- cbz-fix/command_windows.go | 10 +- cbz-fix/command_windows_test.go | 4 +- cbz-fix/convert.go | 2 +- cbz-fix/convert_coder_test.go | 6 +- cbz-fix/main.go | 98 ++++++------- cbz-fix/main_test.go | 235 ++++++++++++++++++++++---------- cbz-fix/processor.go | 2 +- 12 files changed, 315 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index 96a0974..f252776 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Done — processed: 2 renamed: 0 errors: 0 ``` -Ctrl+C stops at the next page 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 stops the page being converted. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. +Ctrl+C stops at the next page 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 stops the page being converted, as closing the terminal or SIGTERM does at once. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. --- diff --git a/cbz-fix/command.go b/cbz-fix/command.go index c2553e5..23d1aea 100644 --- a/cbz-fix/command.go +++ b/cbz-fix/command.go @@ -3,49 +3,38 @@ package main import ( "context" "os/exec" - "time" ) -// childKey keys the context that command's children run under. -type childKey struct{} +// killKey keys the context that kills command's processes. +type killKey struct{} -// withChildContext returns ctx carrying child, the context command's children -// run under: cancelling ctx alone lets them finish, cancelling child kills them. -func withChildContext(ctx, child context.Context) context.Context { - return context.WithValue(ctx, childKey{}, child) +// withKill returns ctx carrying kill: cancelling ctx alone lets command's +// processes finish, and cancelling kill kills them. +func withKill(ctx, kill context.Context) context.Context { + return context.WithValue(ctx, killKey{}, kill) } -// childContext is the context withChildContext stored in ctx, or one that is -// never cancelled. -func childContext(ctx context.Context) context.Context { - if c, ok := ctx.Value(childKey{}).(context.Context); ok { - return c +// killContext is the context withKill stored in ctx, 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) } -// childWaitDelay bounds Wait on a killed child whose pipes a grandchild holds. -const childWaitDelay = 5 * time.Second - // command returns a Cmd for name that the console's Ctrl+C doesn't reach -// (isolate). It runs to completion unless ctx's child context is cancelled, -// which a second Ctrl+C does (interruptContext): a killed magick can leave its -// spooled input in the temp dir, so the first Ctrl+C lets it finish. +// (isolate) and that only ctx's kill context kills. func command(ctx context.Context, name string, args ...string) *exec.Cmd { - cmd := exec.CommandContext(childContext(ctx), name, args...) - cmd.WaitDelay = childWaitDelay + cmd := exec.CommandContext(killContext(ctx), name, args...) isolate(cmd) return cmd } -// runCommand runs cmd. A failure once ctx's child context is cancelled reports -// that context's error, since the child's exit status is then the kill's. -func runCommand(ctx context.Context, cmd *exec.Cmd) error { - err := cmd.Run() - if err != nil { - if ctxErr := childContext(ctx).Err(); ctxErr != nil { - return ctxErr - } +// commandErr is err from running a command, or the kill context's error once +// that is cancelled, since the command's exit status is then the kill's. +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 index 8c2f6ba..f3b29a4 100644 --- a/cbz-fix/command_other.go +++ b/cbz-fix/command_other.go @@ -2,7 +2,13 @@ package main -import "os/exec" +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 diff --git a/cbz-fix/command_unix.go b/cbz-fix/command_unix.go index d97f83f..ac069b4 100644 --- a/cbz-fix/command_unix.go +++ b/cbz-fix/command_unix.go @@ -11,7 +11,7 @@ import ( // 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; WaitDelay then kills it. +// catches to remove its temp files. func isolate(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { @@ -22,3 +22,7 @@ func isolate(cmd *exec.Cmd) { return err } } + +// quitSignals end cbz-fix without reaching its isolated children: a hangup +// goes to the foreground group only. +var quitSignals = []os.Signal{syscall.SIGTERM, syscall.SIGHUP} diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go index bc9430e..3de42e6 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -2,16 +2,66 @@ package main -import "testing" +import ( + "context" + "errors" + "fmt" + "os" + "strconv" + "strings" + "syscall" + "testing" + "time" +) // command starts children in their own process group, so the terminal's -// SIGINT doesn't reach them, and cancels them by signalling that group. +// 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) } - if cmd.Cancel == nil { - t.Error("Cancel unset: a cancel would kill only the group leader") +} + +// 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) + } + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q", line) + } + + stop() + kill() + 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") + } + 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") + } + } +} + +// 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 index 9eb0332..ff30f2e 100644 --- a/cbz-fix/command_windows.go +++ b/cbz-fix/command_windows.go @@ -3,6 +3,7 @@ package main import ( + "os" "os/exec" "syscall" ) @@ -10,8 +11,13 @@ import ( // createNoWindow is CREATE_NO_WINDOW, which syscall doesn't define. const createNoWindow = 0x08000000 -// isolate starts cmd without a console, so neither Ctrl+C nor Ctrl+Break at -// the console reaches it (its stdio are pipes). Cancelling cmd kills it. +// 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 end cbz-fix without reaching its isolated children: Go reports +// a closed console, logoff or shutdown as SIGTERM. +var quitSignals = []os.Signal{syscall.SIGTERM} diff --git a/cbz-fix/command_windows_test.go b/cbz-fix/command_windows_test.go index 090c563..fffa373 100644 --- a/cbz-fix/command_windows_test.go +++ b/cbz-fix/command_windows_test.go @@ -4,8 +4,8 @@ package main import "testing" -// command starts children without a console, so no Ctrl+C or Ctrl+Break -// reaches them. +// 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 { diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index 8fa7d7a..65ee58c 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -43,7 +43,7 @@ func magickToPNG(ctx context.Context, src []byte) ([]byte, error) { var out, stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr - if err := runCommand(ctx, cmd); 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 ab5375c..8c467f5 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -2,7 +2,6 @@ package main import ( "bytes" - "context" "image/png" "os" "os/exec" @@ -121,10 +120,7 @@ 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) { - stubConvert(t, func(context.Context, []byte) ([]byte, error) { - t.Error("convertImage called in dry-run") - return portrait, nil - }) + forbidConvert(t) path := makeCBZ(t, []zipEntry{ {"001.webp", []byte(``)}, diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 35d7250..72b11ee 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -91,19 +91,18 @@ func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bo return false, ctx.Err() case a = <-c: } - if ctxErr := ctx.Err(); ctxErr != nil { - return false, ctxErr + // On Windows a Ctrl+C at the prompt ends the read with EOF, which can + // arrive before the signal does. Waiting for it is best-effort. + 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 { - // On Windows a Ctrl+C at the prompt ends the read with EOF, which - // can arrive before the signal does. Waiting for it is best-effort. - if errors.Is(a.err, io.EOF) { - select { - case <-ctx.Done(): - return false, ctx.Err() - case <-time.After(eofGrace): - } - } return false, fmt.Errorf("read answer from stdin: %w", a.err) } s := strings.ToLower(strings.TrimSpace(a.line)) @@ -124,57 +123,64 @@ func printSummary(w io.Writer, label string, o options, t tally) { } // interruptContext returns a context the first Ctrl+C cancels, so run stops -// at the next page or file. The second also kills the conversion in progress -// (see command), and the third quits at once. +// at the next page or file. The second also kills any conversion in progress +// (see command), and the third quits at once. A quit signal does the first +// two at once. func interruptContext() context.Context { - sig := make(chan os.Signal, 1) - signal.Notify(sig, os.Interrupt) - ctx, interrupt := newInterruptContext(os.Stderr) - go func() { - <-sig - interrupt() - <-sig - signal.Stop(sig) - interrupt() - }() + ctx, stop, kill := newInterruptContext() + interrupts := make(chan os.Signal, 2) + signal.Notify(interrupts, os.Interrupt) + quits := make(chan os.Signal, 1) + if len(quitSignals) > 0 { // Notify with no signals relays them all + signal.Notify(quits, quitSignals...) + } + go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { signal.Stop(interrupts) }) return ctx } -// newInterruptContext returns ctx and interrupt. interrupt's first call -// cancels ctx, and its second cancels ctx's child context, telling w each time. -// It is not safe for concurrent use. -func newInterruptContext(w io.Writer) (ctx context.Context, interrupt func()) { - child, kill := context.WithCancel(context.Background()) - ctx, stop := context.WithCancel(withChildContext(context.Background(), child)) - calls := 0 - return ctx, func() { - calls++ - switch calls { - case 1: - fmt.Fprintln(w, "\ninterrupted: stopping after the current page (Ctrl+C again to stop sooner)") - stop() - case 2: - fmt.Fprintln(w, "\ninterrupted: killing the conversion in progress (Ctrl+C again to quit at once)") - kill() - } +// newInterruptContext returns ctx, stop, which cancels it, and kill, which +// cancels its kill context. +func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) { + killCtx, kill := context.WithCancel(context.Background()) + ctx, stop = context.WithCancel(withKill(context.Background(), killCtx)) + return ctx, stop, kill +} + +// watchSignals calls stop on the first interrupt, and kill then restore on the +// second, so a third gets the default handling. A quit calls stop and kill. +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 page or file (Ctrl+C again to stop sooner)") + case <-quits: + stop() + kill() + return + } + select { + case <-interrupts: + case <-quits: } + kill() + restore() + fmt.Fprintln(w, "\ninterrupted: stopping any conversion in progress (Ctrl+C again to quit at once)") } // run processes every .cbz under dir. Once ctx is cancelled it stops at the -// next page or walk entry and returns ctx's error, also when the cancel came -// during the last file. +// next page 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 ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr - } if err != nil { return err } + if ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } if d.IsDir() { if isHiddenDir(d.Name(), path) { return filepath.SkipDir @@ -249,7 +255,7 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool } return nil }) - if err == nil { + if err == nil { // a cancel during the last file err = ctx.Err() } return t, err diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go index 77c9262..74855fb 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -8,6 +8,7 @@ import ( "fmt" "image/png" "io" + "io/fs" "os" "os/exec" "path/filepath" @@ -16,17 +17,18 @@ import ( "time" ) -// cbzDir puts a.cbz and b.cbz, each holding pages, into one directory, -// returning the directory and the two paths in walk order. -func cbzDir(t *testing.T, pages []zipEntry) (dir, first, second string) { +// 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() - for _, name := range []string{"a.cbz", "b.cbz"} { - if err := os.Rename(makeCBZ(t, pages), filepath.Join(dir, name)); err != nil { + 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, filepath.Join(dir, "a.cbz"), filepath.Join(dir, "b.cbz") + return dir, first, second } // onePage and twoPages need one and two conversions respectively. @@ -54,6 +56,15 @@ func stubConvert(t *testing.T, f func(context.Context, []byte) ([]byte, error)) 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 + }) +} + // 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) { @@ -72,7 +83,7 @@ func cancelOnConvert(t *testing.T, res []byte, err error) (ctx context.Context, // 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) + dir, first, second := cbzDir(t, twoPages, twoPages) firstBefore, secondBefore := readFile(t, first), readFile(t, second) ctx, calls := cancelOnConvert(t, portrait, nil) @@ -98,10 +109,7 @@ func TestRun_InterruptStopsBetweenPages(t *testing.T) { // 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) - if err := os.Rename(makeCBZ(t, []zipEntry{{"001.png", portrait}, {"002.png", portrait}}), second); err != nil { - t.Fatal(err) - } + 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) @@ -139,7 +147,7 @@ func TestRun_InterruptOnLastFile(t *testing.T) { // A real failure that coincides with the interrupt is still counted. func TestRun_FailureDuringInterruptIsCounted(t *testing.T) { - dir, _, second := cbzDir(t, onePage) + dir, _, second := cbzDir(t, onePage, onePage) secondBefore := readFile(t, second) ctx, _ := cancelOnConvert(t, nil, errUnrecognisedFormat) @@ -157,11 +165,8 @@ func TestRun_FailureDuringInterruptIsCounted(t *testing.T) { // A context cancelled before the walk processes nothing. func TestRun_CancelledBeforeStart(t *testing.T) { - dir, _, _ := cbzDir(t, onePage) - stubConvert(t, func(context.Context, []byte) ([]byte, error) { - t.Error("convertImage called after the cancel") - return portrait, nil - }) + dir, _, _ := cbzDir(t, onePage, onePage) + forbidConvert(t) ctx, cancel := context.WithCancel(t.Context()) cancel() @@ -178,12 +183,9 @@ func TestRun_CancelledBeforeStart(t *testing.T) { 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) + dir, first, second := cbzDir(t, onePage, onePage) firstBefore, secondBefore := readFile(t, first), readFile(t, second) - stubConvert(t, func(context.Context, []byte) ([]byte, error) { - t.Error("convertImage called in a dry run") - return portrait, nil - }) + forbidConvert(t) got, err := run(t.Context(), dir, o, noPrompt) if err != nil { @@ -202,7 +204,7 @@ func TestRun_CheckAndDryRunLeaveFiles(t *testing.T) { // 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) + dir, _, _ := cbzDir(t, twoPages, twoPages) stubConvert(t, func(context.Context, []byte) ([]byte, error) { return portrait, nil }) got, err := run(t.Context(), dir, options{}, noPrompt) @@ -279,7 +281,8 @@ func TestPrintSummary(t *testing.T) { // 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. - dir, first, second := cbzDir(t, []zipEntry{{"cover.png", makePNG(100, 200)}, {"p001.png", makePNG(100, 200)}}) + 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) } @@ -310,7 +313,7 @@ func TestFinish(t *testing.T) { cases := []struct { name string o options - t tally + counts tally err error wantCode int wantLabel string @@ -326,7 +329,7 @@ func TestFinish(t *testing.T) { 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.t, tc.err); code != tc.wantCode { + 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+" — ") { @@ -396,45 +399,101 @@ func TestNewPrompt_AnswerAfterInterrupt(t *testing.T) { } } -// The first interrupt cancels ctx but not its children; the second kills them. -func TestNewInterruptContext(t *testing.T) { +// 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) + } +} + +// 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 - ctx, interrupt := newInterruptContext(&w) - child := childContext(ctx) + 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() +} - interrupt() - if ctx.Err() == nil || child.Err() != nil { - t.Fatalf("after one interrupt: ctx %v, child %v; want ctx cancelled only", ctx.Err(), child.Err()) +func TestWatchSignals(t *testing.T) { + cases := []struct { + sends []string + wantCalls string + notices int + }{ + // kill comes before restore, so a third Ctrl+C can't quit with a child running. + {[]string{"interrupt", "interrupt"}, "stop kill restore", 2}, + {[]string{"quit"}, "stop kill", 0}, + {[]string{"interrupt", "quit"}, "stop kill restore", 2}, } - if !strings.Contains(w.String(), "stopping after the current page") { - t.Errorf("first notice = %q", w.String()) + 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) + } } - interrupt() - if child.Err() == nil { - t.Fatal("second interrupt left the child context running") +} + +// 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()) } - if !strings.Contains(w.String(), "killing the conversion in progress") { - t.Errorf("second notice = %q", w.String()) + kill() + if killCtx.Err() == nil { + t.Error("kill left the kill context running") } } -// Without an interrupt context, children are never cancelled. -func TestChildContext_DefaultNeverCancels(t *testing.T) { +// 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 := childContext(ctx).Err(); err != nil { - t.Errorf("childContext of a cancelled plain context: %v", err) + if err := killContext(ctx).Err(); err != nil { + t.Errorf("killContext of a cancelled plain context: %v", err) } } -// magickToPNG lets magick finish after one interrupt, since a killed magick -// leaves its spooled input behind; run stops between pages instead. +// magickToPNG lets magick finish after one interrupt; run stops between pages +// instead. func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { if _, err := exec.LookPath(magickBin); err != nil { t.Skip("ImageMagick not installed") } - ctx, interrupt := newInterruptContext(io.Discard) - interrupt() + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + stop() gif := []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;") out, err := magickToPNG(ctx, gif) if err != nil { @@ -445,10 +504,21 @@ func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { } } -// TestHelperProcess is the child for the command tests, not a test: it says -// it is ready, then sleeps until killed. -func TestHelperProcess(*testing.T) { - if os.Getenv("CBZFIX_TEST_HELPER") != "sleep" { +// TestHelperProcess is the child for the command tests, not a test. It says +// it is ready, then sleeps until killed. In "group" mode it first starts a +// sleeping grandchild in its process group and prints the grandchild's pid. +func TestHelperProcess(t *testing.T) { + switch os.Getenv("CBZFIX_TEST_HELPER") { + case "sleep": + case "group": + gc := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestHelperProcess$") + gc.Env = append(os.Environ(), "CBZFIX_TEST_HELPER=sleep") + if err := gc.Start(); err != nil { + fmt.Println("start grandchild:", err) + os.Exit(1) + } + fmt.Println(gc.Process.Pid) + default: return } fmt.Println("ready") @@ -456,38 +526,65 @@ func TestHelperProcess(*testing.T) { os.Exit(0) } -// A child outlives the first interrupt and is killed by the second, which -// runCommand reports as the interrupt. -func TestRunCommand_SecondInterruptKillsChild(t *testing.T) { - ctx, interrupt := newInterruptContext(io.Discard) +// startHelper runs TestHelperProcess in mode through command, returning its +// stdout and a channel that gets commandErr's verdict once it ends. Cleanup +// kills it, so a failed test leaves nothing running. +func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (*bufio.Reader, <-chan error) { + t.Helper() cmd := command(ctx, os.Args[0], "-test.run=^TestHelperProcess$") - cmd.Env = append(os.Environ(), "CBZFIX_TEST_HELPER=sleep") + cmd.Env = append(os.Environ(), "CBZFIX_TEST_HELPER="+mode) r, w, err := os.Pipe() if err != nil { t.Fatal(err) } - t.Cleanup(func() { r.Close() }) cmd.Stdout = w - done := make(chan error, 1) - go func() { done <- runCommand(ctx, cmd) }() - if line, err := bufio.NewReader(r).ReadString('\n'); err != nil || strings.TrimSpace(line) != "ready" { - t.Fatalf("helper said %q, %v", line, err) + 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() + }) + return bufio.NewReader(r), 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) +} + +// 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() + out, result := startHelper(ctx, t, kill, "sleep") + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q", line) } - w.Close() - interrupt() + stop() select { - case err := <-done: + case err := <-result: t.Fatalf("child ended after the first interrupt: %v", err) case <-time.After(300 * time.Millisecond): } - interrupt() + kill() select { - case err := <-done: + case err := <-result: if !errors.Is(err, context.Canceled) { - t.Errorf("runCommand = %v, want context.Canceled", err) + t.Errorf("commandErr = %v, want context.Canceled", err) } - case <-time.After(childWaitDelay + 5*time.Second): + case <-time.After(10 * time.Second): t.Fatal("child still running after the second interrupt") } } diff --git a/cbz-fix/processor.go b/cbz-fix/processor.go index 5fe8be1..7f218a9 100644 --- a/cbz-fix/processor.go +++ b/cbz-fix/processor.go @@ -162,7 +162,7 @@ func processCBZ(ctx context.Context, path string, dryRun, verbose, noBlank, noBa if dryRun { continue } - // An interrupt stops between pages; magick finishes the page it is on. + // An interrupt stops between pages; a second one also kills magick. if err := ctx.Err(); err != nil { zr.Close() return false, err From ac62ae2a3d02a03d3efd30766637b6c87bd3a585 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 17:34:40 +1300 Subject: [PATCH 06/10] fix(cbz-fix): keep nohup's ignored hangup, restore default signals after a quit, and split out the signal code for the ports --- README.md | 2 +- cbz-fix/command.go | 18 +-- cbz-fix/command_test.go | 152 +++++++++++++++++++++ cbz-fix/command_unix.go | 4 +- cbz-fix/command_unix_test.go | 75 ++++++++-- cbz-fix/convert.go | 2 +- cbz-fix/convert_coder_test.go | 54 ++++++++ cbz-fix/convert_test.go | 17 +++ cbz-fix/interrupt.go | 66 +++++++++ cbz-fix/interrupt_test.go | 78 +++++++++++ cbz-fix/main.go | 62 ++------- cbz-fix/main_test.go | 250 +++++++--------------------------- cbz-fix/processor.go | 2 +- 13 files changed, 503 insertions(+), 279 deletions(-) create mode 100644 cbz-fix/command_test.go create mode 100644 cbz-fix/interrupt.go create mode 100644 cbz-fix/interrupt_test.go diff --git a/README.md b/README.md index f252776..c411d0b 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s Done — processed: 2 renamed: 0 errors: 0 ``` -Ctrl+C stops at the next page 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 stops the page being converted, as closing the terminal or SIGTERM does at once. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. +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. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. --- diff --git a/cbz-fix/command.go b/cbz-fix/command.go index 23d1aea..ea86194 100644 --- a/cbz-fix/command.go +++ b/cbz-fix/command.go @@ -5,16 +5,11 @@ import ( "os/exec" ) -// killKey keys the context that kills command's processes. +// 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{} -// withKill returns ctx carrying kill: cancelling ctx alone lets command's -// processes finish, and cancelling kill kills them. -func withKill(ctx, kill context.Context) context.Context { - return context.WithValue(ctx, killKey{}, kill) -} - -// killContext is the context withKill stored in ctx, or one never cancelled. +// 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 @@ -22,8 +17,9 @@ func killContext(ctx context.Context) context.Context { return context.WithoutCancel(ctx) } -// command returns a Cmd for name that the console's Ctrl+C doesn't reach -// (isolate) and that only ctx's kill context kills. +// 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) @@ -31,7 +27,7 @@ func command(ctx context.Context, name string, args ...string) *exec.Cmd { } // commandErr is err from running a command, or the kill context's error once -// that is cancelled, since the command's exit status is then the kill's. +// 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 diff --git a/cbz-fix/command_test.go b/cbz-fix/command_test.go new file mode 100644 index 0000000..907ebd6 --- /dev/null +++ b/cbz-fix/command_test.go @@ -0,0 +1,152 @@ +package main + +import ( + "bufio" + "context" + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "strings" + "syscall" + "testing" + "time" +) + +// helperEnv names the helperModes entry a child started by these tests runs. +const helperEnv = "CBZFIX_TEST_HELPER" + +// 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. +var helperModes = map[string]func(){ + // sleep says it is ready, then sleeps for a minute or until killed. + "sleep": func() { ready(); time.Sleep(time.Minute) }, + // group starts a sleeping grandchild in its process group and prints the + // grandchild's pid, then sleeps. + "group": func() { + gc := exec.CommandContext(context.Background(), os.Args[0]) + gc.Env = append(os.Environ(), helperEnv+"=sleep") + if err := gc.Start(); err != nil { + fmt.Println("start grandchild:", err) + os.Exit(1) + } + fmt.Println(gc.Process.Pid) + ready() + time.Sleep(time.Minute) + }, + // term says "term" when it gets SIGTERM, then exits. + "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): + } + }, +} + +// ready prints "ready", and creates the file CBZFIX_TEST_READY names for a +// child whose stdout the test can't read. +func ready() { + fmt.Println("ready") + if path := os.Getenv("CBZFIX_TEST_READY"); path != "" { + if err := os.WriteFile(path, nil, 0o600); err != nil { + fmt.Println("write ready file:", err) + os.Exit(1) + } + } +} + +func TestMain(m *testing.M) { + if mode := os.Getenv(helperEnv); mode != "" { + run, ok := helperModes[mode] + if !ok { + fmt.Println("unknown helper mode", mode) + os.Exit(2) + } + run() + os.Exit(0) + } + os.Exit(m.Run()) +} + +// startHelper runs the helper mode through command, returning its stdout and +// a channel that gets commandErr's verdict once it ends. Cleanup kills it, so +// a failed test leaves nothing running. +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) + } + cmd.Stdout = w + 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() + }) + return bufio.NewReader(r), 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") + } +} + +// 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) + } +} + +// 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() + out, result := startHelper(ctx, t, kill, "sleep") + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q", line) + } + + stop() + select { + case err := <-result: + t.Fatalf("child ended after the first interrupt: %v", err) + case <-time.After(300 * time.Millisecond): + } + kill() + wantKilled(t, result) +} diff --git a/cbz-fix/command_unix.go b/cbz-fix/command_unix.go index ac069b4..653aa81 100644 --- a/cbz-fix/command_unix.go +++ b/cbz-fix/command_unix.go @@ -23,6 +23,6 @@ func isolate(cmd *exec.Cmd) { } } -// quitSignals end cbz-fix without reaching its isolated children: a hangup -// goes to the foreground group only. +// quitSignals end cbz-fix without reaching its isolated children, so it has to +// kill them itself. var quitSignals = []os.Signal{syscall.SIGTERM, syscall.SIGHUP} diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go index 3de42e6..594c9f1 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -3,10 +3,11 @@ package main import ( - "context" "errors" "fmt" "os" + "os/exec" + "os/signal" "strconv" "strings" "syscall" @@ -14,6 +15,42 @@ import ( "time" ) +func init() { + // hup and ignored-hup send themselves SIGHUP after interruptContext, the + // latter having ignored it first as nohup does, and say whether ctx ended. + helperModes["hup"] = func() { hangUp(false) } + helperModes["ignored-hup"] = func() { hangUp(true) } +} + +func hangUp(ignore bool) { + if ignore { + signal.Ignore(syscall.SIGHUP) + } + ctx := interruptContext() + if err := syscall.Kill(os.Getpid(), syscall.SIGHUP); err != nil { + fmt.Println("kill:", err) + return + } + select { + case <-ctx.Done(): + fmt.Println("stopped") + case <-time.After(500 * time.Millisecond): + fmt.Println("kept running") + } +} + +// A hangup stops cbz-fix, unless it was started ignoring hangups (nohup). +func TestInterruptContext_HangUp(t *testing.T) { + for mode, want := range map[string]string{"hup": "stopped", "ignored-hup": "kept running"} { + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+mode) + out, err := cmd.Output() + if got := strings.TrimSpace(string(out)); err != nil || got != want { + t.Errorf("%s: said %q (%v), want %q", mode, got, err, want) + } + } +} + // command starts children in their own process group, so the terminal's // SIGINT doesn't reach them. func TestCommand_OwnProcessGroup(t *testing.T) { @@ -38,14 +75,7 @@ func TestCommand_KillReachesProcessGroup(t *testing.T) { stop() kill() - 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") - } + 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) @@ -54,6 +84,33 @@ func TestCommand_KillReachesProcessGroup(t *testing.T) { } } +// 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") + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q", line) + } + + stop() + kill() + if line := readLine(t, out); line != "term" { + t.Errorf("helper said %q, want term", line) + } + wantKilled(t, result) +} + +// Cancelling a child that has already exited is not 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 { diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index 65ee58c..623f5b6 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -13,7 +13,7 @@ import ( ) // magickBin is the ImageMagick v7 CLI used to convert non-JPEG/PNG pages. -const magickBin = "magick" +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 diff --git a/cbz-fix/convert_coder_test.go b/cbz-fix/convert_coder_test.go index 8c467f5..9ce2f9b 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) { @@ -131,3 +132,56 @@ func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { 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; run stops before the +// next conversion instead. +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) + } +} + +// The second interrupt kills a running magick, 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("CBZFIX_TEST_READY", 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); ; time.Sleep(20 * time.Millisecond) { + if _, err := os.Stat(readyFile); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("helper never started") + } + } + + stop() + kill() + wantKilled(t, result) +} diff --git a/cbz-fix/convert_test.go b/cbz-fix/convert_test.go index d6d9e75..c539882 100644 --- a/cbz-fix/convert_test.go +++ b/cbz-fix/convert_test.go @@ -7,6 +7,23 @@ import ( "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. diff --git a/cbz-fix/interrupt.go b/cbz-fix/interrupt.go new file mode 100644 index 0000000..af9b9ec --- /dev/null +++ b/cbz-fix/interrupt.go @@ -0,0 +1,66 @@ +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 the third quits at once. A quit signal does the +// first two at once. +func interruptContext() context.Context { + ctx, stop, kill := newInterruptContext() + interrupts := make(chan os.Signal, 2) + quits := make(chan os.Signal, 1) + notify(interrupts, os.Interrupt) + notify(quits, quitSignals...) + go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { + signal.Stop(interrupts) + signal.Stop(quits) + }) + 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. +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 gets the default handling. A quit calls all three. +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..47e6ba5 --- /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}, + // After a quit, the next Ctrl+C or quit gets the default handling too. + {[]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 72b11ee..d3fce31 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -8,7 +8,6 @@ import ( "fmt" "io" "os" - "os/signal" "path/filepath" "strings" "time" @@ -76,7 +75,11 @@ func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bo line string err error } + eofSeen := false return func(q string) (bool, error) { + if err := ctx.Err(); err != nil { + return false, err + } 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. @@ -92,8 +95,10 @@ func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bo case a = <-c: } // On Windows a Ctrl+C at the prompt ends the read with EOF, which can - // arrive before the signal does. Waiting for it is best-effort. - if errors.Is(a.err, io.EOF) { + // arrive before the signal does. Waiting for it is best-effort, and + // only the first EOF waits: every later read hits EOF at once. + if errors.Is(a.err, io.EOF) && !eofSeen { + eofSeen = true select { case <-ctx.Done(): case <-time.After(eofGrace): @@ -122,53 +127,8 @@ func printSummary(w io.Writer, label string, o options, t tally) { } } -// interruptContext returns a context the first Ctrl+C cancels, so run stops -// at the next page or file. The second also kills any conversion in progress -// (see command), and the third quits at once. A quit signal does the first -// two at once. -func interruptContext() context.Context { - ctx, stop, kill := newInterruptContext() - interrupts := make(chan os.Signal, 2) - signal.Notify(interrupts, os.Interrupt) - quits := make(chan os.Signal, 1) - if len(quitSignals) > 0 { // Notify with no signals relays them all - signal.Notify(quits, quitSignals...) - } - go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { signal.Stop(interrupts) }) - return ctx -} - -// newInterruptContext returns ctx, stop, which cancels it, and kill, which -// cancels its kill context. -func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) { - killCtx, kill := context.WithCancel(context.Background()) - ctx, stop = context.WithCancel(withKill(context.Background(), killCtx)) - return ctx, stop, kill -} - -// watchSignals calls stop on the first interrupt, and kill then restore on the -// second, so a third gets the default handling. A quit calls stop and kill. -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 page or file (Ctrl+C again to stop sooner)") - case <-quits: - stop() - kill() - return - } - select { - case <-interrupts: - case <-quits: - } - kill() - restore() - fmt.Fprintln(w, "\ninterrupted: stopping any conversion in progress (Ctrl+C again to quit at once)") -} - -// run processes every .cbz under dir. Once ctx is cancelled it stops at the -// next page or walk entry and returns ctx's error. +// 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 @@ -255,7 +215,7 @@ func run(ctx context.Context, dir string, o options, prompt func(q string) (bool } return nil }) - if err == nil { // a cancel during the last file + 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 index 74855fb..14b580b 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -1,16 +1,13 @@ package main import ( - "bufio" "bytes" "context" "errors" "fmt" - "image/png" "io" "io/fs" "os" - "os/exec" "path/filepath" "strings" "testing" @@ -48,23 +45,6 @@ func readFile(t *testing.T, path string) []byte { func noPrompt(string) (bool, error) { return false, nil } -// 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 - }) -} - // 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) { @@ -130,10 +110,7 @@ func TestRun_InterruptStopsBeforeNextFile(t *testing.T) { // An interrupt during the only file still reports the interrupt. func TestRun_InterruptOnLastFile(t *testing.T) { - dir := t.TempDir() - if err := os.Rename(makeCBZ(t, onePage), filepath.Join(dir, "a.cbz")); err != nil { - t.Fatal(err) - } + dir := filepath.Dir(makeCBZ(t, onePage)) ctx, _ := cancelOnConvert(t, portrait, nil) got, err := run(ctx, dir, options{}, noPrompt) @@ -163,6 +140,25 @@ func TestRun_FailureDuringInterruptIsCounted(t *testing.T) { } } +// 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) @@ -390,201 +386,49 @@ func TestNewPrompt_EOFBeforeInterrupt(t *testing.T) { } } -// An answer that arrives after the interrupt is not acted on. -func TestNewPrompt_AnswerAfterInterrupt(t *testing.T) { +// A prompt after the interrupt asks nothing. +func TestNewPrompt_InterruptBeforeQuestion(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) cancel() - if yes, err := newPrompt(ctx, strings.NewReader("y\n"), io.Discard)("q"); yes || !errors.Is(err, context.Canceled) { - t.Errorf("got %v, %v; want false, context.Canceled", yes, err) - } -} - -// 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) - } -} - -// 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) - } + if _, err := newPrompt(ctx, strings.NewReader("y\n"), &w)("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) } - select { - case <-done: - case <-time.After(5 * time.Second): - t.Fatal("watchSignals still running") + if w.Len() != 0 { + t.Errorf("question written as %q after the interrupt", w.String()) } - return strings.Join(got, " "), w.String() } -func TestWatchSignals(t *testing.T) { - cases := []struct { - sends []string - wantCalls string - notices int - }{ - // kill comes before restore, so a third Ctrl+C can't quit with a child running. - {[]string{"interrupt", "interrupt"}, "stop kill restore", 2}, - {[]string{"quit"}, "stop kill", 0}, - {[]string{"interrupt", "quit"}, "stop kill restore", 2}, +// Only the first EOF waits for an interrupt: later prompts on a closed stdin +// fail at once. +func TestNewPrompt_OnlyFirstEOFWaits(t *testing.T) { + prompt := newPrompt(t.Context(), strings.NewReader(""), io.Discard) + if _, err := prompt("q"); !errors.Is(err, io.EOF) { + t.Fatalf("first error = %v, want io.EOF", err) } - 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) - } + start := time.Now() + if _, err := prompt("q"); !errors.Is(err, io.EOF) { + t.Fatalf("second error = %v, want io.EOF", err) } -} - -// 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") + if d := time.Since(start); d >= eofGrace { + t.Errorf("second EOF took %v, want under %v", d, eofGrace) } } -// Without an interrupt context, command's processes are never killed. -func TestKillContext_DefaultNeverCancels(t *testing.T) { +// An answer that arrives after the interrupt is not acted on. +func TestNewPrompt_AnswerAfterInterrupt(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) - } -} - -// magickToPNG lets magick finish after one interrupt; run stops between pages -// instead. -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() - gif := []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;") - out, err := magickToPNG(ctx, gif) - 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) - } -} - -// TestHelperProcess is the child for the command tests, not a test. It says -// it is ready, then sleeps until killed. In "group" mode it first starts a -// sleeping grandchild in its process group and prints the grandchild's pid. -func TestHelperProcess(t *testing.T) { - switch os.Getenv("CBZFIX_TEST_HELPER") { - case "sleep": - case "group": - gc := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestHelperProcess$") - gc.Env = append(os.Environ(), "CBZFIX_TEST_HELPER=sleep") - if err := gc.Start(); err != nil { - fmt.Println("start grandchild:", err) - os.Exit(1) - } - fmt.Println(gc.Process.Pid) - default: - return - } - fmt.Println("ready") - time.Sleep(time.Minute) - os.Exit(0) -} - -// startHelper runs TestHelperProcess in mode through command, returning its -// stdout and a channel that gets commandErr's verdict once it ends. Cleanup -// kills it, so a failed test leaves nothing running. -func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (*bufio.Reader, <-chan error) { - t.Helper() - cmd := command(ctx, os.Args[0], "-test.run=^TestHelperProcess$") - cmd.Env = append(os.Environ(), "CBZFIX_TEST_HELPER="+mode) - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - cmd.Stdout = w - 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() - }) - return bufio.NewReader(r), 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) + if yes, err := newPrompt(ctx, strings.NewReader("y\n"), io.Discard)("q"); yes || !errors.Is(err, context.Canceled) { + t.Errorf("got %v, %v; want false, context.Canceled", yes, err) } - return strings.TrimSpace(line) } -// 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() - out, result := startHelper(ctx, t, kill, "sleep") - if line := readLine(t, out); line != "ready" { - t.Fatalf("helper said %q", line) - } - - stop() - select { - case err := <-result: - t.Fatalf("child ended after the first interrupt: %v", err) - case <-time.After(300 * time.Millisecond): - } - kill() - 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 second interrupt") +// 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 7f218a9..82c6bb1 100644 --- a/cbz-fix/processor.go +++ b/cbz-fix/processor.go @@ -162,7 +162,7 @@ func processCBZ(ctx context.Context, path string, dryRun, verbose, noBlank, noBa if dryRun { continue } - // An interrupt stops between pages; a second one also kills magick. + // An interrupt stops before the next conversion; a second one also kills magick. if err := ctx.Err(); err != nil { zr.Close() return false, err From 886f1d4582b213c58fbb297b7604f73263bb7986 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 18:02:51 +1300 Subject: [PATCH 07/10] fix(cbz-fix): keep quit signals caught so a second hangup can't orphan magick, drop the EOF latch, and pin the signal wiring with real signals --- cbz-fix/command_test.go | 123 ++++++++++++++++----------- cbz-fix/command_unix_test.go | 154 ++++++++++++++++++++++++++++------ cbz-fix/convert.go | 3 +- cbz-fix/convert_coder_test.go | 20 +++-- cbz-fix/interrupt.go | 10 +-- cbz-fix/interrupt_test.go | 2 +- cbz-fix/main.go | 7 +- cbz-fix/main_test.go | 25 ------ 8 files changed, 222 insertions(+), 122 deletions(-) diff --git a/cbz-fix/command_test.go b/cbz-fix/command_test.go index 907ebd6..a03abc7 100644 --- a/cbz-fix/command_test.go +++ b/cbz-fix/command_test.go @@ -2,59 +2,38 @@ package main import ( "bufio" + "bytes" "context" "errors" "fmt" "os" - "os/exec" - "os/signal" "strings" - "syscall" "testing" "time" ) -// helperEnv names the helperModes entry a child started by these tests runs. -const helperEnv = "CBZFIX_TEST_HELPER" +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 says it is ready, then sleeps for a minute or until killed. + // sleep sleeps for a minute or until killed. "sleep": func() { ready(); time.Sleep(time.Minute) }, - // group starts a sleeping grandchild in its process group and prints the - // grandchild's pid, then sleeps. - "group": func() { - gc := exec.CommandContext(context.Background(), os.Args[0]) - gc.Env = append(os.Environ(), helperEnv+"=sleep") - if err := gc.Start(); err != nil { - fmt.Println("start grandchild:", err) - os.Exit(1) - } - fmt.Println(gc.Process.Pid) - ready() - time.Sleep(time.Minute) - }, - // term says "term" when it gets SIGTERM, then exits. - "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): - } - }, } -// ready prints "ready", and creates the file CBZFIX_TEST_READY names for a -// child whose stdout the test can't read. +// ready prints "ready", and creates the file readyEnv names, if any. func ready() { fmt.Println("ready") - if path := os.Getenv("CBZFIX_TEST_READY"); path != "" { + if path := os.Getenv(readyEnv); path != "" { if err := os.WriteFile(path, nil, 0o600); err != nil { - fmt.Println("write ready file:", err) + fmt.Fprintln(os.Stderr, "write ready file:", err) os.Exit(1) } } @@ -62,20 +41,21 @@ func ready() { func TestMain(m *testing.M) { if mode := os.Getenv(helperEnv); mode != "" { - run, ok := helperModes[mode] + helper, ok := helperModes[mode] if !ok { - fmt.Println("unknown helper mode", mode) + fmt.Fprintln(os.Stderr, "unknown helper mode", mode) os.Exit(2) } - run() + helper() os.Exit(0) } os.Exit(m.Run()) } -// startHelper runs the helper mode through command, returning its stdout and -// a channel that gets commandErr's verdict once it ends. Cleanup kills it, so -// a failed test leaves nothing running. +// 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]) @@ -84,7 +64,8 @@ func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (* if err != nil { t.Fatal(err) } - cmd.Stdout = w + var stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = w, &stderr result := make(chan error, 1) finished := make(chan struct{}) go func() { @@ -96,8 +77,15 @@ func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (* kill() <-finished r.Close() + if t.Failed() && stderr.Len() > 0 { + t.Logf("helper stderr:\n%s", stderr.String()) + } }) - return bufio.NewReader(r), result + 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. @@ -123,6 +111,16 @@ func wantKilled(t *testing.T, result <-chan error) { } } +// 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()) @@ -132,21 +130,44 @@ func TestKillContext_DefaultNeverCancels(t *testing.T) { } } +// 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() - out, result := startHelper(ctx, t, kill, "sleep") - if line := readLine(t, out); line != "ready" { - t.Fatalf("helper said %q", line) - } + _, result := startHelper(ctx, t, kill, "sleep") stop() - select { - case err := <-result: - t.Fatalf("child ended after the first interrupt: %v", err) - case <-time.After(300 * time.Millisecond): - } + wantRunning(t, result) kill() wantKilled(t, result) } diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go index 594c9f1..6514baa 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -3,6 +3,7 @@ package main import ( + "context" "errors" "fmt" "os" @@ -16,21 +17,95 @@ import ( ) func init() { - // hup and ignored-hup send themselves SIGHUP after interruptContext, the - // latter having ignored it first as nohup does, and say whether ctx ended. - helperModes["hup"] = func() { hangUp(false) } - helperModes["ignored-hup"] = func() { hangUp(true) } -} + // 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): + } + } -func hangUp(ignore bool) { - if ignore { + // 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() { + ctx := interruptContext() + raise(syscall.SIGHUP) + waitFor(killContext(ctx), "stopped and killed") + raise(syscall.SIGHUP) // a closed terminal's second hangup + time.Sleep(200 * time.Millisecond) + fmt.Println("absorbed") + interruptUntilDead() + } + // 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. + helperModes["ignored-int"] = func() { + signal.Ignore(syscall.SIGINT) + ctx := interruptContext() + raise(syscall.SIGWINCH) + sayStopped(ctx) + } +} + +func raise(sig syscall.Signal) { + if err := syscall.Kill(os.Getpid(), sig); err != nil { + fmt.Fprintln(os.Stderr, "kill:", err) + os.Exit(1) + } +} + +// 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): + fmt.Fprintln(os.Stderr, "timed out before:", done) + os.Exit(1) } - ctx := interruptContext() - if err := syscall.Kill(os.Getpid(), syscall.SIGHUP); err != nil { - fmt.Println("kill:", err) - return +} + +// 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") @@ -39,15 +114,45 @@ func hangUp(ignore bool) { } } -// A hangup stops cbz-fix, unless it was started ignoring hangups (nohup). -func TestInterruptContext_HangUp(t *testing.T) { - for mode, want := range map[string]string{"hup": "stopped", "ignored-hup": "kept running"} { - cmd := exec.CommandContext(t.Context(), os.Args[0]) - cmd.Env = append(os.Environ(), helperEnv+"="+mode) - out, err := cmd.Output() - if got := strings.TrimSpace(string(out)); err != nil || got != want { - t.Errorf("%s: said %q (%v), want %q", mode, got, err, want) - } +// The signal sequences interruptContext handles, run in a child that signals +// itself: three Ctrl+Cs (the third quits), a hangup (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}}, + {"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?), 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() + 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) + } + }) } } @@ -69,9 +174,6 @@ func TestCommand_KillReachesProcessGroup(t *testing.T) { if err != nil { t.Fatalf("helper said %q", pidLine) } - if line := readLine(t, out); line != "ready" { - t.Fatalf("helper said %q", line) - } stop() kill() @@ -88,9 +190,6 @@ func TestCommand_KillReachesProcessGroup(t *testing.T) { func TestCommand_KillIsSIGTERM(t *testing.T) { ctx, stop, kill := newInterruptContext() out, result := startHelper(ctx, t, kill, "term") - if line := readLine(t, out); line != "ready" { - t.Fatalf("helper said %q", line) - } stop() kill() @@ -100,7 +199,8 @@ func TestCommand_KillIsSIGTERM(t *testing.T) { wantKilled(t, result) } -// Cancelling a child that has already exited is not an error. +// 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 { diff --git a/cbz-fix/convert.go b/cbz-fix/convert.go index 623f5b6..bfeebdc 100644 --- a/cbz-fix/convert.go +++ b/cbz-fix/convert.go @@ -12,7 +12,8 @@ import ( "strings" ) -// magickBin is the ImageMagick v7 CLI used to convert non-JPEG/PNG pages. +// 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. diff --git a/cbz-fix/convert_coder_test.go b/cbz-fix/convert_coder_test.go index 9ce2f9b..3de446e 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -136,8 +136,8 @@ func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { // 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; run stops before the -// next conversion instead. +// magickToPNG lets magick finish after one interrupt; processCBZ stops before +// the next conversion instead. func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { if _, err := exec.LookPath(magickBin); err != nil { t.Skip("ImageMagick not installed") @@ -154,16 +154,16 @@ func TestMagickToPNG_FinishesAfterInterrupt(t *testing.T) { } } -// The second interrupt kills a running magick, and magickToPNG reports the -// interrupt rather than magick's exit status. A sleeping helper stands in -// for magick. +// 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("CBZFIX_TEST_READY", readyFile) + t.Setenv(readyEnv, readyFile) ctx, stop, kill := newInterruptContext() t.Cleanup(kill) @@ -172,16 +172,22 @@ func TestMagickToPNG_KilledIsTheInterrupt(t *testing.T) { _, err := magickToPNG(ctx, tinyGIF) result <- err }() - for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { + 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/interrupt.go b/cbz-fix/interrupt.go index af9b9ec..6f85a67 100644 --- a/cbz-fix/interrupt.go +++ b/cbz-fix/interrupt.go @@ -12,17 +12,17 @@ import ( // 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 the third quits at once. A quit signal does the -// first two at once. +// first two at once, after which Ctrl+C quits at once. +// +// Quit signals stay caught: a closed terminal sends a second SIGHUP, which +// would otherwise end cbz-fix before its children were killed. func interruptContext() context.Context { ctx, stop, kill := newInterruptContext() interrupts := make(chan os.Signal, 2) quits := make(chan os.Signal, 1) notify(interrupts, os.Interrupt) notify(quits, quitSignals...) - go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { - signal.Stop(interrupts) - signal.Stop(quits) - }) + go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { signal.Stop(interrupts) }) return ctx } diff --git a/cbz-fix/interrupt_test.go b/cbz-fix/interrupt_test.go index 47e6ba5..f551ab6 100644 --- a/cbz-fix/interrupt_test.go +++ b/cbz-fix/interrupt_test.go @@ -48,7 +48,7 @@ func TestWatchSignals(t *testing.T) { // 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}, - // After a quit, the next Ctrl+C or quit gets the default handling too. + // 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}, } diff --git a/cbz-fix/main.go b/cbz-fix/main.go index d3fce31..05c004e 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -75,7 +75,6 @@ func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bo line string err error } - eofSeen := false return func(q string) (bool, error) { if err := ctx.Err(); err != nil { return false, err @@ -95,10 +94,8 @@ func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bo case a = <-c: } // On Windows a Ctrl+C at the prompt ends the read with EOF, which can - // arrive before the signal does. Waiting for it is best-effort, and - // only the first EOF waits: every later read hits EOF at once. - if errors.Is(a.err, io.EOF) && !eofSeen { - eofSeen = true + // 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): diff --git a/cbz-fix/main_test.go b/cbz-fix/main_test.go index 14b580b..98527a1 100644 --- a/cbz-fix/main_test.go +++ b/cbz-fix/main_test.go @@ -399,31 +399,6 @@ func TestNewPrompt_InterruptBeforeQuestion(t *testing.T) { } } -// Only the first EOF waits for an interrupt: later prompts on a closed stdin -// fail at once. -func TestNewPrompt_OnlyFirstEOFWaits(t *testing.T) { - prompt := newPrompt(t.Context(), strings.NewReader(""), io.Discard) - if _, err := prompt("q"); !errors.Is(err, io.EOF) { - t.Fatalf("first error = %v, want io.EOF", err) - } - start := time.Now() - if _, err := prompt("q"); !errors.Is(err, io.EOF) { - t.Fatalf("second error = %v, want io.EOF", err) - } - if d := time.Since(start); d >= eofGrace { - t.Errorf("second EOF took %v, want under %v", d, eofGrace) - } -} - -// An answer that arrives after the interrupt is not acted on. -func TestNewPrompt_AnswerAfterInterrupt(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - cancel() - if yes, err := newPrompt(ctx, strings.NewReader("y\n"), io.Discard)("q"); yes || !errors.Is(err, context.Canceled) { - t.Errorf("got %v, %v; want false, context.Canceled", yes, err) - } -} - // A walk error is reported as one even after an interrupt. func TestRun_WalkErrorAfterInterrupt(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) From 1271c65edadf005159e702da481408b3bc4f904e Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 18:33:50 +1300 Subject: [PATCH 08/10] fix(cbz-fix): catch SIGPIPE once stopping so a pipe reader ended by the same Ctrl+C can't end cbz-fix, and pin SIGTERM and the absorbed second quit --- README.md | 2 +- cbz-fix/command_other.go | 3 ++ cbz-fix/command_unix.go | 9 +++-- cbz-fix/command_unix_test.go | 63 +++++++++++++++++++++++++++------ cbz-fix/command_windows.go | 8 +++-- cbz-fix/command_windows_test.go | 15 +++++++- cbz-fix/convert_coder_test.go | 3 +- cbz-fix/interrupt.go | 19 ++++++---- cbz-fix/main.go | 3 +- 9 files changed, 99 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index c411d0b..0419663 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s 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. A third quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. +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; after either, further SIGTERM or SIGHUP is ignored, so only Ctrl+C or SIGKILL ends a hung run. A third Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. --- diff --git a/cbz-fix/command_other.go b/cbz-fix/command_other.go index f3b29a4..9a732d4 100644 --- a/cbz-fix/command_other.go +++ b/cbz-fix/command_other.go @@ -12,3 +12,6 @@ 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_unix.go b/cbz-fix/command_unix.go index 653aa81..8402c3b 100644 --- a/cbz-fix/command_unix.go +++ b/cbz-fix/command_unix.go @@ -23,6 +23,11 @@ func isolate(cmd *exec.Cmd) { } } -// quitSignals end cbz-fix without reaching its isolated children, so it has to -// kill them itself. +// 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 index 6514baa..ae0c94b 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -51,14 +51,16 @@ func init() { waitFor(killContext(ctx), "killed") interruptUntilDead() } - helperModes["hup"] = func() { + helperModes["hup"] = func() { quitTwice(syscall.SIGHUP) } // a closed terminal + helperModes["sigterm"] = func() { quitTwice(syscall.SIGTERM) } + // Run with stdout and stderr on a broken pipe: Ctrl+C, then the notice + // and the summary's writes. + helperModes["broken-pipe"] = func() { ctx := interruptContext() - raise(syscall.SIGHUP) - waitFor(killContext(ctx), "stopped and killed") - raise(syscall.SIGHUP) // a closed terminal's second hangup - time.Sleep(200 * time.Millisecond) - fmt.Println("absorbed") - interruptUntilDead() + 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() { @@ -68,7 +70,8 @@ func init() { sayStopped(ctx) } // A background job in a script: with SIGINT ignored, no other signal - // becomes an interrupt. + // 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() @@ -95,6 +98,21 @@ func waitFor(ctx context.Context, done string) { } } +// quitTwice sends sig, then sends it again once the kill is requested, as a +// closed terminal does, and checks Ctrl+C then quits. The repeats cover the +// moment watchSignals restores the default handling. +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 { @@ -115,8 +133,9 @@ func sayStopped(ctx context.Context) { } // The signal sequences interruptContext handles, run in a child that signals -// itself: three Ctrl+Cs (the third quits), a hangup (a second is absorbed, and -// Ctrl+C then quits), and signals the process started out ignoring. +// itself: three Ctrl+Cs (the third quits), a quit (a second is absorbed, and +// Ctrl+C then quits), Ctrl+C with output to a broken pipe, and signals the +// process started out ignoring. func TestInterruptContext(t *testing.T) { cases := []struct { mode, want string @@ -125,6 +144,7 @@ func TestInterruptContext(t *testing.T) { }{ {"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.SIGTERM, syscall.SIGINT}}, {"ignored-hup", "kept running", 0, nil}, {"ignored-int", "kept running", 0, nil}, } @@ -132,7 +152,7 @@ func TestInterruptContext(t *testing.T) { t.Run(tc.mode, func(t *testing.T) { for _, sig := range tc.needs { if signal.Ignored(sig) { - t.Skipf("%v is ignored here (nohup?), so the child inherits that", 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]) @@ -156,6 +176,27 @@ func TestInterruptContext(t *testing.T) { } } +// Ctrl+C in `cbz-fix 2>&1 | tee log` ends tee too, so the notice and the +// summary go to a broken pipe: that mustn't end cbz-fix before it kills magick +// and exits 130. +func TestInterruptContext_BrokenPipe(t *testing.T) { + if signal.Ignored(syscall.SIGINT) { + t.Skip("SIGINT is ignored here, so the child inherits that") + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + r.Close() + defer w.Close() + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"=broken-pipe") + cmd.Stdout, cmd.Stderr = w, w + if err := cmd.Run(); err != nil { + t.Errorf("ended with %v, want success", err) + } +} + // command starts children in their own process group, so the terminal's // SIGINT doesn't reach them. func TestCommand_OwnProcessGroup(t *testing.T) { diff --git a/cbz-fix/command_windows.go b/cbz-fix/command_windows.go index ff30f2e..8ef716a 100644 --- a/cbz-fix/command_windows.go +++ b/cbz-fix/command_windows.go @@ -18,6 +18,10 @@ func isolate(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow} } -// quitSignals end cbz-fix without reaching its isolated children: Go reports -// a closed console, logoff or shutdown as SIGTERM. +// 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 index fffa373..bd5cca1 100644 --- a/cbz-fix/command_windows_test.go +++ b/cbz-fix/command_windows_test.go @@ -2,7 +2,12 @@ package main -import "testing" +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. @@ -12,3 +17,11 @@ func TestCommand_NoConsole(t *testing.T) { 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_coder_test.go b/cbz-fix/convert_coder_test.go index 3de446e..71e5e0f 100644 --- a/cbz-fix/convert_coder_test.go +++ b/cbz-fix/convert_coder_test.go @@ -136,8 +136,7 @@ func TestProcessCBZ_DryRunRejectsSVG(t *testing.T) { // 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; processCBZ stops before -// the next conversion instead. +// 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") diff --git a/cbz-fix/interrupt.go b/cbz-fix/interrupt.go index 6f85a67..61d161a 100644 --- a/cbz-fix/interrupt.go +++ b/cbz-fix/interrupt.go @@ -11,17 +11,23 @@ import ( // 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 the third quits at once. A quit signal does the -// first two at once, after which Ctrl+C quits at once. +// 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. // -// Quit signals stay caught: a closed terminal sends a second SIGHUP, which -// would otherwise end cbz-fix before its children were killed. +// Quit signals stay caught, so after a stop or quit further ones are absorbed: +// a closed terminal sends a second SIGHUP, which would otherwise end cbz-fix +// before its children were killed. Once stopping, cbz-fix also catches +// pipeSignals, so a pipe reader that the same Ctrl+C ended can't end it. func interruptContext() context.Context { - ctx, stop, kill := newInterruptContext() + 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 } @@ -44,7 +50,8 @@ func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) } // watchSignals calls stop on the first interrupt, and kill then restore on the -// second, so a third gets the default handling. A quit calls all three. +// second, so a third Ctrl+C gets the default handling. A quit calls all three. +// restore stops only the interrupts, so quits stay caught. func watchSignals(w io.Writer, interrupts, quits <-chan os.Signal, stop, kill, restore func()) { select { case <-interrupts: diff --git a/cbz-fix/main.go b/cbz-fix/main.go index 05c004e..ce9d718 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -68,7 +68,8 @@ 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. +// waiting for an answer. On every platform, a read that ends in EOF first +// waits up to eofGrace for an interrupt. func newPrompt(ctx context.Context, r io.Reader, w io.Writer) func(q string) (bool, error) { br := bufio.NewReader(r) type answer struct { From 43c197f3eb92641151a2c796641b15be053c53b7 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 22:36:20 +1300 Subject: [PATCH 09/10] test(cbz-fix): pin SIGPIPE staying fatal before a stop, report broken-pipe helper failures, and correct the signal docs --- README.md | 2 +- cbz-fix/command_unix_test.go | 98 +++++++++++++++++++++++++----------- cbz-fix/interrupt.go | 11 ++-- cbz-fix/main.go | 4 +- 4 files changed, 79 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 0419663..27a47f0 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s 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; after either, further SIGTERM or SIGHUP is ignored, so only Ctrl+C or SIGKILL ends a hung run. A third Ctrl+C quits at once, which can leave a `cbzfix-*.tmp` (or a truncated `.bak` with `--backup`) beside the comic being written. +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 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. --- diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go index ae0c94b..f484dde 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "os/signal" + "path/filepath" "strconv" "strings" "syscall" @@ -53,8 +54,14 @@ func init() { } helperModes["hup"] = func() { quitTwice(syscall.SIGHUP) } // a closed terminal helperModes["sigterm"] = func() { quitTwice(syscall.SIGTERM) } - // Run with stdout and stderr on a broken pipe: Ctrl+C, then the notice - // and the summary's writes. + // 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() + 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) @@ -80,10 +87,25 @@ func init() { } } +// 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 { - fmt.Fprintln(os.Stderr, "kill:", err) - os.Exit(1) + failHelper("kill:", err) } } @@ -93,14 +115,14 @@ func waitFor(ctx context.Context, done string) { case <-ctx.Done(): fmt.Println(done) case <-time.After(5 * time.Second): - fmt.Fprintln(os.Stderr, "timed out before:", done) - os.Exit(1) + failHelper("timed out before:", done) } } -// quitTwice sends sig, then sends it again once the kill is requested, as a -// closed terminal does, and checks Ctrl+C then quits. The repeats cover the -// moment watchSignals restores the default handling. +// quitTwice sends sig, then sends it five more times once the kill is +// requested (a closed terminal sends SIGHUP twice), and checks they are +// absorbed and Ctrl+C then quits. The repeats cover the moment watchSignals +// restores the default handling. func quitTwice(sig syscall.Signal) { ctx := interruptContext() raise(sig) @@ -134,8 +156,7 @@ func sayStopped(ctx context.Context) { // 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), Ctrl+C with output to a broken pipe, and signals the -// process started out ignoring. +// Ctrl+C then quits), and signals the process started out ignoring. func TestInterruptContext(t *testing.T) { cases := []struct { mode, want string @@ -144,7 +165,7 @@ func TestInterruptContext(t *testing.T) { }{ {"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.SIGTERM, 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}, } @@ -176,24 +197,45 @@ func TestInterruptContext(t *testing.T) { } } -// Ctrl+C in `cbz-fix 2>&1 | tee log` ends tee too, so the notice and the -// summary go to a broken pipe: that mustn't end cbz-fix before it kills magick -// and exits 130. +// 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) { - if signal.Ignored(syscall.SIGINT) { - t.Skip("SIGINT is ignored here, so the child inherits that") - } - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) + 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}}, } - r.Close() - defer w.Close() - cmd := exec.CommandContext(t.Context(), os.Args[0]) - cmd.Env = append(os.Environ(), helperEnv+"=broken-pipe") - cmd.Stdout, cmd.Stderr = w, w - if err := cmd.Run(); err != nil { - t.Errorf("ended with %v, want success", err) + 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() + diag := filepath.Join(t.TempDir(), "diag") + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+tc.mode, diagEnv+"="+diag) + cmd.Stdout, cmd.Stderr = w, w + err = cmd.Run() + said, _ := os.ReadFile(diag) + 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) + } + }) } } diff --git a/cbz-fix/interrupt.go b/cbz-fix/interrupt.go index 61d161a..b5bd173 100644 --- a/cbz-fix/interrupt.go +++ b/cbz-fix/interrupt.go @@ -14,9 +14,10 @@ import ( // 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. // -// Quit signals stay caught, so after a stop or quit further ones are absorbed: -// a closed terminal sends a second SIGHUP, which would otherwise end cbz-fix -// before its children were killed. Once stopping, cbz-fix also catches +// Quit signals stay caught (restore stops only the interrupts), so once the +// children are killed further ones are absorbed: a closed terminal sends a +// second SIGHUP, which would otherwise end cbz-fix before its children were +// killed. Once stopping, 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() @@ -33,7 +34,8 @@ func interruptContext() context.Context { } // notify relays sigs to c, except those the process started out ignoring, -// such as SIGHUP under nohup: Notify would stop them being ignored. +// 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 @@ -51,7 +53,6 @@ func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) // 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 stops only the interrupts, so quits stay caught. func watchSignals(w io.Writer, interrupts, quits <-chan os.Signal, stop, kill, restore func()) { select { case <-interrupts: diff --git a/cbz-fix/main.go b/cbz-fix/main.go index ce9d718..e3a1023 100644 --- a/cbz-fix/main.go +++ b/cbz-fix/main.go @@ -68,8 +68,8 @@ 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. On every platform, a read that ends in EOF first -// waits up to eofGrace for an interrupt. +// 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 { From 6004a9364a097042d667ff525511e8ef2946fb86 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 22:46:44 +1300 Subject: [PATCH 10/10] test(cbz-fix): require the idle broken-pipe helper to reach its write, fail rather than panic on a child that never started, and tighten the signal docs --- README.md | 2 +- cbz-fix/command_unix_test.go | 27 +++++++++++++++++++++------ cbz-fix/interrupt.go | 9 +++++---- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 27a47f0..85567da 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ cbz-fix --update-cover # replace in-archive cover with a higher-res cover.jpg s 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 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. +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. --- diff --git a/cbz-fix/command_unix_test.go b/cbz-fix/command_unix_test.go index f484dde..c0e2492 100644 --- a/cbz-fix/command_unix_test.go +++ b/cbz-fix/command_unix_test.go @@ -58,6 +58,11 @@ func init() { // 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") } @@ -119,10 +124,10 @@ func waitFor(ctx context.Context, done string) { } } -// quitTwice sends sig, then sends it five more times once the kill is -// requested (a closed terminal sends SIGHUP twice), and checks they are -// absorbed and Ctrl+C then quits. The repeats cover the moment watchSignals -// restores the default handling. +// 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) @@ -179,6 +184,9 @@ func TestInterruptContext(t *testing.T) { 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 @@ -222,12 +230,19 @@ func TestInterruptContext_BrokenPipe(t *testing.T) { } r.Close() defer w.Close() - diag := filepath.Join(t.TempDir(), "diag") + 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) + 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) diff --git a/cbz-fix/interrupt.go b/cbz-fix/interrupt.go index b5bd173..19e748c 100644 --- a/cbz-fix/interrupt.go +++ b/cbz-fix/interrupt.go @@ -14,11 +14,11 @@ import ( // 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. // -// Quit signals stay caught (restore stops only the interrupts), so once the -// children are killed further ones are absorbed: a closed terminal sends a +// 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. Once stopping, cbz-fix also catches -// pipeSignals, so a pipe reader that the same Ctrl+C ended can't end it. +// 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) @@ -53,6 +53,7 @@ func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) // 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: