From 754d04d03a16e45d10af29a680b917641f801a19 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 23:14:36 +1300 Subject: [PATCH 1/5] feat(mkv-audit): stop cleanly on Ctrl+C and pass a context to every child process and TMDB request The first Ctrl+C stops before the next file or at a prompt without taking its default; the second kills mkvmerge and mkvextract, never mkvpropedit. Interrupted files are not recorded as failures, and the run exits 130. Part of #294 --- README.md | 2 + mkv-audit/command.go | 36 ++ mkv-audit/command_other.go | 17 + mkv-audit/command_test.go | 173 ++++++++++ mkv-audit/command_unix.go | 32 ++ mkv-audit/command_unix_test.go | 322 ++++++++++++++++++ mkv-audit/command_windows.go | 26 ++ mkv-audit/command_windows_test.go | 27 ++ mkv-audit/convert.go | 36 +- mkv-audit/convert_test.go | 43 +-- mkv-audit/convert_walk_test.go | 35 +- mkv-audit/dirconfig_test.go | 2 +- mkv-audit/interrupt.go | 75 +++++ mkv-audit/interrupt_run_test.go | 543 ++++++++++++++++++++++++++++++ mkv-audit/interrupt_test.go | 78 +++++ mkv-audit/main.go | 57 ++-- mkv-audit/mka_date.go | 6 +- mkv-audit/prompt.go | 66 +++- mkv-audit/remux.go | 12 +- mkv-audit/retag_test.go | 2 +- mkv-audit/runner.go | 144 ++++++-- mkv-audit/runner_test.go | 39 +-- mkv-audit/sibling_cache_test.go | 121 +++---- mkv-audit/tmdb.go | 33 +- mkv-audit/tmdb_test.go | 9 +- mkv-audit/token_redaction_test.go | 6 +- 26 files changed, 1729 insertions(+), 213 deletions(-) create mode 100644 mkv-audit/command.go create mode 100644 mkv-audit/command_other.go create mode 100644 mkv-audit/command_test.go create mode 100644 mkv-audit/command_unix.go create mode 100644 mkv-audit/command_unix_test.go create mode 100644 mkv-audit/command_windows.go create mode 100644 mkv-audit/command_windows_test.go create mode 100644 mkv-audit/interrupt.go create mode 100644 mkv-audit/interrupt_run_test.go create mode 100644 mkv-audit/interrupt_test.go diff --git a/README.md b/README.md index 85567da..2930a97 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,8 @@ The tool scans recursively and prints a summary: Scanned: 120 Fixed: 14 Failed: 0 LangFixes: 9 FlagFixes: 8 ``` +Ctrl+C stops before the next file, or at a prompt without taking its default, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets its edits, and a conversion or trim in progress finishes. A second Ctrl+C also kills the `mkvmerge` or `mkvextract` in progress, as closing the terminal or SIGTERM does; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files skipped by an interrupt aren't recorded as failures, and earlier failures stay on the retry list. From then on SIGTERM and (on Unix) SIGHUP are ignored, and a further Ctrl+C quits at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed. + ### Dependencies - `mkvmerge` — reads track metadata; also used for container conversion and track trimming remux diff --git a/mkv-audit/command.go b/mkv-audit/command.go new file mode 100644 index 0000000..ea86194 --- /dev/null +++ b/mkv-audit/command.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "os/exec" +) + +// killKey keys the kill context a ctx carries for command: cancelling ctx lets +// command's processes finish, and cancelling the kill context kills them. +type killKey struct{} + +// killContext is the kill context ctx carries, or one never cancelled. +func killContext(ctx context.Context) context.Context { + if kill, ok := ctx.Value(killKey{}).(context.Context); ok { + return kill + } + return context.WithoutCancel(ctx) +} + +// command returns a Cmd for name that the terminal's Ctrl+C doesn't reach +// (isolate). Only ctx's kill context kills it: ctx's own cancellation and +// deadline never do. +func command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(killContext(ctx), name, args...) + isolate(cmd) + return cmd +} + +// commandErr is err from running a command, or the kill context's error once +// that is cancelled: any failure is then reported as the kill, its likely cause. +func commandErr(ctx context.Context, err error) error { + if killErr := killContext(ctx).Err(); err != nil && killErr != nil { + return killErr + } + return err +} diff --git a/mkv-audit/command_other.go b/mkv-audit/command_other.go new file mode 100644 index 0000000..9a732d4 --- /dev/null +++ b/mkv-audit/command_other.go @@ -0,0 +1,17 @@ +//go:build !unix && !windows + +package main + +import ( + "os" + "os/exec" +) + +// isolate does nothing where there are no process groups. +func isolate(*exec.Cmd) {} + +// quitSignals is empty: without isolate, children get the same signals. +var quitSignals []os.Signal + +// pipeSignals is empty: there is no SIGPIPE to catch. +var pipeSignals []os.Signal diff --git a/mkv-audit/command_test.go b/mkv-audit/command_test.go new file mode 100644 index 0000000..94cb019 --- /dev/null +++ b/mkv-audit/command_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "strings" + "testing" + "time" +) + +const ( + // helperEnv names the helperModes entry a child started by these tests runs. + helperEnv = "MKVAUDIT_TEST_HELPER" + // readyEnv names a file the helper creates once ready, for a child whose + // stdout the test can't read. + readyEnv = "MKVAUDIT_TEST_READY" +) + +// helperModes are the children the command tests start: the test binary run +// with helperEnv set, which TestMain hands to the mode instead of the tests. +// Those startHelper runs say "ready" first. +var helperModes = map[string]func(){ + // sleep sleeps for a minute or until killed. + "sleep": func() { ready(); time.Sleep(time.Minute) }, +} + +// ready prints "ready", and creates the file readyEnv names, if any. +func ready() { + fmt.Println("ready") + if path := os.Getenv(readyEnv); path != "" { + if err := os.WriteFile(path, nil, 0o600); err != nil { + fmt.Fprintln(os.Stderr, "write ready file:", err) + os.Exit(1) + } + } +} + +func TestMain(m *testing.M) { + if mode := os.Getenv(helperEnv); mode != "" { + helper, ok := helperModes[mode] + if !ok { + fmt.Fprintln(os.Stderr, "unknown helper mode", mode) + os.Exit(2) + } + helper() + os.Exit(0) + } + os.Exit(m.Run()) +} + +// startHelper runs the helper mode through command and waits for it to say +// "ready", returning its stdout and a channel that gets commandErr's verdict +// once it ends. Cleanup kills it, so a failed test leaves nothing running, and +// logs its stderr if the test failed. +func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (*bufio.Reader, <-chan error) { + t.Helper() + cmd := command(ctx, os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+mode) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = w, &stderr + result := make(chan error, 1) + finished := make(chan struct{}) + go func() { + result <- commandErr(ctx, cmd.Run()) + w.Close() // EOF for a reader still waiting on a helper that never spoke + close(finished) + }() + t.Cleanup(func() { + kill() + <-finished + r.Close() + if t.Failed() && stderr.Len() > 0 { + t.Logf("helper stderr:\n%s", stderr.String()) + } + }) + out := bufio.NewReader(r) + if line := readLine(t, out); line != "ready" { + t.Fatalf("helper said %q, want ready", line) + } + return out, result +} + +// readLine reads one line from the helper, failing the test on EOF. +func readLine(t *testing.T, r *bufio.Reader) string { + t.Helper() + line, err := r.ReadString('\n') + if err != nil { + t.Fatalf("helper said %q, then %v", line, err) + } + return strings.TrimSpace(line) +} + +// wantKilled waits for startHelper's verdict, which must be the kill. +func wantKilled(t *testing.T, result <-chan error) { + t.Helper() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Errorf("commandErr = %v, want context.Canceled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("child still running after the kill") + } +} + +// wantRunning fails the test if the helper ends within a short wait. +func wantRunning(t *testing.T, result <-chan error) { + t.Helper() + select { + case err := <-result: + t.Fatalf("child ended after the first interrupt: %v", err) + case <-time.After(300 * time.Millisecond): + } +} + +// Without an interrupt context, command's processes are never killed. +func TestKillContext_DefaultNeverCancels(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := killContext(ctx).Err(); err != nil { + t.Errorf("killContext of a cancelled plain context: %v", err) + } +} + +// commandErr reports a failure as the kill only once the kill context, not +// ctx, is cancelled, and never turns a success into an error. +func TestCommandErr(t *testing.T) { + failed := errors.New("exit status 1") + cases := []struct { + name string + stop, kill bool + in, want error + }{ + {"running", false, false, failed, failed}, + {"stopped", true, false, failed, failed}, + {"killed", true, true, failed, context.Canceled}, + {"killed but succeeded", true, true, nil, nil}, + } + for _, tc := range cases { + ctx, stop, kill := newInterruptContext() + if tc.stop { + stop() + } + if tc.kill { + kill() + } + if got := commandErr(ctx, tc.in); !errors.Is(got, tc.want) || (tc.want == nil) != (got == nil) { + t.Errorf("%s: commandErr = %v, want %v", tc.name, got, tc.want) + } + stop() + kill() + } +} + +// A child outlives the first interrupt and is killed by the second, which +// commandErr reports as the interrupt. +func TestCommand_SecondInterruptKillsChild(t *testing.T) { + ctx, stop, kill := newInterruptContext() + _, result := startHelper(ctx, t, kill, "sleep") + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} diff --git a/mkv-audit/command_unix.go b/mkv-audit/command_unix.go new file mode 100644 index 0000000..fdcd7f0 --- /dev/null +++ b/mkv-audit/command_unix.go @@ -0,0 +1,32 @@ +//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. +func isolate(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } +} + +// quitSignals would end mkv-audit 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 mkv-audit on a write to a broken stdout or +// stderr unless caught. Caught (not ignored, which the children would inherit), the +// write fails instead. +var pipeSignals = []os.Signal{syscall.SIGPIPE} diff --git a/mkv-audit/command_unix_test.go b/mkv-audit/command_unix_test.go new file mode 100644 index 0000000..dd16c56 --- /dev/null +++ b/mkv-audit/command_unix_test.go @@ -0,0 +1,322 @@ +//go:build unix + +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func init() { + // group starts a sleeping grandchild in its process group and prints the + // grandchild's pid, then sleeps. + helperModes["group"] = func() { + gc := exec.CommandContext(context.Background(), os.Args[0]) + gc.Env = append(os.Environ(), helperEnv+"=sleep") + if err := gc.Start(); err != nil { + fmt.Fprintln(os.Stderr, "start grandchild:", err) + os.Exit(1) + } + ready() + fmt.Println(gc.Process.Pid) + time.Sleep(time.Minute) + } + // term says "term" when it gets SIGTERM, then exits. + helperModes["term"] = func() { + terms := make(chan os.Signal, 1) + signal.Notify(terms, syscall.SIGTERM) + ready() + select { + case <-terms: + fmt.Println("term") + case <-time.After(time.Minute): + } + } + + // The modes below run interruptContext and signal themselves. + helperModes["int3"] = func() { + ctx := interruptContext() + raise(syscall.SIGINT) + waitFor(ctx, "stopped") + raise(syscall.SIGINT) + waitFor(killContext(ctx), "killed") + interruptUntilDead() + } + helperModes["hup"] = func() { quitTwice(syscall.SIGHUP) } // a closed terminal + helperModes["sigterm"] = func() { quitTwice(syscall.SIGTERM) } + // The broken-pipe modes run with stdout and stderr on a broken pipe. + // Before a stop, a write ends the process by SIGPIPE as usual. + helperModes["broken-pipe-idle"] = func() { + interruptContext() + // The ready file shows the death below isn't TestMain's write about an + // unknown mode, which a broken pipe ends the same way. + if err := os.WriteFile(os.Getenv(readyEnv), nil, 0o600); err != nil { + failHelper("write ready file:", err) + } + fmt.Println("x") + failHelper("survived a write to a broken pipe") + } + // After Ctrl+C, the notice's and the summary's writes fail instead. + helperModes["broken-pipe"] = func() { + ctx := interruptContext() + raise(syscall.SIGINT) + waitFor(ctx, "stopped") + time.Sleep(100 * time.Millisecond) // the notice's write + fmt.Println("summary") + } + // nohup: an ignored hangup doesn't stop mkv-audit. + helperModes["ignored-hup"] = func() { + signal.Ignore(syscall.SIGHUP) + ctx := interruptContext() + raise(syscall.SIGHUP) + sayStopped(ctx) + } + // A background job in a script: with SIGINT ignored, no other signal + // becomes an interrupt, since notify doesn't Notify an empty list (which + // would relay every signal). + helperModes["ignored-int"] = func() { + signal.Ignore(syscall.SIGINT) + ctx := interruptContext() + raise(syscall.SIGWINCH) + sayStopped(ctx) + } +} + +// diagEnv names a file a helper reports its failure to instead of stderr, for +// a child whose stderr is a broken pipe. +const diagEnv = "MKVAUDIT_TEST_DIAG" + +// failHelper reports a helper's failure and exits 1. +func failHelper(msg ...any) { + w := os.Stderr + if path := os.Getenv(diagEnv); path != "" { + if f, err := os.Create(path); err == nil { + w = f + } + } + fmt.Fprintln(w, msg...) + os.Exit(1) +} + +func raise(sig syscall.Signal) { + if err := syscall.Kill(os.Getpid(), sig); err != nil { + failHelper("kill:", err) + } +} + +// waitFor prints done once ctx is cancelled, or exits if it takes too long. +func waitFor(ctx context.Context, done string) { + select { + case <-ctx.Done(): + fmt.Println(done) + case <-time.After(5 * time.Second): + failHelper("timed out before:", done) + } +} + +// quitTwice sends sig, then repeats it once the kill is requested (a closed +// terminal sends SIGHUP twice), and checks the repeats are absorbed and Ctrl+C +// then quits. Repeating checks that restore, which runs just after the kill, +// leaves the quit signals caught. +func quitTwice(sig syscall.Signal) { + ctx := interruptContext() + raise(sig) + waitFor(killContext(ctx), "stopped and killed") + for range 5 { + raise(sig) + time.Sleep(50 * time.Millisecond) + } + fmt.Println("absorbed") + interruptUntilDead() +} + +// interruptUntilDead sends Ctrl+C until one gets the default handling. +func interruptUntilDead() { + for range 100 { + raise(syscall.SIGINT) + time.Sleep(50 * time.Millisecond) + } + fmt.Println("survived Ctrl+C") +} + +// sayStopped says whether ctx is cancelled after a short wait. +func sayStopped(ctx context.Context) { + select { + case <-ctx.Done(): + fmt.Println("stopped") + case <-time.After(500 * time.Millisecond): + fmt.Println("kept running") + } +} + +// The signal sequences interruptContext handles, run in a child that signals +// itself: three Ctrl+Cs (the third quits), a quit (a second is absorbed, and +// Ctrl+C then quits), and signals the process started out ignoring. +func TestInterruptContext(t *testing.T) { + cases := []struct { + mode, want string + diesBy syscall.Signal // 0: exits normally + needs []syscall.Signal + }{ + {"int3", "stopped\nkilled", syscall.SIGINT, []syscall.Signal{syscall.SIGINT}}, + {"hup", "stopped and killed\nabsorbed", syscall.SIGINT, []syscall.Signal{syscall.SIGHUP, syscall.SIGINT}}, + {"sigterm", "stopped and killed\nabsorbed", syscall.SIGINT, []syscall.Signal{syscall.SIGINT}}, + {"ignored-hup", "kept running", 0, nil}, + {"ignored-int", "kept running", 0, nil}, + } + for _, tc := range cases { + t.Run(tc.mode, func(t *testing.T) { + for _, sig := range tc.needs { + if signal.Ignored(sig) { + t.Skipf("%v is ignored here (nohup, or a background job?), so the child inherits that", sig) + } + } + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+tc.mode) + out, err := cmd.Output() + if cmd.ProcessState == nil { + t.Fatalf("start: %v", err) + } + var stderr []byte + if ee, ok := errors.AsType[*exec.ExitError](err); ok { + stderr = ee.Stderr + } + if got := strings.TrimSpace(string(out)); got != tc.want { + t.Errorf("said %q, want %q (stderr %q)", got, tc.want, stderr) + } + ws, _ := cmd.ProcessState.Sys().(syscall.WaitStatus) + if tc.diesBy == 0 && err != nil { + t.Errorf("exited with %v, want success (stderr %q)", err, stderr) + } + if tc.diesBy != 0 && (!ws.Signaled() || ws.Signal() != tc.diesBy) { + t.Errorf("ended with %v, want death by %v (stderr %q)", err, tc.diesBy, stderr) + } + }) + } +} + +// Output to a broken pipe ends mkv-audit by SIGPIPE as usual (`mkv-audit | head`) +// until Ctrl+C. After it, which in `mkv-audit 2>&1 | tee log` ends tee too, the +// notice's and the summary's writes fail instead, so mkv-audit finishes stopping. +func TestInterruptContext_BrokenPipe(t *testing.T) { + cases := []struct { + mode string + diesBy syscall.Signal // 0: exits normally + needs []syscall.Signal + }{ + {"broken-pipe-idle", syscall.SIGPIPE, nil}, + {"broken-pipe", 0, []syscall.Signal{syscall.SIGINT}}, + } + for _, tc := range cases { + t.Run(tc.mode, func(t *testing.T) { + for _, sig := range tc.needs { + if signal.Ignored(sig) { + t.Skipf("%v is ignored here, so the child inherits that", sig) + } + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + r.Close() + defer w.Close() + dir := t.TempDir() + diag, readyFile := filepath.Join(dir, "diag"), filepath.Join(dir, "ready") + cmd := exec.CommandContext(t.Context(), os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"="+tc.mode, diagEnv+"="+diag, readyEnv+"="+readyFile) + cmd.Stdout, cmd.Stderr = w, w + err = cmd.Run() + if cmd.ProcessState == nil { + t.Fatalf("start: %v", err) + } + said, _ := os.ReadFile(diag) + if _, statErr := os.Stat(readyFile); tc.mode == "broken-pipe-idle" && statErr != nil { + t.Errorf("helper never reached its write (ended with %v)", err) + } + ws, _ := cmd.ProcessState.Sys().(syscall.WaitStatus) + if tc.diesBy == 0 && err != nil { + t.Errorf("ended with %v, want success (helper said %q)", err, said) + } + if tc.diesBy != 0 && (!ws.Signaled() || ws.Signal() != tc.diesBy) { + t.Errorf("ended with %v, want death by %v (helper said %q)", err, tc.diesBy, said) + } + }) + } +} + +// command starts children in their own process group, so the terminal's +// SIGINT doesn't reach them. +func TestCommand_OwnProcessGroup(t *testing.T) { + cmd := command(t.Context(), "mkvmerge") + if cmd.SysProcAttr == nil || !cmd.SysProcAttr.Setpgid { + t.Errorf("SysProcAttr = %+v, want Setpgid", cmd.SysProcAttr) + } +} + +// The kill reaches the child's whole process group, not just the child. +func TestCommand_KillReachesProcessGroup(t *testing.T) { + ctx, stop, kill := newInterruptContext() + out, result := startHelper(ctx, t, kill, "group") + pidLine := readLine(t, out) + pid, err := strconv.Atoi(pidLine) + if err != nil { + t.Fatalf("helper said %q", pidLine) + } + + stop() + kill() + wantKilled(t, result) + for deadline := time.Now().Add(5 * time.Second); running(pid); time.Sleep(20 * time.Millisecond) { + if time.Now().After(deadline) { + _ = syscall.Kill(pid, syscall.SIGKILL) + t.Fatal("grandchild survived the kill") + } + } +} + +// The kill is SIGTERM, which a child can catch to clean up. +func TestCommand_KillIsSIGTERM(t *testing.T) { + ctx, stop, kill := newInterruptContext() + out, result := startHelper(ctx, t, kill, "term") + + stop() + kill() + if line := readLine(t, out); line != "term" { + t.Errorf("helper said %q, want term", line) + } + wantKilled(t, result) +} + +// Cancel maps a child that has already exited to os.ErrProcessDone, which +// exec doesn't report as an error. +func TestCommand_CancelAfterExit(t *testing.T) { + cmd := command(t.Context(), os.Args[0], "-test.run=^$") + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + if err := cmd.Cancel(); !errors.Is(err, os.ErrProcessDone) { + t.Errorf("Cancel = %v, want os.ErrProcessDone", err) + } +} + +// running reports whether pid exists and isn't a zombie waiting to be reaped. +func running(pid int) bool { + if syscall.Kill(pid, 0) != nil { + return false + } + stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return true // no /proc: trust kill + } + return !strings.Contains(string(stat), ") Z ") +} diff --git a/mkv-audit/command_windows.go b/mkv-audit/command_windows.go new file mode 100644 index 0000000..a86838f --- /dev/null +++ b/mkv-audit/command_windows.go @@ -0,0 +1,26 @@ +//go:build windows + +package main + +import ( + "os" + "os/exec" + "syscall" +) + +// createNoWindow is CREATE_NO_WINDOW, which syscall doesn't define. +const createNoWindow = 0x08000000 + +// isolate gives cmd a hidden console of its own, so Ctrl+C and Ctrl+Break at +// ours don't reach it. Cancelling cmd kills it. +func isolate(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow} +} + +// quitSignals would end mkv-audit 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/mkv-audit/command_windows_test.go b/mkv-audit/command_windows_test.go new file mode 100644 index 0000000..e98be9b --- /dev/null +++ b/mkv-audit/command_windows_test.go @@ -0,0 +1,27 @@ +//go:build windows + +package main + +import ( + "os" + "slices" + "syscall" + "testing" +) + +// command starts children in a hidden console of their own, so no Ctrl+C or +// Ctrl+Break at ours reaches them. +func TestCommand_NoConsole(t *testing.T) { + attr := command(t.Context(), "mkvmerge").SysProcAttr + if attr == nil || attr.CreationFlags&createNoWindow == 0 { + t.Errorf("SysProcAttr = %+v, want CREATE_NO_WINDOW", attr) + } +} + +// A closed console, logoff or shutdown arrives as SIGTERM, which must be caught +// so mkv-audit kills mkvmerge 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/mkv-audit/convert.go b/mkv-audit/convert.go index 5b3179f..99a6316 100644 --- a/mkv-audit/convert.go +++ b/mkv-audit/convert.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "fmt" "os" @@ -23,7 +24,8 @@ type MKVConverter interface { // ConvertToMKV writes .mkv next to src, then removes src. A non-empty // path with a non-nil error means the MKV was written but a later step // (copying timestamps, removing src) failed. - ConvertToMKV(src string) (string, error) + // ctx's kill context (see command) kills mkvmerge, leaving src as it was. + ConvertToMKV(ctx context.Context, src string) (string, error) } // convertExts are the video containers the walk converts to MKV. .wmv is @@ -39,7 +41,7 @@ func isConvertible(path string) bool { // list with the MKV in its place. A source that is skipped or fails to // convert is dropped; a failure is also recorded in stats. Each path appears // once, so a retry list holding both x.mp4 and x.mkv doesn't scan x.mkv twice. -func convertAll(paths []string, converter MKVConverter, stats *Stats) []string { +func convertAll(ctx context.Context, paths []string, converter MKVConverter, stats *Stats) []string { out := make([]string, 0, len(paths)) seen := make(map[string]bool, len(paths)) keep := func(p string) { @@ -53,9 +55,14 @@ func convertAll(paths []string, converter MKVConverter, stats *Stats) []string { keep(p) continue } + if ctx.Err() != nil { + continue // not converted, so not scanned either + } base := filepath.Base(p) - dst, err := converter.ConvertToMKV(p) + dst, err := converter.ConvertToMKV(ctx, p) switch { + case errors.Is(err, context.Canceled): + fmt.Printf("[STOP] %s: interrupted; left unchanged\n", base) case errors.Is(err, errMKVExists): fmt.Printf("[WARN] %s: %s already exists, not converting\n", base, filepath.Base(strings.TrimSuffix(p, filepath.Ext(p))+".mkv")) case errors.Is(err, errUnsupportedContainer): @@ -81,20 +88,23 @@ type loggingConverter struct { inner MKVConverter } -func (l *loggingConverter) ConvertToMKV(src string) (string, error) { +func (l *loggingConverter) ConvertToMKV(ctx context.Context, src string) (string, error) { dst := strings.TrimSuffix(src, filepath.Ext(src)) + ".mkv" fmt.Printf(" convert: mkvmerge -o %q %q\n", filepath.Base(dst), filepath.Base(src)) - return l.inner.ConvertToMKV(src) + return l.inner.ConvertToMKV(ctx, src) } // ConvertToMKV implements MKVConverter on realMKVRunner. -func (r *realMKVRunner) ConvertToMKV(src string) (string, error) { - return convertToMKV(src, r, r.mux) +func (r *realMKVRunner) ConvertToMKV(ctx context.Context, src string) (string, error) { + return convertToMKV(ctx, src, r, r.mux) } // mux runs mkvmerge to copy every track of src into a new MKV at dst. -func (r *realMKVRunner) mux(src, dst string) error { - out, err := exec.Command(r.mkvmerge, "-o", dst, src).CombinedOutput() +func (r *realMKVRunner) mux(ctx context.Context, src, dst string) error { + out, err := command(ctx, r.mkvmerge, "-o", dst, src).CombinedOutput() + if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { + return err + } var exitErr *exec.ExitError if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 { // Warnings only: the output is complete, but show them, since the @@ -112,7 +122,7 @@ func (r *realMKVRunner) mux(src, dst string) error { // has every source track, gives it src's timestamps so the cutoff filter still // sees the real date, and then removes src. On any failure before the rename // src is left untouched and no MKV is created. -func convertToMKV(src string, ident MKVIdentifier, mux func(src, dst string) error) (string, error) { +func convertToMKV(ctx context.Context, src string, ident MKVIdentifier, mux func(ctx context.Context, src, dst string) error) (string, error) { dst := strings.TrimSuffix(src, filepath.Ext(src)) + ".mkv" if _, err := os.Lstat(dst); err == nil { return "", errMKVExists @@ -124,7 +134,7 @@ func convertToMKV(src string, ident MKVIdentifier, mux func(src, dst string) err } // Identify parses mkvmerge's JSON even when it exits non-zero, so an // unreadable container shows up as no tracks; an error is a real failure. - srcInfo, err := ident.Identify(src) + srcInfo, err := ident.Identify(ctx, src) if err != nil { return "", fmt.Errorf("identify: %w", err) } @@ -142,11 +152,11 @@ func convertToMKV(src string, ident MKVIdentifier, mux func(src, dst string) err _ = tmpFile.Close() _ = os.Remove(tmp) // mkvmerge creates the output file itself - if err := mux(src, tmp); err != nil { + if err := mux(ctx, src, tmp); err != nil { _ = os.Remove(tmp) return "", err } - outInfo, err := ident.Identify(tmp) + outInfo, err := ident.Identify(ctx, tmp) if err != nil { _ = os.Remove(tmp) return "", fmt.Errorf("identify converted file: %w", err) diff --git a/mkv-audit/convert_test.go b/mkv-audit/convert_test.go index 0d9583c..44f091b 100644 --- a/mkv-audit/convert_test.go +++ b/mkv-audit/convert_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "os" "os/exec" @@ -19,7 +20,7 @@ type pathIdentifier struct { srcErr error } -func (p *pathIdentifier) Identify(path string) (*MKVInfo, error) { +func (p *pathIdentifier) Identify(_ context.Context, path string) (*MKVInfo, error) { n := p.outTracks if strings.EqualFold(filepath.Ext(path), p.srcExt) { if p.srcErr != nil { @@ -34,10 +35,12 @@ func (p *pathIdentifier) Identify(path string) (*MKVInfo, error) { return info, nil } -func (p *pathIdentifier) ReadTagDate(string) (time.Time, bool) { return time.Time{}, false } +func (p *pathIdentifier) ReadTagDate(context.Context, string) (time.Time, bool) { + return time.Time{}, false +} // writeMux stands in for mkvmerge: it writes dst. -func writeMux(_, dst string) error { +func writeMux(_ context.Context, _, dst string) error { return os.WriteFile(dst, []byte("mkv"), 0o644) } @@ -75,7 +78,7 @@ func TestConvertToMKV_Success(t *testing.T) { dir := t.TempDir() src, mod := oldSource(t, dir, "Movie (2019).mp4") - dst, err := convertToMKV(src, &pathIdentifier{srcExt: ".mp4", srcTracks: 2, outTracks: 2}, writeMux) + dst, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".mp4", srcTracks: 2, outTracks: 2}, writeMux) if err != nil { t.Fatal(err) } @@ -99,9 +102,9 @@ func TestConvertToMKV_MKVExists_LeavesBoth(t *testing.T) { t.Fatal(err) } muxed := false - mux := func(string, string) error { muxed = true; return nil } + mux := func(context.Context, string, string) error { muxed = true; return nil } - _, err := convertToMKV(src, &pathIdentifier{srcExt: ".avi", srcTracks: 1, outTracks: 1}, mux) + _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".avi", srcTracks: 1, outTracks: 1}, mux) if !errors.Is(err, errMKVExists) { t.Errorf("err = %v, want errMKVExists", err) } @@ -115,7 +118,7 @@ func TestConvertToMKV_MKVExists_LeavesBoth(t *testing.T) { func TestConvertToMKV_UnsupportedContainer(t *testing.T) { dir := t.TempDir() src, _ := oldSource(t, dir, "clip.wmv") - _, err := convertToMKV(src, &pathIdentifier{srcExt: ".wmv"}, writeMux) + _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".wmv"}, writeMux) if !errors.Is(err, errUnsupportedContainer) { t.Errorf("err = %v, want errUnsupportedContainer", err) } @@ -127,7 +130,7 @@ func TestConvertToMKV_UnsupportedContainer(t *testing.T) { func TestConvertToMKV_IdentifyError_IsAFailure(t *testing.T) { dir := t.TempDir() src, _ := oldSource(t, dir, "clip.mp4") - _, err := convertToMKV(src, &pathIdentifier{srcExt: ".mp4", srcErr: errors.New("mkvmerge not found")}, writeMux) + _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".mp4", srcErr: errors.New("mkvmerge not found")}, writeMux) if err == nil || errors.Is(err, errUnsupportedContainer) { t.Errorf("err = %v, want a plain failure", err) } @@ -139,14 +142,14 @@ func TestConvertToMKV_IdentifyError_IsAFailure(t *testing.T) { func TestConvertToMKV_MKVAppearsDuringMux_LeavesBoth(t *testing.T) { dir := t.TempDir() src, _ := oldSource(t, dir, "ep.mp4") - racing := func(_, dst string) error { + racing := func(_ context.Context, _, dst string) error { if err := os.WriteFile(filepath.Join(dir, "ep.mkv"), []byte("existing"), 0o644); err != nil { return err } return os.WriteFile(dst, []byte("mkv"), 0o644) } - _, err := convertToMKV(src, &pathIdentifier{srcExt: ".mp4", srcTracks: 1, outTracks: 1}, racing) + _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".mp4", srcTracks: 1, outTracks: 1}, racing) if !errors.Is(err, errMKVExists) { t.Errorf("err = %v, want errMKVExists", err) } @@ -159,7 +162,7 @@ func TestConvertToMKV_IdentifyOutputFails_KeepsSource(t *testing.T) { src, _ := oldSource(t, dir, "ep.mp4") ident := &outErrIdentifier{pathIdentifier{srcExt: ".mp4", srcTracks: 2}} - if _, err := convertToMKV(src, ident, writeMux); err == nil { + if _, err := convertToMKV(t.Context(), src, ident, writeMux); err == nil { t.Fatal("want an error") } assertOnly(t, dir, "ep.mp4") @@ -168,11 +171,11 @@ func TestConvertToMKV_IdentifyOutputFails_KeepsSource(t *testing.T) { // outErrIdentifier fails to identify anything but the source. type outErrIdentifier struct{ pathIdentifier } -func (o *outErrIdentifier) Identify(path string) (*MKVInfo, error) { +func (o *outErrIdentifier) Identify(ctx context.Context, path string) (*MKVInfo, error) { if !strings.EqualFold(filepath.Ext(path), o.srcExt) { return nil, errors.New("truncated output") } - return o.pathIdentifier.Identify(path) + return o.pathIdentifier.Identify(ctx, path) } func assertContent(t *testing.T, path, want string) { @@ -189,12 +192,12 @@ func assertContent(t *testing.T, path, want string) { func TestConvertToMKV_MuxFails_KeepsSource(t *testing.T) { dir := t.TempDir() src, _ := oldSource(t, dir, "ep.mpg") - partial := func(_, dst string) error { + partial := func(_ context.Context, _, dst string) error { _ = os.WriteFile(dst, []byte("half"), 0o644) return errors.New("mkvmerge: exit status 2") } - if _, err := convertToMKV(src, &pathIdentifier{srcExt: ".mpg", srcTracks: 2, outTracks: 2}, partial); err == nil { + if _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".mpg", srcTracks: 2, outTracks: 2}, partial); err == nil { t.Fatal("want an error") } assertOnly(t, dir, "ep.mpg") @@ -204,7 +207,7 @@ func TestConvertToMKV_TrackCountMismatch_KeepsSource(t *testing.T) { dir := t.TempDir() src, _ := oldSource(t, dir, "ep.mov") - _, err := convertToMKV(src, &pathIdentifier{srcExt: ".mov", srcTracks: 3, outTracks: 2}, writeMux) + _, err := convertToMKV(t.Context(), src, &pathIdentifier{srcExt: ".mov", srcTracks: 3, outTracks: 2}, writeMux) if err == nil || !strings.Contains(err.Error(), "2 tracks, source has 3") { t.Errorf("err = %v, want a track count mismatch", err) } @@ -225,7 +228,7 @@ func TestRealMKVRunner_ConvertToMKV(t *testing.T) { dir := t.TempDir() makeClip := func(name, vcodec, acodec string) string { path := filepath.Join(dir, name) - out, err := exec.Command(ffmpeg, "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=1:size=64x64:rate=5", + out, err := exec.CommandContext(t.Context(), ffmpeg, "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=1:size=64x64:rate=5", "-f", "lavfi", "-i", "sine=duration=1", "-c:v", vcodec, "-c:a", acodec, "-shortest", path).CombinedOutput() if err != nil { t.Fatalf("ffmpeg %s: %v\n%s", name, err, out) @@ -242,11 +245,11 @@ func TestRealMKVRunner_ConvertToMKV(t *testing.T) { t.Fatal(err) } - dst, err := runner.ConvertToMKV(mp4) + dst, err := runner.ConvertToMKV(t.Context(), mp4) if err != nil { t.Fatal(err) } - info, err := runner.Identify(dst) + info, err := runner.Identify(t.Context(), dst) if err != nil { t.Fatal(err) } @@ -265,7 +268,7 @@ func TestRealMKVRunner_ConvertToMKV(t *testing.T) { } wmv := makeClip("other.wmv", "wmv2", "wmav2") - if _, err := runner.ConvertToMKV(wmv); !errors.Is(err, errUnsupportedContainer) { + if _, err := runner.ConvertToMKV(t.Context(), wmv); !errors.Is(err, errUnsupportedContainer) { t.Errorf("wmv: err = %v, want errUnsupportedContainer", err) } assertOnly(t, dir, "clip.mkv", "other.wmv") diff --git a/mkv-audit/convert_walk_test.go b/mkv-audit/convert_walk_test.go index fcbb56c..0a117c2 100644 --- a/mkv-audit/convert_walk_test.go +++ b/mkv-audit/convert_walk_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "os" "os/exec" @@ -18,7 +19,7 @@ type recordingIdentifier struct { paths []string } -func (r *recordingIdentifier) Identify(path string) (*MKVInfo, error) { +func (r *recordingIdentifier) Identify(_ context.Context, path string) (*MKVInfo, error) { r.mu.Lock() defer r.mu.Unlock() if !slices.Contains(r.paths, path) { @@ -27,7 +28,9 @@ func (r *recordingIdentifier) Identify(path string) (*MKVInfo, error) { return &MKVInfo{}, nil } -func (r *recordingIdentifier) ReadTagDate(string) (time.Time, bool) { return time.Time{}, false } +func (r *recordingIdentifier) ReadTagDate(context.Context, string) (time.Time, bool) { + return time.Time{}, false +} func (r *recordingIdentifier) names() []string { var out []string @@ -47,7 +50,7 @@ type fakeConverter struct { calls []string } -func (f *fakeConverter) ConvertToMKV(src string) (string, error) { +func (f *fakeConverter) ConvertToMKV(_ context.Context, src string) (string, error) { f.calls = append(f.calls, filepath.Base(src)) if err, ok := f.errs[filepath.Base(src)]; ok { return "", err @@ -76,7 +79,7 @@ func TestRunAll_ConvertsOtherContainers(t *testing.T) { var stats Stats out := captureStdout(t, func() { - stats = RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) + stats, _ = RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) }) if got, want := ident.names(), []string{"a.mkv", "b.mkv"}; !slices.Equal(got, want) { @@ -105,7 +108,7 @@ func TestRunAll_NilConverterIgnoresOtherContainers(t *testing.T) { makeMKVFile(t, dir, "a.mp4") ident := &recordingIdentifier{} - RunAll(dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) if len(ident.paths) != 0 { t.Errorf("scanned %v, want nothing without a converter", ident.names()) @@ -122,7 +125,7 @@ func TestRunAll_ConvertRespectsCutoff(t *testing.T) { } conv := &fakeConverter{} - stats := RunAll(dir, t.TempDir(), nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{}, nil, nil, conv, cutoff) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{}, nil, nil, conv, cutoff) if len(conv.calls) != 0 || stats.SkippedOld != 1 { t.Errorf("converted %v, SkippedOld = %d; want an old source skipped", conv.calls, stats.SkippedOld) @@ -137,7 +140,7 @@ func TestRunAll_RetryConvertsFailedSource(t *testing.T) { } ident := &recordingIdentifier{} - stats := RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, &fakeConverter{}, time.Time{}) + stats, _ := RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, &fakeConverter{}, time.Time{}) if stats.Converted != 1 || !slices.Equal(ident.names(), []string{"ep.mkv"}) { t.Errorf("Converted = %d, scanned %v; want ep.mp4 converted and ep.mkv scanned", stats.Converted, ident.names()) @@ -157,7 +160,7 @@ func TestRunAll_FullScanDropsFailureForSkippedSource(t *testing.T) { } conv := &fakeConverter{errs: map[string]error{"ep.mp4": errMKVExists}} - RunAll(dir, stateDir, nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) if got := loadFailedCache(stateDir); len(got) != 0 { t.Errorf("failed cache = %v, want empty", got) @@ -170,7 +173,7 @@ func TestRunAll_VerboseConverterPrintsPlan(t *testing.T) { conv := &loggingConverter{inner: &fakeConverter{}} out := captureStdout(t, func() { - RunAll(dir, t.TempDir(), nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{}, nil, nil, conv, time.Time{}) + _, _ = RunAll(t.Context(), dir, t.TempDir(), nil, &recordingIdentifier{}, &fakeEditor{}, &fakePrompter{}, nil, nil, conv, time.Time{}) }) if !strings.Contains(out, ` convert: mkvmerge -o "ep.mkv" "ep.mp4"`) { @@ -191,14 +194,14 @@ func TestRunAll_ConvertsRealMP4(t *testing.T) { } dir := t.TempDir() mp4 := filepath.Join(dir, "clip.mp4") - if out, err := exec.Command(ffmpeg, "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=1:size=64x64:rate=5", + if out, err := exec.CommandContext(t.Context(), ffmpeg, "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=1:size=64x64:rate=5", "-f", "lavfi", "-i", "sine=duration=1", "-c:v", "mpeg4", "-c:a", "aac", "-shortest", mp4).CombinedOutput(); err != nil { t.Fatalf("ffmpeg: %v\n%s", err, out) } var stats Stats out := captureStdout(t, func() { - stats = RunAll(dir, t.TempDir(), nil, runner, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, runner, time.Time{}) + stats, _ = RunAll(t.Context(), dir, t.TempDir(), nil, runner, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, runner, time.Time{}) }) if stats.Converted != 1 || stats.Scanned != 1 || stats.Failed != 0 { @@ -218,7 +221,7 @@ func TestRunAll_ConvertPartialSuccess_ScansMKVAndWarns(t *testing.T) { var stats Stats out := captureStdout(t, func() { - stats = RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) + stats, _ = RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, conv, time.Time{}) }) if stats.Converted != 1 || stats.Failed != 0 || !slices.Equal(ident.names(), []string{"ep.mkv"}) { @@ -240,7 +243,7 @@ func TestRunAll_RetryWithSourceAndMKVScansMKVOnce(t *testing.T) { } ident := &countingIdentifier{} - RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, &fakeConverter{}, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, &fakeConverter{}, time.Time{}) if n := ident.count["ep.mkv"]; n != 2 { // once in the und pass, once in the main pass t.Errorf("ep.mkv identified %d times, want 2 (scanned once)", n) @@ -253,7 +256,7 @@ type countingIdentifier struct { count map[string]int } -func (c *countingIdentifier) Identify(path string) (*MKVInfo, error) { +func (c *countingIdentifier) Identify(_ context.Context, path string) (*MKVInfo, error) { c.mu.Lock() defer c.mu.Unlock() if c.count == nil { @@ -263,4 +266,6 @@ func (c *countingIdentifier) Identify(path string) (*MKVInfo, error) { return &MKVInfo{}, nil } -func (c *countingIdentifier) ReadTagDate(string) (time.Time, bool) { return time.Time{}, false } +func (c *countingIdentifier) ReadTagDate(context.Context, string) (time.Time, bool) { + return time.Time{}, false +} diff --git a/mkv-audit/dirconfig_test.go b/mkv-audit/dirconfig_test.go index 6808bd2..8eb5b40 100644 --- a/mkv-audit/dirconfig_test.go +++ b/mkv-audit/dirconfig_test.go @@ -405,7 +405,7 @@ func TestFetchOrigins_FolderNameStartingWithDots(t *testing.T) { langs: map[string]string{"11": "en"}, } captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "movie", tmdb, &fakePrompter{answer: "y"}) + origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, &fakePrompter{answer: "y"}) if origins[name].OrigLang != "en" { t.Errorf("origins = %v; want en for %s", origins, name) } diff --git a/mkv-audit/interrupt.go b/mkv-audit/interrupt.go new file mode 100644 index 0000000..de4205c --- /dev/null +++ b/mkv-audit/interrupt.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "os/signal" + "slices" +) + +// interruptContext returns a context the first Ctrl+C cancels, so run stops +// before the next file or step. The second also kills any mkvmerge or +// mkvextract in progress (see command), though never mkvpropedit, and a third Ctrl+C quits at once. A quit signal does +// the first two at once, after which Ctrl+C quits at once. +// +// Only the interrupts get their default handling back, so once the children +// are killed further quit signals are absorbed: a closed terminal sends a +// second SIGHUP, which would otherwise end mkv-audit before its children were +// killed. From the first stop or quit, mkv-audit also catches pipeSignals, so a +// pipe reader that the same Ctrl+C ended can't end it. +func interruptContext() context.Context { + ctx, cancel, kill := newInterruptContext() + interrupts := make(chan os.Signal, 2) + quits := make(chan os.Signal, 1) + notify(interrupts, os.Interrupt) + notify(quits, quitSignals...) + stop := func() { + notify(make(chan os.Signal, 1), pipeSignals...) + cancel() + } + go watchSignals(os.Stderr, interrupts, quits, stop, kill, func() { signal.Stop(interrupts) }) + return ctx +} + +// notify relays sigs to c, except those the process started out ignoring, +// such as SIGHUP under nohup: Notify would stop them being ignored. Go reports +// that only for SIGHUP and SIGINT. +func notify(c chan<- os.Signal, sigs ...os.Signal) { + sigs = slices.DeleteFunc(slices.Clone(sigs), signal.Ignored) + if len(sigs) > 0 { // Notify with no signals relays them all + signal.Notify(c, sigs...) + } +} + +// newInterruptContext returns ctx, stop, which cancels it, and kill, which +// cancels the kill context ctx carries for command. +func newInterruptContext() (ctx context.Context, stop, kill context.CancelFunc) { + killCtx, kill := context.WithCancel(context.Background()) + ctx, stop = context.WithCancel(context.WithValue(context.Background(), killKey{}, killCtx)) + return ctx, stop, kill +} + +// watchSignals calls stop on the first interrupt, and kill then restore on the +// second, so a third Ctrl+C gets the default handling. A quit calls all three. +// restore releases only the interrupts; quits stay caught. +func watchSignals(w io.Writer, interrupts, quits <-chan os.Signal, stop, kill, restore func()) { + select { + case <-interrupts: + stop() + fmt.Fprintln(w, "\ninterrupted: stopping before the next 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 mkvmerge in progress (Ctrl+C again to quit at once)") +} diff --git a/mkv-audit/interrupt_run_test.go b/mkv-audit/interrupt_run_test.go new file mode 100644 index 0000000..c211478 --- /dev/null +++ b/mkv-audit/interrupt_run_test.go @@ -0,0 +1,543 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +func init() { + // mkvmerge stands in for mkvmerge: it answers --identify with one video + // track, and otherwise says it's ready and sleeps until killed. + helperModes["mkvmerge"] = func() { + if slices.Contains(os.Args, "--identify") { + fmt.Println(`{"tracks":[{"id":0,"type":"video"}]}`) + return + } + ready() + time.Sleep(time.Minute) + } +} + +// stopPrompter is a Ctrl+C at the prompt: it stops the run and returns the +// blank answer that accepts a prompt's default. +type stopPrompter struct { + stop func() + asked int +} + +func (p *stopPrompter) Ask(string) (string, error) { + p.asked++ + p.stop() + return "", context.Canceled +} + +// interruptingIdentifier returns info, and on call number at (from 1) first +// stops the run, and kills it too when kill is set, returning +// context.Canceled after a kill as the real one does. +type interruptingIdentifier struct { + info *MKVInfo + at int64 + stop, kill func() + calls atomic.Int64 +} + +func (f *interruptingIdentifier) Identify(context.Context, string) (*MKVInfo, error) { + if f.calls.Add(1) != f.at { + return f.info, nil + } + f.stop() + if f.kill != nil { + f.kill() + return nil, fmt.Errorf("identify: %w", context.Canceled) + } + return f.info, nil +} + +func (f *interruptingIdentifier) ReadTagDate(context.Context, string) (time.Time, bool) { + return time.Time{}, false +} + +// cleanAudio needs no edits; needsLangFix needs one. +var ( + cleanAudio = &MKVInfo{Tracks: []Track{{ID: 0, Type: "audio", Properties: TrackProperties{ + Language: "eng", LanguageIETF: "en-US", CodecID: "A_FLAC", AudioChannels: 6, DefaultTrack: true, + }}}} + needsLangFix = &MKVInfo{Tracks: []Track{{ID: 0, Type: "audio", Properties: TrackProperties{ + Language: "en", LanguageIETF: "en", CodecID: "A_AC3", AudioChannels: 2, DefaultTrack: true, + }}}} +) + +// A Ctrl+C before the run starts stops it before anything is read. +func TestRunAll_InterruptedBeforeStart(t *testing.T) { + dir := t.TempDir() + makeMKVFile(t, dir, "a.mkv") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + stop() + ident := &interruptingIdentifier{info: cleanAudio} + + stats, err := RunAll(ctx, dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if n := ident.calls.Load(); n != 0 || stats.Scanned != 0 { + t.Errorf("identified %d files, scanned %d; want none", n, stats.Scanned) + } +} + +// A Ctrl+C at the und prompt applies nothing: the blank answer it reads +// would otherwise accept the default language. +func TestRunAll_InterruptAtUndPromptAppliesNothing(t *testing.T) { + dir := t.TempDir() + makeMKVFile(t, dir, "a.mkv") + und := &MKVInfo{Tracks: []Track{{ID: 0, Type: "audio", Properties: TrackProperties{Language: "und", CodecID: "A_AC3", AudioChannels: 2}}}} + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + editor := &fakeEditor{} + p := &stopPrompter{stop: stop} + + var err error + captureStdout(t, func() { + _, err = RunAll(ctx, dir, t.TempDir(), nil, &fakeIdentifier{info: und}, editor, p, nil, nil, nil, time.Time{}) + }) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if p.asked != 1 || len(editor.calls) != 0 { + t.Errorf("asked %d times, applied %v; want one question and no edits", p.asked, editor.calls) + } +} + +// A Ctrl+C at the TMDB prompt saves no ID: the blank answer it reads would +// otherwise accept the top result. +func TestFetchOrigins_InterruptAtPromptSavesNothing(t *testing.T) { + root, paths := siblingLibrary(t, "Show (2020)", "Show - S01E01.mkv") + paths = append(paths, addEntry(t, root, "Other (2021)", "Other - S01E01.mkv")...) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + p := &stopPrompter{stop: stop} + + out := captureStdout(t, func() { + if origins, _ := fetchOrigins(ctx, paths, root, "tv", searchTMDB{}, p); len(origins) != 0 { + t.Errorf("origins = %v; want none", origins) + } + }) + if p.asked != 1 || strings.Contains(out, "no input") { + t.Errorf("asked %d times; want 1, with no 'no input' line:\n%s", p.asked, out) + } + if _, err := os.Stat(tvShowCachePath()); !os.IsNotExist(err) { + t.Errorf("show cache saved; want nothing saved (%v)", err) + } +} + +// A read the second Ctrl+C killed leaves the file unscanned rather than +// failed, and the failure list keeps earlier failures the run never retried. +func TestRunAll_KilledIdentifyIsNotAFailure(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + old := filepath.Join(dir, "old.mkv") + if err := saveFailedCache(stateDir, []string{old}); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + // Call 1 is the und pass; call 2 is the main pass. + ident := &interruptingIdentifier{info: cleanAudio, at: 2, stop: stop, kill: kill} + + var stats Stats + var err error + captureStdout(t, func() { + stats, err = RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + }) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if stats.Failed != 0 || stats.Scanned != 0 { + t.Errorf("Failed = %d, Scanned = %d; want 0 and 0", stats.Failed, stats.Scanned) + } + if got := loadFailedCache(stateDir); !slices.Equal(got, []string{old}) { + t.Errorf("failure list = %v, want the untried %v", got, []string{old}) + } +} + +// After the second Ctrl+C no edit starts, even for a file already read. +func TestRunAll_NoEditAfterKill(t *testing.T) { + dir := t.TempDir() + makeMKVFile(t, dir, "a.mkv") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + ident := &interruptingIdentifier{info: needsLangFix, at: 2, stop: func() { stop(); kill() }} + editor := &fakeEditor{} + + stats, err := RunAll(ctx, dir, t.TempDir(), nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if len(editor.calls) != 0 || stats.Scanned != 0 { + t.Errorf("applied %v, scanned %d; want no edit and no scan", editor.calls, stats.Scanned) + } +} + +// After one Ctrl+C a file already read is still edited, so it isn't left +// with half its fixes. +func TestRunAll_EditFinishesAfterStop(t *testing.T) { + dir := t.TempDir() + makeMKVFile(t, dir, "a.mkv") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + ident := &interruptingIdentifier{info: needsLangFix, at: 2, stop: stop} + editor := &fakeEditor{} + + var stats Stats + captureStdout(t, func() { + stats, _ = RunAll(ctx, dir, t.TempDir(), nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + }) + if len(editor.calls) != 1 || stats.Fixed != 1 { + t.Errorf("applied %v, fixed %d; want the read file edited", editor.calls, stats.Fixed) + } +} + +// A Ctrl+C in the main pass starts no more files than are already running. +func TestRunAll_InterruptStopsStartingFiles(t *testing.T) { + dir := t.TempDir() + n := 4*runtime.NumCPU() + 4 + for i := range n { + makeMKVFile(t, dir, fmt.Sprintf("%03d.mkv", i)) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + // The und pass reads all n; the main pass's first read stops the run. + ident := &interruptingIdentifier{info: cleanAudio, at: int64(n) + 1, stop: stop} + + var stats Stats + var err error + captureStdout(t, func() { + stats, err = RunAll(ctx, dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + }) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if extra := ident.calls.Load() - int64(n); extra > int64(runtime.NumCPU()) || stats.Scanned > runtime.NumCPU() { + t.Errorf("main pass read %d files and scanned %d after the interrupt; want at most %d", extra, stats.Scanned, runtime.NumCPU()) + } +} + +// interruptingRemuxer stops the run during its first remux. With kill set it +// also kills it and reports the interrupt, as a killed mkvmerge does. +type interruptingRemuxer struct { + stop, kill func() + calls int +} + +func (r *interruptingRemuxer) Remux(context.Context, string, *TrimPlan, MKVInfo) error { + r.calls++ + if r.calls > 1 { + return nil + } + r.stop() + if r.kill != nil { + r.kill() + return fmt.Errorf("mkvmerge: %w", context.Canceled) + } + return nil +} + +// trimLibrary is two episodes whose French subtitles a jpn-origin library trims. +func trimLibrary(t *testing.T) (dir string, lib *Library, info *MKVInfo) { + t.Helper() + dir = t.TempDir() + makeMKVFile(t, dir, "e1.mkv") + makeMKVFile(t, dir, "e2.mkv") + lib = &Library{Path: dir, Overrides: []DirOverride{{Path: ".", OriginLang: "jpn"}}} + info = &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "video", Properties: TrackProperties{Language: "jpn", LanguageIETF: "ja"}}, + {ID: 1, Type: "audio", Properties: TrackProperties{Language: "jpn", LanguageIETF: "ja", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, + {ID: 2, Type: "subtitles", Properties: TrackProperties{Language: "fre", LanguageIETF: "fr", CodecID: "S_TEXT/ASS"}}, + }} + return dir, lib, info +} + +// A Ctrl+C during a remux lets it finish and starts no other. +func TestRunAll_InterruptStopsBeforeNextRemux(t *testing.T) { + dir, lib, info := trimLibrary(t) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + remuxer := &interruptingRemuxer{stop: stop} + + var stats Stats + captureStdout(t, func() { + stats, _ = RunAll(ctx, dir, t.TempDir(), lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "a"}, nil, remuxer, nil, time.Time{}) + }) + if remuxer.calls != 1 || stats.Trimmed != 1 { + t.Errorf("remuxed %d, trimmed %d; want 1 and 1", remuxer.calls, stats.Trimmed) + } +} + +// A remux the second Ctrl+C killed is reported as stopped, not failed. +func TestRunAll_KilledRemuxIsNotAFailure(t *testing.T) { + dir, lib, info := trimLibrary(t) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + remuxer := &interruptingRemuxer{stop: stop, kill: kill} + + var stats Stats + out := captureStdout(t, func() { + stats, _ = RunAll(ctx, dir, t.TempDir(), lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "a"}, nil, remuxer, nil, time.Time{}) + }) + if stats.Failed != 0 || stats.Trimmed != 0 || remuxer.calls != 1 { + t.Errorf("Failed = %d, Trimmed = %d, remuxes = %d; want 0, 0, 1", stats.Failed, stats.Trimmed, remuxer.calls) + } + if strings.Count(out, ".mkv: interrupted; left unchanged") != 1 { // trim order follows the parallel scan + t.Errorf("missing the stop line:\n%s", out) + } +} + +// killingConverter kills the run during its first conversion. +type killingConverter struct { + stop, kill func() + calls int +} + +func (c *killingConverter) ConvertToMKV(context.Context, string) (string, error) { + c.calls++ + c.stop() + c.kill() + return "", fmt.Errorf("mkvmerge: %w", context.Canceled) +} + +// A conversion the second Ctrl+C killed isn't a failure, and no other starts. +func TestConvertAll_KilledIsNotAFailure(t *testing.T) { + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + conv := &killingConverter{stop: stop, kill: kill} + var stats Stats + + var out []string + printed := captureStdout(t, func() { + out = convertAll(ctx, []string{"a.mp4", "b.mp4", "c.mkv"}, conv, &stats) + }) + if conv.calls != 1 || stats.Failed != 0 || stats.Converted != 0 { + t.Errorf("conversions %d, Failed %d, Converted %d; want 1, 0, 0", conv.calls, stats.Failed, stats.Converted) + } + if !slices.Equal(out, []string{"c.mkv"}) { + t.Errorf("kept %v, want only c.mkv", out) + } + if !strings.Contains(printed, "[STOP] a.mp4: interrupted; left unchanged") { + t.Errorf("missing the stop line:\n%s", printed) + } +} + +// waitReady waits for the helper's ready file, failing if result ends first. +func waitReady[T any](t *testing.T, readyFile string, result <-chan T) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); ; { + if _, err := os.Stat(readyFile); err == nil { + return + } + select { + case r := <-result: + t.Fatalf("ended before the helper was ready: %v", r) + case <-time.After(20 * time.Millisecond): + } + if time.Now().After(deadline) { + t.Fatal("helper never started") + } + } +} + +// fakeMKVMerge points a runner's mkvmerge at the test binary's helper mode. +func fakeMKVMerge(t *testing.T, mode string) (r *realMKVRunner, readyFile string) { + t.Helper() + readyFile = filepath.Join(t.TempDir(), "ready") + t.Setenv(helperEnv, mode) + t.Setenv(readyEnv, readyFile) + return &realMKVRunner{mkvmerge: os.Args[0]}, readyFile +} + +// mkvmerge's read outlives the first Ctrl+C; the second kills it and Identify +// reports the interrupt. +func TestIdentify_KilledIsTheInterrupt(t *testing.T) { + r, readyFile := fakeMKVMerge(t, "sleep") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { + _, err := r.Identify(ctx, "a.mkv") + result <- err + }() + waitReady(t, readyFile, result) + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} + +// A remux the second Ctrl+C kills leaves the file as it was and no temp file. +func TestRemux_KilledLeavesFile(t *testing.T) { + r, readyFile := fakeMKVMerge(t, "mkvmerge") + dir := t.TempDir() + src := filepath.Join(dir, "a.mkv") + if err := os.WriteFile(src, []byte("original"), 0o644); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { result <- r.Remux(ctx, src, &TrimPlan{}, MKVInfo{}) }() + waitReady(t, readyFile, result) + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) + if got, err := os.ReadFile(src); err != nil || string(got) != "original" { + t.Errorf("file = %q, %v; want it unchanged", got, err) + } + assertNoTempFiles(t, dir) +} + +// A conversion the second Ctrl+C kills leaves the source and makes no MKV. +func TestConvertToMKV_KilledLeavesSource(t *testing.T) { + r, readyFile := fakeMKVMerge(t, "mkvmerge") + dir := t.TempDir() + src := filepath.Join(dir, "a.mp4") + if err := os.WriteFile(src, []byte("original"), 0o644); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { + _, err := r.ConvertToMKV(ctx, src) + result <- err + }() + waitReady(t, readyFile, result) + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) + if _, err := os.Stat(src); err != nil { + t.Errorf("source gone: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "a.mkv")); !os.IsNotExist(err) { + t.Errorf("a.mkv exists after the kill (%v)", err) + } + assertNoTempFiles(t, dir) +} + +// A TMDB request in flight ends with the Ctrl+C, and the error still hides +// the API key. +func TestGetTMDB_InterruptEndsRequest(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + t.Cleanup(srv.Close) + c := &httpTMDBOriginClient{apiKey: "secret", client: srv.Client()} + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(50*time.Millisecond, cancel) + + resp, err := c.getTMDB(ctx, srv.URL+"/3/tv/1?api_key=secret") + if err == nil { + resp.Body.Close() + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if err != nil && strings.Contains(err.Error(), "secret") { + t.Errorf("err = %v shows the API key", err) + } +} + +func TestFinish(t *testing.T) { + cases := []struct { + name string + err error + wantCode int + wantLabel string + }{ + {"done", nil, 0, "FINAL SUMMARY"}, + {"interrupted", fmt.Errorf("walk: %w", context.Canceled), 130, "INTERRUPTED"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var w strings.Builder + if code := finish(&w, Stats{Fixed: 3}, tc.err); code != tc.wantCode { + t.Errorf("exit code = %d, want %d", code, tc.wantCode) + } + if !strings.Contains(w.String(), "=\n"+tc.wantLabel+"\n=") || !strings.Contains(w.String(), "Total Fixed: 3") { + t.Errorf("summary = %q, want it headed %q with the counts", w.String(), tc.wantLabel) + } + }) + } +} + +func TestPrompter_Answers(t *testing.T) { + cases := []struct{ input, want string }{{"y\n", "y"}, {" a \r\n", "a"}, {"\n", ""}, {"en-GB", "en-GB"}} + for _, tc := range cases { + var w strings.Builder + got, err := newPrompter(t.Context(), strings.NewReader(tc.input), &w).Ask("fix? ") + if err != nil || got != tc.want { + t.Errorf("answer %q = %q, %v; want %q", tc.input, got, err, tc.want) + } + if w.String() != "fix? " { + t.Errorf("question written as %q", w.String()) + } + } +} + +// EOF with no answer and no interrupt is an error, as it was. +func TestPrompter_EOF(t *testing.T) { + if _, err := newPrompter(t.Context(), strings.NewReader(""), io.Discard).Ask("q"); !errors.Is(err, io.EOF) { + t.Errorf("error = %v, want io.EOF", err) + } +} + +// An interrupt stops a prompt that is waiting for an answer. +func TestPrompter_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 := newPrompter(ctx, r, io.Discard).Ask("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 TestPrompter_EOFBeforeInterrupt(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(eofGrace/5, cancel) + + if _, err := newPrompter(ctx, strings.NewReader(""), io.Discard).Ask("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } +} + +// A prompt after the interrupt asks nothing. +func TestPrompter_InterruptBeforeQuestion(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var w strings.Builder + if _, err := newPrompter(ctx, strings.NewReader("y\n"), &w).Ask("q"); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } + if w.Len() != 0 { + t.Errorf("question written as %q after the interrupt", w.String()) + } +} diff --git a/mkv-audit/interrupt_test.go b/mkv-audit/interrupt_test.go new file mode 100644 index 0000000..f551ab6 --- /dev/null +++ b/mkv-audit/interrupt_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "os" + "strings" + "testing" + "time" +) + +// watchSignalsOn runs watchSignals, sending it "interrupt" or "quit" for each +// of sends, and returns the stop/kill/restore calls it made and its notices. +func watchSignalsOn(t *testing.T, sends ...string) (calls, notices string) { + t.Helper() + interrupts, quits := make(chan os.Signal), make(chan os.Signal) + var w strings.Builder + var got []string + record := func(name string) func() { return func() { got = append(got, name) } } + done := make(chan struct{}) + go func() { + watchSignals(&w, interrupts, quits, record("stop"), record("kill"), record("restore")) + close(done) + }() + for _, s := range sends { + ch := interrupts + if s == "quit" { + ch = quits + } + select { + case ch <- os.Interrupt: + case <-done: + t.Fatalf("watchSignals returned before %s", s) + } + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("watchSignals still running") + } + return strings.Join(got, " "), w.String() +} + +func TestWatchSignals(t *testing.T) { + cases := []struct { + sends []string + wantCalls string + notices int + }{ + // kill comes before restore, so the kill is requested before a third + // Ctrl+C gets the default handling. + {[]string{"interrupt", "interrupt"}, "stop kill restore", 2}, + // A quit calls restore too, so a Ctrl+C after it quits at once. + {[]string{"quit"}, "stop kill restore", 0}, + {[]string{"interrupt", "quit"}, "stop kill restore", 2}, + } + for _, tc := range cases { + calls, notices := watchSignalsOn(t, tc.sends...) + if calls != tc.wantCalls { + t.Errorf("%v: calls %q, want %q", tc.sends, calls, tc.wantCalls) + } + if n := strings.Count(notices, "interrupted:"); n != tc.notices { + t.Errorf("%v: %d notices, want %d: %q", tc.sends, n, tc.notices, notices) + } + } +} + +// The first stop leaves the kill context running; kill cancels it. +func TestNewInterruptContext(t *testing.T) { + ctx, stop, kill := newInterruptContext() + killCtx := killContext(ctx) + stop() + if ctx.Err() == nil || killCtx.Err() != nil { + t.Fatalf("after stop: ctx %v, kill context %v; want ctx cancelled only", ctx.Err(), killCtx.Err()) + } + kill() + if killCtx.Err() == nil { + t.Error("kill left the kill context running") + } +} diff --git a/mkv-audit/main.go b/mkv-audit/main.go index d226f83..0a1b071 100644 --- a/mkv-audit/main.go +++ b/mkv-audit/main.go @@ -1,8 +1,11 @@ package main import ( + "context" + "errors" "flag" "fmt" + "io" "os" "path/filepath" "strings" @@ -112,24 +115,40 @@ func main() { ed = &loggingEditor{inner: runner} conv = &loggingConverter{inner: runner} } - stats := RunAll(dir, stateDir, lib, runner, ed, newStdinPrompter(), tmdb, runner, conv, cutoffDate) + ctx := interruptContext() + stats, err := RunAll(ctx, dir, stateDir, lib, runner, ed, newStdinPrompter(ctx), tmdb, runner, conv, cutoffDate) + os.Exit(finish(os.Stdout, stats, err)) +} + +// finish prints RunAll's summary and returns the exit code: 130 after an +// interrupt, else 0. +func finish(w io.Writer, stats Stats, err error) int { + if errors.Is(err, context.Canceled) { + printSummary(w, "INTERRUPTED", stats) + return 130 + } + printSummary(w, "FINAL SUMMARY", stats) + return 0 +} - fmt.Println() - fmt.Println("========================================") - fmt.Printf("%-24s%s\n", "FINAL SUMMARY", "") - fmt.Println("========================================") - fmt.Printf("Total Converted to MKV: %d\n", stats.Converted) - fmt.Printf("Total Scanned: %d\n", stats.Scanned) - fmt.Printf("Total Skipped (old): %d\n", stats.SkippedOld) - fmt.Printf("Total Fixed: %d\n", stats.Fixed) - fmt.Printf("Total Trimmed: %d\n", stats.Trimmed) - fmt.Printf("Total Failed/Skipped: %d\n", stats.Failed) - fmt.Println("----------------------------------------") - fmt.Printf("Langs Normalized: %d\n", stats.LangFixes) - fmt.Printf("IETF Tags Fixed: %d\n", stats.IETFFixes) - fmt.Printf("Video Lang Inherited: %d\n", stats.VideoInherit) - fmt.Printf("Flag Rules Applied: %d\n", stats.FlagFixes) - fmt.Printf("Names Added: %d\n", stats.NamesAdded) - fmt.Printf("Date Header Fixes: %d\n", stats.DateFixes) - fmt.Println("========================================") +// printSummary writes the closing counts, headed by label. +func printSummary(w io.Writer, label string, stats Stats) { + fmt.Fprintln(w) + fmt.Fprintln(w, "========================================") + fmt.Fprintln(w, label) + fmt.Fprintln(w, "========================================") + fmt.Fprintf(w, "Total Converted to MKV: %d\n", stats.Converted) + fmt.Fprintf(w, "Total Scanned: %d\n", stats.Scanned) + fmt.Fprintf(w, "Total Skipped (old): %d\n", stats.SkippedOld) + fmt.Fprintf(w, "Total Fixed: %d\n", stats.Fixed) + fmt.Fprintf(w, "Total Trimmed: %d\n", stats.Trimmed) + fmt.Fprintf(w, "Total Failed/Skipped: %d\n", stats.Failed) + fmt.Fprintln(w, "----------------------------------------") + fmt.Fprintf(w, "Langs Normalized: %d\n", stats.LangFixes) + fmt.Fprintf(w, "IETF Tags Fixed: %d\n", stats.IETFFixes) + fmt.Fprintf(w, "Video Lang Inherited: %d\n", stats.VideoInherit) + fmt.Fprintf(w, "Flag Rules Applied: %d\n", stats.FlagFixes) + fmt.Fprintf(w, "Names Added: %d\n", stats.NamesAdded) + fmt.Fprintf(w, "Date Header Fixes: %d\n", stats.DateFixes) + fmt.Fprintln(w, "========================================") } diff --git a/mkv-audit/mka_date.go b/mkv-audit/mka_date.go index b53580e..c2aacdc 100644 --- a/mkv-audit/mka_date.go +++ b/mkv-audit/mka_date.go @@ -1,10 +1,10 @@ package main import ( + "context" "encoding/xml" "fmt" "os" - "os/exec" "strings" "time" ) @@ -25,7 +25,7 @@ type mkaTagsDoc struct { // readTagDateFromMKA extracts the DATE_RECORDED tag from an MKA (or MKV) file's // Matroska tags section using mkvextract. Returns the date and true on success. -func readTagDateFromMKA(mkvextractPath, path string) (time.Time, bool) { +func readTagDateFromMKA(ctx context.Context, mkvextractPath, path string) (time.Time, bool) { tmp, err := os.CreateTemp("", "mkv-audit-tags-*.xml") if err != nil { return time.Time{}, false @@ -33,7 +33,7 @@ func readTagDateFromMKA(mkvextractPath, path string) (time.Time, bool) { tmp.Close() defer os.Remove(tmp.Name()) - cmd := exec.Command(mkvextractPath, path, "tags", tmp.Name()) + cmd := command(ctx, mkvextractPath, path, "tags", tmp.Name()) cmd.Stdout = nil cmd.Stderr = nil if err := cmd.Run(); err != nil { diff --git a/mkv-audit/prompt.go b/mkv-audit/prompt.go index e4a5c8b..d105ab4 100644 --- a/mkv-audit/prompt.go +++ b/mkv-audit/prompt.go @@ -2,9 +2,13 @@ package main import ( "bufio" + "context" + "errors" "fmt" + "io" "os" "strings" + "time" ) // Prompter prints a prompt and reads a line of user input. @@ -12,21 +16,65 @@ type Prompter interface { Ask(prompt string) (string, error) } +// eofGrace is how long a prompt that read EOF waits for the interrupt that +// may have caused it. +const eofGrace = 250 * time.Millisecond + type stdinPrompter struct { - scanner *bufio.Scanner + ctx context.Context + r *bufio.Reader + w io.Writer +} + +// newStdinPrompter asks on stdout and reads answers from stdin until ctx is +// cancelled. +func newStdinPrompter(ctx context.Context) *stdinPrompter { + return newPrompter(ctx, os.Stdin, os.Stdout) } -func newStdinPrompter() *stdinPrompter { - return &stdinPrompter{scanner: bufio.NewScanner(os.Stdin)} +func newPrompter(ctx context.Context, r io.Reader, w io.Writer) *stdinPrompter { + return &stdinPrompter{ctx: ctx, r: bufio.NewReader(r), w: w} } +// Ask writes prompt and returns the trimmed answer. Once ctx is cancelled it +// returns ctx's error without waiting for an answer. A read that ends in EOF +// first waits up to eofGrace for ctx to be cancelled. func (p *stdinPrompter) Ask(prompt string) (string, error) { - fmt.Print(prompt) - if !p.scanner.Scan() { - if err := p.scanner.Err(); err != nil { - return "", err + if err := p.ctx.Err(); err != nil { + return "", err + } + fmt.Fprint(p.w, prompt) + type answer struct { + line string + err error + } + // 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 := p.r.ReadString('\n') + c <- answer{line, err} + }() + var a answer + select { + case <-p.ctx.Done(): + return "", p.ctx.Err() + case a = <-c: + } + // On Windows a Ctrl+C at the prompt ends the read with EOF, which can + // arrive before the signal does, so any EOF waits briefly for it. + if errors.Is(a.err, io.EOF) { + select { + case <-p.ctx.Done(): + case <-time.After(eofGrace): } - return "", fmt.Errorf("EOF") } - return strings.TrimSpace(p.scanner.Text()), nil + if err := p.ctx.Err(); err != nil { + return "", err + } + // A last line without a newline is still an answer. + if a.err != nil && (!errors.Is(a.err, io.EOF) || a.line == "") { + return "", a.err + } + return strings.TrimSpace(a.line), nil } diff --git a/mkv-audit/remux.go b/mkv-audit/remux.go index 333d4a9..a4dfa5f 100644 --- a/mkv-audit/remux.go +++ b/mkv-audit/remux.go @@ -1,9 +1,10 @@ package main import ( + "context" + "errors" "fmt" "os" - "os/exec" "path/filepath" "strconv" "strings" @@ -11,13 +12,13 @@ import ( // MKVRemuxer creates a new MKV file with a subset/reordering of tracks. type MKVRemuxer interface { - Remux(filePath string, plan *TrimPlan, info MKVInfo) error + Remux(ctx context.Context, filePath string, plan *TrimPlan, info MKVInfo) error } // Remux implements MKVRemuxer on realMKVRunner. It uses mkvmerge to produce a // new file containing only the tracks in plan.KeepAudio and plan.KeepSubs, in // the desired order, then atomically replaces the original file. -func (r *realMKVRunner) Remux(filePath string, plan *TrimPlan, info MKVInfo) error { +func (r *realMKVRunner) Remux(ctx context.Context, filePath string, plan *TrimPlan, info MKVInfo) error { // Use a short-named temp file in the same directory so rename works across // the same drive, but the path stays within MAX_PATH even for long filenames. tmpFile, err := os.CreateTemp(filepath.Dir(filePath), "mkv-audit-*.tmp") @@ -72,8 +73,11 @@ func (r *realMKVRunner) Remux(filePath string, plan *TrimPlan, info MKVInfo) err args = append(args, filePath) - if out, err := exec.Command(r.mkvmerge, args...).CombinedOutput(); err != nil { + if out, err := command(ctx, r.mkvmerge, args...).CombinedOutput(); err != nil { os.Remove(tmpPath) + if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { + return err + } return fmt.Errorf("mkvmerge: %w\n%s", err, out) } diff --git a/mkv-audit/retag_test.go b/mkv-audit/retag_test.go index a6ef364..6088828 100644 --- a/mkv-audit/retag_test.go +++ b/mkv-audit/retag_test.go @@ -73,7 +73,7 @@ func runRetag(t *testing.T, originLang string, files []string, audioLangs []stri } var stats Stats out := captureStdout(t, func() { - stats = RunAll(dir, t.TempDir(), lib, &fakeIdentifier{info: &MKVInfo{Tracks: tracks}}, ed, pr, nil, &recordingRemuxer{}, nil, time.Time{}) + stats, _ = RunAll(t.Context(), dir, t.TempDir(), lib, &fakeIdentifier{info: &MKVInfo{Tracks: tracks}}, ed, pr, nil, &recordingRemuxer{}, nil, time.Time{}) }) return stats, out } diff --git a/mkv-audit/runner.go b/mkv-audit/runner.go index 46bea63..3225d00 100644 --- a/mkv-audit/runner.go +++ b/mkv-audit/runner.go @@ -1,7 +1,9 @@ package main import ( + "context" "encoding/json" + "errors" "fmt" "os" "os/exec" @@ -20,14 +22,16 @@ const ( ) // MKVIdentifier reads track metadata from an MKV file. +// ctx's kill context (see command) kills a read in progress. type MKVIdentifier interface { - Identify(filePath string) (*MKVInfo, error) + Identify(ctx context.Context, filePath string) (*MKVInfo, error) // ReadTagDate returns the DATE_RECORDED Matroska tag value and true when // present. Returns zero time and false when absent or unsupported. - ReadTagDate(filePath string) (time.Time, bool) + ReadTagDate(ctx context.Context, filePath string) (time.Time, bool) } -// MKVEditor applies edits to an MKV file via mkvpropedit. +// MKVEditor applies edits to an MKV file via mkvpropedit. It takes no ctx: +// mkvpropedit edits the file in place, so it is never killed part-way. type MKVEditor interface { Apply(filePath string, edits []string) error } @@ -51,15 +55,18 @@ func newRealMKVRunner() (*realMKVRunner, error) { return &realMKVRunner{mkvmerge: merge, mkvpropedit: prop, mkvextract: extract}, nil } -func (r *realMKVRunner) ReadTagDate(filePath string) (time.Time, bool) { +func (r *realMKVRunner) ReadTagDate(ctx context.Context, filePath string) (time.Time, bool) { if r.mkvextract == "" { return time.Time{}, false } - return readTagDateFromMKA(r.mkvextract, filePath) + return readTagDateFromMKA(ctx, r.mkvextract, filePath) } -func (r *realMKVRunner) Identify(filePath string) (*MKVInfo, error) { - out, err := exec.Command(r.mkvmerge, "--identify", "--identification-format", "json", filePath).Output() +func (r *realMKVRunner) Identify(ctx context.Context, filePath string) (*MKVInfo, error) { + out, err := command(ctx, r.mkvmerge, "--identify", "--identification-format", "json", filePath).Output() + if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { + return nil, err + } if err != nil { // mkvmerge exits non-zero on warnings; try parsing anyway. if len(out) == 0 { @@ -75,7 +82,8 @@ func (r *realMKVRunner) Identify(filePath string) (*MKVInfo, error) { func (r *realMKVRunner) Apply(filePath string, edits []string) error { args := append([]string{filePath}, edits...) - cmd := exec.Command(r.mkvpropedit, args...) + // Background: no kill context, so an in-place edit always finishes. + cmd := command(context.Background(), r.mkvpropedit, args...) out, err := cmd.CombinedOutput() if err != nil { if len(out) > 0 { @@ -236,7 +244,7 @@ func groupsMovieFolders(libraryRoot, rel string, memo map[string]bool) bool { // and the user is prompted to accept it, enter a manual TMDB ID, or skip. An // ID whose origin TMDB returns is saved back to the sibling cache so future // runs (and mkv-tvshow / mkv-movie) can skip the search step. -func fetchOrigins(filesToScan []string, libraryRoot, libType string, tmdb TMDBOriginClient, prompter Prompter) (origins map[string]OriginInfo, roots map[string]string) { +func fetchOrigins(ctx context.Context, filesToScan []string, libraryRoot, libType string, tmdb TMDBOriginClient, prompter Prompter) (origins map[string]OriginInfo, roots map[string]string) { origins = make(map[string]OriginInfo) if tmdb == nil || libraryRoot == "" || (libType != "tv" && libType != "movie") { return origins, nil @@ -260,6 +268,9 @@ func fetchOrigins(filesToScan []string, libraryRoot, libType string, tmdb TMDBOr dirFiles[dir] = append(dirFiles[dir], path) } for _, dir := range dirs { + if ctx.Err() != nil { + break + } title, year := dirTitleYear(filepath.Base(dir)) if title == "" { continue @@ -279,7 +290,7 @@ func fetchOrigins(filesToScan []string, libraryRoot, libType string, tmdb TMDBOr } cached := len(ids) > 0 if !cached && !skipAll { - if id := resolveTMDBID(dir, title, year, libType, tmdb, prompter, &autoAll, &skipAll); id != "" { + if id := resolveTMDBID(ctx, dir, title, year, libType, tmdb, prompter, &autoAll, &skipAll); id != "" { ids = []string{id} } } @@ -293,10 +304,13 @@ func fetchOrigins(filesToScan []string, libraryRoot, libType string, tmdb TMDBOr fmt.Printf("[TMDB] %s: no original language from TMDB for id %s, trying id %s\n", dir, id, next) } id = next - if info, found, err = getOrigin(id); err != nil || found { + if info, found, err = getOrigin(ctx, id); err != nil || found { break } } + if ctx.Err() != nil { + break // the lookup may have been cut short + } if err != nil { fmt.Printf("[TMDB] %s: %v\n", dir, err) continue @@ -349,7 +363,7 @@ func fetchOrigins(filesToScan []string, libraryRoot, libType string, tmdb TMDBOr // result or enter a manual ID, and returns the confirmed ID. // Returns "" when the user skips or no prompter is available. When the // prompter fails (stdin closed), it sets skipAll, so no more are asked. -func resolveTMDBID(dir, title, year, libType string, tmdb TMDBOriginClient, prompter Prompter, autoAll, skipAll *bool) string { +func resolveTMDBID(ctx context.Context, dir, title, year, libType string, tmdb TMDBOriginClient, prompter Prompter, autoAll, skipAll *bool) string { if prompter == nil || *skipAll { return "" } @@ -358,7 +372,10 @@ func resolveTMDBID(dir, title, year, libType string, tmdb TMDBOriginClient, prom switch libType { case "tv": - candidates, err := tmdb.SearchTV(title, year) + candidates, err := tmdb.SearchTV(ctx, title, year) + if ctx.Err() != nil { + return "" + } if err != nil { fmt.Printf("[TMDB] %s: search error: %v\n", dir, err) return "" @@ -369,7 +386,10 @@ func resolveTMDBID(dir, title, year, libType string, tmdb TMDBOriginClient, prom topYear = candidates[0].Year } case "movie": - candidates, err := tmdb.SearchMovie(title, year) + candidates, err := tmdb.SearchMovie(ctx, title, year) + if ctx.Err() != nil { + return "" + } if err != nil { fmt.Printf("[TMDB] %s: search error: %v\n", dir, err) return "" @@ -390,6 +410,9 @@ func resolveTMDBID(dir, title, year, libType string, tmdb TMDBOriginClient, prom } for { ans, err := prompter.Ask(prompt) + if ctx.Err() != nil { + return "" // not the blank answer that accepts the top result + } if err != nil { *skipAll = true fmt.Printf("\n[TMDB] no input (%v), so TMDB lookups are skipped for the rest of the run\n", err) @@ -469,8 +492,12 @@ type trimCandidate struct { // retagOnlyAudio offers to set a file's only audio track to the original // language: language, plus language-ietf when the language has an IETF mapping. -// Answering "a" sets *all so later files are retagged without asking. -func retagOnlyAudio(tc trimCandidate, track Track, editor MKVEditor, prompter Prompter, all *bool, stats *Stats) { +// Answering "a" sets *all so later files are retagged without asking. Once ctx +// is cancelled it does nothing. +func retagOnlyAudio(ctx context.Context, tc trimCandidate, track Track, editor MKVEditor, prompter Prompter, all *bool, stats *Stats) { + if ctx.Err() != nil { + return + } basename := filepath.Base(tc.path) ietf, hasIETF := tc.ietfMap[tc.originLang] if !*all { @@ -480,6 +507,9 @@ func retagOnlyAudio(tc trimCandidate, track Track, editor MKVEditor, prompter Pr } ans, _ := prompter.Ask(fmt.Sprintf("[RETAG] %s\n audio track: %q → %s\n Retag as the original language? (y/n/a=all): ", basename, normalizeLanguage(track.Properties.Language), target)) + if ctx.Err() != nil { + return + } switch strings.ToLower(strings.TrimSpace(ans)) { case "a": *all = true @@ -530,7 +560,12 @@ func applyLangFixes(tracks []Track, fixes []langFix) []Track { // skip track trimming entirely. // converter remuxes other video containers (see convertExts) to MKV before // processing; pass nil to process only .mkv and .mka files. -func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKVEditor, prompter Prompter, tmdb TMDBOriginClient, remuxer MKVRemuxer, converter MKVConverter, cutoffDate time.Time) Stats { +// +// Once ctx is cancelled it starts no more files, prompts or remuxes, and +// returns ctx's error; a file already being edited is finished. Its kill +// context (see command) kills mkvmerge and mkvextract, never mkvpropedit, and a +// file whose read was killed is left unchanged rather than counted as failed. +func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVIdentifier, editor MKVEditor, prompter Prompter, tmdb TMDBOriginClient, remuxer MKVRemuxer, converter MKVConverter, cutoffDate time.Time) (Stats, error) { var stats Stats var trimCandidates []trimCandidate var langMismatches []langMismatchCandidate @@ -542,6 +577,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV oldFails := loadFailedCache(stateDir) if len(oldFails) > 0 { ans, _ := prompter.Ask(fmt.Sprintf("Found %d previously failed files. Run only these? (y/n): ", len(oldFails))) + if err := ctx.Err(); err != nil { + return stats, err + } if strings.ToLower(strings.TrimSpace(ans)) == "y" { filesToScan = oldFails } @@ -550,8 +588,11 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV fullScan := len(filesToScan) == 0 var unreadable []string if fullScan { - // The callback never returns an error, so neither does WalkDir. + // The callback returns only ctx's error, which the run reports below. _ = filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if ctxErr := ctx.Err(); ctxErr != nil { + return ctxErr + } if err != nil { fmt.Printf("[WARN] skipping unreadable %s: %v\n", path, err) unreadable = append(unreadable, path) @@ -581,7 +622,7 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV // earlier failure on a source counts as retried even if it's skipped now. attempted := filesToScan if converter != nil { - filesToScan = convertAll(filesToScan, converter, &stats) + filesToScan = convertAll(ctx, filesToScan, converter, &stats) } // Pre-compute TMDB origin info sequentially before the concurrent phase. @@ -591,7 +632,7 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV libRoot = lib.Path libType = lib.Type } - origins, roots := fetchOrigins(filesToScan, libRoot, libType, tmdb, prompter) + origins, roots := fetchOrigins(ctx, filesToScan, libRoot, libType, tmdb, prompter) // Per-title audio language preferences from mkv-tvshow / mkv-movie, so trim // keeps the audio each Plex account actually watches. @@ -605,12 +646,18 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV var mu sync.Mutex var wg sync.WaitGroup for _, path := range filesToScan { + if ctx.Err() != nil { + break + } wg.Add(1) sem <- struct{}{} go func(p string) { defer wg.Done() defer func() { <-sem }() - info, err := ident.Identify(p) + if ctx.Err() != nil { + return + } + info, err := ident.Identify(ctx, p) if err != nil { return } @@ -641,6 +688,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV if len(undCandidates) > 0 { autoAll := false for _, uc := range undCandidates { + if ctx.Err() != nil { + break + } basename := filepath.Base(uc.path) defaultIETF := uc.resolvedIETF["eng"] if defaultIETF == "" { @@ -649,6 +699,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV ietfChoice := defaultIETF if !autoAll { ans, _ := prompter.Ask(fmt.Sprintf("[UND] %s: audio track language is 'und'. Enter IETF language [%s]: ", basename, defaultIETF)) + if ctx.Err() != nil { + break // not the blank answer that accepts the default + } ans = strings.TrimSpace(ans) switch { case strings.EqualFold(ans, "a"): @@ -687,11 +740,17 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV var wg sync.WaitGroup for _, path := range filesToScan { + if ctx.Err() != nil { + break + } wg.Add(1) sem <- struct{}{} go func(p string) { defer wg.Done() defer func() { <-sem }() + if ctx.Err() != nil { + return + } basename := filepath.Base(p) var buf strings.Builder @@ -704,8 +763,11 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV ietfMap := resolveIETFMap(p, libRoot, lib, origin) originLang := resolveOriginLang(p, libRoot, lib, origin) - info, err := ident.Identify(p) + info, err := ident.Identify(ctx, p) var res AnalysisResult + if errors.Is(err, context.Canceled) { + return // killed: the file is unchanged and not a failure + } if err != nil { fmt.Fprintf(&buf, "[ERR] %s: %v\n", basename, err) local.Failed++ @@ -773,7 +835,7 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV // the container date header; append a fix edit when they differ. var dateFix int if !res.Failed && strings.EqualFold(filepath.Ext(basename), ".mka") { - if tagDate, ok := ident.ReadTagDate(p); ok { + if tagDate, ok := ident.ReadTagDate(ctx, p); ok { needsFix := true if info.Container.Properties.DateUTC != nil { containerDate := time.Unix(int64(*info.Container.Properties.DateUTC), 0).UTC() @@ -787,6 +849,11 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV } } + // After a second Ctrl+C, start no edit and leave the file + // unscanned: a killed mkvextract may have hidden a date fix. + if killContext(ctx).Err() != nil { + return + } if res.Failed { fmt.Fprintf(&buf, "[FAILED] %s: %s\n", basename, strings.Join(res.FailReasons, ", ")) local.Failed++ @@ -855,6 +922,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV if len(langMismatches) > 0 { autoAll := false for _, lm := range langMismatches { + if ctx.Err() != nil { + break + } basename := filepath.Base(lm.path) if !autoAll { var lines []string @@ -862,6 +932,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV lines = append(lines, fmt.Sprintf(" %s track: %q → %s (%s)", f.trackType, f.currentLang, f.targetLang, f.targetIETF)) } ans, _ := prompter.Ask(fmt.Sprintf("[LANGFIX] %s\n%s\n Fix language? (y/n/a=all): ", basename, strings.Join(lines, "\n"))) + if ctx.Err() != nil { + break + } ans = strings.ToLower(strings.TrimSpace(ans)) switch ans { case "a": @@ -893,6 +966,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV if remuxer != nil { autoAll, retagAll := false, false for _, tc := range trimCandidates { + if ctx.Err() != nil { + break + } // Reflect any lang fixes applied above so the plan doesn't drop a // track whose language was just corrected on disk. if fixes, ok := appliedLangFixes[tc.path]; ok { @@ -911,14 +987,17 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV // With one audio track the tag is the likely mistake, so offer to // fix it. With several it isn't clear which one to retag. if len(plan.MismatchedAudio) == 1 { - retagOnlyAudio(tc, plan.MismatchedAudio[0], editor, prompter, &retagAll, &stats) + retagOnlyAudio(ctx, tc, plan.MismatchedAudio[0], editor, prompter, &retagAll, &stats) } - if !plan.NeedsChange { + if !plan.NeedsChange || ctx.Err() != nil { continue } if !autoAll { summary := TrimSummary(plan) ans, _ := prompter.Ask(fmt.Sprintf("[TRIM] %s\n%s Proceed? (y/n/a=all): ", basename, summary)) + if ctx.Err() != nil { + break + } ans = strings.ToLower(strings.TrimSpace(ans)) switch ans { case "a": @@ -931,7 +1010,9 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV } } fmt.Printf("[TRIMMING] %s...\n", basename) - if err := remuxer.Remux(tc.path, plan, tc.info); err != nil { + if err := remuxer.Remux(ctx, tc.path, plan, tc.info); errors.Is(err, context.Canceled) { + fmt.Printf("[STOP] %s: interrupted; left unchanged\n", basename) + } else if err != nil { fmt.Printf("[ERR] %s: remux: %v\n", basename, err) stats.Failed++ stats.FailedPaths = append(stats.FailedPaths, tc.path) @@ -943,9 +1024,14 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV } // Persist failure list and unknown codecs. Earlier failures a full scan - // didn't retry stay listed. + // didn't retry stay listed, as do all of them after an interrupt, which + // may have skipped any file. failed := stats.FailedPaths - if fullScan { + if ctx.Err() != nil { + failed = slices.Concat(oldFails, failed) + slices.Sort(failed) + failed = slices.Compact(failed) + } else if fullScan { failed = slices.Concat(failed, unscannedFailures(oldFails, slices.Concat(attempted, filesToScan), root, unreadable)) } if len(failed) > 0 { @@ -968,5 +1054,5 @@ func RunAll(root, stateDir string, lib *Library, ident MKVIdentifier, editor MKV } } - return stats + return stats, ctx.Err() } diff --git a/mkv-audit/runner_test.go b/mkv-audit/runner_test.go index 52d27c6..3804d68 100644 --- a/mkv-audit/runner_test.go +++ b/mkv-audit/runner_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "io" "os" @@ -18,11 +19,11 @@ type fakeIdentifier struct { err error } -func (f *fakeIdentifier) Identify(_ string) (*MKVInfo, error) { +func (f *fakeIdentifier) Identify(_ context.Context, _ string) (*MKVInfo, error) { return f.info, f.err } -func (f *fakeIdentifier) ReadTagDate(_ string) (time.Time, bool) { +func (f *fakeIdentifier) ReadTagDate(_ context.Context, _ string) (time.Time, bool) { return time.Time{}, false } @@ -66,7 +67,7 @@ func TestRunAll_NoEditsNeeded_OK(t *testing.T) { }} editor := &fakeEditor{} - stats := RunAll(dir, t.TempDir(), nil, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) if stats.Scanned != 1 { t.Errorf("Scanned=%d, want 1", stats.Scanned) @@ -81,7 +82,7 @@ func TestRunAll_IdentifyError_CountsFailed(t *testing.T) { makeMKVFile(t, dir, "bad.mkv") ident := &fakeIdentifier{err: fmt.Errorf("mkvmerge failed")} - stats := RunAll(dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) if stats.Failed != 1 { t.Errorf("Failed=%d, want 1", stats.Failed) @@ -104,7 +105,7 @@ func TestRunAll_EditsApplied_CountsFixed(t *testing.T) { }} editor := &fakeEditor{} - stats := RunAll(dir, t.TempDir(), nil, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) if stats.Fixed != 1 { t.Errorf("Fixed=%d, want 1", stats.Fixed) @@ -120,7 +121,7 @@ func TestRunAll_SkipsNonMKV(t *testing.T) { t.Fatal(err) } - stats := RunAll(dir, t.TempDir(), nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) if stats.Scanned != 0 { t.Errorf("Scanned=%d, want 0 for non-MKV file", stats.Scanned) } @@ -137,7 +138,7 @@ func TestRunAll_MKAIncluded(t *testing.T) { }}, }} - stats := RunAll(dir, t.TempDir(), nil, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + stats, _ := RunAll(t.Context(), dir, t.TempDir(), nil, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) if stats.Scanned != 1 { t.Errorf("Scanned=%d, want 1 for .mka file", stats.Scanned) } @@ -165,7 +166,7 @@ func TestRunAll_UnreadableRootWarns(t *testing.T) { var stats Stats out := captureStdout(t, func() { - stats = RunAll(root, t.TempDir(), nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + stats, _ = RunAll(t.Context(), root, t.TempDir(), nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) }) if stats.Scanned != 0 { t.Errorf("Scanned=%d, want 0", stats.Scanned) @@ -180,7 +181,7 @@ func TestRunAll_SavesFailedCache(t *testing.T) { makeMKVFile(t, dir, "bad.mkv") ident := &fakeIdentifier{err: fmt.Errorf("mkvmerge failed")} - RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) got := loadFailedCache(stateDir) if want := filepath.Join(dir, "bad.mkv"); len(got) != 1 || got[0] != want { @@ -197,7 +198,7 @@ func TestRunAll_UnreadableRootKeepsEarlierFailures(t *testing.T) { } captureStdout(t, func() { - RunAll(root, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), root, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) }) if got := loadFailedCache(stateDir); !slices.Equal(got, old) { @@ -213,7 +214,7 @@ func TestRunAll_FullScanDropsFixedFailuresKeepsOthers(t *testing.T) { t.Fatal(err) } - RunAll(dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) if got := loadFailedCache(stateDir); !slices.Equal(got, []string{outside}) { t.Errorf("failed cache = %v, want [%s]", got, outside) @@ -233,7 +234,7 @@ func TestRunAll_FullScanKeepsFailuresSkippedByCutoff(t *testing.T) { t.Fatal(err) } - RunAll(dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, cutoff) + _, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, cutoff) // old.mkv wasn't retried, so it stays; deleted.mkv is in a scanned folder and gone. if got, want := loadFailedCache(stateDir), []string{filepath.Join(dir, "old.mkv")}; !slices.Equal(got, want) { @@ -248,7 +249,7 @@ func TestRunAll_RetryOnlyReplacesFailedCache(t *testing.T) { t.Fatal(err) } - RunAll(dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, nil, time.Time{}) if _, err := os.Stat(filepath.Join(stateDir, failedCacheFile)); !os.IsNotExist(err) { t.Errorf("failed cache still present after every retried file passed (stat err %v)", err) @@ -266,7 +267,7 @@ func TestRunAll_FailedCacheSaveErrorWarns(t *testing.T) { ident := &fakeIdentifier{err: fmt.Errorf("mkvmerge failed")} out := captureStdout(t, func() { - RunAll(dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{}, nil, nil, nil, time.Time{}) }) if want := "[WARN] could not save " + filepath.Join(stateDir, failedCacheFile); !strings.Contains(out, want) { t.Errorf("output missing %q:\n%s", want, out) @@ -283,7 +284,7 @@ func TestRunAll_CorruptFailedCacheScansAll(t *testing.T) { var stats Stats out := captureStdout(t, func() { // "y" would restrict the run to the cached paths, if any loaded. - stats = RunAll(dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, nil, time.Time{}) + stats, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: &MKVInfo{}}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, nil, time.Time{}) }) if stats.Scanned != 1 { t.Errorf("Scanned=%d, want 1", stats.Scanned) @@ -303,7 +304,7 @@ func TestRunAll_UnknownCodecSaveErrorWarns(t *testing.T) { info := &MKVInfo{Tracks: []Track{audioTrack(0, "eng", "A_UNKNOWN_FORMAT", 2, true)}} out := captureStdout(t, func() { - RunAll(dir, stateDir, nil, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) }) if !strings.Contains(out, "[WARN] could not save new formats") { t.Errorf("output missing the save warning:\n%s", out) @@ -318,7 +319,7 @@ type recordingRemuxer struct { plans []*TrimPlan } -func (r *recordingRemuxer) Remux(_ string, plan *TrimPlan, _ MKVInfo) error { +func (r *recordingRemuxer) Remux(_ context.Context, _ string, plan *TrimPlan, _ MKVInfo) error { r.plans = append(r.plans, plan) return nil } @@ -340,7 +341,7 @@ func TestRunAll_TrimKeepsOnlyAudioTrackAndWarns(t *testing.T) { remuxer := &recordingRemuxer{} out := captureStdout(t, func() { - RunAll(dir, t.TempDir(), lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, remuxer, nil, time.Time{}) + _, _ = RunAll(t.Context(), dir, t.TempDir(), lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, remuxer, nil, time.Time{}) }) if len(remuxer.plans) != 1 { @@ -381,7 +382,7 @@ func TestRunAll_GroupingFolderMoviesUseOwnOrigins(t *testing.T) { editor := &pathEditor{edits: map[string][]string{}} out := captureStdout(t, func() { - RunAll(root, t.TempDir(), &Library{Path: root, Type: "movie"}, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, tmdb, nil, nil, time.Time{}) + _, _ = RunAll(t.Context(), root, t.TempDir(), &Library{Path: root, Type: "movie"}, &fakeIdentifier{info: info}, editor, &fakePrompter{answer: "n"}, tmdb, nil, nil, time.Time{}) }) for _, tc := range []struct { diff --git a/mkv-audit/sibling_cache_test.go b/mkv-audit/sibling_cache_test.go index ee19e63..b9bbfd0 100644 --- a/mkv-audit/sibling_cache_test.go +++ b/mkv-audit/sibling_cache_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "context" "encoding/json" "errors" "maps" @@ -16,19 +17,19 @@ import ( // searchTMDB finds one movie and one show, and knows both by ID. type searchTMDB struct{} -func (searchTMDB) GetTVOriginByID(string) (OriginInfo, bool, error) { +func (searchTMDB) GetTVOriginByID(context.Context, string) (OriginInfo, bool, error) { return OriginInfo{OrigLang: "ja"}, true, nil } -func (searchTMDB) GetMovieOriginByID(string) (OriginInfo, bool, error) { +func (searchTMDB) GetMovieOriginByID(context.Context, string) (OriginInfo, bool, error) { return OriginInfo{OrigLang: "fr"}, true, nil } -func (searchTMDB) SearchTV(string, string) ([]TVSearchCandidate, error) { +func (searchTMDB) SearchTV(context.Context, string, string) ([]TVSearchCandidate, error) { return []TVSearchCandidate{{ID: "77", Name: "Show", Year: "2020"}}, nil } -func (searchTMDB) SearchMovie(string, string) ([]MovieSearchCandidate, error) { +func (searchTMDB) SearchMovie(context.Context, string, string) ([]MovieSearchCandidate, error) { return []MovieSearchCandidate{{ID: "42", Title: "Amelie", Year: "2001"}}, nil } @@ -42,11 +43,11 @@ type titleTMDB struct { onOrigin func(id string) // runs on each ID lookup, when set } -func (f titleTMDB) GetTVOriginByID(id string) (OriginInfo, bool, error) { - return f.GetMovieOriginByID(id) +func (f titleTMDB) GetTVOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) { + return f.GetMovieOriginByID(ctx, id) } -func (f titleTMDB) GetMovieOriginByID(id string) (OriginInfo, bool, error) { +func (f titleTMDB) GetMovieOriginByID(_ context.Context, id string) (OriginInfo, bool, error) { if f.onOrigin != nil { f.onOrigin(id) } @@ -57,7 +58,7 @@ func (f titleTMDB) GetMovieOriginByID(id string) (OriginInfo, bool, error) { return OriginInfo{OrigLang: lang}, ok, nil } -func (f titleTMDB) SearchTV(title, year string) ([]TVSearchCandidate, error) { +func (f titleTMDB) SearchTV(_ context.Context, title, year string) ([]TVSearchCandidate, error) { if f.onSearch != nil { f.onSearch() } @@ -67,7 +68,7 @@ func (f titleTMDB) SearchTV(title, year string) ([]TVSearchCandidate, error) { return []TVSearchCandidate{{ID: f.ids[title], Name: title, Year: year}}, nil } -func (f titleTMDB) SearchMovie(title, year string) ([]MovieSearchCandidate, error) { +func (f titleTMDB) SearchMovie(_ context.Context, title, year string) ([]MovieSearchCandidate, error) { if f.onSearch != nil { f.onSearch() } @@ -206,7 +207,7 @@ func TestFetchOrigins_MovieIDSavedWithFiles(t *testing.T) { writeSibling(t, cachePath, `{"movies":{"9":"M"},"tmdb_ids":{"Coco:2017":"9"},"files":{"C:\\coco.mkv":"9"}}`) captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) + origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) if origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr for the confirmed movie", origins) } @@ -236,7 +237,7 @@ func TestFetchOrigins_TwoMoviesGetTheirOwnIDs(t *testing.T) { } captureStdout(t, func() { - origins, _ := fetchOrigins(append(amelie, coco...), root, "movie", tmdb, &fakePrompter{answer: "y"}) + origins, _ := fetchOrigins(t.Context(), append(amelie, coco...), root, "movie", tmdb, &fakePrompter{answer: "y"}) if origins["Amelie (2001)"].OrigLang != "fr" || origins["Coco (2017)"].OrigLang != "es" { t.Errorf("origins = %v; want Amelie fr and Coco es", origins) } @@ -264,7 +265,7 @@ func TestFetchOrigins_FirstRunCreatesSiblingCache(t *testing.T) { t.Run(tc.libType, func(t *testing.T) { root, paths := siblingLibrary(t, tc.entry, "a.mkv") out := captureStdout(t, func() { - fetchOrigins(paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) }) if strings.Contains(out, "[WARN]") { t.Errorf("unexpected warning:\n%s", out) @@ -284,7 +285,7 @@ func TestFetchOrigins_NullMovieCacheIsEmpty(t *testing.T) { writeSibling(t, movieRatingCachePath(), content) out := captureStdout(t, func() { - fetchOrigins(paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) }) if strings.Contains(out, "[WARN]") { @@ -327,7 +328,7 @@ func TestFetchOrigins_MovieFoundByMappedFile(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}) + origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}) if origins["Amelie.(2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the mapped file's ID", origins) } @@ -342,7 +343,7 @@ func TestFetchOrigins_FlatMovieLibrary(t *testing.T) { path := filepath.Join(root, "Amelie (2001).mkv") captureStdout(t, func() { - origins, _ := fetchOrigins([]string{path}, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) + origins, _ := fetchOrigins(t.Context(), []string{path}, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}) if origins["Amelie (2001).mkv"].OrigLang != "fr" { t.Errorf("origins = %v; want fr for the flat movie", origins) } @@ -385,7 +386,7 @@ func TestFetchOrigins_CorruptSiblingCacheLeftAlone(t *testing.T) { writeSibling(t, tc.cachePath(), tc.corrupt) out := captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) + origins, _ := fetchOrigins(t.Context(), paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) for _, e := range tc.entries { if origins[e].IsZero() { t.Errorf("origins[%q] unset (%v); want the confirmed ID used for this run", e, origins) @@ -411,7 +412,7 @@ func TestFetchOrigins_ShowCacheTrailingDataAccepted(t *testing.T) { writeSibling(t, tvShowCachePath(), `{"Old Show":"5"} junk`) out := captureStdout(t, func() { - fetchOrigins(paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) }) if strings.Contains(out, "[WARN]") { @@ -430,7 +431,7 @@ func TestFetchOrigins_ShowIDSaved(t *testing.T) { writeSibling(t, tvShowCachePath(), `{"Old Show": 123}`) captureStdout(t, func() { - fetchOrigins(paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) }) saved := readSibling(t, tvShowCachePath()) @@ -489,7 +490,7 @@ func TestFetchOrigins_SaveFailureRetried(t *testing.T) { t.Cleanup(func() { beforeFinalSiblingSave = old }) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, &fakePrompter{answer: "y"}); len(origins) != 2 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, &fakePrompter{answer: "y"}); len(origins) != 2 { t.Errorf("origins = %v; want both movies despite the failed save", origins) } }) @@ -590,7 +591,7 @@ func TestFetchOrigins_SaveFailureRetriedAnyPlatform(t *testing.T) { t.Cleanup(func() { beforeFinalSiblingSave = old }) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, lib.libType, tmdb, &fakePrompter{answer: "y"}); len(origins) != 2 { + if origins, _ := fetchOrigins(t.Context(), paths, root, lib.libType, tmdb, &fakePrompter{answer: "y"}); len(origins) != 2 { t.Errorf("origins = %v; want both despite the failed save", origins) } }) @@ -634,7 +635,7 @@ func TestFetchOrigins_ShowPathAnySpelling(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"77": "ja"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "tv", tmdb, noPrompter{t}); origins["Show (2020)"].OrigLang != "ja" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "tv", tmdb, noPrompter{t}); origins["Show (2020)"].OrigLang != "ja" { t.Errorf("origins = %v; want ja from the cached ID", origins) } }) @@ -646,7 +647,7 @@ func TestFetchOrigins_ShowPathAnySpelling(t *testing.T) { writeSibling(t, tvShowCachePath(), mustJSON(t, map[string]any{upper: true})) captureStdout(t, func() { - fetchOrigins(paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, "tv", searchTMDB{}, &fakePrompter{answer: "y"}) }) saved := readSibling(t, tvShowCachePath()) @@ -727,7 +728,7 @@ func TestFetchOrigins_ShowCacheHit(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"77": "ja"}} captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "tv", tmdb, noPrompter{t}) + origins, _ := fetchOrigins(t.Context(), paths, root, "tv", tmdb, noPrompter{t}) if origins["Show (2020)"].OrigLang != "ja" { t.Errorf("origins = %v; want ja from cached ID 77", origins) } @@ -752,7 +753,7 @@ func TestFetchOrigins_UnloadableIDNotSaved(t *testing.T) { tmdb := titleTMDB{ids: map[string]string{"Amelie": "42"}, langs: tc.langs} captureStdout(t, func() { - fetchOrigins(paths, root, tc.libType, tmdb, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, tc.libType, tmdb, &fakePrompter{answer: "y"}) }) if b, err := os.ReadFile(tc.cachePath()); !os.IsNotExist(err) { @@ -789,7 +790,7 @@ func TestFetchOrigins_ManualIDMustBeDigits(t *testing.T) { } captureStdout(t, func() { - fetchOrigins(paths, root, libType, tmdb, p) + fetchOrigins(t.Context(), paths, root, libType, tmdb, p) }) if len(p.asked) != len(tc.answers) { @@ -847,7 +848,7 @@ func TestFetchOrigins_NoInputSkipsLookups(t *testing.T) { p := &scriptPrompter{} out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, p); len(origins) != 0 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, p); len(origins) != 0 { t.Errorf("origins = %v; want none", origins) } }) @@ -874,7 +875,7 @@ func TestFetchOrigins_OnlyOwnLibraryCacheLoaded(t *testing.T) { writeSibling(t, tc.otherCache(), `{"tmdb_ids":`) out := captureStdout(t, func() { - fetchOrigins(paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) }) if strings.Contains(out, "[WARN]") { @@ -897,7 +898,7 @@ func TestFetchOrigins_NoConfigDirWarnsOnce(t *testing.T) { } out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}); len(origins) != 2 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}); len(origins) != 2 { t.Errorf("origins = %v; want both movies", origins) } }) @@ -923,7 +924,7 @@ func TestFetchOrigins_CacheCorruptedMidRunSaveHint(t *testing.T) { } out := captureStdout(t, func() { - fetchOrigins(paths, root, "movie", tmdb, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, "movie", tmdb, &fakePrompter{answer: "y"}) }) if !strings.Contains(out, "could not save") || strings.Contains(strings.ToLower(out), "close any program") { @@ -950,7 +951,7 @@ func TestFetchOrigins_LoadWarningSaysWhatHappens(t *testing.T) { writeSibling(t, tc.cachePath(), `{`) out := captureStdout(t, func() { - fetchOrigins(paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) + fetchOrigins(t.Context(), paths, root, tc.libType, searchTMDB{}, &fakePrompter{answer: "y"}) }) for _, w := range tc.want { @@ -972,7 +973,7 @@ func TestFetchOrigins_UnreadableCacheNotCalledCorrupt(t *testing.T) { } out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}); len(origins) != 1 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &fakePrompter{answer: "y"}); len(origins) != 1 { t.Errorf("origins = %v; want the confirmed movie", origins) } }) @@ -995,7 +996,7 @@ func TestFetchOrigins_SameMovieKeyAskedOnce(t *testing.T) { p := &scriptPrompter{answers: []string{"y", "y"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, p); len(origins) != 2 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, p); len(origins) != 2 { t.Errorf("origins = %v; want both roots", origins) } }) @@ -1046,7 +1047,7 @@ func TestFetchOrigins_CollectionUsesMostMappedID(t *testing.T) { } captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}) + origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}) if got, want := origins["Kill Bill Collection"].OrigLang, tmdb.langs[tc.wantID]; got != want { t.Errorf("origin = %q; want %q from ID %s", got, want, tc.wantID) } @@ -1068,7 +1069,7 @@ func TestFetchOrigins_TitleKeyHitMapsFiles(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the title key", origins) } }) @@ -1078,7 +1079,7 @@ func TestFetchOrigins_TitleKeyHitMapsFiles(t *testing.T) { t.Errorf("tmdb_ids = %v, files = %v; want the title key kept and the .mkv → 194", ids, files) } before, _ := os.ReadFile(movieRatingCachePath()) - captureStdout(t, func() { fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}) }) + captureStdout(t, func() { fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}) }) if after, _ := os.ReadFile(movieRatingCachePath()); string(after) != string(before) { t.Errorf("second run rewrote the cache:\n%s", after) } @@ -1095,7 +1096,7 @@ func TestFetchOrigins_UnloadableMovieCacheNotUsed(t *testing.T) { p := &scriptPrompter{answers: []string{"y"}} out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, p); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, p); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the confirmed search result", origins) } }) @@ -1151,7 +1152,7 @@ func TestFetchOrigins_MovieFileMappingUsed(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"1": "en", "5": "de", "194": "fr"}} captureStdout(t, func() { - origins, _ := fetchOrigins([]string{path}, root, "movie", tmdb, noPrompter{t}) + origins, _ := fetchOrigins(t.Context(), []string{path}, root, "movie", tmdb, noPrompter{t}) if len(origins) != 1 { t.Fatalf("origins = %v; want one", origins) } @@ -1180,7 +1181,7 @@ func TestFetchOrigins_MappedFileMatchesAnySpelling(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the mapped file", origins) } }) @@ -1216,7 +1217,7 @@ func TestFetchOrigins_TitleKeyNotMappedToSeveralFiles(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the title key", origins) } }) @@ -1259,7 +1260,7 @@ func TestFetchOrigins_RootFilesBeatExtras(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"5": "en", "194": "fr"}} captureStdout(t, func() { - origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}) + origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}) if got, want := origins["Amelie (2001)"].OrigLang, tmdb.langs[tc.wantID]; got != want { t.Errorf("origin = %q; want %q from ID %s", got, want, tc.wantID) } @@ -1279,7 +1280,7 @@ func TestFetchOrigins_GoneFileMappingIgnored(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"5": "en", "194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the file that exists", origins) } }) @@ -1297,7 +1298,7 @@ func TestFetchOrigins_GroupingFolderAsked(t *testing.T) { p := &scriptPrompter{answers: []string{""}} captureStdout(t, func() { - if origins, _ := fetchOrigins(append(amelie, coco...), root, "movie", tmdb, p); len(origins) != 0 { + if origins, _ := fetchOrigins(t.Context(), append(amelie, coco...), root, "movie", tmdb, p); len(origins) != 0 { t.Errorf("origins = %v; want none, the question was skipped", origins) } }) @@ -1330,7 +1331,7 @@ func TestFetchOrigins_GroupingFolderMoviesGetOwnOrigins(t *testing.T) { p := &scriptPrompter{answers: tc.answers} captureStdout(t, func() { - origins, roots := fetchOrigins(append(amelie, coco...), root, "movie", tmdb, p) + origins, roots := fetchOrigins(t.Context(), append(amelie, coco...), root, "movie", tmdb, p) if origins[amelieDir].OrigLang != "fr" || origins[cocoDir].OrigLang != "es" || len(origins) != 2 { t.Errorf("origins = %v; want %s fr and %s es", origins, amelieDir, cocoDir) } @@ -1364,7 +1365,7 @@ func TestFetchOrigins_GroupingFolderOneMovieMapped(t *testing.T) { p := &scriptPrompter{answers: []string{"y"}} captureStdout(t, func() { - origins, _ := fetchOrigins(append(amelie, coco...), root, "movie", tmdb, p) + origins, _ := fetchOrigins(t.Context(), append(amelie, coco...), root, "movie", tmdb, p) if origins[filepath.Join("A-M", "Amelie (2001)")].OrigLang != "fr" || origins[filepath.Join("A-M", "Coco (2017)")].OrigLang != "es" { t.Errorf("origins = %v; want Amelie fr from its mapping and Coco es from the answer", origins) } @@ -1390,7 +1391,7 @@ func TestFetchOrigins_GroupingFolderMovieFolderRules(t *testing.T) { tmdb := titleTMDB{ids: map[string]string{"Amelie": "42", "Kill Bill Collection": "24"}, langs: map[string]string{"42": "fr", "24": "en"}} out := captureStdout(t, func() { - origins, _ := fetchOrigins(append(discs, collection...), root, "movie", tmdb, &scriptPrompter{answers: []string{"y", "y"}}) + origins, _ := fetchOrigins(t.Context(), append(discs, collection...), root, "movie", tmdb, &scriptPrompter{answers: []string{"y", "y"}}) if origins[filepath.Join("A-M", "Amelie (2001)")].OrigLang != "fr" || origins[filepath.Join("A-M", "Kill Bill Collection")].OrigLang != "en" { t.Errorf("origins = %v; want Amelie fr and the collection en", origins) } @@ -1467,7 +1468,7 @@ func TestFetchOrigins_MissingIDFallsBack(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} // no 5 out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from ID 194", origins) } }) @@ -1490,7 +1491,7 @@ func TestFetchOrigins_EmptyMappingNotRewritten(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the title key", origins) } }) @@ -1532,7 +1533,7 @@ func TestFetchOrigins_BackfillSaveFailure(t *testing.T) { beforeFinalSiblingSave = func() {} t.Cleanup(func() { beforeFinalSiblingSave = old }) - out := captureStdout(t, func() { fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}) }) + out := captureStdout(t, func() { fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}) }) lost := strings.Contains(out, "lost, and the next run asks for them again: Amelie (2001) (id 194)") unmapped := strings.Contains(out, "files aren't mapped to their IDs yet; the next run maps them, unless mkv-movie --clean drops the IDs first: Amelie (2001) (id 194)") @@ -1593,7 +1594,7 @@ func TestFetchOrigins_AnswerForSeveralMoviesNotSaved(t *testing.T) { before, _ := os.ReadFile(movieRatingCachePath()) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}); origins["A-M"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}); origins["A-M"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the confirmed answer", origins) } }) @@ -1629,7 +1630,7 @@ func TestFetchOrigins_BackfillKeepsTypedID(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}, onOrigin: func(id string) { looked = append(looked, id) }} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr", origins) } }) @@ -1653,7 +1654,7 @@ func TestFetchOrigins_TMDBErrorDoesNotFallBack(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"5": "", "194": "fr"}, onOrigin: func(id string) { looked = append(looked, id) }} out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); len(origins) != 0 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); len(origins) != 0 { t.Errorf("origins = %v; want none after the error", origins) } }) @@ -1676,7 +1677,7 @@ func TestFetchOrigins_AllIDsMissing(t *testing.T) { before, _ := os.ReadFile(movieRatingCachePath()) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", titleTMDB{}, noPrompter{t}); len(origins) != 0 { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", titleTMDB{}, noPrompter{t}); len(origins) != 0 { t.Errorf("origins = %v; want none", origins) } }) @@ -1696,14 +1697,16 @@ func TestFetchOrigins_MultiDiscMovieSaved(t *testing.T) { paths := addEntry(t, root, filepath.Join("Amelie (2001)", "Disc1"), "a.mkv") paths = append(paths, addEntry(t, root, filepath.Join("Amelie (2001)", "Disc2"), "b.mkv")...) - captureStdout(t, func() { fetchOrigins(paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}) }) + captureStdout(t, func() { + fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}) + }) ids, files := readMovieSections(t) if ids["Amelie:2001"] != "42" || files[paths[0]] != "42" || files[paths[1]] != "42" { t.Errorf("tmdb_ids = %v, files = %v; want the answer saved for both discs", ids, files) } captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("run 2 origins = %v; want fr without asking", origins) } }) @@ -1728,7 +1731,7 @@ func TestFetchOrigins_FlatCollectionFilesNotMapped(t *testing.T) { before, _ := os.ReadFile(movieRatingCachePath()) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}); origins[tc.entry].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, &scriptPrompter{answers: []string{"y"}}); origins[tc.entry].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the confirmed answer", origins) } }) @@ -1746,7 +1749,7 @@ func TestFetchOrigins_FlatCollectionFilesNotMapped(t *testing.T) { } saved, _ := os.ReadFile(movieRatingCachePath()) captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", searchTMDB{}, noPrompter{t}); origins[tc.entry].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", searchTMDB{}, noPrompter{t}); origins[tc.entry].OrigLang != "fr" { t.Errorf("run 2 origins = %v; want fr from the title key without asking", origins) } }) @@ -1764,7 +1767,7 @@ func TestFetchOrigins_SingleNestedIDUsed(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the subfolder files' ID", origins) } }) @@ -1781,7 +1784,7 @@ func TestFetchOrigins_OfflineDriveMappingCounts(t *testing.T) { tmdb := titleTMDB{langs: map[string]string{"194": "fr"}} captureStdout(t, func() { - if origins, _ := fetchOrigins([]string{path}, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { + if origins, _ := fetchOrigins(t.Context(), []string{path}, root, "movie", tmdb, noPrompter{t}); origins["Amelie (2001)"].OrigLang != "fr" { t.Errorf("origins = %v; want fr from the offline file's ID", origins) } }) @@ -1817,7 +1820,7 @@ func TestFetchOrigins_GroupingFolderNoYearSubfolderNotSaved(t *testing.T) { } captureStdout(t, func() { - origins, _ := fetchOrigins(append(vol1, extras...), root, "movie", tmdb, &scriptPrompter{answers: []string{"a"}}) + origins, _ := fetchOrigins(t.Context(), append(vol1, extras...), root, "movie", tmdb, &scriptPrompter{answers: []string{"a"}}) if origins[vol1Dir].OrigLang != "en" || origins[extrasDir].OrigLang != "ja" { t.Errorf("origins = %v; want each folder's answer for the run", origins) } diff --git a/mkv-audit/tmdb.go b/mkv-audit/tmdb.go index 54e49e2..ecc336f 100644 --- a/mkv-audit/tmdb.go +++ b/mkv-audit/tmdb.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -54,13 +55,13 @@ type MovieSearchCandidate struct { type TMDBOriginClient interface { // GetTVOriginByID fetches origin info directly via a known TMDB show ID, // skipping the search step. - GetTVOriginByID(id string) (OriginInfo, bool, error) + GetTVOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) // GetMovieOriginByID fetches origin info directly via a known TMDB movie ID. - GetMovieOriginByID(id string) (OriginInfo, bool, error) + GetMovieOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) // SearchTV returns candidate TV shows matching title+year, ordered by relevance. - SearchTV(title, year string) ([]TVSearchCandidate, error) + SearchTV(ctx context.Context, title, year string) ([]TVSearchCandidate, error) // SearchMovie returns candidate movies matching title+year, ordered by relevance. - SearchMovie(title, year string) ([]MovieSearchCandidate, error) + SearchMovie(ctx context.Context, title, year string) ([]MovieSearchCandidate, error) } // httpTMDBOriginClient is the production TMDBOriginClient. @@ -76,8 +77,12 @@ func newHTTPTMDBOriginClient(apiKey string) *httpTMDBOriginClient { // getTMDB performs a GET and rejects non-2xx responses. TMDB returns a JSON // error body (e.g. invalid api_key, rate-limit) that would otherwise decode // into an empty struct and be indistinguishable from "no result found". -func (c *httpTMDBOriginClient) getTMDB(u string) (*http.Response, error) { - resp, err := c.client.Get(u) +func (c *httpTMDBOriginClient) getTMDB(ctx context.Context, u string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, redactAPIKey(err) + } + resp, err := c.client.Do(req) if err != nil { return nil, redactAPIKey(err) } @@ -107,9 +112,9 @@ func isTMDBNotFound(err error) bool { // GetTVOriginByID fetches origin data from /tv/{id} using a known TMDB show ID. // An ID TMDB doesn't have (404) is not found rather than an error. -func (c *httpTMDBOriginClient) GetTVOriginByID(id string) (OriginInfo, bool, error) { +func (c *httpTMDBOriginClient) GetTVOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) { detURL := fmt.Sprintf("%s/tv/%s?api_key=%s", tmdbOriginBase, id, url.QueryEscape(c.apiKey)) - resp, err := c.getTMDB(detURL) + resp, err := c.getTMDB(ctx, detURL) if isTMDBNotFound(err) { return OriginInfo{}, false, nil } @@ -137,9 +142,9 @@ func (c *httpTMDBOriginClient) GetTVOriginByID(id string) (OriginInfo, bool, err // GetMovieOriginByID fetches origin data from /movie/{id} using a known TMDB // movie ID. An ID TMDB doesn't have (404) is not found rather than an error. -func (c *httpTMDBOriginClient) GetMovieOriginByID(id string) (OriginInfo, bool, error) { +func (c *httpTMDBOriginClient) GetMovieOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) { detURL := fmt.Sprintf("%s/movie/%s?api_key=%s", tmdbOriginBase, id, url.QueryEscape(c.apiKey)) - detResp, err := c.getTMDB(detURL) + detResp, err := c.getTMDB(ctx, detURL) if isTMDBNotFound(err) { return OriginInfo{}, false, nil } @@ -168,12 +173,12 @@ func (c *httpTMDBOriginClient) GetMovieOriginByID(id string) (OriginInfo, bool, } // SearchTV returns TMDB TV show candidates for the given title and optional year. -func (c *httpTMDBOriginClient) SearchTV(title, year string) ([]TVSearchCandidate, error) { +func (c *httpTMDBOriginClient) SearchTV(ctx context.Context, title, year string) ([]TVSearchCandidate, error) { params := url.Values{"api_key": {c.apiKey}, "query": {title}, "include_adult": {"true"}} if year != "" { params.Set("first_air_date_year", year) } - resp, err := c.getTMDB(tmdbOriginBase + "/search/tv?" + params.Encode()) + resp, err := c.getTMDB(ctx, tmdbOriginBase+"/search/tv?"+params.Encode()) if err != nil { return nil, err } @@ -200,12 +205,12 @@ func (c *httpTMDBOriginClient) SearchTV(title, year string) ([]TVSearchCandidate } // SearchMovie returns TMDB movie candidates for the given title and optional year. -func (c *httpTMDBOriginClient) SearchMovie(title, year string) ([]MovieSearchCandidate, error) { +func (c *httpTMDBOriginClient) SearchMovie(ctx context.Context, title, year string) ([]MovieSearchCandidate, error) { params := url.Values{"api_key": {c.apiKey}, "query": {title}, "include_adult": {"true"}} if year != "" { params.Set("year", year) } - resp, err := c.getTMDB(tmdbOriginBase + "/search/movie?" + params.Encode()) + resp, err := c.getTMDB(ctx, tmdbOriginBase+"/search/movie?"+params.Encode()) if err != nil { return nil, err } diff --git a/mkv-audit/tmdb_test.go b/mkv-audit/tmdb_test.go index 370aaba..2d5b73e 100644 --- a/mkv-audit/tmdb_test.go +++ b/mkv-audit/tmdb_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "io" "net/http" "os" @@ -39,13 +40,13 @@ func TestHTTPTMDBOriginClient_NotFoundIsNoMatch(t *testing.T) { }{http.StatusNotFound, `{"status_code":34,"status_message":"The resource you requested could not be found."}`} c := stubClient(stubTMDB{"/3/movie/5": notFound, "/3/tv/5": notFound}) - for name, get := range map[string]func(string) (OriginInfo, bool, error){ + for name, get := range map[string]func(context.Context, string) (OriginInfo, bool, error){ "movie": c.GetMovieOriginByID, "tv": c.GetTVOriginByID, } { - if _, found, err := get("5"); found || err != nil { + if _, found, err := get(t.Context(), "5"); found || err != nil { t.Errorf("%s 404: found = %v, err = %v; want not found and no error", name, found, err) } - if _, _, err := get("6"); err == nil || !strings.Contains(err.Error(), "status") { + if _, _, err := get(t.Context(), "6"); err == nil || !strings.Contains(err.Error(), "status") { t.Errorf("%s 500: err = %v; want the status as an error", name, err) } } @@ -62,7 +63,7 @@ func TestFetchOrigins_HTTPNotFoundFallsBack(t *testing.T) { }) out := captureStdout(t, func() { - if origins, _ := fetchOrigins(paths, root, "movie", c, noPrompter{t}); origins["Amelie (2001)"] != (OriginInfo{OrigLang: "fr", OriginCountry: "FR"}) { + if origins, _ := fetchOrigins(t.Context(), paths, root, "movie", c, noPrompter{t}); origins["Amelie (2001)"] != (OriginInfo{OrigLang: "fr", OriginCountry: "FR"}) { t.Errorf("origins = %v; want fr-FR from ID 194", origins) } }) diff --git a/mkv-audit/token_redaction_test.go b/mkv-audit/token_redaction_test.go index d132704..fee80ef 100644 --- a/mkv-audit/token_redaction_test.go +++ b/mkv-audit/token_redaction_test.go @@ -16,8 +16,8 @@ func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) { func TestTMDBOriginClient_TransportErrorOmitsAPIKey(t *testing.T) { const key = "s3cret-key" c := &httpTMDBOriginClient{apiKey: key, client: &http.Client{Transport: failingTransport{}}} - _, _, tvErr := c.GetTVOriginByID("1399") - _, _, movieErr := c.GetMovieOriginByID("949") + _, _, tvErr := c.GetTVOriginByID(t.Context(), "1399") + _, _, movieErr := c.GetMovieOriginByID(t.Context(), "949") for _, err := range []error{tvErr, movieErr} { if err == nil { t.Fatal("expected a transport error") @@ -36,7 +36,7 @@ func TestTMDBOriginClient_TransportErrorOmitsAPIKey(t *testing.T) { func TestTMDBOriginClient_OddIDOmitsAPIKey(t *testing.T) { for _, id := range []string{"12%zz", "1399?x=1", "1399#x"} { c := &httpTMDBOriginClient{apiKey: "s3cret-key", client: &http.Client{Transport: failingTransport{}}} - _, _, err := c.GetTVOriginByID(id) + _, _, err := c.GetTVOriginByID(t.Context(), id) if err == nil { t.Fatalf("id %q: expected an error", id) } From ad1b34d19f5029550fa26fb2b91357a9fabbf9de Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 23:48:09 +1300 Subject: [PATCH 2/5] fix(mkv-audit): keep only unfinished failures after an interrupt, stop re-waiting on EOF, and pin the interrupt paths An interrupted run now takes the failures it got through, and those that are gone, off the retry list. Once stdin has ended, prompts return at once instead of each waiting for an interrupt. A file the interrupt skips prints a [STOP] line, and an ID whose lookup finished is still saved. Tests now cover the post-prompt checks, auto-all loops, mux and mkvextract kills, and fail rather than hang. --- README.md | 2 +- mkv-audit/convert.go | 10 +- mkv-audit/interrupt.go | 11 +- mkv-audit/interrupt_run_test.go | 393 ++++++++++++++++++++++++++++++-- mkv-audit/main.go | 2 +- mkv-audit/prompt.go | 33 +-- mkv-audit/remux.go | 8 +- mkv-audit/runner.go | 73 +++--- 8 files changed, 444 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 2930a97..be68d49 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ The tool scans recursively and prints a summary: Scanned: 120 Fixed: 14 Failed: 0 LangFixes: 9 FlagFixes: 8 ``` -Ctrl+C stops before the next file, or at a prompt without taking its default, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets its edits, and a conversion or trim in progress finishes. A second Ctrl+C also kills the `mkvmerge` or `mkvextract` in progress, as closing the terminal or SIGTERM does; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files skipped by an interrupt aren't recorded as failures, and earlier failures stay on the retry list. From then on SIGTERM and (on Unix) SIGHUP are ignored, and a further Ctrl+C quits at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed. +Ctrl+C stops before the next file or lookup, and at a prompt without acting on the answer, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets the fixes that need no answer, and a conversion or trim in progress finishes. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge` or `mkvextract` in progress and starts no more edits; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files the interrupt skips aren't recorded as failures, and earlier failures it didn't reach stay on the retry list. From then on only Ctrl+C quits, at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed. ### Dependencies diff --git a/mkv-audit/convert.go b/mkv-audit/convert.go index 99a6316..2422959 100644 --- a/mkv-audit/convert.go +++ b/mkv-audit/convert.go @@ -24,7 +24,8 @@ type MKVConverter interface { // ConvertToMKV writes .mkv next to src, then removes src. A non-empty // path with a non-nil error means the MKV was written but a later step // (copying timestamps, removing src) failed. - // ctx's kill context (see command) kills mkvmerge, leaving src as it was. + // ctx's kill context (see command) kills mkvmerge; the error then matches + // context.Canceled and src is left as it was. ConvertToMKV(ctx context.Context, src string) (string, error) } @@ -38,8 +39,8 @@ func isConvertible(path string) bool { } // convertAll converts each convertible path in paths to MKV and returns a new -// list with the MKV in its place. A source that is skipped or fails to -// convert is dropped; a failure is also recorded in stats. Each path appears +// list with the MKV in its place. A source that is skipped, fails to convert +// or is left by an interrupt is dropped; a failure is also recorded in stats. Each path appears // once, so a retry list holding both x.mp4 and x.mkv doesn't scan x.mkv twice. func convertAll(ctx context.Context, paths []string, converter MKVConverter, stats *Stats) []string { out := make([]string, 0, len(paths)) @@ -102,7 +103,8 @@ func (r *realMKVRunner) ConvertToMKV(ctx context.Context, src string) (string, e // mux runs mkvmerge to copy every track of src into a new MKV at dst. func (r *realMKVRunner) mux(ctx context.Context, src, dst string) error { out, err := command(ctx, r.mkvmerge, "-o", dst, src).CombinedOutput() - if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { + // First, since a killed mkvmerge exits 1 on Windows, like warnings. + if err = commandErr(ctx, err); errors.Is(err, context.Canceled) { return err } var exitErr *exec.ExitError diff --git a/mkv-audit/interrupt.go b/mkv-audit/interrupt.go index de4205c..4887d85 100644 --- a/mkv-audit/interrupt.go +++ b/mkv-audit/interrupt.go @@ -9,10 +9,11 @@ import ( "slices" ) -// interruptContext returns a context the first Ctrl+C cancels, so run stops -// before the next file or step. The second also kills any mkvmerge or -// mkvextract in progress (see command), though never mkvpropedit, and a third Ctrl+C quits at once. A quit signal does -// the first two at once, after which Ctrl+C quits at once. +// interruptContext returns a context the first Ctrl+C cancels, so the run +// stops before the next file or step. The second also kills any mkvmerge or +// mkvextract in progress (see command), though never mkvpropedit, and a third +// Ctrl+C quits at once. A quit signal does the first two at once, after which +// Ctrl+C quits at once. // // Only the interrupts get their default handling back, so once the children // are killed further quit signals are absorbed: a closed terminal sends a @@ -71,5 +72,5 @@ func watchSignals(w io.Writer, interrupts, quits <-chan os.Signal, stop, kill, r } kill() restore() - fmt.Fprintln(w, "\ninterrupted: stopping any mkvmerge in progress (Ctrl+C again to quit at once)") + fmt.Fprintln(w, "\ninterrupted: stopping any mkvmerge or mkvextract in progress (Ctrl+C again to quit at once)") } diff --git a/mkv-audit/interrupt_run_test.go b/mkv-audit/interrupt_run_test.go index c211478..80e9e73 100644 --- a/mkv-audit/interrupt_run_test.go +++ b/mkv-audit/interrupt_run_test.go @@ -18,13 +18,19 @@ import ( ) func init() { - // mkvmerge stands in for mkvmerge: it answers --identify with one video - // track, and otherwise says it's ready and sleeps until killed. + // The mkvmerge helper mode stands in for mkvmerge: it answers --identify with one video + // track, and otherwise starts its -o file, says it's ready and sleeps until + // killed. helperModes["mkvmerge"] = func() { if slices.Contains(os.Args, "--identify") { fmt.Println(`{"tracks":[{"id":0,"type":"video"}]}`) return } + if i := slices.Index(os.Args, "-o"); i >= 0 && i+1 < len(os.Args) { + if err := os.WriteFile(os.Args[i+1], []byte("partial"), 0o644); err != nil { + panic(err) + } + } ready() time.Sleep(time.Minute) } @@ -147,8 +153,9 @@ func TestFetchOrigins_InterruptAtPromptSavesNothing(t *testing.T) { func TestRunAll_KilledIdentifyIsNotAFailure(t *testing.T) { dir, stateDir := t.TempDir(), t.TempDir() makeMKVFile(t, dir, "a.mkv") - old := filepath.Join(dir, "old.mkv") - if err := saveFailedCache(stateDir, []string{old}); err != nil { + // a.mkv is read but killed; old.mkv is outside the scan. + old := []string{filepath.Join(dir, "a.mkv"), filepath.Join(t.TempDir(), "old.mkv")} + if err := saveFailedCache(stateDir, old); err != nil { t.Fatal(err) } ctx, stop, kill := newInterruptContext() @@ -167,8 +174,8 @@ func TestRunAll_KilledIdentifyIsNotAFailure(t *testing.T) { if stats.Failed != 0 || stats.Scanned != 0 { t.Errorf("Failed = %d, Scanned = %d; want 0 and 0", stats.Failed, stats.Scanned) } - if got := loadFailedCache(stateDir); !slices.Equal(got, []string{old}) { - t.Errorf("failure list = %v, want the untried %v", got, []string{old}) + if got := loadFailedCache(stateDir); !slices.Equal(got, old) { + t.Errorf("failure list = %v, want the untried %v", got, old) } } @@ -181,13 +188,224 @@ func TestRunAll_NoEditAfterKill(t *testing.T) { ident := &interruptingIdentifier{info: needsLangFix, at: 2, stop: func() { stop(); kill() }} editor := &fakeEditor{} - stats, err := RunAll(ctx, dir, t.TempDir(), nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + var stats Stats + var err error + out := captureStdout(t, func() { + stats, err = RunAll(ctx, dir, t.TempDir(), nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + }) if !errors.Is(err, context.Canceled) { t.Errorf("err = %v, want context.Canceled", err) } if len(editor.calls) != 0 || stats.Scanned != 0 { t.Errorf("applied %v, scanned %d; want no edit and no scan", editor.calls, stats.Scanned) } + if !strings.Contains(out, "[STOP] a.mkv: interrupted; left unchanged") { + t.Errorf("missing the stop line:\n%s", out) + } +} + +// An interrupted run takes the failures it got through off the list, and +// those that are gone, but keeps the ones it never reached. +func TestRunAll_InterruptKeepsOnlyUnfinishedFailures(t *testing.T) { + dir, lib, info := trimLibrary(t) + stateDir := t.TempDir() + fixed := filepath.Join(dir, "e1.mkv") + gone := filepath.Join(dir, "gone.mkv") + elsewhere := filepath.Join(t.TempDir(), "x.mkv") // outside the scan + if err := saveFailedCache(stateDir, []string{fixed, gone, elsewhere}); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + // A full scan, stopped at the first trim prompt, after every file is read. + p := &stopAtPrompter{prefix: "[TRIM]", stop: stop} + remuxer := &recordingRemuxer{} + + var err error + captureStdout(t, func() { + _, err = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, p, nil, remuxer, nil, time.Time{}) + }) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if len(remuxer.plans) != 0 { + t.Errorf("remuxed %d files after the interrupt at the trim prompt", len(remuxer.plans)) + } + if got := loadFailedCache(stateDir); !slices.Equal(got, []string{elsewhere}) { + t.Errorf("failure list = %v, want only the unreached %v", got, elsewhere) + } +} + +// stopAtPrompter answers "n" until a prompt starting with prefix, which it +// answers "y" just as the Ctrl+C lands. It counts the edits made before then. +type stopAtPrompter struct { + prefix string + stop func() + editor *fakeEditor + before int // editor calls when the Ctrl+C landed + asked []string +} + +func (p *stopAtPrompter) Ask(q string) (string, error) { + p.asked = append(p.asked, q) + if !strings.HasPrefix(q, p.prefix) { + return "n", nil + } + if p.editor != nil { + p.before = len(p.editor.calls) + } + p.stop() + return "y", nil +} + +// A Ctrl+C as a yes/no prompt is answered applies nothing, and asks nothing +// more. +func TestRunAll_InterruptAtPromptAppliesNothing(t *testing.T) { + cases := []struct { + prefix string + setup func(t *testing.T) (dir string, lib *Library, info *MKVInfo) + }{ + {"[RETAG]", func(t *testing.T) (string, *Library, *MKVInfo) { + t.Helper() + // The only audio track is English in a Japanese library. + dir := t.TempDir() + makeMKVFile(t, dir, "e1.mkv") + makeMKVFile(t, dir, "e2.mkv") + return dir, &Library{Path: dir, Overrides: []DirOverride{{Path: ".", OriginLang: "jpn"}}}, &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "video", Properties: TrackProperties{Language: "jpn", LanguageIETF: "ja"}}, + {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, + {ID: 2, Type: "subtitles", Properties: TrackProperties{Language: "fre", LanguageIETF: "fr", CodecID: "S_TEXT/ASS"}}, + }} + }}, + {"[TRIM]", trimLibrary}, + {"[LANGFIX]", func(t *testing.T) (string, *Library, *MKVInfo) { + t.Helper() + // The folder's override says Japanese; the tracks say English. + dir := t.TempDir() + makeMKVFile(t, dir, "e1.mkv") + makeMKVFile(t, dir, "e2.mkv") + return dir, &Library{Path: dir, Overrides: []DirOverride{{Path: ".", IETF: map[string]string{"jpn": "ja-JP"}}}}, &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "video", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US"}}, + {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, + }} + }}, + } + for _, tc := range cases { + t.Run(tc.prefix, func(t *testing.T) { + dir, lib, info := tc.setup(t) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + editor := &fakeEditor{} + p := &stopAtPrompter{prefix: tc.prefix, stop: stop, editor: editor} + remuxer := &recordingRemuxer{} + + captureStdout(t, func() { + _, _ = RunAll(ctx, dir, t.TempDir(), lib, &fakeIdentifier{info: info}, editor, p, nil, remuxer, nil, time.Time{}) + }) + var at int + for _, q := range p.asked { + if strings.HasPrefix(q, tc.prefix) { + at++ + } + } + if at != 1 { + t.Fatalf("asked %d %s prompts, want 1 (asked: %q)", at, tc.prefix, p.asked) + } + if !strings.HasPrefix(p.asked[len(p.asked)-1], tc.prefix) { + t.Errorf("asked %q after the interrupt", p.asked[len(p.asked)-1]) + } + if len(editor.calls) != p.before || len(remuxer.plans) != 0 { + t.Errorf("%d edits and %d remuxes after the interrupt; want none", len(editor.calls)-p.before, len(remuxer.plans)) + } + }) + } +} + +// A Ctrl+C at the retry prompt stops before anything is read, and leaves the +// failure list alone. +func TestRunAll_InterruptAtRetryPrompt(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + old := []string{filepath.Join(dir, "a.mkv")} + if err := saveFailedCache(stateDir, old); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + ident := &interruptingIdentifier{info: cleanAudio} + + _, err := RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &stopPrompter{stop: stop}, nil, nil, nil, time.Time{}) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if n := ident.calls.Load(); n != 0 { + t.Errorf("identified %d files, want none", n) + } + if got := loadFailedCache(stateDir); !slices.Equal(got, old) { + t.Errorf("failure list = %v, want it unchanged", got) + } +} + +// stoppingTMDB is searchTMDB with a Ctrl+C landing during the origin lookup. +// With cut set the lookup ends with the interrupt; otherwise it completes. +type stoppingTMDB struct { + searchTMDB + stop func() + cut bool + searches *int +} + +func (f stoppingTMDB) SearchTV(ctx context.Context, title, year string) ([]TVSearchCandidate, error) { + *f.searches++ + return f.searchTMDB.SearchTV(ctx, title, year) +} + +func (f stoppingTMDB) GetTVOriginByID(ctx context.Context, id string) (OriginInfo, bool, error) { + f.stop() + if f.cut { + return OriginInfo{}, false, fmt.Errorf("get: %w", context.Canceled) + } + return f.searchTMDB.GetTVOriginByID(ctx, id) +} + +// A confirmed ID is saved if its lookup finished before the Ctrl+C took +// effect, and not if the Ctrl+C cut it short. No later show is looked up. +func TestFetchOrigins_InterruptDuringLookup(t *testing.T) { + for _, cut := range []bool{false, true} { + t.Run(fmt.Sprintf("cut=%v", cut), func(t *testing.T) { + root, paths := siblingLibrary(t, "Show (2020)", "Show - S01E01.mkv") + paths = append(paths, addEntry(t, root, "Zed (2021)", "Zed - S01E01.mkv")...) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + p := &scriptPrompter{answers: []string{"y", "y"}} + var searches int + + var origins map[string]OriginInfo + out := captureStdout(t, func() { + origins, _ = fetchOrigins(ctx, paths, root, "tv", stoppingTMDB{stop: stop, cut: cut, searches: &searches}, p) + }) + if len(p.asked) != 1 || searches != 1 { + t.Errorf("asked %d times and searched %d; want 1 and 1", len(p.asked), searches) + } + if strings.Contains(out, "canceled") { + t.Errorf("the interrupt was reported as a TMDB error:\n%s", out) + } + show := filepath.Join(root, "Show (2020)") + _, statErr := os.Stat(tvShowCachePath()) + if cut { + if len(origins) != 0 || !os.IsNotExist(statErr) { + t.Errorf("origins = %v, cache err = %v; want nothing found or saved", origins, statErr) + } + return + } + if origins["Show (2020)"].OrigLang != "ja" { + t.Errorf("origins = %v, want Show's", origins) + } + if got := string(readSibling(t, tvShowCachePath())[show]); got != `"77"` { + t.Errorf("saved %s for Show, want \"77\"", got) + } + }) + } } // After one Ctrl+C a file already read is still edited, so it isn't left @@ -340,7 +558,7 @@ func TestConvertAll_KilledIsNotAFailure(t *testing.T) { } // waitReady waits for the helper's ready file, failing if result ends first. -func waitReady[T any](t *testing.T, readyFile string, result <-chan T) { +func waitReady(t *testing.T, readyFile string, result <-chan error) { t.Helper() for deadline := time.Now().Add(10 * time.Second); ; { if _, err := os.Stat(readyFile); err == nil { @@ -406,7 +624,102 @@ func TestRemux_KilledLeavesFile(t *testing.T) { if got, err := os.ReadFile(src); err != nil || string(got) != "original" { t.Errorf("file = %q, %v; want it unchanged", got, err) } - assertNoTempFiles(t, dir) + assertOnly(t, dir, "a.mkv") +} + +// mkvmerge's mux outlives the first Ctrl+C; the second kills it, and mux +// reports the interrupt, not the warnings a Windows exit code 1 would mean. +func TestMux_KilledIsTheInterrupt(t *testing.T) { + r, readyFile := fakeMKVMerge(t, "mkvmerge") + dir := t.TempDir() + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { result <- r.mux(ctx, filepath.Join(dir, "a.mp4"), filepath.Join(dir, "a.mkv")) }() + waitReady(t, readyFile, result) + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} + +// mkvextract outlives the first Ctrl+C and the second kills it. +func TestReadTagDate_Killed(t *testing.T) { + readyFile := filepath.Join(t.TempDir(), "ready") + t.Setenv(helperEnv, "sleep") + t.Setenv(readyEnv, readyFile) + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { + if _, ok := readTagDateFromMKA(ctx, os.Args[0], "a.mka"); ok { + result <- errors.New("found a date") + return + } + result <- context.Canceled // what wantKilled looks for + }() + waitReady(t, readyFile, result) + + stop() + wantRunning(t, result) + kill() + wantKilled(t, result) +} + +// matchEditor records edits, and stops the run on the first edit holding match. +type matchEditor struct { + match string + stop func() + hits int +} + +func (e *matchEditor) Apply(_ string, edits []string) error { + if slices.ContainsFunc(edits, func(s string) bool { return strings.Contains(s, e.match) }) { + e.hits++ + if e.hits == 1 { + e.stop() + } + } + return nil +} + +// After "a" (all) at a prompt, a Ctrl+C during an edit starts no more. +func TestRunAll_InterruptStopsAutoAll(t *testing.T) { + cases := []struct { + prompt, match string + lib func(dir string) *Library + info *MKVInfo + }{ + {"[UND]", "language=eng", func(string) *Library { return nil }, &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "audio", Properties: TrackProperties{Language: "und", CodecID: "A_AC3", AudioChannels: 2}}, + }}}, + {"[LANGFIX]", "language=jpn", func(dir string) *Library { + return &Library{Path: dir, Overrides: []DirOverride{{Path: ".", IETF: map[string]string{"jpn": "ja-JP"}}}} + }, &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "video", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US"}}, + {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, + }}}, + } + for _, tc := range cases { + t.Run(tc.prompt, func(t *testing.T) { + dir := t.TempDir() + for _, f := range []string{"a.mkv", "b.mkv", "c.mkv"} { + makeMKVFile(t, dir, f) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + ed := &matchEditor{match: tc.match, stop: stop} + p := &prefixPrompter{answers: map[string]string{tc.prompt: "a"}} + + captureStdout(t, func() { + _, _ = RunAll(ctx, dir, t.TempDir(), tc.lib(dir), &fakeIdentifier{info: tc.info}, ed, p, nil, nil, nil, time.Time{}) + }) + if p.count(tc.prompt) != 1 || ed.hits != 1 { + t.Errorf("asked %d %s prompts, made %d %s edits; want 1 and only the one in progress", p.count(tc.prompt), tc.prompt, ed.hits, tc.match) + } + }) + } } // A conversion the second Ctrl+C kills leaves the source and makes no MKV. @@ -430,13 +743,7 @@ func TestConvertToMKV_KilledLeavesSource(t *testing.T) { wantRunning(t, result) kill() wantKilled(t, result) - if _, err := os.Stat(src); err != nil { - t.Errorf("source gone: %v", err) - } - if _, err := os.Stat(filepath.Join(dir, "a.mkv")); !os.IsNotExist(err) { - t.Errorf("a.mkv exists after the kill (%v)", err) - } - assertNoTempFiles(t, dir) + assertOnly(t, dir, "a.mp4") } // A TMDB request in flight ends with the Ctrl+C, and the error still hides @@ -450,10 +757,15 @@ func TestGetTMDB_InterruptEndsRequest(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(50*time.Millisecond, cancel) - resp, err := c.getTMDB(ctx, srv.URL+"/3/tv/1?api_key=secret") - if err == nil { - resp.Body.Close() - } + result := make(chan error, 1) + go func() { + resp, err := c.getTMDB(ctx, srv.URL+"/3/tv/1?api_key=secret") + if err == nil { + resp.Body.Close() + } + result <- err + }() + err := awaitErr(t, result) if !errors.Is(err, context.Canceled) { t.Errorf("err = %v, want context.Canceled", err) } @@ -506,6 +818,28 @@ func TestPrompter_EOF(t *testing.T) { } } +// Once input has ended, later prompts still print their question but return +// io.EOF at once: only the first waits for an interrupt. +func TestPrompter_EOFSticks(t *testing.T) { + var w strings.Builder + p := newPrompter(t.Context(), strings.NewReader("y"), &w) + if got, err := p.Ask("1 "); got != "y" || err != nil { + t.Fatalf("last line without a newline = %q, %v; want y", got, err) + } + start := time.Now() + for _, q := range []string{"2 ", "3 ", "4 ", "5 "} { + if _, err := p.Ask(q); !errors.Is(err, io.EOF) { + t.Fatalf("Ask(%q) error = %v, want io.EOF", q, err) + } + } + if d := time.Since(start); d > 2*eofGrace { + t.Errorf("4 prompts after EOF took %v; want one eofGrace at most", d) + } + if w.String() != "1 2 3 4 5 " { + t.Errorf("questions written as %q", w.String()) + } +} + // An interrupt stops a prompt that is waiting for an answer. func TestPrompter_InterruptWhileWaiting(t *testing.T) { r, w := io.Pipe() @@ -513,11 +847,28 @@ func TestPrompter_InterruptWhileWaiting(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(50*time.Millisecond, cancel) - if _, err := newPrompter(ctx, r, io.Discard).Ask("q"); !errors.Is(err, context.Canceled) { + result := make(chan error, 1) + go func() { + _, err := newPrompter(ctx, r, io.Discard).Ask("q") + result <- err + }() + if err := awaitErr(t, result); !errors.Is(err, context.Canceled) { t.Errorf("error = %v, want context.Canceled", err) } } +// awaitErr returns result's error, failing the test if none comes in 5s. +func awaitErr(t *testing.T, result <-chan error) error { + t.Helper() + select { + case err := <-result: + return err + case <-time.After(5 * time.Second): + t.Fatal("still waiting after the interrupt") + return nil + } +} + // An EOF that beats the interrupt it came from (Windows' Ctrl+C) is still // reported as the interrupt. func TestPrompter_EOFBeforeInterrupt(t *testing.T) { diff --git a/mkv-audit/main.go b/mkv-audit/main.go index 0a1b071..01eb3dc 100644 --- a/mkv-audit/main.go +++ b/mkv-audit/main.go @@ -116,7 +116,7 @@ func main() { conv = &loggingConverter{inner: runner} } ctx := interruptContext() - stats, err := RunAll(ctx, dir, stateDir, lib, runner, ed, newStdinPrompter(ctx), tmdb, runner, conv, cutoffDate) + stats, err := RunAll(ctx, dir, stateDir, lib, runner, ed, newPrompter(ctx, os.Stdin, os.Stdout), tmdb, runner, conv, cutoffDate) os.Exit(finish(os.Stdout, stats, err)) } diff --git a/mkv-audit/prompt.go b/mkv-audit/prompt.go index d105ab4..2709fa9 100644 --- a/mkv-audit/prompt.go +++ b/mkv-audit/prompt.go @@ -6,12 +6,12 @@ import ( "errors" "fmt" "io" - "os" "strings" "time" ) -// Prompter prints a prompt and reads a line of user input. +// Prompter prints a prompt and reads a line of user input. After an interrupt +// the answer is meaningless, so callers check ctx rather than the error. type Prompter interface { Ask(prompt string) (string, error) } @@ -20,30 +20,30 @@ type Prompter interface { // may have caused it. const eofGrace = 250 * time.Millisecond -type stdinPrompter struct { +type linePrompter struct { ctx context.Context r *bufio.Reader w io.Writer + eof bool // input ended with no interrupt; no more reads } -// newStdinPrompter asks on stdout and reads answers from stdin until ctx is -// cancelled. -func newStdinPrompter(ctx context.Context) *stdinPrompter { - return newPrompter(ctx, os.Stdin, os.Stdout) -} - -func newPrompter(ctx context.Context, r io.Reader, w io.Writer) *stdinPrompter { - return &stdinPrompter{ctx: ctx, r: bufio.NewReader(r), w: w} +// newPrompter asks on w and reads answers from r until ctx is cancelled. +func newPrompter(ctx context.Context, r io.Reader, w io.Writer) *linePrompter { + return &linePrompter{ctx: ctx, r: bufio.NewReader(r), w: w} } // Ask writes prompt and returns the trimmed answer. Once ctx is cancelled it -// returns ctx's error without waiting for an answer. A read that ends in EOF -// first waits up to eofGrace for ctx to be cancelled. -func (p *stdinPrompter) Ask(prompt string) (string, error) { +// returns ctx's error without waiting for an answer. The first read that ends +// in EOF waits up to eofGrace for ctx to be cancelled; once input has ended, +// every later Ask returns io.EOF at once. +func (p *linePrompter) Ask(prompt string) (string, error) { if err := p.ctx.Err(); err != nil { return "", err } fmt.Fprint(p.w, prompt) + if p.eof { + return "", io.EOF + } type answer struct { line string err error @@ -62,7 +62,7 @@ func (p *stdinPrompter) Ask(prompt string) (string, error) { case a = <-c: } // On Windows a Ctrl+C at the prompt ends the read with EOF, which can - // arrive before the signal does, so any EOF waits briefly for it. + // arrive before the signal does, so an EOF waits briefly for it. if errors.Is(a.err, io.EOF) { select { case <-p.ctx.Done(): @@ -72,8 +72,9 @@ func (p *stdinPrompter) Ask(prompt string) (string, error) { if err := p.ctx.Err(); err != nil { return "", err } + p.eof = errors.Is(a.err, io.EOF) // A last line without a newline is still an answer. - if a.err != nil && (!errors.Is(a.err, io.EOF) || a.line == "") { + if a.err != nil && (!p.eof || a.line == "") { return "", a.err } return strings.TrimSpace(a.line), nil diff --git a/mkv-audit/remux.go b/mkv-audit/remux.go index a4dfa5f..380a6c5 100644 --- a/mkv-audit/remux.go +++ b/mkv-audit/remux.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "fmt" "os" "path/filepath" @@ -11,6 +10,8 @@ import ( ) // MKVRemuxer creates a new MKV file with a subset/reordering of tracks. +// ctx's kill context (see command) kills mkvmerge; Remux then returns an error +// matching context.Canceled and leaves the file as it was. type MKVRemuxer interface { Remux(ctx context.Context, filePath string, plan *TrimPlan, info MKVInfo) error } @@ -75,10 +76,7 @@ func (r *realMKVRunner) Remux(ctx context.Context, filePath string, plan *TrimPl if out, err := command(ctx, r.mkvmerge, args...).CombinedOutput(); err != nil { os.Remove(tmpPath) - if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { - return err - } - return fmt.Errorf("mkvmerge: %w\n%s", err, out) + return fmt.Errorf("mkvmerge: %w\n%s", commandErr(ctx, err), out) } // Atomic-ish replacement. Windows does not support rename-over-existing, diff --git a/mkv-audit/runner.go b/mkv-audit/runner.go index 3225d00..c7a2485 100644 --- a/mkv-audit/runner.go +++ b/mkv-audit/runner.go @@ -64,8 +64,8 @@ func (r *realMKVRunner) ReadTagDate(ctx context.Context, filePath string) (time. func (r *realMKVRunner) Identify(ctx context.Context, filePath string) (*MKVInfo, error) { out, err := command(ctx, r.mkvmerge, "--identify", "--identification-format", "json", filePath).Output() - if err := commandErr(ctx, err); errors.Is(err, context.Canceled) { - return nil, err + if err = commandErr(ctx, err); errors.Is(err, context.Canceled) { + return nil, err // killed: its partial output isn't worth parsing } if err != nil { // mkvmerge exits non-zero on warnings; try parsing anyway. @@ -123,7 +123,7 @@ func saveFailedCache(stateDir string, paths []string) error { return writeStateJSON(stateDir, failedCacheFile, paths) } -// unscannedFailures returns the entries of oldFails that a full scan of root +// unscannedFailures returns the entries of oldFails that a scan of root // didn't retry: not in scanned, and outside root, inside a folder in // unreadable, or still on disk (e.g. skipped as older than the cutoff). func unscannedFailures(oldFails, scanned []string, root string, unreadable []string) []string { @@ -308,8 +308,8 @@ func fetchOrigins(ctx context.Context, filesToScan []string, libraryRoot, libTyp break } } - if ctx.Err() != nil { - break // the lookup may have been cut short + if err != nil && ctx.Err() != nil { + break // the lookup was cut short } if err != nil { fmt.Printf("[TMDB] %s: %v\n", dir, err) @@ -361,8 +361,9 @@ func fetchOrigins(ctx context.Context, filesToScan []string, libraryRoot, libTyp // resolveTMDBID searches TMDB for dir and prompts the user to confirm the top // result or enter a manual ID, and returns the confirmed ID. -// Returns "" when the user skips or no prompter is available. When the -// prompter fails (stdin closed), it sets skipAll, so no more are asked. +// Returns "" when the user skips, no prompter is available or ctx is +// cancelled. When the prompter fails (stdin closed), it sets skipAll, so no +// more are asked. func resolveTMDBID(ctx context.Context, dir, title, year, libType string, tmdb TMDBOriginClient, prompter Prompter, autoAll, skipAll *bool) string { if prompter == nil || *skipAll { return "" @@ -492,12 +493,9 @@ type trimCandidate struct { // retagOnlyAudio offers to set a file's only audio track to the original // language: language, plus language-ietf when the language has an IETF mapping. -// Answering "a" sets *all so later files are retagged without asking. Once ctx -// is cancelled it does nothing. +// Answering "a" sets *all so later files are retagged without asking. An +// interrupt at the prompt retags nothing. func retagOnlyAudio(ctx context.Context, tc trimCandidate, track Track, editor MKVEditor, prompter Prompter, all *bool, stats *Stats) { - if ctx.Err() != nil { - return - } basename := filepath.Base(tc.path) ietf, hasIETF := tc.ietfMap[tc.originLang] if !*all { @@ -561,10 +559,11 @@ func applyLangFixes(tracks []Track, fixes []langFix) []Track { // converter remuxes other video containers (see convertExts) to MKV before // processing; pass nil to process only .mkv and .mka files. // -// Once ctx is cancelled it starts no more files, prompts or remuxes, and -// returns ctx's error; a file already being edited is finished. Its kill -// context (see command) kills mkvmerge and mkvextract, never mkvpropedit, and a -// file whose read was killed is left unchanged rather than counted as failed. +// Once ctx is cancelled it starts no more conversions, lookups, files, +// prompts or remuxes, and returns ctx's error; an edit or remux already +// running is finished. Its kill context (see command) kills mkvmerge and +// mkvextract, never mkvpropedit, and after the kill no edit starts. A file the +// interrupt skipped is left unchanged rather than counted as failed. func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVIdentifier, editor MKVEditor, prompter Prompter, tmdb TMDBOriginClient, remuxer MKVRemuxer, converter MKVConverter, cutoffDate time.Time) (Stats, error) { var stats Stats var trimCandidates []trimCandidate @@ -577,9 +576,6 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI oldFails := loadFailedCache(stateDir) if len(oldFails) > 0 { ans, _ := prompter.Ask(fmt.Sprintf("Found %d previously failed files. Run only these? (y/n): ", len(oldFails))) - if err := ctx.Err(); err != nil { - return stats, err - } if strings.ToLower(strings.TrimSpace(ans)) == "y" { filesToScan = oldFails } @@ -738,6 +734,9 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI sem := make(chan struct{}, runtime.NumCPU()) var mu sync.Mutex var wg sync.WaitGroup + // finished lists the files the scan got through, which an interrupted run + // takes off the failure list. + var finished []string for _, path := range filesToScan { if ctx.Err() != nil { @@ -765,10 +764,10 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI info, err := ident.Identify(ctx, p) var res AnalysisResult - if errors.Is(err, context.Canceled) { - return // killed: the file is unchanged and not a failure - } - if err != nil { + stopped := errors.Is(err, context.Canceled) // the read was killed + if stopped { + fmt.Fprintf(&buf, "[STOP] %s: interrupted; left unchanged\n", basename) + } else if err != nil { fmt.Fprintf(&buf, "[ERR] %s: %v\n", basename, err) local.Failed++ local.FailedPaths = append(local.FailedPaths, p) @@ -849,15 +848,15 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI } } - // After a second Ctrl+C, start no edit and leave the file - // unscanned: a killed mkvextract may have hidden a date fix. - if killContext(ctx).Err() != nil { - return - } if res.Failed { fmt.Fprintf(&buf, "[FAILED] %s: %s\n", basename, strings.Join(res.FailReasons, ", ")) local.Failed++ local.FailedPaths = append(local.FailedPaths, p) + } else if killContext(ctx).Err() != nil { + // After a second Ctrl+C, start no edit: a killed + // mkvextract may have hidden a date fix. + stopped = true + fmt.Fprintf(&buf, "[STOP] %s: interrupted; left unchanged\n", basename) } else if len(res.Edits) == 0 { fmt.Fprintf(&buf, "[OK] %s (no changes needed)\n", basename) } else if err := editor.Apply(p, res.Edits); err != nil { @@ -877,7 +876,12 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI } mu.Lock() + defer mu.Unlock() fmt.Print(buf.String()) + if stopped { + return + } + finished = append(finished, p) stats.Scanned++ stats.Failed += local.Failed stats.FailedPaths = append(stats.FailedPaths, local.FailedPaths...) @@ -906,7 +910,6 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI accountLangs: accountLangs.forFile(p, libRoot), }) } - mu.Unlock() }(path) } @@ -989,7 +992,10 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI if len(plan.MismatchedAudio) == 1 { retagOnlyAudio(ctx, tc, plan.MismatchedAudio[0], editor, prompter, &retagAll, &stats) } - if !plan.NeedsChange || ctx.Err() != nil { + if ctx.Err() != nil { + break // interrupted at the retag prompt + } + if !plan.NeedsChange { continue } if !autoAll { @@ -1024,13 +1030,10 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI } // Persist failure list and unknown codecs. Earlier failures a full scan - // didn't retry stay listed, as do all of them after an interrupt, which - // may have skipped any file. + // didn't retry stay listed, as do those an interrupted run didn't finish. failed := stats.FailedPaths if ctx.Err() != nil { - failed = slices.Concat(oldFails, failed) - slices.Sort(failed) - failed = slices.Compact(failed) + failed = slices.Concat(failed, unscannedFailures(oldFails, finished, root, unreadable)) } else if fullScan { failed = slices.Concat(failed, unscannedFailures(oldFails, slices.Concat(attempted, filesToScan), root, unreadable)) } From 9f4bde25f78fd2cf6f8ad72076177b70463cc917 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sat, 5 Dec 2026 19:31:31 +1300 Subject: [PATCH 3/5] fix(mkv-audit): keep failures a later phase never finished, list each failure once, and say nothing about a TMDB match an interrupt cut short --- README.md | 2 +- mkv-audit/convert.go | 8 +- mkv-audit/interrupt_run_test.go | 231 ++++++++++++++++++++++---------- mkv-audit/prompt.go | 3 +- mkv-audit/runner.go | 64 ++++++--- 5 files changed, 212 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index be68d49..95f06a9 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ The tool scans recursively and prints a summary: Scanned: 120 Fixed: 14 Failed: 0 LangFixes: 9 FlagFixes: 8 ``` -Ctrl+C stops before the next file or lookup, and at a prompt without acting on the answer, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets the fixes that need no answer, and a conversion or trim in progress finishes. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge` or `mkvextract` in progress and starts no more edits; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files the interrupt skips aren't recorded as failures, and earlier failures it didn't reach stay on the retry list. From then on only Ctrl+C quits, at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed. +Ctrl+C stops before the next file or lookup, and at a prompt without acting on the answer, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets the fixes that need no answer, and a conversion or trim in progress finishes. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge` or `mkvextract` in progress and starts no more edits; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files the interrupt skips aren't recorded as failures, and an earlier failure stays on the retry list unless the run got all the way through that file. From then on only Ctrl+C quits, at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed. ### Dependencies diff --git a/mkv-audit/convert.go b/mkv-audit/convert.go index 2422959..ce06fd6 100644 --- a/mkv-audit/convert.go +++ b/mkv-audit/convert.go @@ -40,8 +40,9 @@ func isConvertible(path string) bool { // convertAll converts each convertible path in paths to MKV and returns a new // list with the MKV in its place. A source that is skipped, fails to convert -// or is left by an interrupt is dropped; a failure is also recorded in stats. Each path appears -// once, so a retry list holding both x.mp4 and x.mkv doesn't scan x.mkv twice. +// or is left by an interrupt is dropped; a failure is also recorded in stats. +// Each path appears once, so a retry list holding both x.mp4 and x.mkv +// doesn't scan x.mkv twice. func convertAll(ctx context.Context, paths []string, converter MKVConverter, stats *Stats) []string { out := make([]string, 0, len(paths)) seen := make(map[string]bool, len(paths)) @@ -103,7 +104,8 @@ func (r *realMKVRunner) ConvertToMKV(ctx context.Context, src string) (string, e // mux runs mkvmerge to copy every track of src into a new MKV at dst. func (r *realMKVRunner) mux(ctx context.Context, src, dst string) error { out, err := command(ctx, r.mkvmerge, "-o", dst, src).CombinedOutput() - // First, since a killed mkvmerge exits 1 on Windows, like warnings. + // Before the exit-code-1 case: a killed mkvmerge exits 1 on Windows too, + // like a run with warnings. if err = commandErr(ctx, err); errors.Is(err, context.Canceled) { return err } diff --git a/mkv-audit/interrupt_run_test.go b/mkv-audit/interrupt_run_test.go index 80e9e73..4a392f2 100644 --- a/mkv-audit/interrupt_run_test.go +++ b/mkv-audit/interrupt_run_test.go @@ -18,9 +18,9 @@ import ( ) func init() { - // The mkvmerge helper mode stands in for mkvmerge: it answers --identify with one video - // track, and otherwise starts its -o file, says it's ready and sleeps until - // killed. + // The mkvmerge helper stands in for mkvmerge: it answers --identify with one + // video track, and otherwise writes its -o file, reports ready and sleeps + // until killed. helperModes["mkvmerge"] = func() { if slices.Contains(os.Args, "--identify") { fmt.Println(`{"tracks":[{"id":0,"type":"video"}]}`) @@ -140,8 +140,8 @@ func TestFetchOrigins_InterruptAtPromptSavesNothing(t *testing.T) { t.Errorf("origins = %v; want none", origins) } }) - if p.asked != 1 || strings.Contains(out, "no input") { - t.Errorf("asked %d times; want 1, with no 'no input' line:\n%s", p.asked, out) + if p.asked != 1 || strings.Contains(out, "no input") || strings.Contains(out, "no match") { + t.Errorf("asked %d times; want 1, with no 'no input' or 'no match' line:\n%s", p.asked, out) } if _, err := os.Stat(tvShowCachePath()); !os.IsNotExist(err) { t.Errorf("show cache saved; want nothing saved (%v)", err) @@ -165,7 +165,7 @@ func TestRunAll_KilledIdentifyIsNotAFailure(t *testing.T) { var stats Stats var err error - captureStdout(t, func() { + out := captureStdout(t, func() { stats, err = RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "n"}, nil, nil, nil, time.Time{}) }) if !errors.Is(err, context.Canceled) { @@ -174,6 +174,9 @@ func TestRunAll_KilledIdentifyIsNotAFailure(t *testing.T) { if stats.Failed != 0 || stats.Scanned != 0 { t.Errorf("Failed = %d, Scanned = %d; want 0 and 0", stats.Failed, stats.Scanned) } + if !strings.Contains(out, "[STOP] a.mkv: interrupted; left unchanged") { + t.Errorf("missing the stop line:\n%s", out) + } if got := loadFailedCache(stateDir); !slices.Equal(got, old) { t.Errorf("failure list = %v, want the untried %v", got, old) } @@ -204,35 +207,81 @@ func TestRunAll_NoEditAfterKill(t *testing.T) { } } -// An interrupted run takes the failures it got through off the list, and -// those that are gone, but keeps the ones it never reached. +// An interrupted run takes a failure off the list only once every phase has +// finished that file. It keeps the rest, including one whose file is gone, +// since a walk it cut short can't tell a gone file from an offline drive. func TestRunAll_InterruptKeepsOnlyUnfinishedFailures(t *testing.T) { - dir, lib, info := trimLibrary(t) - stateDir := t.TempDir() - fixed := filepath.Join(dir, "e1.mkv") - gone := filepath.Join(dir, "gone.mkv") - elsewhere := filepath.Join(t.TempDir(), "x.mkv") // outside the scan - if err := saveFailedCache(stateDir, []string{fixed, gone, elsewhere}); err != nil { + cases := []struct { + name string + // run stops the run in the trim phase and returns the files trimmed. + run func(ctx context.Context, stop, kill func(), dir, stateDir string, lib *Library, info *MKVInfo) []string + }{ + {"stop at the trim prompt", func(ctx context.Context, stop, _ func(), dir, stateDir string, lib *Library, info *MKVInfo) []string { + _, _ = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, &stopAtPrompter{prefix: "[TRIM]", stop: stop}, nil, &recordingRemuxer{}, nil, time.Time{}) + return nil + }}, + {"stop during a remux", func(ctx context.Context, stop, _ func(), dir, stateDir string, lib *Library, info *MKVInfo) []string { + r := &interruptingRemuxer{stop: stop} + _, _ = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "a"}, nil, r, nil, time.Time{}) + return r.paths + }}, + {"kill during a remux", func(ctx context.Context, stop, kill func(), dir, stateDir string, lib *Library, info *MKVInfo) []string { + r := &interruptingRemuxer{stop: stop, kill: kill} + _, _ = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, &fakePrompter{answer: "a"}, nil, r, nil, time.Time{}) + return nil + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir, lib, info := trimLibrary(t) + stateDir := t.TempDir() + e1, e2 := filepath.Join(dir, "e1.mkv"), filepath.Join(dir, "e2.mkv") + gone := filepath.Join(dir, "gone.mkv") + elsewhere := filepath.Join(t.TempDir(), "x.mkv") // outside the scan + if err := saveFailedCache(stateDir, []string{e1, e2, gone, elsewhere}); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + + var trimmed []string + captureStdout(t, func() { trimmed = tc.run(ctx, stop, kill, dir, stateDir, lib, info) }) + var want []string + for _, p := range []string{e1, e2, gone, elsewhere} { + if !slices.Contains(trimmed, p) { + want = append(want, p) + } + } + if got := loadFailedCache(stateDir); !slices.Equal(got, want) { + t.Errorf("failure list = %v, want %v", got, want) + } + }) + } +} + +// A file that fails twice before the interrupt is listed once. +func TestRunAll_InterruptListsAFailureOnce(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + a := filepath.Join(dir, "a.mkv") + if err := saveFailedCache(stateDir, []string{a}); err != nil { t.Fatal(err) } ctx, stop, kill := newInterruptContext() t.Cleanup(kill) - // A full scan, stopped at the first trim prompt, after every file is read. - p := &stopAtPrompter{prefix: "[TRIM]", stop: stop} - remuxer := &recordingRemuxer{} + und := &MKVInfo{Tracks: []Track{{ID: 0, Type: "audio", Properties: TrackProperties{Language: "und", CodecID: "A_AC3", AudioChannels: 2}}}} + // The und edit fails, then the main pass's read (call 2) is killed. + ident := &interruptingIdentifier{info: und, at: 2, stop: stop, kill: kill} + editor := &fakeEditor{err: errors.New("locked")} - var err error captureStdout(t, func() { - _, err = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, p, nil, remuxer, nil, time.Time{}) + _, _ = RunAll(ctx, dir, stateDir, nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) }) - if !errors.Is(err, context.Canceled) { - t.Errorf("err = %v, want context.Canceled", err) + if len(editor.calls) != 1 { + t.Fatalf("applied %v, want the one failing und edit", editor.calls) } - if len(remuxer.plans) != 0 { - t.Errorf("remuxed %d files after the interrupt at the trim prompt", len(remuxer.plans)) - } - if got := loadFailedCache(stateDir); !slices.Equal(got, []string{elsewhere}) { - t.Errorf("failure list = %v, want only the unreached %v", got, elsewhere) + if got := loadFailedCache(stateDir); !slices.Equal(got, []string{a}) { + t.Errorf("failure list = %v, want [%s]", got, a) } } @@ -258,12 +307,24 @@ func (p *stopAtPrompter) Ask(q string) (string, error) { return "y", nil } -// A Ctrl+C as a yes/no prompt is answered applies nothing, and asks nothing -// more. +// A Ctrl+C landing as a prompt is answered "y" applies nothing more, asks +// nothing more, and keeps the earlier failures of the files it stopped. func TestRunAll_InterruptAtPromptAppliesNothing(t *testing.T) { + langFix := func(t *testing.T) (string, *Library, *MKVInfo) { + t.Helper() + // The folder's override says Japanese; the tracks say English. + dir := t.TempDir() + makeMKVFile(t, dir, "e1.mkv") + makeMKVFile(t, dir, "e2.mkv") + return dir, &Library{Path: dir, Overrides: []DirOverride{{Path: ".", IETF: map[string]string{"jpn": "ja-JP"}}}}, &MKVInfo{Tracks: []Track{ + {ID: 0, Type: "video", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US"}}, + {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, + }} + } cases := []struct { prefix string setup func(t *testing.T) (dir string, lib *Library, info *MKVInfo) + noTrim bool // run with no remuxer, so no trim phase }{ {"[RETAG]", func(t *testing.T) (string, *Library, *MKVInfo) { t.Helper() @@ -276,32 +337,36 @@ func TestRunAll_InterruptAtPromptAppliesNothing(t *testing.T) { {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, {ID: 2, Type: "subtitles", Properties: TrackProperties{Language: "fre", LanguageIETF: "fr", CodecID: "S_TEXT/ASS"}}, }} - }}, - {"[TRIM]", trimLibrary}, - {"[LANGFIX]", func(t *testing.T) (string, *Library, *MKVInfo) { - t.Helper() - // The folder's override says Japanese; the tracks say English. - dir := t.TempDir() - makeMKVFile(t, dir, "e1.mkv") - makeMKVFile(t, dir, "e2.mkv") - return dir, &Library{Path: dir, Overrides: []DirOverride{{Path: ".", IETF: map[string]string{"jpn": "ja-JP"}}}}, &MKVInfo{Tracks: []Track{ - {ID: 0, Type: "video", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US"}}, - {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, - }} - }}, + }, false}, + {"[TRIM]", trimLibrary, false}, + {"[LANGFIX]", langFix, false}, + {"[LANGFIX]", langFix, true}, } for _, tc := range cases { t.Run(tc.prefix, func(t *testing.T) { dir, lib, info := tc.setup(t) + // Both files failed before; neither gets through this run. + stateDir := t.TempDir() + old := []string{filepath.Join(dir, "e1.mkv"), filepath.Join(dir, "e2.mkv")} + if err := saveFailedCache(stateDir, old); err != nil { + t.Fatal(err) + } ctx, stop, kill := newInterruptContext() t.Cleanup(kill) editor := &fakeEditor{} p := &stopAtPrompter{prefix: tc.prefix, stop: stop, editor: editor} remuxer := &recordingRemuxer{} + var rm MKVRemuxer = remuxer + if tc.noTrim { + rm = nil + } captureStdout(t, func() { - _, _ = RunAll(ctx, dir, t.TempDir(), lib, &fakeIdentifier{info: info}, editor, p, nil, remuxer, nil, time.Time{}) + _, _ = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, editor, p, nil, rm, nil, time.Time{}) }) + if got := loadFailedCache(stateDir); !slices.Equal(got, old) { + t.Errorf("failure list = %v, want both kept", got) + } var at int for _, q := range p.asked { if strings.HasPrefix(q, tc.prefix) { @@ -322,27 +387,35 @@ func TestRunAll_InterruptAtPromptAppliesNothing(t *testing.T) { } // A Ctrl+C at the retry prompt stops before anything is read, and leaves the -// failure list alone. +// failure list alone, even when the library is offline. func TestRunAll_InterruptAtRetryPrompt(t *testing.T) { - dir, stateDir := t.TempDir(), t.TempDir() - makeMKVFile(t, dir, "a.mkv") - old := []string{filepath.Join(dir, "a.mkv")} - if err := saveFailedCache(stateDir, old); err != nil { - t.Fatal(err) - } - ctx, stop, kill := newInterruptContext() - t.Cleanup(kill) - ident := &interruptingIdentifier{info: cleanAudio} + for _, offline := range []bool{false, true} { + t.Run(fmt.Sprintf("offline=%v", offline), func(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + old := []string{filepath.Join(dir, "a.mkv")} + if offline { + dir = filepath.Join(dir, "offline") + old = []string{filepath.Join(dir, "Show", "a.mkv")} + } + if err := saveFailedCache(stateDir, old); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + ident := &interruptingIdentifier{info: cleanAudio} - _, err := RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &stopPrompter{stop: stop}, nil, nil, nil, time.Time{}) - if !errors.Is(err, context.Canceled) { - t.Errorf("err = %v, want context.Canceled", err) - } - if n := ident.calls.Load(); n != 0 { - t.Errorf("identified %d files, want none", n) - } - if got := loadFailedCache(stateDir); !slices.Equal(got, old) { - t.Errorf("failure list = %v, want it unchanged", got) + _, err := RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &stopPrompter{stop: stop}, nil, nil, nil, time.Time{}) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if n := ident.calls.Load(); n != 0 { + t.Errorf("identified %d files, want none", n) + } + if got := loadFailedCache(stateDir); !slices.Equal(got, old) { + t.Errorf("failure list = %v, want it unchanged", got) + } + }) } } @@ -457,18 +530,19 @@ func TestRunAll_InterruptStopsStartingFiles(t *testing.T) { type interruptingRemuxer struct { stop, kill func() calls int + paths []string // the files it remuxed } -func (r *interruptingRemuxer) Remux(context.Context, string, *TrimPlan, MKVInfo) error { +func (r *interruptingRemuxer) Remux(_ context.Context, path string, _ *TrimPlan, _ MKVInfo) error { r.calls++ - if r.calls > 1 { - return nil - } - r.stop() - if r.kill != nil { - r.kill() - return fmt.Errorf("mkvmerge: %w", context.Canceled) + if r.calls == 1 { + r.stop() + if r.kill != nil { + r.kill() + return fmt.Errorf("mkvmerge: %w", context.Canceled) + } } + r.paths = append(r.paths, path) return nil } @@ -690,22 +764,28 @@ func TestRunAll_InterruptStopsAutoAll(t *testing.T) { prompt, match string lib func(dir string) *Library info *MKVInfo + kept int // earlier failures still listed: those not finished }{ {"[UND]", "language=eng", func(string) *Library { return nil }, &MKVInfo{Tracks: []Track{ {ID: 0, Type: "audio", Properties: TrackProperties{Language: "und", CodecID: "A_AC3", AudioChannels: 2}}, - }}}, + }}, 3}, {"[LANGFIX]", "language=jpn", func(dir string) *Library { return &Library{Path: dir, Overrides: []DirOverride{{Path: ".", IETF: map[string]string{"jpn": "ja-JP"}}}} }, &MKVInfo{Tracks: []Track{ {ID: 0, Type: "video", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US"}}, {ID: 1, Type: "audio", Properties: TrackProperties{Language: "eng", LanguageIETF: "en-US", CodecID: "A_AC3", AudioChannels: 6, DefaultTrack: true}}, - }}}, + }}, 2}, } for _, tc := range cases { t.Run(tc.prompt, func(t *testing.T) { - dir := t.TempDir() + dir, stateDir := t.TempDir(), t.TempDir() + var old []string for _, f := range []string{"a.mkv", "b.mkv", "c.mkv"} { makeMKVFile(t, dir, f) + old = append(old, filepath.Join(dir, f)) + } + if err := saveFailedCache(stateDir, old); err != nil { + t.Fatal(err) } ctx, stop, kill := newInterruptContext() t.Cleanup(kill) @@ -713,11 +793,14 @@ func TestRunAll_InterruptStopsAutoAll(t *testing.T) { p := &prefixPrompter{answers: map[string]string{tc.prompt: "a"}} captureStdout(t, func() { - _, _ = RunAll(ctx, dir, t.TempDir(), tc.lib(dir), &fakeIdentifier{info: tc.info}, ed, p, nil, nil, nil, time.Time{}) + _, _ = RunAll(ctx, dir, stateDir, tc.lib(dir), &fakeIdentifier{info: tc.info}, ed, p, nil, nil, nil, time.Time{}) }) if p.count(tc.prompt) != 1 || ed.hits != 1 { t.Errorf("asked %d %s prompts, made %d %s edits; want 1 and only the one in progress", p.count(tc.prompt), tc.prompt, ed.hits, tc.match) } + if got := loadFailedCache(stateDir); len(got) != tc.kept { + t.Errorf("failure list = %v, want %d of %v", got, tc.kept, old) + } }) } } @@ -811,7 +894,7 @@ func TestPrompter_Answers(t *testing.T) { } } -// EOF with no answer and no interrupt is an error, as it was. +// EOF with no answer and no interrupt is an error. func TestPrompter_EOF(t *testing.T) { if _, err := newPrompter(t.Context(), strings.NewReader(""), io.Discard).Ask("q"); !errors.Is(err, io.EOF) { t.Errorf("error = %v, want io.EOF", err) diff --git a/mkv-audit/prompt.go b/mkv-audit/prompt.go index 2709fa9..5cf75bf 100644 --- a/mkv-audit/prompt.go +++ b/mkv-audit/prompt.go @@ -11,7 +11,8 @@ import ( ) // Prompter prints a prompt and reads a line of user input. After an interrupt -// the answer is meaningless, so callers check ctx rather than the error. +// a blank answer would accept a default, so callers check ctx before acting +// on the answer. type Prompter interface { Ask(prompt string) (string, error) } diff --git a/mkv-audit/runner.go b/mkv-audit/runner.go index c7a2485..91e35f0 100644 --- a/mkv-audit/runner.go +++ b/mkv-audit/runner.go @@ -127,15 +127,8 @@ func saveFailedCache(stateDir string, paths []string) error { // didn't retry: not in scanned, and outside root, inside a folder in // unreadable, or still on disk (e.g. skipped as older than the cutoff). func unscannedFailures(oldFails, scanned []string, root string, unreadable []string) []string { - seen := make(map[string]bool, len(scanned)) - for _, p := range scanned { - seen[pathKey(p)] = true - } var out []string - for _, p := range oldFails { - if seen[pathKey(p)] { - continue - } + for _, p := range without(oldFails, scanned) { _, err := os.Stat(p) if !within(p, root) || slices.ContainsFunc(unreadable, func(dir string) bool { return within(p, dir) }) || !os.IsNotExist(err) { out = append(out, p) @@ -144,6 +137,22 @@ func unscannedFailures(oldFails, scanned []string, root string, unreadable []str return out } +// without returns the entries of paths that aren't in drop, each path once. +func without(paths, drop []string) []string { + seen := make(map[string]bool, len(drop)+len(paths)) + for _, p := range drop { + seen[pathKey(p)] = true + } + var out []string + for _, p := range paths { + if k := pathKey(p); !seen[k] { + seen[k] = true + out = append(out, p) + } + } + return out +} + // pathKey normalises p for comparison; Windows paths are case-insensitive. func pathKey(p string) string { if abs, err := filepath.Abs(p); err == nil { @@ -308,8 +317,8 @@ func fetchOrigins(ctx context.Context, filesToScan []string, libraryRoot, libTyp break } } - if err != nil && ctx.Err() != nil { - break // the lookup was cut short + if ctx.Err() != nil && (err != nil || !found) { + break // the prompt, search or lookup was cut short } if err != nil { fmt.Printf("[TMDB] %s: %v\n", dir, err) @@ -734,8 +743,8 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI sem := make(chan struct{}, runtime.NumCPU()) var mu sync.Mutex var wg sync.WaitGroup - // finished lists the files the scan got through, which an interrupted run - // takes off the failure list. + // finished lists the files the main pass got through. An interrupted run + // takes them off the failure list, unless a later phase didn't finish them. var finished []string for _, path := range filesToScan { @@ -921,11 +930,18 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI // whose language was just corrected here could be dropped as foreign). appliedLangFixes := make(map[string][]langFix) + // The phases below stop at index langStop and trimStop on an interrupt. + // The files from there on, and any whose remux was killed, are unfinished + // and keep their earlier failures. + langStop, trimStop := len(langMismatches), len(trimCandidates) + var unfinished []string + // Sequential lang-mismatch fix phase: prompt per file, then apply. if len(langMismatches) > 0 { autoAll := false - for _, lm := range langMismatches { + for i, lm := range langMismatches { if ctx.Err() != nil { + langStop = i break } basename := filepath.Base(lm.path) @@ -936,6 +952,7 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI } ans, _ := prompter.Ask(fmt.Sprintf("[LANGFIX] %s\n%s\n Fix language? (y/n/a=all): ", basename, strings.Join(lines, "\n"))) if ctx.Err() != nil { + langStop = i break } ans = strings.ToLower(strings.TrimSpace(ans)) @@ -968,8 +985,9 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI // Sequential trim phase: prompt per file, then remux. if remuxer != nil { autoAll, retagAll := false, false - for _, tc := range trimCandidates { + for i, tc := range trimCandidates { if ctx.Err() != nil { + trimStop = i break } // Reflect any lang fixes applied above so the plan doesn't drop a @@ -993,7 +1011,8 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI retagOnlyAudio(ctx, tc, plan.MismatchedAudio[0], editor, prompter, &retagAll, &stats) } if ctx.Err() != nil { - break // interrupted at the retag prompt + trimStop = i // interrupted at the retag prompt + break } if !plan.NeedsChange { continue @@ -1002,6 +1021,7 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI summary := TrimSummary(plan) ans, _ := prompter.Ask(fmt.Sprintf("[TRIM] %s\n%s Proceed? (y/n/a=all): ", basename, summary)) if ctx.Err() != nil { + trimStop = i break } ans = strings.ToLower(strings.TrimSpace(ans)) @@ -1018,6 +1038,7 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI fmt.Printf("[TRIMMING] %s...\n", basename) if err := remuxer.Remux(ctx, tc.path, plan, tc.info); errors.Is(err, context.Canceled) { fmt.Printf("[STOP] %s: interrupted; left unchanged\n", basename) + unfinished = append(unfinished, tc.path) } else if err != nil { fmt.Printf("[ERR] %s: remux: %v\n", basename, err) stats.Failed++ @@ -1030,13 +1051,22 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI } // Persist failure list and unknown codecs. Earlier failures a full scan - // didn't retry stay listed, as do those an interrupted run didn't finish. + // didn't retry stay listed, as do those an interrupted run didn't finish: + // it may not have walked far enough to tell a gone file from an offline + // drive, so it keeps them all. failed := stats.FailedPaths if ctx.Err() != nil { - failed = slices.Concat(failed, unscannedFailures(oldFails, finished, root, unreadable)) + for _, lm := range langMismatches[langStop:] { + unfinished = append(unfinished, lm.path) + } + for _, tc := range trimCandidates[trimStop:] { + unfinished = append(unfinished, tc.path) + } + failed = slices.Concat(failed, without(oldFails, without(finished, unfinished))) } else if fullScan { failed = slices.Concat(failed, unscannedFailures(oldFails, slices.Concat(attempted, filesToScan), root, unreadable)) } + failed = without(failed, nil) // a file can fail in more than one phase if len(failed) > 0 { if err := saveFailedCache(stateDir, failed); err != nil { fmt.Printf("[WARN] could not save %s: %v\n", filepath.Join(stateDir, failedCacheFile), err) From c66e1b0050c4a1054748b32e3a7da311aa23a0f0 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sat, 5 Dec 2026 19:45:19 +1300 Subject: [PATCH 4/5] fix(mkv-audit): take a converted failure off the list once its MKV is finished, and pin new and repeated failures in the list --- mkv-audit/convert.go | 10 +++-- mkv-audit/interrupt_run_test.go | 72 ++++++++++++++++++++++++++++++++- mkv-audit/runner.go | 13 ++++-- 3 files changed, 86 insertions(+), 9 deletions(-) diff --git a/mkv-audit/convert.go b/mkv-audit/convert.go index ce06fd6..cab6266 100644 --- a/mkv-audit/convert.go +++ b/mkv-audit/convert.go @@ -42,9 +42,10 @@ func isConvertible(path string) bool { // list with the MKV in its place. A source that is skipped, fails to convert // or is left by an interrupt is dropped; a failure is also recorded in stats. // Each path appears once, so a retry list holding both x.mp4 and x.mkv -// doesn't scan x.mkv twice. -func convertAll(ctx context.Context, paths []string, converter MKVConverter, stats *Stats) []string { - out := make([]string, 0, len(paths)) +// doesn't scan x.mkv twice. sources maps each new MKV's pathKey to its source. +func convertAll(ctx context.Context, paths []string, converter MKVConverter, stats *Stats) (out []string, sources map[string]string) { + out = make([]string, 0, len(paths)) + sources = make(map[string]string) seen := make(map[string]bool, len(paths)) keep := func(p string) { if k := pathKey(p); !seen[k] { @@ -79,10 +80,11 @@ func convertAll(ctx context.Context, paths []string, converter MKVConverter, sta fmt.Printf("[WARN] %s: %v\n", base, err) } stats.Converted++ + sources[pathKey(dst)] = p keep(dst) } } - return out + return out, sources } // loggingConverter wraps an MKVConverter and prints the planned conversion. diff --git a/mkv-audit/interrupt_run_test.go b/mkv-audit/interrupt_run_test.go index 4a392f2..293bb2e 100644 --- a/mkv-audit/interrupt_run_test.go +++ b/mkv-audit/interrupt_run_test.go @@ -259,7 +259,75 @@ func TestRunAll_InterruptKeepsOnlyUnfinishedFailures(t *testing.T) { } } -// A file that fails twice before the interrupt is listed once. +// An earlier failure the run converted, then finished as an MKV, comes off +// the list even if the run is interrupted afterwards. +func TestRunAll_InterruptDropsAFinishedConversion(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + src := filepath.Join(dir, "x.mp4") + if err := os.WriteFile(src, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := saveFailedCache(stateDir, []string{src}); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + // Call 1 is the und pass; the Ctrl+C lands during the main pass's read. + ident := &interruptingIdentifier{info: cleanAudio, at: 2, stop: stop} + + var err error + captureStdout(t, func() { + _, err = RunAll(ctx, dir, stateDir, nil, ident, &fakeEditor{}, &fakePrompter{answer: "y"}, nil, nil, &fakeConverter{}, time.Time{}) + }) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if got := loadFailedCache(stateDir); len(got) != 0 { + t.Errorf("failure list = %v, want it empty", got) + } +} + +// A failure from an interrupted run is listed. +func TestRunAll_InterruptListsANewFailure(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + // The Ctrl+C lands during the main pass's read; the edit then fails. + ident := &interruptingIdentifier{info: needsLangFix, at: 2, stop: stop} + editor := &fakeEditor{err: errors.New("locked")} + + captureStdout(t, func() { + _, _ = RunAll(ctx, dir, stateDir, nil, ident, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + }) + if len(editor.calls) != 1 { + t.Fatalf("applied %v, want the one failing edit", editor.calls) + } + if got, want := loadFailedCache(stateDir), filepath.Join(dir, "a.mkv"); !slices.Equal(got, []string{want}) { + t.Errorf("failure list = %v, want [%s]", got, want) + } +} + +// A file that fails in two phases of one run is listed once. +func TestRunAll_ListsAFailureOnce(t *testing.T) { + dir, stateDir := t.TempDir(), t.TempDir() + makeMKVFile(t, dir, "a.mkv") + und := &MKVInfo{Tracks: []Track{{ID: 0, Type: "audio", Properties: TrackProperties{Language: "und", CodecID: "A_AC3", AudioChannels: 2}}}} + editor := &fakeEditor{err: errors.New("locked")} + + captureStdout(t, func() { + _, _ = RunAll(t.Context(), dir, stateDir, nil, &fakeIdentifier{info: und}, editor, &fakePrompter{}, nil, nil, nil, time.Time{}) + }) + if len(editor.calls) != 2 { + t.Fatalf("applied %v, want the und edit and the main-pass edit", editor.calls) + } + if got, want := loadFailedCache(stateDir), filepath.Join(dir, "a.mkv"); !slices.Equal(got, []string{want}) { + t.Errorf("failure list = %v, want [%s]", got, want) + } +} + +// A file on the failure list that fails again before the interrupt is +// listed once. func TestRunAll_InterruptListsAFailureOnce(t *testing.T) { dir, stateDir := t.TempDir(), t.TempDir() makeMKVFile(t, dir, "a.mkv") @@ -618,7 +686,7 @@ func TestConvertAll_KilledIsNotAFailure(t *testing.T) { var out []string printed := captureStdout(t, func() { - out = convertAll(ctx, []string{"a.mp4", "b.mp4", "c.mkv"}, conv, &stats) + out, _ = convertAll(ctx, []string{"a.mp4", "b.mp4", "c.mkv"}, conv, &stats) }) if conv.calls != 1 || stats.Failed != 0 || stats.Converted != 0 { t.Errorf("conversions %d, Failed %d, Converted %d; want 1, 0, 0", conv.calls, stats.Failed, stats.Converted) diff --git a/mkv-audit/runner.go b/mkv-audit/runner.go index 91e35f0..dfb4968 100644 --- a/mkv-audit/runner.go +++ b/mkv-audit/runner.go @@ -317,7 +317,7 @@ func fetchOrigins(ctx context.Context, filesToScan []string, libraryRoot, libTyp break } } - if ctx.Err() != nil && (err != nil || !found) { + if ctx.Err() != nil && !found { break // the prompt, search or lookup was cut short } if err != nil { @@ -626,8 +626,9 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI // Convert other containers to MKV and scan the result in their place. An // earlier failure on a source counts as retried even if it's skipped now. attempted := filesToScan + var sources map[string]string if converter != nil { - filesToScan = convertAll(ctx, filesToScan, converter, &stats) + filesToScan, sources = convertAll(ctx, filesToScan, converter, &stats) } // Pre-compute TMDB origin info sequentially before the concurrent phase. @@ -1062,7 +1063,13 @@ func RunAll(ctx context.Context, root, stateDir string, lib *Library, ident MKVI for _, tc := range trimCandidates[trimStop:] { unfinished = append(unfinished, tc.path) } - failed = slices.Concat(failed, without(oldFails, without(finished, unfinished))) + done := without(finished, unfinished) + for _, p := range done { + if src, ok := sources[pathKey(p)]; ok { + done = append(done, src) // the run converted it, then finished the MKV + } + } + failed = slices.Concat(failed, without(oldFails, done)) } else if fullScan { failed = slices.Concat(failed, unscannedFailures(oldFails, slices.Concat(attempted, filesToScan), root, unreadable)) } From 56a6b39355d24e40387a71f812f01874a2f38f6a Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sat, 5 Dec 2026 19:52:52 +1300 Subject: [PATCH 5/5] test(mkv-audit): keep a converted failure listed when the interrupt stops its MKV's trim --- mkv-audit/interrupt_run_test.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/mkv-audit/interrupt_run_test.go b/mkv-audit/interrupt_run_test.go index 293bb2e..efb6a10 100644 --- a/mkv-audit/interrupt_run_test.go +++ b/mkv-audit/interrupt_run_test.go @@ -287,6 +287,30 @@ func TestRunAll_InterruptDropsAFinishedConversion(t *testing.T) { } } +// An earlier failure the run converted stays listed if the interrupt stopped +// the trim of its MKV. +func TestRunAll_InterruptKeepsAnUnfinishedConversion(t *testing.T) { + dir, lib, info := trimLibrary(t) + stateDir := t.TempDir() + src := filepath.Join(dir, "x.mp4") + if err := os.WriteFile(src, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := saveFailedCache(stateDir, []string{src}); err != nil { + t.Fatal(err) + } + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + p := &stopAtPrompter{prefix: "[TRIM]", stop: stop} + + captureStdout(t, func() { + _, _ = RunAll(ctx, dir, stateDir, lib, &fakeIdentifier{info: info}, &fakeEditor{}, p, nil, &recordingRemuxer{}, &fakeConverter{}, time.Time{}) + }) + if got := loadFailedCache(stateDir); !slices.Equal(got, []string{src}) { + t.Errorf("failure list = %v, want [%s]", got, src) + } +} + // A failure from an interrupted run is listed. func TestRunAll_InterruptListsANewFailure(t *testing.T) { dir, stateDir := t.TempDir(), t.TempDir()