From df45088b95b4938eeb206865e08c099afad55e7d Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 6 Dec 2026 00:35:22 +1300 Subject: [PATCH 1/4] feat(mkv-music): stop cleanly on Ctrl+C and pass a context to every child process and Plex request --- README.md | 2 + mkv-music/audio_timestamps.go | 43 ++- mkv-music/command.go | 36 ++ mkv-music/command_other.go | 17 + mkv-music/command_test.go | 184 ++++++++++ mkv-music/command_unix.go | 32 ++ mkv-music/command_unix_test.go | 322 ++++++++++++++++++ mkv-music/command_windows.go | 26 ++ mkv-music/command_windows_test.go | 27 ++ mkv-music/interrupt.go | 76 +++++ mkv-music/interrupt_run_test.go | 539 ++++++++++++++++++++++++++++++ mkv-music/interrupt_test.go | 78 +++++ mkv-music/main.go | 35 +- mkv-music/plex.go | 37 +- mkv-music/plex_listing_test.go | 44 +-- mkv-music/plex_refresh_test.go | 6 +- mkv-music/processor.go | 120 +++++-- mkv-music/processor_test.go | 121 +++---- mkv-music/prompt.go | 76 ++++- mkv-music/prompt_test.go | 107 ++++++ mkv-music/tag_outcome_test.go | 12 +- mkv-music/tags.go | 48 ++- mkv-music/tags_mka.go | 41 ++- mkv-music/tags_mka_test.go | 6 +- mkv-music/token_redaction_test.go | 12 +- 25 files changed, 1827 insertions(+), 220 deletions(-) create mode 100644 mkv-music/command.go create mode 100644 mkv-music/command_other.go create mode 100644 mkv-music/command_test.go create mode 100644 mkv-music/command_unix.go create mode 100644 mkv-music/command_unix_test.go create mode 100644 mkv-music/command_windows.go create mode 100644 mkv-music/command_windows_test.go create mode 100644 mkv-music/interrupt.go create mode 100644 mkv-music/interrupt_run_test.go create mode 100644 mkv-music/interrupt_test.go create mode 100644 mkv-music/prompt_test.go diff --git a/README.md b/README.md index 95f06a9..6bb881b 100644 --- a/README.md +++ b/README.md @@ -604,6 +604,8 @@ date header has no timestamps to sync; one already up to date isn't counted), and lists each one whose tag copy or timestamp sync failed, naming the step (`tags`, `date` when the header can't be read, `ctime`, `mtime`). +Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips the audio timestamp sync, lists any artists it hasn't asked Plex to refresh, prints the summary headed `INTERRUPTED` and exits 130. A video in progress is finished. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress, and that video's tags or timestamps are left as they were for the next run. `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. + ### Flags | Flag | Description | diff --git a/mkv-music/audio_timestamps.go b/mkv-music/audio_timestamps.go index 24775df..20d0323 100644 --- a/mkv-music/audio_timestamps.go +++ b/mkv-music/audio_timestamps.go @@ -1,9 +1,9 @@ package main import ( + "context" "fmt" "os" - "os/exec" "path/filepath" "strings" "time" @@ -27,11 +27,15 @@ type AudioTimestampStats struct { } // SetAudioTimestamps walks root, reads each audio file's embedded date tag and -// sets OS file timestamps. Files older than cutoffDate are skipped. -func SetAudioTimestamps(root string, cutoffDate time.Time, timer FileTimer, exiftoolPath string) AudioTimestampStats { +// sets OS file timestamps. Files older than cutoffDate are skipped. Once ctx +// is cancelled it starts no more files, and it returns ctx's error. +func SetAudioTimestamps(ctx context.Context, root string, cutoffDate time.Time, timer FileTimer, exiftoolPath string) (AudioTimestampStats, error) { var stats AudioTimestampStats - // The callback never returns an error, so neither does WalkDir. - _ = filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + // The callback returns only ctx's error. + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if ctx.Err() != nil { + return ctx.Err() + } if err != nil { fmt.Printf("[AUDIO] Skipping unreadable %s: %v\n", path, err) return nil @@ -50,7 +54,10 @@ func SetAudioTimestamps(root string, cutoffDate time.Time, timer FileTimer, exif return nil } } - dt, ok := readAudioFileDate(path, ext, exiftoolPath) + dt, ok, err := readAudioFileDate(ctx, path, ext, exiftoolPath) + if err != nil { // the kill stopped exiftool: no verdict on this file + return err + } if !ok { fmt.Printf("[AUDIO] No date tag: %s\n", filepath.Base(path)) stats.NoDate++ @@ -65,21 +72,22 @@ func SetAudioTimestamps(root string, cutoffDate time.Time, timer FileTimer, exif stats.Updated++ return nil }) - return stats + return stats, err } // readAudioFileDate returns the embedded date for an audio file. // Non-MKA formats are read via go-taglib (supports WMA, FLAC, MP3, M4A, DSF, etc.). -// MKA uses exiftool via stdin since TagLib doesn't support Matroska. -func readAudioFileDate(path, ext, exiftoolPath string) (time.Time, bool) { +// MKA uses exiftool via stdin since TagLib doesn't support Matroska. err is +// the kill context's error once that stopped exiftool. +func readAudioFileDate(ctx context.Context, path, ext, exiftoolPath string) (time.Time, bool, error) { if ext != ".mka" { tags, err := readAudioTags(path) if err == nil && tags.Date != "" { if dt, ok := parseAudioDate(tags.Date); ok { - return dt, true + return dt, true, nil } } - return time.Time{}, false + return time.Time{}, false, nil } for _, tagName := range []string{ "Matroska:DateTimeOriginal-en-US", @@ -89,23 +97,26 @@ func readAudioFileDate(path, ext, exiftoolPath string) (time.Time, bool) { "Date", "Year", } { - dt, ok := exiftoolReadTag(exiftoolPath, path, tagName) + dt, ok := exiftoolReadTag(ctx, exiftoolPath, path, tagName) + if err := killContext(ctx).Err(); err != nil { + return time.Time{}, false, err + } if ok { - return dt, true + return dt, true, nil } } - return time.Time{}, false + return time.Time{}, false, nil } // exiftoolReadTag runs exiftool on path for a single tag, piping the file via // stdin to avoid filename encoding issues on Windows. -func exiftoolReadTag(exiftoolPath, path, tagName string) (time.Time, bool) { +func exiftoolReadTag(ctx context.Context, exiftoolPath, path, tagName string) (time.Time, bool) { f, err := os.Open(path) if err != nil { return time.Time{}, false } defer f.Close() - cmd := exec.Command(exiftoolPath, "-s3", "-"+tagName, "-") + cmd := command(ctx, exiftoolPath, "-s3", "-"+tagName, "-") cmd.Stdin = f out, err := cmd.Output() if err != nil { diff --git a/mkv-music/command.go b/mkv-music/command.go new file mode 100644 index 0000000..ea86194 --- /dev/null +++ b/mkv-music/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-music/command_other.go b/mkv-music/command_other.go new file mode 100644 index 0000000..9a732d4 --- /dev/null +++ b/mkv-music/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-music/command_test.go b/mkv-music/command_test.go new file mode 100644 index 0000000..3bfa458 --- /dev/null +++ b/mkv-music/command_test.go @@ -0,0 +1,184 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "slices" + "strings" + "testing" + "time" +) + +const ( + // helperEnv names the helperModes entry a child started by these tests runs. + helperEnv = "MKVMUSIC_TEST_HELPER" + // readyEnv names a file the helper creates once ready, for a child whose + // stdout the test can't read. + readyEnv = "MKVMUSIC_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 says it is ready and ends. + "ready": ready, + // slow-edit is a tool that answers reads at once but takes a second over + // an mkvpropedit edit (--tags), saying ready as that starts. + "slow-edit": func() { + if slices.Contains(os.Args, "--tags") { + ready() + time.Sleep(time.Second) + } + }, +} + +// 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-music/command_unix.go b/mkv-music/command_unix.go new file mode 100644 index 0000000..7d26e27 --- /dev/null +++ b/mkv-music/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-music 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-music 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-music/command_unix_test.go b/mkv-music/command_unix_test.go new file mode 100644 index 0000000..55f7dc4 --- /dev/null +++ b/mkv-music/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-music. + 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 = "MKVMUSIC_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-music by SIGPIPE as usual (`mkv-music | head`) +// until Ctrl+C. After it, which in `mkv-music 2>&1 | tee log` ends tee too, the +// notice's and the summary's writes fail instead, so mkv-music 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-music/command_windows.go b/mkv-music/command_windows.go new file mode 100644 index 0000000..1d6b483 --- /dev/null +++ b/mkv-music/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-music 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-music/command_windows_test.go b/mkv-music/command_windows_test.go new file mode 100644 index 0000000..8ccebc6 --- /dev/null +++ b/mkv-music/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-music 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-music/interrupt.go b/mkv-music/interrupt.go new file mode 100644 index 0000000..013b2a3 --- /dev/null +++ b/mkv-music/interrupt.go @@ -0,0 +1,76 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "os/signal" + "slices" +) + +// 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, +// mkvextract or exiftool 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-music before its children were +// killed. From the first stop or quit, mkv-music 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, mkvextract or exiftool in progress (Ctrl+C again to quit at once)") +} diff --git a/mkv-music/interrupt_run_test.go b/mkv-music/interrupt_run_test.go new file mode 100644 index 0000000..a809f58 --- /dev/null +++ b/mkv-music/interrupt_run_test.go @@ -0,0 +1,539 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// artistDirs makes root// for each "artist/file" in names. +func artistDirs(t *testing.T, names ...string) string { + t.Helper() + root := t.TempDir() + for _, n := range names { + path := filepath.Join(root, filepath.FromSlash(n)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +// exists reports whether root/name exists. +func exists(t *testing.T, root, name string) bool { + t.Helper() + _, err := os.Stat(filepath.Join(root, filepath.FromSlash(name))) + return err == nil +} + +// stopAtPrompter answers each question from answers; at the one whose index +// is stopAt, the Ctrl+C lands just as it is answered. +type stopAtPrompter struct { + answers []string + stopAt int + stop func() + asked []string +} + +func (p *stopAtPrompter) Ask(q string) (string, error) { + i := len(p.asked) + p.asked = append(p.asked, q) + if i == p.stopAt { + p.stop() + } + if i < len(p.answers) { + return p.answers[i], nil + } + return "", nil +} + +// Two misnamed videos, one per artist, each offered a rename. +var misnamed = []string{"A/01 - Foo.flac", "A/01 - Fooo.mkv", "B/01 - Bar.flac", "B/01 - Barr.mkv"} + +// A Ctrl+C landing as the rename prompt is answered "r" renames nothing and +// asks nothing more. +func TestRun_InterruptAtRenamePromptRenamesNothing(t *testing.T) { + root := artistDirs(t, misnamed...) + ctx, stop := context.WithCancel(t.Context()) + defer stop() + prompter := &stopAtPrompter{answers: []string{"r", "r"}, stopAt: 0, stop: stop} + p := NewProcessor(root, "", prompter) + tagger := &fakeTagger{} + p.tagger = tagger + + var stats Stats + out := captureStdout(t, func() { stats, _, _ = p.Run(ctx) }) + if stats != (Stats{}) { + t.Errorf("stats = %+v, want none", stats) + } + if len(prompter.asked) != 1 { + t.Errorf("asked %d questions, want 1", len(prompter.asked)) + } + if !exists(t, root, "A/01 - Fooo.mkv") || !exists(t, root, "B/01 - Barr.mkv") { + t.Error("a video was renamed after the interrupt") + } + if len(tagger.calls) != 0 { + t.Errorf("tags copied after the interrupt: %v", tagger.calls) + } + if !strings.Contains(out, "[STOP] Interrupted; left unchanged.") { + t.Errorf("output missing the stop notice:\n%s", out) + } +} + +// Without the interrupt the same answers rename both, so the test above can +// tell an interrupt from a run that renames nothing anyway. +func TestRun_RenamePromptControl(t *testing.T) { + root := artistDirs(t, misnamed...) + prompter := &stopAtPrompter{answers: []string{"r", "r"}, stopAt: -1} + var stats Stats + captureStdout(t, func() { stats, _, _ = NewProcessor(root, "", prompter).Run(t.Context()) }) + if stats.Renamed != 2 || !exists(t, root, "A/01 - Foo - Foo-video.mkv") || !exists(t, root, "B/01 - Bar - Bar-video.mkv") { + t.Errorf("stats = %+v; want both renamed", stats) + } +} + +// A Ctrl+C landing as the pattern prompt is answered saves no pattern. +func TestRun_InterruptAtPatternPromptSavesNothing(t *testing.T) { + root := artistDirs(t, "A/01 - Foo.flac", "A/01 - Foo [HD].mkv") + ignoreFile := filepath.Join(t.TempDir(), "ignore.json") + ctx, stop := context.WithCancel(t.Context()) + defer stop() + prompter := &stopAtPrompter{answers: []string{"i", " [HD]"}, stopAt: 1, stop: stop} + p := NewProcessor(root, ignoreFile, prompter) + + out := captureStdout(t, func() { p.Run(ctx) }) + if _, err := os.Stat(ignoreFile); !errors.Is(err, os.ErrNotExist) { + t.Errorf("ignore file written after the interrupt: %v", err) + } + if len(p.ignoreData.FilePatterns) != 0 { + t.Errorf("patterns = %v, want none", p.ignoreData.FilePatterns) + } + if !strings.Contains(out, "[STOP] Interrupted; left unchanged.") { + t.Errorf("output missing the stop notice:\n%s", out) + } +} + +// An interrupt before the run starts nothing. +func TestRun_InterruptedBeforeStart(t *testing.T) { + root := artistDirs(t, misnamed...) + ctx, stop := context.WithCancel(t.Context()) + stop() + prompter := &stopAtPrompter{stopAt: -1} + captureStdout(t, func() { NewProcessor(root, "", prompter).Run(ctx) }) + if len(prompter.asked) != 0 { + t.Errorf("asked %v after the interrupt", prompter.asked) + } +} + +// stoppingTagger is a fakeTagger whose first copy is interrupted by the +// first Ctrl+C, which lets it finish. +type stoppingTagger struct { + fakeTagger + stop func() +} + +func (f *stoppingTagger) CopyTagsToMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) error { + f.stop() + return f.fakeTagger.CopyTagsToMKV(ctx, audioPath, mkvPath, titleSuffix) +} + +// The file in progress at the first Ctrl+C is finished, and no other started. +func TestRun_InterruptFinishesCurrentFile(t *testing.T) { + root := artistDirs(t, "A/01 - Foo.flac", "A/01 - Foo - Foo-video.mkv", "B/01 - Bar.flac", "B/01 - Bar - Bar-video.mkv") + ctx, stop := context.WithCancel(t.Context()) + defer stop() + tagger := &stoppingTagger{stop: stop} + p := NewProcessor(root, "", &stopAtPrompter{stopAt: -1}) + p.tagger = tagger + captureStdout(t, func() { p.Run(ctx) }) + if len(tagger.calls) != 1 || p.Tags().Copied != 1 { + t.Errorf("copies = %v, outcome %+v; want the first file's only", tagger.calls, p.Tags()) + } +} + +// killingTagger is a fakeTagger whose step named by at is stopped by the +// kill (the second Ctrl+C), returning the kill's error. +type killingTagger struct { + fakeTagger + at string // "match", "copy" or "date" + kill func() +} + +func (f *killingTagger) killed(step string) error { + if f.at != step { + return nil + } + f.kill() + return context.Canceled +} + +func (f *killingTagger) TagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) { + if err := f.killed("match"); err != nil { + return false, err + } + return f.fakeTagger.TagsMatchMKV(ctx, audioPath, mkvPath, titleSuffix) +} + +func (f *killingTagger) CopyTagsToMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) error { + if err := f.killed("copy"); err != nil { + return err + } + return f.fakeTagger.CopyTagsToMKV(ctx, audioPath, mkvPath, titleSuffix) +} + +func (f *killingTagger) MKVDate(ctx context.Context, mkvPath string) (time.Time, bool, error) { + if err := f.killed("date"); err != nil { + return time.Time{}, false, err + } + return f.fakeTagger.MKVDate(ctx, mkvPath) +} + +// A tagging step the kill stops is neither a failure nor a copy, and is +// reported as left unchanged; the next run redoes it. +func TestCopyTags_KilledIsNotAFailure(t *testing.T) { + for _, tc := range []struct{ at, notice string }{ + {"match", "[STOP] Interrupted; tags left unchanged"}, + {"copy", "[STOP] Interrupted; tags left unchanged"}, + {"date", "[STOP] Interrupted; timestamps left unchanged"}, + } { + t.Run(tc.at, func(t *testing.T) { + ctx, stop, kill := newInterruptContext() + defer kill() + stop() + dir := t.TempDir() + tagger := &killingTagger{at: tc.at, kill: kill} + tagger.date = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC) + p := NewProcessor(dir, "", nil) + p.tagger, p.timer = tagger, &fakeFileTimer{} + mkv := filepath.Join(dir, "01 - Foo - Foo-video.mkv") + out := captureStdout(t, func() { + p.copyTagsIfConfigured(ctx, mkv, "01 - Foo", "01 - Foo - Foo", "", dir, mkv, map[string]string{"01 - Foo": "01 - Foo.flac"}) + }) + if got := p.Tags(); got.Copied != 0 || len(got.Failed) != 0 { + t.Errorf("outcome = %+v, want neither copied nor failed", got) + } + if tc.at == "match" && len(tagger.calls) != 0 { + t.Errorf("copied after a killed check: %v", tagger.calls) + } + if !strings.Contains(out, tc.notice) { + t.Errorf("output missing %q:\n%s", tc.notice, out) + } + }) + } +} + +// fakePlex records the calls made to it. +type fakePlex struct { + calls []string + find func() // runs as FindArtistByTitle is called + onRefresh func() // runs as RefreshMetadata is called +} + +func (f *fakePlex) FindArtistByTitle(_ context.Context, title string) (string, error) { + f.calls = append(f.calls, "find "+title) + if f.find != nil { + f.find() + } + return title, nil +} + +func (f *fakePlex) RefreshMetadata(_ context.Context, key string) error { + f.calls = append(f.calls, "refresh "+key) + if f.onRefresh != nil { + f.onRefresh() + } + return nil +} + +func (f *fakePlex) AnalyzeMedia(_ context.Context, key string) error { + f.calls = append(f.calls, "analyze "+key) + return nil +} + +// An interrupt during the Plex refresh lists the artists left unrefreshed, +// the one in progress included, and sends nothing more. +func TestRefreshPlexArtists_Interrupted(t *testing.T) { + ctx, stop := context.WithCancel(t.Context()) + defer stop() + plex := &fakePlex{find: stop} + p := NewProcessor(t.TempDir(), "", nil) + p.plex = plex + for _, a := range []string{"C", "A", "B"} { + p.touchedArtists[a] = struct{}{} + } + out := captureStdout(t, func() { p.refreshPlexArtists(ctx) }) + if !slices.Equal(plex.calls, []string{"find A"}) { + t.Errorf("calls = %v, want only the first find", plex.calls) + } + want := " [Plex] Not refreshed (interrupted): \"A\"\n [Plex] Not refreshed (interrupted): \"B\"\n [Plex] Not refreshed (interrupted): \"C\"\n" + if out != want { + t.Errorf("output = %q, want %q", out, want) + } +} + +// Uninterrupted, every touched artist is refreshed and analysed. +func TestRefreshPlexArtists_All(t *testing.T) { + plex := &fakePlex{} + p := NewProcessor(t.TempDir(), "", nil) + p.plex = plex + p.touchedArtists["B"], p.touchedArtists["A"] = struct{}{}, struct{}{} + captureStdout(t, func() { p.refreshPlexArtists(t.Context()) }) + want := []string{"find A", "refresh A", "analyze A", "find B", "refresh B", "analyze B"} + if !slices.Equal(plex.calls, want) { + t.Errorf("calls = %v, want %v", plex.calls, want) + } +} + +// A Plex request takes ctx: once it is cancelled, nothing is sent. +func TestHTTPPlexClient_CancelledSendsNothing(t *testing.T) { + var reqs int + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reqs++ })) + defer srv.Close() + ctx, cancel := context.WithCancel(t.Context()) + cancel() + c := newHTTPPlexClient(srv.URL, "token") + if _, err := c.FindArtistByTitle(ctx, "A"); !errors.Is(err, context.Canceled) { + t.Errorf("find error = %v, want context.Canceled", err) + } + if err := c.RefreshMetadata(ctx, "1"); !errors.Is(err, context.Canceled) { + t.Errorf("refresh error = %v, want context.Canceled", err) + } + if reqs != 0 { + t.Errorf("%d requests sent after the interrupt", reqs) + } +} + +// waitReady waits for the helper to create readyFile. +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 { + 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") + } + } +} + +// helperTool makes every child run the test binary's helper mode, which +// creates the returned file once ready. +func helperTool(t *testing.T, mode string) (path, readyFile string) { + t.Helper() + readyFile = filepath.Join(t.TempDir(), "ready") + t.Setenv(helperEnv, mode) + t.Setenv(readyEnv, readyFile) + return os.Args[0], readyFile +} + +// mkvmerge's header read outlives the first Ctrl+C; the second kills it, and +// the read reports the kill, not the exit code 1 a killed Windows child gets. +func TestReadMKVHeaderDate_KilledIsTheInterrupt(t *testing.T) { + mkvmerge, readyFile := helperTool(t, "sleep") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + go func() { + _, _, err := readMKVHeaderDate(ctx, mkvmerge, "a.mkv") + result <- err + }() + waitReady(t, readyFile, result) + stop() + wantRunning(t, result) + kill() + if err := awaitErr(t, result); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } +} + +// After the kill, CopyTagsToMKV runs no mkvpropedit: tags read by a killed +// mkvextract would be incomplete. Without the kill, the same call runs it. +func TestCopyTagsToMKV_NoEditAfterKill(t *testing.T) { + for _, killed := range []bool{true, false} { + t.Run(map[bool]string{true: "killed", false: "control"}[killed], func(t *testing.T) { + tool, readyFile := helperTool(t, "ready") + tagger := &realMusicVideoTagger{mkvpropeditPath: tool, mkvextractPath: "", mkvmergePath: ""} + ctx, stop, kill := newInterruptContext() + defer kill() + if killed { + stop() + kill() + } + dir := t.TempDir() + err := tagger.CopyTagsToMKV(ctx, filepath.Join(dir, "a.mka"), filepath.Join(dir, "a.mkv"), "") + _, statErr := os.Stat(readyFile) + if ran := statErr == nil; ran == killed { + t.Errorf("mkvpropedit ran = %v (error %v)", ran, err) + } + if killed != errors.Is(err, context.Canceled) { + t.Errorf("error = %v", err) + } + }) + } +} + +// exiftool's read outlives the first Ctrl+C; the second kills it, and the +// audio pass stops without counting the file as having no date. +func TestSetAudioTimestamps_KilledIsTheInterrupt(t *testing.T) { + exiftool, readyFile := helperTool(t, "sleep") + root := artistDirs(t, "A/01 - Foo.mka") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + result := make(chan error, 1) + var stats AudioTimestampStats + go func() { + var err error + stats, err = SetAudioTimestamps(ctx, root, time.Time{}, &fakeFileTimer{}, exiftool) + result <- err + }() + waitReady(t, readyFile, result) + stop() + wantRunning(t, result) + kill() + if err := awaitErr(t, result); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } + if stats != (AudioTimestampStats{}) { + t.Errorf("stats = %+v, want none", stats) + } +} + +// An interrupted run's summary is headed INTERRUPTED, and it exits 130. +func TestFinish(t *testing.T) { + cancelled, cancel := context.WithCancel(t.Context()) + cancel() + for _, tc := range []struct { + ctx context.Context + code int + heading string + }{ + {t.Context(), 0, "--- Scan Complete ---"}, + {cancelled, 130, "--- INTERRUPTED ---"}, + } { + var code int + out := captureStdout(t, func() { code = finish(tc.ctx, Stats{}, []string{"x.mkv"}, nil, TagOutcome{}) }) + if code != tc.code || !strings.Contains(out, tc.heading) || !strings.Contains(out, "x.mkv") { + t.Errorf("exit %d, output %q; want %d under %q", code, out, tc.code, tc.heading) + } + } +} + +// After the kill, every read fails, which for an untagged audio file and MKV +// would look like a match: TagsMatchMKV reports the kill instead. +func TestTagsMatchMKV_KilledIsNoMatch(t *testing.T) { + ctx, stop, kill := newInterruptContext() + stop() + kill() + dir := t.TempDir() + tagger := &realMusicVideoTagger{mkvextractPath: "mkvextract", mkvmergePath: "mkvmerge"} + match, err := tagger.TagsMatchMKV(ctx, filepath.Join(dir, "a.mka"), filepath.Join(dir, "a.mkv"), "") + if match || !errors.Is(err, context.Canceled) { + t.Errorf("TagsMatchMKV = %v, %v; want false, context.Canceled", match, err) + } +} + +// An audio pass started after the interrupt reads no file. +func TestSetAudioTimestamps_InterruptedBeforeStart(t *testing.T) { + root := artistDirs(t, "A/01 - Foo.flac") + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var stats AudioTimestampStats + var err error + out := captureStdout(t, func() { stats, err = SetAudioTimestamps(ctx, root, time.Time{}, &fakeFileTimer{}, "") }) + if stats != (AudioTimestampStats{}) || !errors.Is(err, context.Canceled) || out != "" { + t.Errorf("stats %+v, err %v, output %q; want nothing done", stats, err, out) + } +} + +// An interrupt during an artist's refresh leaves the rest unrefreshed. +func TestRefreshPlexArtists_InterruptedAfterFind(t *testing.T) { + ctx, stop := context.WithCancel(t.Context()) + defer stop() + plex := &fakePlex{onRefresh: stop} + p := NewProcessor(t.TempDir(), "", nil) + p.plex = plex + p.touchedArtists["A"], p.touchedArtists["B"] = struct{}{}, struct{}{} + out := captureStdout(t, func() { p.refreshPlexArtists(ctx) }) + if !slices.Equal(plex.calls, []string{"find A", "refresh A", "analyze A"}) { + t.Errorf("calls = %v, want only A's", plex.calls) + } + if !strings.Contains(out, "Not refreshed (interrupted): \"B\"") || strings.Contains(out, "Not refreshed (interrupted): \"A\"") { + t.Errorf("output = %q, want only B listed", out) + } +} + +// Once the walk sees the interrupt it reads no further, so even an +// unreadable root goes unreported. +func TestRun_InterruptedBeforeStartWalksNothing(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + root := filepath.Join(t.TempDir(), "missing") + if out := captureStdout(t, func() { NewProcessor(root, "", nil).Run(ctx) }); out != "" { + t.Errorf("output = %q, want nothing", out) + } +} + +// mkvpropedit edits in place, so the kill lets it finish. +func TestCopyTagsToMKV_KillSparesTheEdit(t *testing.T) { + tool, readyFile := helperTool(t, "slow-edit") + tagger := &realMusicVideoTagger{mkvpropeditPath: tool, mkvextractPath: tool, mkvmergePath: tool} + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + dir := t.TempDir() + result := make(chan error, 1) + go func() { + result <- tagger.CopyTagsToMKV(ctx, filepath.Join(dir, "a.mka"), filepath.Join(dir, "a.mkv"), "") + }() + waitReady(t, readyFile, result) + stop() + kill() + wantRunning(t, result) + if err := awaitErr(t, result); err != nil { + t.Errorf("error = %v, want the edit to finish", err) + } +} + +// The kill reaches every read a tag check or copy makes: a read it missed +// would sleep for a minute. +func TestTagger_KillReachesEveryRead(t *testing.T) { + for _, name := range []string{"match", "copy"} { + t.Run(name, func(t *testing.T) { + tool, readyFile := helperTool(t, "sleep") + tagger := &realMusicVideoTagger{mkvpropeditPath: tool, mkvextractPath: tool, mkvmergePath: tool} + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + dir := t.TempDir() + audio, mkv := filepath.Join(dir, "a.mka"), filepath.Join(dir, "a.mkv") + result := make(chan error, 1) + go func() { + if name == "match" { + _, err := tagger.TagsMatchMKV(ctx, audio, mkv, "") + result <- err + } else { + result <- tagger.CopyTagsToMKV(ctx, audio, mkv, "") + } + }() + waitReady(t, readyFile, result) + stop() + kill() + if err := awaitErr(t, result); !errors.Is(err, context.Canceled) { + t.Errorf("error = %v, want context.Canceled", err) + } + }) + } +} diff --git a/mkv-music/interrupt_test.go b/mkv-music/interrupt_test.go new file mode 100644 index 0000000..f551ab6 --- /dev/null +++ b/mkv-music/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-music/main.go b/mkv-music/main.go index 7af6a4c..6d43e2e 100644 --- a/mkv-music/main.go +++ b/mkv-music/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "flag" "fmt" "os" @@ -63,7 +64,8 @@ func main() { plexURL := os.Getenv("PLEX_URL") plexToken := os.Getenv("PLEX_TOKEN") - prompter := newStdinPrompter() + ctx := interruptContext() + prompter := newPrompter(ctx, os.Stdin, os.Stdout) processor := NewProcessor(root, ignoreFile, prompter) processor.timer = &win32FileTimer{} if plexURL != "" && plexToken != "" { @@ -90,26 +92,39 @@ func main() { } fmt.Printf("--- Scanning and Matching in: %s ---\n\n", root) - stats, skippedVideos, unmatchedVideos := processor.Run() + stats, skippedVideos, unmatchedVideos := processor.Run(ctx) // Audio timestamp pass: set OS file timestamps from embedded date tags. exiftoolPath, exiftoolErr := exec.LookPath("exiftool") - if exiftoolErr != nil { + switch { + case ctx.Err() != nil: // interrupted: no next step + case exiftoolErr != nil: fmt.Fprintln(os.Stderr, "Warning: exiftool not found in PATH — audio timestamp sync disabled") - } else { + default: fmt.Printf("\n--- Syncing audio file timestamps in: %s ---\n\n", root) - aStats := SetAudioTimestamps(root, cutoff, &win32FileTimer{}, exiftoolPath) + aStats, _ := SetAudioTimestamps(ctx, root, cutoff, &win32FileTimer{}, exiftoolPath) fmt.Printf("\nAudio timestamps: %d updated, %d no date, %d failed, %d skipped (old)\n", aStats.Updated, aStats.NoDate, aStats.Failed, aStats.SkippedOld) } - printRunSummary(stats, skippedVideos, unmatchedVideos, processor.Tags()) + os.Exit(finish(ctx, stats, skippedVideos, unmatchedVideos, processor.Tags())) +} + +// finish prints the run summary and returns the exit code: 130, under an +// INTERRUPTED heading, once ctx is cancelled. +func finish(ctx context.Context, stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) int { + if ctx.Err() != nil { + printRunSummary("INTERRUPTED", stats, skippedVideos, unmatchedVideos, tags) + return 130 + } + printRunSummary("Scan Complete", stats, skippedVideos, unmatchedVideos, tags) + return 0 } -// printRunSummary prints the end-of-run report: unmatched and skipped videos, -// old files skipped, and the tagging outcome. -func printRunSummary(stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) { - fmt.Println("\n--- Scan Complete ---") +// printRunSummary prints the end-of-run report under heading: unmatched and +// skipped videos, old files skipped, and the tagging outcome. +func printRunSummary(heading string, stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) { + fmt.Printf("\n--- %s ---\n", heading) if len(unmatchedVideos) > 0 { fmt.Printf("\n--- UNMATCHED MUSIC VIDEOS (%d) ---\n", len(unmatchedVideos)) for _, path := range unmatchedVideos { diff --git a/mkv-music/plex.go b/mkv-music/plex.go index e35b418..23bd480 100644 --- a/mkv-music/plex.go +++ b/mkv-music/plex.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -23,15 +24,15 @@ type PlexClient interface { // FindArtistByTitle searches all "artist" (music) library sections for an // item whose normalised title matches title. Returns the ratingKey on // success, or ErrArtistNotFound if no match exists. - FindArtistByTitle(title string) (string, error) + FindArtistByTitle(ctx context.Context, title string) (string, error) // RefreshMetadata triggers a metadata refresh for the item identified by // ratingKey, causing Plex to re-read embedded metadata from the files. - RefreshMetadata(ratingKey string) error + RefreshMetadata(ctx context.Context, ratingKey string) error // AnalyzeMedia triggers a media analysis for the item and all its children, // causing Plex to re-read codec, resolution, and other stream properties. // This is needed when a file's codec changes (e.g. AV1 → HEVC) so Plex // stops transcoding using the old codec profile. - AnalyzeMedia(ratingKey string) error + AnalyzeMedia(ctx context.Context, ratingKey string) error } // httpPlexClient is the production PlexClient that communicates with a real @@ -85,9 +86,9 @@ func newHTTPPlexClient(baseURL, token string) *httpPlexClient { // plexGet performs a GET request to path (relative to baseURL) with an // Accept: application/json header. The Plex token goes in a header, not the // URL, so transport errors (which print the URL) can't leak it. -func (c *httpPlexClient) plexGet(path string) (*http.Response, error) { +func (c *httpPlexClient) plexGet(ctx context.Context, path string) (*http.Response, error) { u := c.baseURL + path - req, err := http.NewRequest(http.MethodGet, u, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return nil, err } @@ -104,12 +105,12 @@ func (c *httpPlexClient) plexGet(path string) (*http.Response, error) { // It searches the section listings fetched earlier in this run, then fresh // listings, as Plex may have added the artist since; a cached match in any // section wins over a copy newly added to another. -func (c *httpPlexClient) FindArtistByTitle(title string) (string, error) { +func (c *httpPlexClient) FindArtistByTitle(ctx context.Context, title string) (string, error) { matches := titleMatcher(title) if matches == nil { return "", ErrArtistNotFound } - sections, err := c.artistSectionKeys() + sections, err := c.artistSectionKeys(ctx) if err != nil { return "", err } @@ -119,7 +120,7 @@ func (c *httpPlexClient) FindArtistByTitle(title string) (string, error) { if fresh && fetched[section] { continue } - items, wasFetched, err := c.sectionListing(section, fresh) + items, wasFetched, err := c.sectionListing(ctx, section, fresh) if err != nil { return "", err } @@ -135,8 +136,8 @@ func (c *httpPlexClient) FindArtistByTitle(title string) (string, error) { } // artistSectionKeys returns the keys of Plex's music library sections. -func (c *httpPlexClient) artistSectionKeys() ([]string, error) { - resp, err := c.plexGet("/library/sections") +func (c *httpPlexClient) artistSectionKeys(ctx context.Context) ([]string, error) { + resp, err := c.plexGet(ctx, "/library/sections") if err != nil { return nil, fmt.Errorf("plex: list sections: %w", err) } @@ -165,11 +166,11 @@ func (c *httpPlexClient) artistSectionKeys() ([]string, error) { // sectionListing returns the artists in a Plex section: the listing fetched // earlier in this run, unless fresh or there is none. fetched reports a // request. -func (c *httpPlexClient) sectionListing(sectionKey string, fresh bool) (items []plexArtistItem, fetched bool, err error) { +func (c *httpPlexClient) sectionListing(ctx context.Context, sectionKey string, fresh bool) (items []plexArtistItem, fetched bool, err error) { if items, ok := c.sectionItems[sectionKey]; ok && !fresh { return items, false, nil } - resp, err := c.plexGet("/library/sections/" + sectionKey + "/all?type=8") + resp, err := c.plexGet(ctx, "/library/sections/"+sectionKey+"/all?type=8") if err != nil { return nil, false, fmt.Errorf("plex: list section %s: %w", sectionKey, err) } @@ -189,9 +190,9 @@ func (c *httpPlexClient) sectionListing(sectionKey string, fresh bool) (items [] // plexPut performs a PUT request to path (relative to baseURL), sending the // Plex token in a header. -func (c *httpPlexClient) plexPut(path string) (*http.Response, error) { +func (c *httpPlexClient) plexPut(ctx context.Context, path string) (*http.Response, error) { u := c.baseURL + path - req, err := http.NewRequest(http.MethodPut, u, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, u, nil) if err != nil { return nil, err } @@ -218,8 +219,8 @@ func doPlexRequest(client *http.Client, req *http.Request, path string) (*http.R // RefreshMetadata implements PlexClient. It sends a PUT, the only method the // Plex API defines for the item refresh endpoint. -func (c *httpPlexClient) RefreshMetadata(ratingKey string) error { - resp, err := c.plexPut("/library/metadata/" + ratingKey + "/refresh") +func (c *httpPlexClient) RefreshMetadata(ctx context.Context, ratingKey string) error { + resp, err := c.plexPut(ctx, "/library/metadata/"+ratingKey+"/refresh") if err != nil { return fmt.Errorf("plex: refresh metadata %s: %w", ratingKey, err) } @@ -230,8 +231,8 @@ func (c *httpPlexClient) RefreshMetadata(ratingKey string) error { // AnalyzeMedia implements PlexClient. It sends a PUT to the analyze endpoint, // causing Plex to re-read codec and stream properties for the item and all // its children (albums and tracks under an artist). -func (c *httpPlexClient) AnalyzeMedia(ratingKey string) error { - resp, err := c.plexPut("/library/metadata/" + ratingKey + "/analyze") +func (c *httpPlexClient) AnalyzeMedia(ctx context.Context, ratingKey string) error { + resp, err := c.plexPut(ctx, "/library/metadata/"+ratingKey+"/analyze") if err != nil { return fmt.Errorf("plex: analyze media %s: %w", ratingKey, err) } diff --git a/mkv-music/plex_listing_test.go b/mkv-music/plex_listing_test.go index 085f854..b5e555e 100644 --- a/mkv-music/plex_listing_test.go +++ b/mkv-music/plex_listing_test.go @@ -75,9 +75,9 @@ func TestHTTPPlexClient_FindArtistByTitle_ReusesSectionListing(t *testing.T) { f, c := newFakeArtistServer(t, map[string][]string{"1": {"Alpha", "Beta"}, "2": {"Gamma"}}) for title, want := range map[string]string{"Gamma": "20", "alpha": "10", "Beta": "11"} { - got, err := c.FindArtistByTitle(title) + got, err := c.FindArtistByTitle(t.Context(), title) if err != nil || got != want { - t.Errorf("FindArtistByTitle(%q) = %q, %v; want %q", title, got, err, want) + t.Errorf("FindArtistByTitle(t.Context(), %q) = %q, %v; want %q", title, got, err, want) } } wantListings(t, f, "after three hits", map[string]int{"1": 1, "2": 1}) @@ -88,11 +88,11 @@ func TestHTTPPlexClient_FindArtistByTitle_ReusesSectionListing(t *testing.T) { func TestHTTPPlexClient_FindArtistByTitle_MissListsEachSectionOnce(t *testing.T) { f, c := newFakeArtistServer(t, map[string][]string{"1": {"Alpha"}, "2": {"Gamma"}}) - if _, err := c.FindArtistByTitle("Nobody"); !errors.Is(err, ErrArtistNotFound) { + if _, err := c.FindArtistByTitle(t.Context(), "Nobody"); !errors.Is(err, ErrArtistNotFound) { t.Fatalf("err = %v; want ErrArtistNotFound", err) } wantListings(t, f, "first miss", map[string]int{"1": 1, "2": 1}) - if _, err := c.FindArtistByTitle("Nobody"); !errors.Is(err, ErrArtistNotFound) { + if _, err := c.FindArtistByTitle(t.Context(), "Nobody"); !errors.Is(err, ErrArtistNotFound) { t.Fatalf("err = %v; want ErrArtistNotFound", err) } wantListings(t, f, "second miss", map[string]int{"1": 2, "2": 2}) @@ -102,14 +102,14 @@ func TestHTTPPlexClient_FindArtistByTitle_MissListsEachSectionOnce(t *testing.T) // pass, which caches the new listing for later lookups. func TestHTTPPlexClient_FindArtistByTitle_FreshPassFindsAddedArtist(t *testing.T) { f, c := newFakeArtistServer(t, map[string][]string{"1": {"Alpha"}, "2": {"Gamma"}}) - if _, err := c.FindArtistByTitle("Gamma"); err != nil { // lists both sections - t.Fatalf("FindArtistByTitle(Gamma): %v", err) + if _, err := c.FindArtistByTitle(t.Context(), "Gamma"); err != nil { // lists both sections + t.Fatalf("FindArtistByTitle(t.Context(), Gamma): %v", err) } f.set(func() { f.artists["2"] = append(f.artists["2"], "Delta") }) for range 2 { - if got, err := c.FindArtistByTitle("Delta"); err != nil || got != "21" { - t.Errorf("FindArtistByTitle(Delta) = %q, %v; want 21", got, err) + if got, err := c.FindArtistByTitle(t.Context(), "Delta"); err != nil || got != "21" { + t.Errorf("FindArtistByTitle(t.Context(), Delta) = %q, %v; want 21", got, err) } } wantListings(t, f, "after the fresh hit and a repeat", map[string]int{"1": 2, "2": 2}) @@ -118,13 +118,13 @@ func TestHTTPPlexClient_FindArtistByTitle_FreshPassFindsAddedArtist(t *testing.T // A cached match wins over a copy Plex added to another section since. func TestHTTPPlexClient_FindArtistByTitle_CachedMatchWins(t *testing.T) { f, c := newFakeArtistServer(t, map[string][]string{"2": {"Alpha"}}) - if _, err := c.FindArtistByTitle("Alpha"); err != nil { // lists both sections - t.Fatalf("FindArtistByTitle(Alpha): %v", err) + if _, err := c.FindArtistByTitle(t.Context(), "Alpha"); err != nil { // lists both sections + t.Fatalf("FindArtistByTitle(t.Context(), Alpha): %v", err) } f.set(func() { f.artists["1"] = []string{"Alpha"} }) - if got, err := c.FindArtistByTitle("Alpha"); err != nil || got != "20" { - t.Errorf("FindArtistByTitle(Alpha) = %q, %v; want the cached 20", got, err) + if got, err := c.FindArtistByTitle(t.Context(), "Alpha"); err != nil || got != "20" { + t.Errorf("FindArtistByTitle(t.Context(), Alpha) = %q, %v; want the cached 20", got, err) } wantListings(t, f, "after the cached hit", map[string]int{"1": 1, "2": 1}) } @@ -134,7 +134,7 @@ func TestHTTPPlexClient_FindArtistByTitle_ListingError(t *testing.T) { f, c := newFakeArtistServer(t, nil) f.listErr = true - _, err := c.FindArtistByTitle("Alpha") + _, err := c.FindArtistByTitle(t.Context(), "Alpha") if err == nil || errors.Is(err, ErrArtistNotFound) || !strings.Contains(err.Error(), "list section 1") { t.Errorf("err = %v; want the section 1 listing error", err) } @@ -144,17 +144,17 @@ func TestHTTPPlexClient_FindArtistByTitle_ListingError(t *testing.T) { // serves later hits. func TestHTTPPlexClient_FindArtistByTitle_FreshPassListingError(t *testing.T) { f, c := newFakeArtistServer(t, map[string][]string{"1": {"Alpha"}}) - if _, err := c.FindArtistByTitle("Alpha"); err != nil { - t.Fatalf("FindArtistByTitle(Alpha): %v", err) + if _, err := c.FindArtistByTitle(t.Context(), "Alpha"); err != nil { + t.Fatalf("FindArtistByTitle(t.Context(), Alpha): %v", err) } f.set(func() { f.listErr = true }) - _, err := c.FindArtistByTitle("Nobody") + _, err := c.FindArtistByTitle(t.Context(), "Nobody") if err == nil || errors.Is(err, ErrArtistNotFound) || !strings.Contains(err.Error(), "list section") { t.Errorf("miss: err = %v; want a section listing error", err) } - if got, err := c.FindArtistByTitle("Alpha"); err != nil || got != "10" { - t.Errorf("FindArtistByTitle(Alpha) after the error = %q, %v; want the cached 10", got, err) + if got, err := c.FindArtistByTitle(t.Context(), "Alpha"); err != nil || got != "10" { + t.Errorf("FindArtistByTitle(t.Context(), Alpha) after the error = %q, %v; want the cached 10", got, err) } } @@ -164,13 +164,13 @@ func TestHTTPPlexClient_FindArtistByTitle_NonASCIITitle(t *testing.T) { _, c := newFakeArtistServer(t, map[string][]string{"1": {"椎名林檎", "宇多田ヒカル", "ÉÈ"}}) for title, want := range map[string]string{"宇多田ヒカル": "11", "éè": "12"} { - if got, err := c.FindArtistByTitle(title); err != nil || got != want { - t.Errorf("FindArtistByTitle(%q) = %q, %v; want %s", title, got, err, want) + if got, err := c.FindArtistByTitle(t.Context(), title); err != nil || got != want { + t.Errorf("FindArtistByTitle(t.Context(), %q) = %q, %v; want %s", title, got, err, want) } } for _, title := range []string{"浜崎あゆみ", " "} { - if got, err := c.FindArtistByTitle(title); !errors.Is(err, ErrArtistNotFound) { - t.Errorf("FindArtistByTitle(%q) = %q, %v; want ErrArtistNotFound", title, got, err) + if got, err := c.FindArtistByTitle(t.Context(), title); !errors.Is(err, ErrArtistNotFound) { + t.Errorf("FindArtistByTitle(t.Context(), %q) = %q, %v; want ErrArtistNotFound", title, got, err) } } } diff --git a/mkv-music/plex_refresh_test.go b/mkv-music/plex_refresh_test.go index 19a2b8e..46db48b 100644 --- a/mkv-music/plex_refresh_test.go +++ b/mkv-music/plex_refresh_test.go @@ -15,7 +15,7 @@ func TestHTTPPlexClient_RefreshMetadata_PutsCorrectPath(t *testing.T) { })) defer srv.Close() - if err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata("42"); err != nil { + if err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata(t.Context(), "42"); err != nil { t.Fatalf("unexpected error: %v", err) } if gotMethod != http.MethodPut { @@ -30,7 +30,7 @@ func TestHTTPPlexClient_RefreshMetadata_Non2xxIsError(t *testing.T) { srv := httptest.NewServer(http.NotFoundHandler()) defer srv.Close() - err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata("42") + err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata(t.Context(), "42") if err == nil || !strings.Contains(err.Error(), "PUT") || !strings.Contains(err.Error(), "404") { t.Errorf("err = %v; want a PUT 404 error", err) } @@ -57,7 +57,7 @@ func TestHTTPPlexClient_RefreshMetadata_Redirects(t *testing.T) { } w.WriteHeader(http.StatusOK) })) - err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata("42") + err := newHTTPPlexClient(srv.URL, "token").RefreshMetadata(t.Context(), "42") srv.Close() if tc.wantErr { if err == nil || !strings.Contains(err.Error(), "refusing a redirect that would send PUT as GET") { diff --git a/mkv-music/processor.go b/mkv-music/processor.go index 7b09c50..8dd4109 100644 --- a/mkv-music/processor.go +++ b/mkv-music/processor.go @@ -2,10 +2,12 @@ package main import ( "cmp" + "context" "encoding/json" "errors" "fmt" "io/fs" + "maps" "os" "path/filepath" "slices" @@ -92,13 +94,24 @@ func (p *Processor) markArtistTouched(dir string) { } // refreshPlexArtists triggers a Plex metadata refresh for every artist dir -// that was touched during this run. No-op when Plex is not configured. -func (p *Processor) refreshPlexArtists() { +// that was touched during this run. No-op when Plex is not configured. Once +// ctx is cancelled it lists the artists left unrefreshed instead. +func (p *Processor) refreshPlexArtists(ctx context.Context) { if p.plex == nil || len(p.touchedArtists) == 0 { return } - for artist := range p.touchedArtists { - ratingKey, err := p.plex.FindArtistByTitle(artist) + artists := slices.Sorted(maps.Keys(p.touchedArtists)) + for i, artist := range artists { + ratingKey, err := "", ctx.Err() + if err == nil { + ratingKey, err = p.plex.FindArtistByTitle(ctx, artist) + } + if ctx.Err() != nil { + for _, a := range artists[i:] { + fmt.Printf(" [Plex] Not refreshed (interrupted): %q\n", a) + } + return + } if err != nil { if errors.Is(err, ErrArtistNotFound) { fmt.Printf(" [Plex] Artist not found in library: %q\n", artist) @@ -107,12 +120,12 @@ func (p *Processor) refreshPlexArtists() { } continue } - if err := p.plex.RefreshMetadata(ratingKey); err != nil { + if err := p.plex.RefreshMetadata(ctx, ratingKey); err != nil { fmt.Printf(" [Plex] Refresh failed for %q: %v\n", artist, err) } else { fmt.Printf(" [Plex] Refreshed artist: %q\n", artist) } - if err := p.plex.AnalyzeMedia(ratingKey); err != nil { + if err := p.plex.AnalyzeMedia(ctx, ratingKey); err != nil { fmt.Printf(" [Plex] Analyze failed for %q: %v\n", artist, err) } else { fmt.Printf(" [Plex] Media analysis triggered for %q\n", artist) @@ -580,7 +593,7 @@ func dropContained(ts []string) []string { // stripping; postSuffix is extra title text (" (Second Version)" after the // suffix, or kept "(Special Music Video)"). Both build the MKV title suffix. // Other video formats are skipped: mkvpropedit only edits MKVs. -func (p *Processor) copyTagsIfConfigured(mkvPath, matchKey, cleanVideo, postSuffix, videoDir, videoPath string, audioPaths map[string]string) { +func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, cleanVideo, postSuffix, videoDir, videoPath string, audioPaths map[string]string) { if p.tagger == nil || audioPaths == nil || !strings.EqualFold(filepath.Ext(mkvPath), ".mkv") { return } @@ -605,25 +618,41 @@ func (p *Processor) copyTagsIfConfigured(mkvPath, matchKey, cleanVideo, postSuff parts = append(parts, t) } titleSuffix := strings.Join(parts, " ") - if match, err := p.tagger.TagsMatchMKV(audioFullPath, mkvPath, titleSuffix); err == nil && match { + match, err := p.tagger.TagsMatchMKV(ctx, audioFullPath, mkvPath, titleSuffix) + if err != nil && killContext(ctx).Err() != nil { + tagsStopped(mkvPath) + return + } + if err == nil && match { fmt.Printf(" [TAG] Already up to date: %s\n", filepath.Base(mkvPath)) - p.recordTagFailure(mkvPath, p.syncTimestamps(mkvPath)) + failed, _ := p.syncTimestamps(ctx, mkvPath) + p.recordTagFailure(mkvPath, failed) return } - if err := p.tagger.CopyTagsToMKV(audioFullPath, mkvPath, titleSuffix); err != nil { + if err := p.tagger.CopyTagsToMKV(ctx, audioFullPath, mkvPath, titleSuffix); err != nil { + if killContext(ctx).Err() != nil { + tagsStopped(mkvPath) + return + } fmt.Printf(" [ERROR] tag copy failed for %s: %v\n", filepath.Base(mkvPath), err) p.recordTagFailure(mkvPath, []string{"tags"}) return } fmt.Printf(" [TAG] Copied tags from %s\n", audioFilename) p.markArtistTouched(videoDir) - if failed := p.syncTimestamps(mkvPath); len(failed) > 0 { + if failed, stopped := p.syncTimestamps(ctx, mkvPath); len(failed) > 0 { p.recordTagFailure(mkvPath, failed) - } else { + } else if !stopped { p.tags.Copied++ } } +// tagsStopped reports that the kill stopped reading mkvPath's tags, so they +// were left as they were; the next run copies them. +func tagsStopped(mkvPath string) { + fmt.Printf(" [STOP] Interrupted; tags left unchanged: %s\n", filepath.Base(mkvPath)) +} + // recordTagFailure adds mkvPath to the run's tagging failures, naming the // failed steps. No-op when failed is empty. func (p *Processor) recordTagFailure(mkvPath string, failed []string) { @@ -635,18 +664,23 @@ func (p *Processor) recordTagFailure(mkvPath string, failed []string) { // syncTimestamps sets mkvPath's modified and created timestamps to match the // date stored in the MKV container header, and returns the steps that failed // ("date" when the header can't be read, "ctime", "mtime"). No-op if timer or -// tagger is nil, or if the MKV has no date header. -func (p *Processor) syncTimestamps(mkvPath string) (failed []string) { +// tagger is nil, or if the MKV has no date header. stopped reports that the +// kill stopped the header read, leaving the timestamps as they were. +func (p *Processor) syncTimestamps(ctx context.Context, mkvPath string) (failed []string, stopped bool) { if p.timer == nil || p.tagger == nil { - return nil + return nil, false + } + dt, ok, err := p.tagger.MKVDate(ctx, mkvPath) + if err != nil && killContext(ctx).Err() != nil { + fmt.Printf(" [STOP] Interrupted; timestamps left unchanged: %s\n", filepath.Base(mkvPath)) + return nil, true } - dt, ok, err := p.tagger.MKVDate(mkvPath) if err != nil { fmt.Printf(" [ERROR] read date failed for %s: %v\n", filepath.Base(mkvPath), err) - return []string{"date"} + return []string{"date"}, false } if !ok { - return nil + return nil, false } dt = dt.Local() if p.timer.CreationTimeNeedsUpdate(mkvPath, dt.Unix()) { @@ -659,7 +693,7 @@ func (p *Processor) syncTimestamps(mkvPath string) (failed []string) { fmt.Printf(" [ERROR] set mtime failed for %s: %v\n", filepath.Base(mkvPath), err) failed = append(failed, "mtime") } - return failed + return failed, false } // videoPlan is what processVideo decides for one video filename. @@ -757,8 +791,9 @@ func (p *Processor) planVideo(videoDir, videoFile string, audioData map[string]s // processVideo handles one video file: matches it to audio data, prints a // mismatch if needed, and interactively renames/ignores/skips. -// Returns "renamed", "skipped", or "" (no action / no match). -func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPaths map[string]string) string { +// Returns "renamed", "skipped", "unmatched", "stopped" (interrupted at a +// prompt) or "" (no action). +func (p *Processor) processVideo(ctx context.Context, videoDir, videoFile string, audioData, audioPaths map[string]string) string { videoPath := filepath.Join(videoDir, videoFile) ext := filepath.Ext(videoFile) plan, ok := p.planVideo(videoDir, videoFile, audioData) @@ -771,7 +806,7 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat fullPath := videoPath if plan.correct { // Filename is already correct — just copy tags. - p.copyTagsIfConfigured(fullPath, matchKey, cleanVideo, tagPost, videoDir, videoPath, audioPaths) + p.copyTagsIfConfigured(ctx, fullPath, matchKey, cleanVideo, tagPost, videoDir, videoPath, audioPaths) return "" } @@ -781,6 +816,9 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat fmt.Printf(" Expected: %s\n", matchedBase) choice, err := p.prompter.Ask(" (r)ename, (i)gnore pattern, (s)kip: ") + if ctx.Err() != nil { // the Ctrl+C may land just after an answer + return promptStopped() + } if err != nil { return "" } @@ -806,9 +844,9 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat p.moveFilePatterns(videoPath, newPath) // Tag from the new name, as the next run will, so the tag settles now. if next, ok := p.planVideo(videoDir, targetName+ext, audioData); ok && next.correct { - p.copyTagsIfConfigured(newPath, next.matchKey, next.cleanVideo, next.tagPost, videoDir, newPath, audioPaths) + p.copyTagsIfConfigured(ctx, newPath, next.matchKey, next.cleanVideo, next.tagPost, videoDir, newPath, audioPaths) } else { - p.copyTagsIfConfigured(newPath, matchKey, cleanVideo, tagPost, videoDir, newPath, audioPaths) // the patterns moved there + p.copyTagsIfConfigured(ctx, newPath, matchKey, cleanVideo, tagPost, videoDir, newPath, audioPaths) // the patterns moved there } return "renamed" } @@ -818,6 +856,9 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat diff = strings.TrimSpace(plan.postSuffixIgnored) } pattern, err := p.prompter.Ask(fmt.Sprintf(" Enter the part to ignore (default: '%s'): ", diff)) + if ctx.Err() != nil { + return promptStopped() + } if err != nil { return "" } @@ -837,7 +878,7 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat // Re-plan as the next run will, since the target may now keep this text. if next, ok := p.planVideo(videoDir, videoFile, audioData); ok && next.correct { fmt.Println(" [OK] File now matches after ignoring pattern!") - p.copyTagsIfConfigured(fullPath, next.matchKey, next.cleanVideo, next.tagPost, videoDir, videoPath, audioPaths) + p.copyTagsIfConfigured(ctx, fullPath, next.matchKey, next.cleanVideo, next.tagPost, videoDir, videoPath, audioPaths) } else { fmt.Println(" Still doesn't match after ignoring") } @@ -849,16 +890,27 @@ func (p *Processor) processVideo(videoDir, videoFile string, audioData, audioPat return "" } +// promptStopped reports an interrupt at a prompt, whose answer is ignored. +func promptStopped() string { + fmt.Println(" [STOP] Interrupted; left unchanged.") + return "stopped" +} + // Run walks root, groups files by directory, and processes each video file. -func (p *Processor) Run() (Stats, []string, []string) { +// Once ctx is cancelled it starts no more files, and skips any it hadn't +// started when the walk was cut short. +func (p *Processor) Run(ctx context.Context) (Stats, []string, []string) { var stats Stats var skippedVideos []string var unmatchedVideos []string dirOrder := []string{} dirFiles := map[string][]string{} - // The callback never returns an error, so neither does WalkDir. - _ = filepath.WalkDir(p.root, func(path string, d fs.DirEntry, err error) error { + // The callback returns only ctx's error, which leaves nothing to process. + if filepath.WalkDir(p.root, func(path string, d fs.DirEntry, err error) error { + if ctx.Err() != nil { + return ctx.Err() + } if err != nil { fmt.Printf("[WARN] Skipping unreadable %s: %v\n", path, err) return nil @@ -872,8 +924,11 @@ func (p *Processor) Run() (Stats, []string, []string) { } dirFiles[dir] = append(dirFiles[dir], d.Name()) return nil - }) + }) != nil { + return stats, nil, nil + } +scan: for _, dir := range dirOrder { files := dirFiles[dir] audioData := buildAudioData(files) @@ -883,6 +938,9 @@ func (p *Processor) Run() (Stats, []string, []string) { return cmp.Compare(p.videoRank(dir, a), p.videoRank(dir, b)) }) for _, f := range files { + if ctx.Err() != nil { + break scan + } ext := strings.ToLower(filepath.Ext(f)) if !containsStr(videoExts, ext) { continue @@ -894,7 +952,7 @@ func (p *Processor) Run() (Stats, []string, []string) { continue } } - result := p.processVideo(dir, f, audioData, audioPaths) + result := p.processVideo(ctx, dir, f, audioData, audioPaths) switch result { case "renamed": stats.Renamed++ @@ -907,7 +965,7 @@ func (p *Processor) Run() (Stats, []string, []string) { } } } - p.refreshPlexArtists() + p.refreshPlexArtists(ctx) return stats, skippedVideos, unmatchedVideos } diff --git a/mkv-music/processor_test.go b/mkv-music/processor_test.go index e570209..90e7ad0 100644 --- a/mkv-music/processor_test.go +++ b/mkv-music/processor_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "fmt" "io" @@ -42,16 +43,16 @@ type taggerCall struct { titleSuffix string } -func (f *fakeTagger) TagsMatchMKV(audioPath, mkvPath, titleSuffix string) (bool, error) { +func (f *fakeTagger) TagsMatchMKV(_ context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) { return f.tagsMatch, nil } -func (f *fakeTagger) CopyTagsToMKV(audioPath, mkvPath, titleSuffix string) error { +func (f *fakeTagger) CopyTagsToMKV(_ context.Context, audioPath, mkvPath, titleSuffix string) error { f.calls = append(f.calls, taggerCall{audioPath, mkvPath, titleSuffix}) return f.err } -func (f *fakeTagger) MKVDate(mkvPath string) (time.Time, bool, error) { +func (f *fakeTagger) MKVDate(_ context.Context, mkvPath string) (time.Time, bool, error) { if f.dateErr != nil { return time.Time{}, false, f.dateErr } @@ -143,7 +144,7 @@ func TestRun_SuffixKeywordInTitleStaysRenamed(t *testing.T) { dir := musicDir(t, "01 - Long-lived.flac", "01 - Old - Old-video (Second Version).mkv") assertTagsStable(t, dir, nil, "r") assertFiles(t, dir, "01 - Long-lived - Long-lived-video.mkv") - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(); stats != (Stats{}) { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(t.Context()); stats != (Stats{}) { t.Errorf("third run stats = %+v, want none", stats) } } @@ -153,7 +154,7 @@ func TestRun_SuffixKeywordInTitleStaysRenamed(t *testing.T) { func TestProcessVideo_NoAudioData_Unmatched(t *testing.T) { dir := t.TempDir() p := NewProcessor(dir, "", &fakePrompter{}) - result := p.processVideo(dir, "Unknown - Song-video.mkv", map[string]string{}, nil) + result := p.processVideo(t.Context(), dir, "Unknown - Song-video.mkv", map[string]string{}, nil) if result != "unmatched" { t.Errorf("got %q, want 'unmatched'", result) } @@ -164,7 +165,7 @@ func TestProcessVideo_AlreadyCorrect_NoAction(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{}) audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} // Video is already named correctly. - result := p.processVideo(dir, "Artist - Song - Song-video.mkv", audioData, nil) + result := p.processVideo(t.Context(), dir, "Artist - Song - Song-video.mkv", audioData, nil) if result != "" { t.Errorf("got %q, want empty (already correct)", result) } @@ -179,7 +180,7 @@ func TestProcessVideo_RenameChosen_RenamesFile(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}) audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} - result := p.processVideo(dir, "Artist - Song-video.mkv", audioData, nil) + result := p.processVideo(t.Context(), dir, "Artist - Song-video.mkv", audioData, nil) if result != "renamed" { t.Errorf("got %q, want 'renamed'", result) } @@ -193,7 +194,7 @@ func TestProcessVideo_SkipChosen_ReturnsSkipped(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{answers: []string{"s"}}) audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} - result := p.processVideo(dir, "Artist - Song-video.mkv", audioData, nil) + result := p.processVideo(t.Context(), dir, "Artist - Song-video.mkv", audioData, nil) if result != "skipped" { t.Errorf("got %q, want 'skipped'", result) } @@ -212,7 +213,7 @@ func TestProcessVideo_IgnoreChosen_SavesPattern(t *testing.T) { } audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} - p.processVideo(dir, "Artist - Song OFFICIAL-video.mkv", audioData, nil) + p.processVideo(t.Context(), dir, "Artist - Song OFFICIAL-video.mkv", audioData, nil) wantVideoPath := filepath.Join(dir, "Artist - Song OFFICIAL-video.mkv") if savedPattern != " OFFICIAL" { @@ -242,7 +243,7 @@ func TestProcessVideo_PostSuffix_PromptsAndIgnores(t *testing.T) { } audioData := map[string]string{"08 - Rise & Shine": "08 - Rise & Shine - Rise & Shine"} - p.processVideo(dir, mkvFile, audioData, nil) + p.processVideo(t.Context(), dir, mkvFile, audioData, nil) if savedPattern != "(Second Version)" { t.Errorf("saved pattern %q, want '(Second Version)'", savedPattern) @@ -260,7 +261,7 @@ func TestProcessVideo_PostSuffix_AlreadyIgnored_NoPrompt(t *testing.T) { p.ignoreData.FilePatterns = map[string][]string{filepath.Join(dir, mkvFile): {" (Second Version)"}} audioData := map[string]string{"08 - Rise & Shine": "08 - Rise & Shine - Rise & Shine"} - result := p.processVideo(dir, mkvFile, audioData, nil) + result := p.processVideo(t.Context(), dir, mkvFile, audioData, nil) if result != "" { t.Errorf("got %q, want empty (already correct after ignore)", result) } @@ -271,7 +272,7 @@ func TestProcessVideo_DefaultSuffix_WhenNoKnownSuffix(t *testing.T) { // Video has no known suffix → effective suffix defaults to "-video". audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} p := NewProcessor(dir, "", &fakePrompter{answers: []string{"s"}}) - result := p.processVideo(dir, "Artist - Song.mkv", audioData, nil) + result := p.processVideo(t.Context(), dir, "Artist - Song.mkv", audioData, nil) if result != "skipped" { t.Errorf("got %q, want 'skipped'", result) } @@ -289,7 +290,7 @@ func TestRun_AlreadyCorrect_NoStats(t *testing.T) { } p := NewProcessor(dir, "", &fakePrompter{}) - stats, skipped, _ := p.Run() + stats, skipped, _ := p.Run(t.Context()) if stats.Renamed != 0 || stats.Skipped != 0 || len(skipped) != 0 { t.Errorf("expected no actions, got %+v skipped=%v", stats, skipped) } @@ -305,7 +306,7 @@ func TestRun_SkipsNonVideoFiles(t *testing.T) { } p := NewProcessor(dir, "", &fakePrompter{}) - stats, _, _ := p.Run() + stats, _, _ := p.Run(t.Context()) if stats.Renamed != 0 || stats.Skipped != 0 { t.Errorf("non-video files should produce no stats, got %+v", stats) } @@ -322,7 +323,7 @@ func TestRun_CountsUnmatched(t *testing.T) { } p := NewProcessor(dir, "", &fakePrompter{}) - stats, _, unmatched := p.Run() + stats, _, unmatched := p.Run(t.Context()) if stats.Unmatched != 1 { t.Errorf("Unmatched=%d, want 1", stats.Unmatched) } @@ -342,7 +343,7 @@ func TestRun_CountsSkipped(t *testing.T) { } p := NewProcessor(dir, "", &fakePrompter{answers: []string{"s"}}) - stats, skipped, _ := p.Run() + stats, skipped, _ := p.Run(t.Context()) if stats.Skipped != 1 { t.Errorf("Skipped=%d, want 1", stats.Skipped) } @@ -366,7 +367,7 @@ func TestRun_SuffixedVideoPromptedBeforeUnsuffixed(t *testing.T) { } p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "s"}}) - p.Run() + p.Run(t.Context()) for _, name := range []string{"01 - foo - foo-video.mkv", "01 - bob - bob (Special Music Video).mkv"} { if _, err := os.Stat(filepath.Join(dir, name)); err != nil { t.Errorf("want %q to exist: %v", name, err) @@ -391,7 +392,7 @@ func TestRun_TakenNameKeepsExtraText(t *testing.T) { tagger := &fakeTagger{} p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}) p.tagger = tagger - if stats, _, _ := p.Run(); stats.Renamed != 2 { + if stats, _, _ := p.Run(t.Context()); stats.Renamed != 2 { t.Errorf("Renamed=%d, want 2", stats.Renamed) } special := filepath.Join(dir, "01 - foo - foo (Special Music Video)-video.mkv") @@ -405,7 +406,7 @@ func TestRun_TakenNameKeepsExtraText(t *testing.T) { } // A second run finds both names correct: no prompts. - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(); stats != (Stats{}) { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(t.Context()); stats != (Stats{}) { t.Errorf("second run stats = %+v, want none", stats) } } @@ -418,9 +419,9 @@ func TestRun_PlainSuffixedVideoPromptedBeforeVersioned(t *testing.T) { t.Fatal(err) } } - NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}).Run(t.Context()) assertFiles(t, dir, "01 - New - New-video.mkv", "01 - New - New-video (Second Version).mkv") - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(); stats != (Stats{}) { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(t.Context()); stats != (Stats{}) { t.Errorf("second run stats = %+v, want none", stats) } } @@ -463,7 +464,7 @@ func assertTagsStable(t *testing.T, dir string, global []string, answers ...stri p := NewProcessor(dir, "", &fakePrompter{answers: answers}) p.ignoreData.Global = global p.tagger = tagger - p.Run() + p.Run(t.Context()) got := map[string]string{} for _, c := range tagger.calls { got[filepath.Base(c.mkvPath)] = c.titleSuffix @@ -513,14 +514,14 @@ func TestRun_RenameTagsLikeNextRun(t *testing.T) { func TestRun_UnsuffixedPlainBeatsVersioned(t *testing.T) { // A plain unsuffixed video owns the standard name over "-video (Second Version)". dir := musicDir(t, "01 - New.flac", "01 - Old - Old.mkv", "01 - Old - Old-video (Second Version).mkv") - NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}).Run(t.Context()) assertFiles(t, dir, "01 - New - New-video.mkv", "01 - New - New-video (Second Version).mkv") } func TestRun_UnsuffixedHolderCountsAsTaken(t *testing.T) { // "01 - foo - foo.mkv" is accepted as the "-video" file, so it holds the name. dir := musicDir(t, "01 - foo.flac", "01 - foo - foo.mkv", "01 - bob - bob (Special Music Video).mkv") - NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) assertFiles(t, dir, "01 - foo - foo.mkv", "01 - foo - foo (Special Music Video)-video.mkv") } @@ -529,11 +530,11 @@ func TestRun_OnlyIgnoredTextSetsApart(t *testing.T) { dir := musicDir(t, "01 - New.flac", "01 - New - New-video.mkv", "01 - Old - Old-video [HD].mkv") p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}) p.ignoreData.Global = []string{" [HD]"} - p.Run() + p.Run(t.Context()) assertFiles(t, dir, "01 - New - New-video [HD].mkv") p2 := NewProcessor(dir, "", &fakePrompter{}) p2.ignoreData = p.ignoreData - if stats, _, _ := p2.Run(); stats != (Stats{}) { + if stats, _, _ := p2.Run(t.Context()); stats != (Stats{}) { t.Errorf("second run stats = %+v, want none", stats) } } @@ -544,7 +545,7 @@ func TestRun_PlainBeatsIgnoredOnlyText(t *testing.T) { dir := musicDir(t, "01 - New.flac", plain, "01 - Old - Old-video [HD].mkv") p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}) p.ignoreData.Global = []string{" [HD]"} - p.Run() + p.Run(t.Context()) assertFiles(t, dir, "01 - New - New-video.mkv", "01 - New - New-video [HD].mkv") } } @@ -554,7 +555,7 @@ func TestRun_RankAppliesIgnorePatterns(t *testing.T) { dir := musicDir(t, "01 - New.flac", "01 - Old - Old (Live).mkv", "01 - Old - Old (Official Video).mkv") p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r", "r"}}) p.ignoreData.Global = []string{" (Official Video)"} - p.Run() + p.Run(t.Context()) assertFiles(t, dir, "01 - New - New-video.mkv", "01 - New - New (Live)-video.mkv") } @@ -566,7 +567,7 @@ func TestRun_TakenNameOtherExtension(t *testing.T) { t.Fatal(err) } } - NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if _, err := os.Stat(filepath.Join(dir, "01 - foo - foo (Special Music Video)-video.mkv")); err != nil { t.Error(err) } @@ -580,7 +581,7 @@ func TestRun_TakenNameExtraAlreadyInTitle(t *testing.T) { t.Fatal(err) } } - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(); stats.Skipped != 1 { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()); stats.Skipped != 1 { t.Errorf("stats = %+v, want Skipped=1 (standard name taken)", stats) } } @@ -597,13 +598,13 @@ func TestRun_TakenNameIgnoredTextSettles(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{answers: []string{"i", " [HD]"}}) p.tagger = tagger p.patternAppender = func(_, _, _ string) error { return nil } - p.Run() + p.Run(t.Context()) if last := tagger.calls[len(tagger.calls)-1]; filepath.Base(last.mkvPath) != "01 - New [HD] - New [HD] (Live)-video.mkv" || last.titleSuffix != "[HD] (Live)" { t.Errorf("tag calls = %+v", tagger.calls) } p2 := NewProcessor(dir, "", &fakePrompter{}) p2.ignoreData = p.ignoreData - if stats, _, _ := p2.Run(); stats != (Stats{}) { + if stats, _, _ := p2.Run(t.Context()); stats != (Stats{}) { t.Errorf("second run stats = %+v, want none", stats) } } @@ -617,7 +618,7 @@ func TestRun_RenameTagsFromRenameMatchWhenNewNameRematches(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}) p.ignoreData.Global = []string{" Love"} p.tagger = tagger - p.Run() + p.Run(t.Context()) assertFiles(t, dir, "01 - Love - Love-video.mkv") if len(tagger.calls) != 1 || filepath.Base(tagger.calls[0].mkvPath) != "01 - Love - Love-video.mkv" || filepath.Base(tagger.calls[0].audioPath) != "01 - Love.flac" { @@ -629,9 +630,9 @@ func TestRun_RenamedVideoKeepsItsTrack(t *testing.T) { // "01 - Love - Love" is closer to "01 - Love Love" by filename, but it is // exactly the display name of "01 - Love": it must not move on run 2. dir := musicDir(t, "01 - Love.flac", "01 - Love Love.flac", "01 - Old - Old (Live).mkv") - NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) assertFiles(t, dir, "01 - Love - Love-video.mkv") - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(); stats != (Stats{}) { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(t.Context()); stats != (Stats{}) { t.Errorf("second run stats = %+v, want none", stats) } } @@ -643,7 +644,7 @@ func TestRun_TitleSuffixNotDoubled(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{}) p.ignoreData.Global = []string{" (Official Video)"} p.tagger = tagger - p.Run() + p.Run(t.Context()) last := tagger.calls[len(tagger.calls)-1] if filepath.Base(last.mkvPath) != "01 - New - New (Live) (Official Video)-video.mkv" || last.titleSuffix != "(Official Video) (Live)" { t.Errorf("tag calls = %+v", tagger.calls) @@ -658,7 +659,7 @@ func TestCopyTags_ShortPostSuffixInsidePatternKept(t *testing.T) { p.ignoreData.Global = []string{"(Take 2)"} p.tagger = tagger mkv := filepath.Join(dir, "v.mkv") - p.copyTagsIfConfigured(mkv, "k", "01 - New (Take 2) - New (Take 2)", "2", dir, mkv, map[string]string{"k": "a.flac"}) + p.copyTagsIfConfigured(t.Context(), mkv, "k", "01 - New (Take 2) - New (Take 2)", "2", dir, mkv, map[string]string{"k": "a.flac"}) if len(tagger.calls) != 1 || tagger.calls[0].titleSuffix != "(Take 2) 2" { t.Errorf("tag calls = %+v", tagger.calls) } @@ -672,7 +673,7 @@ func TestCopyTags_SamePatternTwiceTaggedOnce(t *testing.T) { mkv := filepath.Join(dir, "v.mkv") p.ignoreData = IgnoreData{Global: []string{"[HD]"}, FilePatterns: map[string][]string{mkv: {" [HD]"}}} p.tagger = tagger - p.copyTagsIfConfigured(mkv, "k", "01 - Song [HD] - Song [HD]", "", dir, mkv, map[string]string{"k": "a.flac"}) + p.copyTagsIfConfigured(t.Context(), mkv, "k", "01 - Song [HD] - Song [HD]", "", dir, mkv, map[string]string{"k": "a.flac"}) if len(tagger.calls) != 1 || tagger.calls[0].titleSuffix != "[HD]" { t.Errorf("tag calls = %+v", tagger.calls) } @@ -697,7 +698,7 @@ func TestCopyTags_IgnoredPatternInPostSuffixNotRepeated(t *testing.T) { p.ignoreData.Global = []string{" (Official Video)"} p.tagger = tagger mkv := filepath.Join(dir, "v.mkv") - p.copyTagsIfConfigured(mkv, "k", "01 - New - New (Official Video)", "(Official Video) (Live)", dir, mkv, map[string]string{"k": "a.flac"}) + p.copyTagsIfConfigured(t.Context(), mkv, "k", "01 - New - New (Official Video)", "(Official Video) (Live)", dir, mkv, map[string]string{"k": "a.flac"}) if len(tagger.calls) != 1 || tagger.calls[0].titleSuffix != "(Official Video) (Live)" { t.Errorf("tag calls = %+v", tagger.calls) } @@ -711,7 +712,7 @@ func TestRun_IgnoreOnUnsuffixedTakenNameStillNeedsRename(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{answers: []string{"i", "zzz"}}) p.patternAppender = func(string, string, string) error { return nil } p.tagger = tagger - p.Run() + p.Run(t.Context()) for _, c := range tagger.calls { if filepath.Base(c.mkvPath) == "01 - foo - foo (Live).mkv" { t.Errorf("tagged %s as matched after ignoring an unrelated pattern", c.mkvPath) @@ -725,16 +726,16 @@ func TestRun_SkippedPlainVideoKeepsTheStandardName(t *testing.T) { t.Run(versioned, func(t *testing.T) { dir := musicDir(t, "01 - New.flac", "01 - Old - Old.mkv", versioned) // Skip the plain video; the versioned one must keep its extra text. - NewProcessor(dir, "", &fakePrompter{answers: []string{"s", "r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"s", "r"}}).Run(t.Context()) kept := map[string]string{ "01 - Old - Old (Special Music Video).mkv": "01 - New - New (Special Music Video)-video.mkv", "01 - Old - Old-video (Second Version).mkv": "01 - New - New-video (Second Version).mkv", }[versioned] assertFiles(t, dir, "01 - Old - Old.mkv", kept) // The plain video can still take the standard name later. - NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) assertFiles(t, dir, "01 - New - New-video.mkv", kept) - if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(); stats != (Stats{}) { + if stats, _, _ := NewProcessor(dir, "", &fakePrompter{}).Run(t.Context()); stats != (Stats{}) { t.Errorf("third run stats = %+v, want none", stats) } }) @@ -777,7 +778,7 @@ func TestRun_RenameKeepsFilePatternText(t *testing.T) { t.Fatal(err) } p.tagger = tagger - stats, _, _ := p.Run() + stats, _, _ := p.Run(t.Context()) return stats, tagger } tagOf := func(tg *fakeTagger) string { @@ -849,7 +850,7 @@ func TestRun_RenameReportsFailedPatternMove(t *testing.T) { } p.tagger = tagger p.patternMover = func(string, string, string) error { return os.ErrPermission } - out := captureStdout(t, func() { p.Run() }) + out := captureStdout(t, func() { p.Run(t.Context()) }) assertFiles(t, dir, want) if msg := fmt.Sprintf("[ERROR] Could not move ignore patterns in %s from %q to %q", ignoreFile, oldPath, newPath); !strings.Contains(out, msg) { @@ -931,7 +932,7 @@ func TestProcessVideo_IgnoreWithKeptTextMatchesNow(t *testing.T) { p.ignoreData.FilePatterns = map[string][]string{filepath.Join(dir, video): {" (Alt)"}} p.patternAppender = func(string, string, string) error { return nil } p.tagger = tagger - out := captureStdout(t, func() { p.Run() }) + out := captureStdout(t, func() { p.Run(t.Context()) }) if !strings.Contains(out, "File now matches after ignoring pattern!") { t.Errorf("output:\n%s", out) @@ -976,7 +977,7 @@ func TestRun_FreeNameStillGetsStandardName(t *testing.T) { t.Fatal(err) } - NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if _, err := os.Stat(filepath.Join(dir, "01 - foo - foo-video.mkv")); err != nil { t.Error(err) } @@ -1018,7 +1019,7 @@ func TestRun_CaseOnlyRename(t *testing.T) { t.Fatal(err) } - stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if stats.Renamed != 1 { t.Errorf("stats = %+v, want Renamed=1", stats) } @@ -1045,7 +1046,7 @@ func TestRun_DifferentFileWithSameNameStillProtected(t *testing.T) { t.Fatal(err) } - stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if stats.Skipped != 1 { t.Errorf("stats = %+v, want Skipped=1", stats) } @@ -1069,7 +1070,7 @@ func TestRun_SymlinkToTargetNotRenamedOverIt(t *testing.T) { t.Skipf("cannot create symlink: %v", err) } - stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if stats.Skipped != 1 { t.Errorf("stats = %+v, want Skipped=1", stats) } @@ -1102,7 +1103,7 @@ func TestRun_FoldEqualDifferentFileProtected(t *testing.T) { t.Skip("filesystem treats the two names as one") } - stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if stats.Skipped != 1 { t.Errorf("stats = %+v, want Skipped=1", stats) } @@ -1124,7 +1125,7 @@ func TestRun_FoldEqualSymlinkNotRenamedOverTarget(t *testing.T) { t.Skipf("cannot create symlink: %v", err) } - stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run() + stats, _, _ := NewProcessor(dir, "", &fakePrompter{answers: []string{"r"}}).Run(t.Context()) if stats.Skipped != 1 { t.Errorf("stats = %+v, want Skipped=1", stats) } @@ -1215,7 +1216,7 @@ func TestProcessVideo_AlreadyCorrect_CopiesTags(t *testing.T) { audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} audioPaths := map[string]string{"Artist - Song": "Artist - Song.flac"} - result := p.processVideo(dir, mkvFile, audioData, audioPaths) + result := p.processVideo(t.Context(), dir, mkvFile, audioData, audioPaths) if result != "" { t.Errorf("got %q, want empty (already correct)", result) } @@ -1246,7 +1247,7 @@ func TestProcessVideo_Renamed_CopiesTagsToNewPath(t *testing.T) { audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} audioPaths := map[string]string{"Artist - Song": "Artist - Song.flac"} - result := p.processVideo(dir, "Artist - Song-video.mkv", audioData, audioPaths) + result := p.processVideo(t.Context(), dir, "Artist - Song-video.mkv", audioData, audioPaths) if result != "renamed" { t.Errorf("got %q, want 'renamed'", result) } @@ -1269,7 +1270,7 @@ func TestProcessVideo_Skipped_NoTagCopy(t *testing.T) { audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} audioPaths := map[string]string{"Artist - Song": "Artist - Song.flac"} - result := p.processVideo(dir, "Artist - Song-video.mkv", audioData, audioPaths) + result := p.processVideo(t.Context(), dir, "Artist - Song-video.mkv", audioData, audioPaths) if result != "skipped" { t.Errorf("got %q, want 'skipped'", result) } @@ -1336,7 +1337,7 @@ func TestProcessVideo_AlreadyCorrect_TagsUpToDate_SkipsCopy(t *testing.T) { audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} audioPaths := map[string]string{"Artist - Song": "Artist - Song.flac"} - p.processVideo(dir, mkvFile, audioData, audioPaths) + p.processVideo(t.Context(), dir, mkvFile, audioData, audioPaths) if len(ft.calls) != 0 { t.Errorf("expected no CopyTagsToMKV call when tags already match, got %d", len(ft.calls)) @@ -1363,7 +1364,7 @@ func TestProcessVideo_Ignore_MatchesAfterPattern_CopiesTags(t *testing.T) { audioData := map[string]string{"Artist - Song": "Artist - Song - Song"} audioPaths := map[string]string{"Artist - Song": "Artist - Song.flac"} - p.processVideo(dir, mkvFile, audioData, audioPaths) + p.processVideo(t.Context(), dir, mkvFile, audioData, audioPaths) if len(ft.calls) != 1 { t.Fatalf("expected 1 tagger call after ignore match, got %d", len(ft.calls)) @@ -1392,7 +1393,7 @@ func TestProcessVideo_IgnorePatternInFilename_PassesTitleSuffix(t *testing.T) { audioData := map[string]string{"09 - On My Way": "09 - On My Way - On My Way"} audioPaths := map[string]string{"09 - On My Way": "09 - On My Way.flac"} - p.processVideo(dir, mkvFile, audioData, audioPaths) + p.processVideo(t.Context(), dir, mkvFile, audioData, audioPaths) if len(ft.calls) != 1 { t.Fatalf("expected 1 tagger call, got %d", len(ft.calls)) @@ -1518,7 +1519,7 @@ func TestRun_UnreadableRootWarns(t *testing.T) { root := filepath.Join(t.TempDir(), "missing") p := NewProcessor(root, filepath.Join(t.TempDir(), "ignore.json"), &fakePrompter{}) - out := captureStdout(t, func() { p.Run() }) + out := captureStdout(t, func() { p.Run(t.Context()) }) if want := "[WARN] Skipping unreadable " + root; !strings.Contains(out, want) { t.Errorf("output missing %q:\n%s", want, out) } @@ -1528,7 +1529,7 @@ func TestSetAudioTimestamps_UnreadableRootWarns(t *testing.T) { root := filepath.Join(t.TempDir(), "missing") var stats AudioTimestampStats - out := captureStdout(t, func() { stats = SetAudioTimestamps(root, time.Time{}, nil, "") }) + out := captureStdout(t, func() { stats, _ = SetAudioTimestamps(t.Context(), root, time.Time{}, nil, "") }) if stats != (AudioTimestampStats{}) { t.Errorf("stats = %+v, want zero", stats) } diff --git a/mkv-music/prompt.go b/mkv-music/prompt.go index a9851e8..18e0749 100644 --- a/mkv-music/prompt.go +++ b/mkv-music/prompt.go @@ -2,28 +2,82 @@ package main import ( "bufio" + "context" + "errors" "fmt" - "os" + "io" "strings" + "time" ) -// Prompter asks the user a question and returns their trimmed answer. +// Prompter prints a prompt and reads a line of user input. After an interrupt +// a blank answer would accept a default, so callers check ctx before acting +// on the answer. type Prompter interface { Ask(prompt string) (string, error) } -type stdinPrompter struct { - scanner *bufio.Scanner +// eofGrace is how long a prompt that read EOF waits for the interrupt that +// may have caused it. +const eofGrace = 250 * time.Millisecond + +type linePrompter struct { + ctx context.Context + r *bufio.Reader + w io.Writer + eof bool // input ended with no interrupt; no more reads } -func newStdinPrompter() Prompter { - return &stdinPrompter{scanner: bufio.NewScanner(os.Stdin)} +// 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} } -func (p *stdinPrompter) Ask(prompt string) (string, error) { - fmt.Print(prompt) - if !p.scanner.Scan() { - return "", p.scanner.Err() +// Ask writes prompt and returns the answer without its line ending. Spaces +// stay: an ignore pattern can start or end with one. Once ctx is cancelled it +// 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 + } + // 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 an EOF waits briefly for it. + if errors.Is(a.err, io.EOF) { + select { + case <-p.ctx.Done(): + case <-time.After(eofGrace): + } + } + 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 && (!p.eof || a.line == "") { + return "", a.err } - return strings.TrimRight(p.scanner.Text(), "\r"), nil + return strings.TrimRight(a.line, "\r\n"), nil } diff --git a/mkv-music/prompt_test.go b/mkv-music/prompt_test.go new file mode 100644 index 0000000..773671d --- /dev/null +++ b/mkv-music/prompt_test.go @@ -0,0 +1,107 @@ +package main + +import ( + "context" + "errors" + "io" + "strings" + "testing" + "time" +) + +// Answers lose only their line ending: an ignore pattern's spaces matter. +func TestPrompter_Answers(t *testing.T) { + cases := []struct{ input, want string }{{"r\n", "r"}, {" [HD] \r\n", " [HD] "}, {"\n", ""}, {"(Live)", "(Live)"}} + for _, tc := range cases { + var w strings.Builder + got, err := newPrompter(t.Context(), strings.NewReader(tc.input), &w).Ask("rename? ") + if err != nil || got != tc.want { + t.Errorf("answer %q = %q, %v; want %q", tc.input, got, err, tc.want) + } + if w.String() != "rename? " { + t.Errorf("question written as %q", w.String()) + } + } +} + +// 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) + } +} + +// 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("s"), &w) + if got, err := p.Ask("1 "); got != "s" || err != nil { + t.Fatalf("last line without a newline = %q, %v; want s", 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() + t.Cleanup(func() { w.Close() }) + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(50*time.Millisecond, cancel) + + 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) { + 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("r\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-music/tag_outcome_test.go b/mkv-music/tag_outcome_test.go index 5937eb4..6982d41 100644 --- a/mkv-music/tag_outcome_test.go +++ b/mkv-music/tag_outcome_test.go @@ -38,7 +38,7 @@ func runTagged(t *testing.T, tagger *fakeTagger, timer *fakeFileTimer) (TagOutco p.tagger = tagger p.timer = timer var tags TagOutcome - out := captureStdout(t, func() { p.Run(); tags = p.Tags() }) + out := captureStdout(t, func() { p.Run(t.Context()); tags = p.Tags() }) return tags, out, filepath.Join(dir, outcomeVideo) } @@ -140,7 +140,7 @@ func TestRun_TagOutcome_DateHeader(t *testing.T) { if tt.timer != nil { p.timer = tt.timer } - out := captureStdout(t, func() { p.Run() }) + out := captureStdout(t, func() { p.Run(t.Context()) }) tags := p.Tags() if tags.Copied != tt.wantCopied { @@ -180,7 +180,7 @@ func TestRun_TagOutcome_Renamed_RecordsNewPath(t *testing.T) { p.tagger = &fakeTagger{err: tt.copyErr, date: headerDate} p.timer = &fakeFileTimer{} var stats Stats - captureStdout(t, func() { stats, _, _ = p.Run() }) + captureStdout(t, func() { stats, _, _ = p.Run(t.Context()) }) if stats.Renamed != 1 { t.Fatalf("Renamed = %d, want 1", stats.Renamed) } @@ -207,7 +207,7 @@ func TestRun_TagOutcome_Accumulates(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{}) p.tagger = &fakeTagger{date: headerDate} p.timer = &failOnTimer{fail: "Artist - Bad - Bad-video.mkv"} - captureStdout(t, func() { p.Run() }) + captureStdout(t, func() { p.Run(t.Context()) }) tags := p.Tags() want := []string{filepath.Join(dir, "Artist - Bad - Bad-video.mkv") + " (failed: mtime)"} @@ -237,7 +237,7 @@ func TestRun_TagOutcome_NonMKV_NotTagged(t *testing.T) { p := NewProcessor(dir, "", &fakePrompter{}) p.tagger = tagger p.timer = timer - captureStdout(t, func() { p.Run() }) + captureStdout(t, func() { p.Run(t.Context()) }) if len(tagger.calls) != 0 { t.Errorf("CopyTagsToMKV called %v for a non-MKV video", tagger.calls) @@ -254,7 +254,7 @@ func TestRun_TagOutcome_NonMKV_NotTagged(t *testing.T) { func TestPrintRunSummary_IncludesTagOutcome(t *testing.T) { out := captureStdout(t, func() { - printRunSummary(Stats{SkippedOld: 2}, []string{`C:\m\skipped.mkv`}, nil, + printRunSummary("Scan Complete", Stats{SkippedOld: 2}, []string{`C:\m\skipped.mkv`}, nil, TagOutcome{Copied: 1, Failed: []string{`C:\m\b.mkv (failed: tags)`}}) }) want := []string{ diff --git a/mkv-music/tags.go b/mkv-music/tags.go index 2193abe..093af0f 100644 --- a/mkv-music/tags.go +++ b/mkv-music/tags.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "context" "fmt" "io" "os" @@ -16,15 +17,17 @@ import ( // MusicVideoTagger copies tags and cover art from a source audio file to a // destination MKV file, and can check whether the MKV tags already match. +// Each returns the kill context's error once ctx's kill (see command) has +// stopped a read, and CopyTagsToMKV then edits nothing. type MusicVideoTagger interface { // TagsMatchMKV returns true if the MKV at mkvPath already has tags // identical to what CopyTagsToMKV would write from audioPath. // Returns false (not true) on any error so the caller falls back to copying. - TagsMatchMKV(audioPath, mkvPath, titleSuffix string) (bool, error) - CopyTagsToMKV(audioPath, mkvPath, titleSuffix string) error + TagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) + CopyTagsToMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) error // MKVDate returns the date stored in the MKV container header and true, // false when the header has no date, or an error when it can't be read. - MKVDate(mkvPath string) (time.Time, bool, error) + MKVDate(ctx context.Context, mkvPath string) (time.Time, bool, error) } // AudioTags holds the metadata extracted from an audio file. @@ -252,19 +255,27 @@ func newRealMusicVideoTagger() (*realMusicVideoTagger, error) { } // MKVDate implements MusicVideoTagger. -func (t *realMusicVideoTagger) MKVDate(mkvPath string) (time.Time, bool, error) { - return readMKVHeaderDate(t.mkvmergePath, mkvPath) +func (t *realMusicVideoTagger) MKVDate(ctx context.Context, mkvPath string) (time.Time, bool, error) { + return readMKVHeaderDate(ctx, t.mkvmergePath, mkvPath) } // TagsMatchMKV implements MusicVideoTagger. // It reads tags from audioPath and the current tags embedded in mkvPath, // then compares all text fields and cover art. // Returns false on any error so the caller falls back to copying. -func (t *realMusicVideoTagger) TagsMatchMKV(audioPath, mkvPath, titleSuffix string) (bool, error) { +func (t *realMusicVideoTagger) TagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) { + match, err := t.tagsMatchMKV(ctx, audioPath, mkvPath, titleSuffix) + if killErr := killContext(ctx).Err(); killErr != nil { // a killed read can look like a match + return false, killErr + } + return match, err +} + +func (t *realMusicVideoTagger) tagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) { var want AudioTags var err error if strings.EqualFold(filepath.Ext(audioPath), ".mka") { - want, err = readAudioTagsFromMKA(audioPath, t.mkvextractPath, t.mkvmergePath) + want, err = readAudioTagsFromMKA(ctx, audioPath, t.mkvextractPath, t.mkvmergePath) } else { want, err = readAudioTags(audioPath) } @@ -282,7 +293,7 @@ func (t *realMusicVideoTagger) TagsMatchMKV(audioPath, mkvPath, titleSuffix stri xmlTmp.Close() defer os.Remove(xmlTmp.Name()) - cmd := exec.Command(t.mkvextractPath, mkvPath, "tags", xmlTmp.Name()) + cmd := command(ctx, t.mkvextractPath, mkvPath, "tags", xmlTmp.Name()) cmd.Stdout = io.Discard cmd.Stderr = io.Discard _ = cmd.Run() // a failed extract leaves the XML empty, which parseMKVTagsXML reads as no tags @@ -305,13 +316,13 @@ func (t *realMusicVideoTagger) TagsMatchMKV(audioPath, mkvPath, titleSuffix stri return false, nil } - if readMKVHeaderTitle(t.mkvmergePath, mkvPath) != buildHeaderTitle(want, "") { + if readMKVHeaderTitle(ctx, t.mkvmergePath, mkvPath) != buildHeaderTitle(want, "") { return false, nil } // Check MKV header date matches the audio date. if wantDt, ok := parseAudioDate(want.Date); ok { - mkvDate, hasMKVDate, _ := readMKVHeaderDate(t.mkvmergePath, mkvPath) // unreadable → no match → copy + mkvDate, hasMKVDate, _ := readMKVHeaderDate(ctx, t.mkvmergePath, mkvPath) // unreadable → no match → copy if !hasMKVDate || mkvDate.UTC().Format("2006-01-02") != wantDt.UTC().Format("2006-01-02") { return false, nil } @@ -319,18 +330,19 @@ func (t *realMusicVideoTagger) TagsMatchMKV(audioPath, mkvPath, titleSuffix stri // Compare cover art: extract the current attachment from the MKV and check // it byte-for-byte against the source. - mkvCover, _ := extractMKACover(t.mkvextractPath, t.mkvmergePath, mkvPath) + mkvCover, _ := extractMKACover(ctx, t.mkvextractPath, t.mkvmergePath, mkvPath) return bytes.Equal(want.CoverData, mkvCover), nil } // CopyTagsToMKV implements MusicVideoTagger. // It reads tags from audioPath, optionally appends titleSuffix to the title // (with a space separator), then writes tags and cover art to mkvPath. -func (t *realMusicVideoTagger) CopyTagsToMKV(audioPath, mkvPath, titleSuffix string) error { +// mkvpropedit edits in place, so it is never killed. +func (t *realMusicVideoTagger) CopyTagsToMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) error { var tags AudioTags var err error if strings.EqualFold(filepath.Ext(audioPath), ".mka") { - tags, err = readAudioTagsFromMKA(audioPath, t.mkvextractPath, t.mkvmergePath) + tags, err = readAudioTagsFromMKA(ctx, audioPath, t.mkvextractPath, t.mkvmergePath) } else { tags, err = readAudioTags(audioPath) } @@ -343,7 +355,11 @@ func (t *realMusicVideoTagger) CopyTagsToMKV(audioPath, mkvPath, titleSuffix str // Preserve ReplayGain tags already on the MKV — they differ from the source // audio file because loudness normalisation is run separately on the video. - extra50, extra30 := extractReplayGainTags(t.mkvextractPath, mkvPath) + extra50, extra30 := extractReplayGainTags(ctx, t.mkvextractPath, mkvPath) + // A killed read leaves tags or ReplayGain out, which the edit would drop. + if err := killContext(ctx).Err(); err != nil { + return err + } // Write tags XML to a temp file. xmlFile, err := os.CreateTemp("", "mkv-musicvideo-tags-*.xml") @@ -382,7 +398,7 @@ func (t *realMusicVideoTagger) CopyTagsToMKV(audioPath, mkvPath, titleSuffix str // fine — we swallow the error intentionally. Stdout/stderr are // discarded to suppress the "The file is being analyzed." progress line. deleteAttachment := func(name string) { - cmd := exec.Command(t.mkvpropeditPath, mkvPath, "--delete-attachment", "name:"+name) + cmd := command(context.Background(), t.mkvpropeditPath, mkvPath, "--delete-attachment", "name:"+name) cmd.Stdout = io.Discard cmd.Stderr = io.Discard _ = cmd.Run() @@ -412,7 +428,7 @@ func (t *realMusicVideoTagger) CopyTagsToMKV(audioPath, mkvPath, titleSuffix str "--add-attachment", coverTmpPath, ) } - cmd := exec.Command(t.mkvpropeditPath, args...) + cmd := command(context.Background(), t.mkvpropeditPath, args...) var out bytes.Buffer cmd.Stdout = &out cmd.Stderr = &out diff --git a/mkv-music/tags_mka.go b/mkv-music/tags_mka.go index 30d5dcf..885b42b 100644 --- a/mkv-music/tags_mka.go +++ b/mkv-music/tags_mka.go @@ -2,12 +2,12 @@ package main import ( "bytes" + "context" "encoding/json" "encoding/xml" "fmt" "io" "os" - "os/exec" "strconv" "strings" "time" @@ -102,9 +102,9 @@ type mkvmergeIdentify struct { // readMKVHeaderTitle returns the file-header title stored in an MKV, or "" // when the title is absent or the identify call fails. -func readMKVHeaderTitle(mkvmergePath, mkvPath string) string { +func readMKVHeaderTitle(ctx context.Context, mkvmergePath, mkvPath string) string { var buf bytes.Buffer - cmd := exec.Command(mkvmergePath, "--identify", "--identification-format", "json", mkvPath) + cmd := command(ctx, mkvmergePath, "--identify", "--identification-format", "json", mkvPath) cmd.Stdout = &buf cmd.Stderr = io.Discard if cmd.Run() != nil { @@ -119,15 +119,20 @@ func readMKVHeaderTitle(mkvmergePath, mkvPath string) string { // readMKVHeaderDate returns the date stored in the MKV container header. // Returns false when the header has no date, and an error when mkvmerge -// can't read the file. -func readMKVHeaderDate(mkvmergePath, mkvPath string) (time.Time, bool, error) { +// can't read the file, or the kill context's error once that killed it. +func readMKVHeaderDate(ctx context.Context, mkvmergePath, mkvPath string) (time.Time, bool, error) { var buf bytes.Buffer - cmd := exec.Command(mkvmergePath, "--identify", "--identification-format", "json", mkvPath) + cmd := command(ctx, mkvmergePath, "--identify", "--identification-format", "json", mkvPath) cmd.Stdout = &buf cmd.Stderr = io.Discard - // Exit code 1 means warnings only. - if err := cmd.Run(); err != nil && (cmd.ProcessState == nil || cmd.ProcessState.ExitCode() != 1) { - return time.Time{}, false, fmt.Errorf("mkvmerge --identify: %w", err) + // Exit code 1 means warnings only, unless the kill made it (Windows). + if err := cmd.Run(); err != nil { + if killErr := killContext(ctx).Err(); killErr != nil { + return time.Time{}, false, killErr + } + if cmd.ProcessState == nil || cmd.ProcessState.ExitCode() != 1 { + return time.Time{}, false, fmt.Errorf("mkvmerge --identify: %w", err) + } } var info mkvmergeIdentify if err := json.Unmarshal(buf.Bytes(), &info); err != nil { @@ -141,9 +146,9 @@ func readMKVHeaderDate(mkvmergePath, mkvPath string) (time.Time, bool, error) { // extractMKACover finds the first image attachment in mkaPath and returns its // raw bytes and MIME type. Returns nil, "" when no image attachment exists. -func extractMKACover(mkvextractPath, mkvmergePath, mkaPath string) ([]byte, string) { +func extractMKACover(ctx context.Context, mkvextractPath, mkvmergePath, mkaPath string) ([]byte, string) { var identBuf bytes.Buffer - idCmd := exec.Command(mkvmergePath, "--identify", "--identification-format", "json", mkaPath) + idCmd := command(ctx, mkvmergePath, "--identify", "--identification-format", "json", mkaPath) idCmd.Stdout = &identBuf idCmd.Stderr = io.Discard if idCmd.Run() != nil { @@ -166,7 +171,7 @@ func extractMKACover(mkvextractPath, mkvmergePath, mkaPath string) ([]byte, stri tmp.Close() defer os.Remove(tmp.Name()) - extract := exec.Command(mkvextractPath, mkaPath, "attachments", + extract := command(ctx, mkvextractPath, mkaPath, "attachments", fmt.Sprintf("%d:%s", att.ID, tmp.Name())) extract.Stdout = io.Discard extract.Stderr = io.Discard @@ -184,7 +189,7 @@ func extractMKACover(mkvextractPath, mkvmergePath, mkaPath string) ([]byte, stri // readAudioTagsFromMKA reads metadata from a Matroska Audio (.mka) file using // mkvextract (for global tags) and mkvmerge (for attachment discovery). // dhowden/tag does not support the Matroska container format. -func readAudioTagsFromMKA(path, mkvextractPath, mkvmergePath string) (AudioTags, error) { +func readAudioTagsFromMKA(ctx context.Context, path, mkvextractPath, mkvmergePath string) (AudioTags, error) { xmlTmp, err := os.CreateTemp("", "mka-tags-*.xml") if err != nil { return AudioTags{}, fmt.Errorf("create temp tags file: %w", err) @@ -193,7 +198,7 @@ func readAudioTagsFromMKA(path, mkvextractPath, mkvmergePath string) (AudioTags, defer os.Remove(xmlTmp.Name()) // A failed extract leaves the XML empty, which parseMKVTagsXML reads as no tags. - cmd := exec.Command(mkvextractPath, path, "tags", xmlTmp.Name()) + cmd := command(ctx, mkvextractPath, path, "tags", xmlTmp.Name()) cmd.Stdout = io.Discard cmd.Stderr = io.Discard _ = cmd.Run() @@ -210,7 +215,7 @@ func readAudioTagsFromMKA(path, mkvextractPath, mkvmergePath string) (AudioTags, } // Fall back to the MKV container header date when DATE_RECORDED is absent. if dateStr == "" { - if dt, ok, _ := readMKVHeaderDate(mkvmergePath, path); ok { + if dt, ok, _ := readMKVHeaderDate(ctx, mkvmergePath, path); ok { dateStr = dt.UTC().Format("2006-01-02") } } @@ -219,7 +224,7 @@ func readAudioTagsFromMKA(path, mkvextractPath, mkvmergePath string) (AudioTags, year = dt.Year() } - coverData, coverMIME := extractMKACover(mkvextractPath, mkvmergePath, path) + coverData, coverMIME := extractMKACover(ctx, mkvextractPath, mkvmergePath, path) return AudioTags{ Title: lvl30["TITLE"], @@ -238,7 +243,7 @@ func readAudioTagsFromMKA(path, mkvextractPath, mkvmergePath string) (AudioTags, // extractReplayGainTags reads existing ReplayGain/R128 tags from mkvPath and // returns them keyed by level. Returns empty maps on any error. -func extractReplayGainTags(mkvextractPath, mkvPath string) (extra50, extra30 map[string]string) { +func extractReplayGainTags(ctx context.Context, mkvextractPath, mkvPath string) (extra50, extra30 map[string]string) { extra50 = make(map[string]string) extra30 = make(map[string]string) @@ -249,7 +254,7 @@ func extractReplayGainTags(mkvextractPath, mkvPath string) (extra50, extra30 map tmp.Close() defer os.Remove(tmp.Name()) - cmd := exec.Command(mkvextractPath, mkvPath, "tags", tmp.Name()) + cmd := command(ctx, mkvextractPath, mkvPath, "tags", tmp.Name()) cmd.Stdout = io.Discard cmd.Stderr = io.Discard _ = cmd.Run() // a failed extract leaves the XML empty, which parseMKVTagsXML reads as no tags diff --git a/mkv-music/tags_mka_test.go b/mkv-music/tags_mka_test.go index 1de2bf6..d711f03 100644 --- a/mkv-music/tags_mka_test.go +++ b/mkv-music/tags_mka_test.go @@ -277,7 +277,7 @@ func TestParseMKVTagsXML_FirstValueWins(t *testing.T) { func TestReadMKVHeaderDate_MissingMkvmerge_Errors(t *testing.T) { dir := t.TempDir() - _, ok, err := readMKVHeaderDate(filepath.Join(dir, "no-mkvmerge.exe"), filepath.Join(dir, "a.mkv")) + _, ok, err := readMKVHeaderDate(t.Context(), filepath.Join(dir, "no-mkvmerge.exe"), filepath.Join(dir, "a.mkv")) if err == nil || ok { t.Errorf("ok = %v, err = %v; want false and an error", ok, err) } @@ -291,7 +291,7 @@ func TestReadMKVHeaderDate_RealMkvmerge(t *testing.T) { } dir := t.TempDir() - if _, ok, err := readMKVHeaderDate(mkvmerge, filepath.Join(dir, "gone.mkv")); err == nil || ok { + if _, ok, err := readMKVHeaderDate(t.Context(), mkvmerge, filepath.Join(dir, "gone.mkv")); err == nil || ok { t.Errorf("missing file: ok = %v, err = %v; want false and an error", ok, err) } @@ -299,7 +299,7 @@ func TestReadMKVHeaderDate_RealMkvmerge(t *testing.T) { if err := os.WriteFile(notMKV, []byte("not a matroska file"), 0o644); err != nil { t.Fatal(err) } - if _, ok, err := readMKVHeaderDate(mkvmerge, notMKV); err != nil || ok { + if _, ok, err := readMKVHeaderDate(t.Context(), mkvmerge, notMKV); err != nil || ok { t.Errorf("unrecognised file: ok = %v, err = %v; want false and no error (no date header)", ok, err) } } diff --git a/mkv-music/token_redaction_test.go b/mkv-music/token_redaction_test.go index c5aec27..5e7c18a 100644 --- a/mkv-music/token_redaction_test.go +++ b/mkv-music/token_redaction_test.go @@ -26,11 +26,11 @@ func TestPlexClient_SendsTokenInHeader(t *testing.T) { defer srv.Close() c := newHTTPPlexClient(srv.URL, secretToken) - _, _ = c.FindArtistByTitle("Artist") - if err := c.RefreshMetadata("77"); err != nil { + _, _ = c.FindArtistByTitle(t.Context(), "Artist") + if err := c.RefreshMetadata(t.Context(), "77"); err != nil { t.Errorf("RefreshMetadata: %v", err) } - if err := c.AnalyzeMedia("77"); err != nil { + if err := c.AnalyzeMedia(t.Context(), "77"); err != nil { t.Errorf("AnalyzeMedia: %v", err) } if requests < 3 { @@ -43,8 +43,8 @@ func TestPlexClient_TransportErrorOmitsToken(t *testing.T) { srv.Close() // requests now fail in the transport with a *url.Error c := newHTTPPlexClient(srv.URL, secretToken) - _, getErr := c.FindArtistByTitle("Artist") - for _, err := range []error{getErr, c.AnalyzeMedia("77")} { + _, getErr := c.FindArtistByTitle(t.Context(), "Artist") + for _, err := range []error{getErr, c.AnalyzeMedia(t.Context(), "77")} { if err == nil { t.Fatal("expected a connection error") } @@ -77,7 +77,7 @@ func TestPlexClient_RedirectToOtherHostDropsToken(t *testing.T) { })) t.Cleanup(plex.Close) - _, _ = newHTTPPlexClient(plex.URL, secretToken).FindArtistByTitle("Artist") + _, _ = newHTTPPlexClient(plex.URL, secretToken).FindArtistByTitle(t.Context(), "Artist") if len(sameHostTokens) == 0 || sameHostTokens[0] != secretToken { t.Errorf("same-host redirect tokens = %q, want %q kept", sameHostTokens, secretToken) } From d456f347be48fd26d7e0c37e991229806472d2a7 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 6 Dec 2026 00:51:16 +1300 Subject: [PATCH 2/4] fix(mkv-music): skip videos at end of input, finish the Plex artist in progress, list stopped videos --- README.md | 2 +- mkv-music/audio_timestamps.go | 5 +- mkv-music/interrupt_run_test.go | 260 ++++++++++++++++++++++++-------- mkv-music/main.go | 48 +++--- mkv-music/processor.go | 85 +++++++---- mkv-music/tag_outcome_test.go | 2 +- mkv-music/tags.go | 4 +- 7 files changed, 297 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index 6bb881b..39fcefb 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,7 @@ date header has no timestamps to sync; one already up to date isn't counted), and lists each one whose tag copy or timestamp sync failed, naming the step (`tags`, `date` when the header can't be read, `ctime`, `mtime`). -Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips the audio timestamp sync, lists any artists it hasn't asked Plex to refresh, prints the summary headed `INTERRUPTED` and exits 130. A video in progress is finished. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress, and that video's tags or timestamps are left as they were for the next run. `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. +Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips the audio timestamp sync, lists the artists Plex wasn't asked to refresh, prints the summary headed `INTERRUPTED` and exits 130. A video already past its prompt is finished, as is the Plex refresh of the artist in progress. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress and abandons the Plex request; a tag copy or timestamp sync it stops is skipped and listed under `TAGGING INTERRUPTED` (rerun with a `--cutoff-date` that covers it). `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. With input ended (stdin closed), each prompt skips its video. ### Flags diff --git a/mkv-music/audio_timestamps.go b/mkv-music/audio_timestamps.go index 20d0323..3d54245 100644 --- a/mkv-music/audio_timestamps.go +++ b/mkv-music/audio_timestamps.go @@ -28,10 +28,11 @@ type AudioTimestampStats struct { // SetAudioTimestamps walks root, reads each audio file's embedded date tag and // sets OS file timestamps. Files older than cutoffDate are skipped. Once ctx -// is cancelled it starts no more files, and it returns ctx's error. +// is cancelled it starts no more files; it returns ctx's error, or the kill +// context's once that stopped exiftool. func SetAudioTimestamps(ctx context.Context, root string, cutoffDate time.Time, timer FileTimer, exiftoolPath string) (AudioTimestampStats, error) { var stats AudioTimestampStats - // The callback returns only ctx's error. + // The callback returns only ctx's or the kill context's error. err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { if ctx.Err() != nil { return ctx.Err() diff --git a/mkv-music/interrupt_run_test.go b/mkv-music/interrupt_run_test.go index a809f58..e650f83 100644 --- a/mkv-music/interrupt_run_test.go +++ b/mkv-music/interrupt_run_test.go @@ -3,6 +3,8 @@ package main import ( "context" "errors" + "fmt" + "io" "net/http" "net/http/httptest" "os" @@ -198,29 +200,34 @@ func (f *killingTagger) MKVDate(ctx context.Context, mkvPath string) (time.Time, return f.fakeTagger.MKVDate(ctx, mkvPath) } -// A tagging step the kill stops is neither a failure nor a copy, and is -// reported as left unchanged; the next run redoes it. +// A tagging step the kill stops is neither a failure nor a copy: it is +// reported as left unchanged and listed in the summary, for the next run. func TestCopyTags_KilledIsNotAFailure(t *testing.T) { - for _, tc := range []struct{ at, notice string }{ - {"match", "[STOP] Interrupted; tags left unchanged"}, - {"copy", "[STOP] Interrupted; tags left unchanged"}, - {"date", "[STOP] Interrupted; timestamps left unchanged"}, + for _, tc := range []struct { + at, notice string + upToDate bool + }{ + {"match", "[STOP] Interrupted; tags left unchanged", false}, + {"copy", "[STOP] Interrupted; tags left unchanged", false}, + {"date", "[STOP] Interrupted; timestamps left unchanged", false}, + {"date", "[STOP] Interrupted; timestamps left unchanged", true}, } { - t.Run(tc.at, func(t *testing.T) { + t.Run(fmt.Sprintf("%s up-to-date=%v", tc.at, tc.upToDate), func(t *testing.T) { ctx, stop, kill := newInterruptContext() defer kill() stop() dir := t.TempDir() tagger := &killingTagger{at: tc.at, kill: kill} tagger.date = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC) + tagger.tagsMatch = tc.upToDate p := NewProcessor(dir, "", nil) p.tagger, p.timer = tagger, &fakeFileTimer{} mkv := filepath.Join(dir, "01 - Foo - Foo-video.mkv") out := captureStdout(t, func() { p.copyTagsIfConfigured(ctx, mkv, "01 - Foo", "01 - Foo - Foo", "", dir, mkv, map[string]string{"01 - Foo": "01 - Foo.flac"}) }) - if got := p.Tags(); got.Copied != 0 || len(got.Failed) != 0 { - t.Errorf("outcome = %+v, want neither copied nor failed", got) + if got := p.Tags(); got.Copied != 0 || len(got.Failed) != 0 || !slices.Equal(got.Stopped, []string{mkv}) { + t.Errorf("outcome = %+v, want neither copied nor failed, and listed as stopped", got) } if tc.at == "match" && len(tagger.calls) != 0 { t.Errorf("copied after a killed check: %v", tagger.calls) @@ -232,52 +239,84 @@ func TestCopyTags_KilledIsNotAFailure(t *testing.T) { } } -// fakePlex records the calls made to it. +// fakePlex records the calls made to it. Like the real client, a call whose +// ctx is done sends nothing and returns ctx's error. on runs for each call +// sent, keyed by the call ("refresh A"), before it answers. type fakePlex struct { - calls []string - find func() // runs as FindArtistByTitle is called - onRefresh func() // runs as RefreshMetadata is called + calls []string + on map[string]func() } -func (f *fakePlex) FindArtistByTitle(_ context.Context, title string) (string, error) { - f.calls = append(f.calls, "find "+title) - if f.find != nil { - f.find() +func (f *fakePlex) call(ctx context.Context, name string) error { + if err := ctx.Err(); err != nil { + return err } - return title, nil + f.calls = append(f.calls, name) + if hook := f.on[name]; hook != nil { + hook() + } + return ctx.Err() } -func (f *fakePlex) RefreshMetadata(_ context.Context, key string) error { - f.calls = append(f.calls, "refresh "+key) - if f.onRefresh != nil { - f.onRefresh() - } - return nil +func (f *fakePlex) FindArtistByTitle(ctx context.Context, title string) (string, error) { + return title, f.call(ctx, "find "+title) } -func (f *fakePlex) AnalyzeMedia(_ context.Context, key string) error { - f.calls = append(f.calls, "analyze "+key) - return nil +func (f *fakePlex) RefreshMetadata(ctx context.Context, key string) error { + return f.call(ctx, "refresh "+key) } -// An interrupt during the Plex refresh lists the artists left unrefreshed, -// the one in progress included, and sends nothing more. +func (f *fakePlex) AnalyzeMedia(ctx context.Context, key string) error { + return f.call(ctx, "analyze "+key) +} + +// The first Ctrl+C during the Plex refresh lets the artist in progress +// finish; the second abandons it. Either way the artists left unrefreshed are +// listed, and nothing is reported as a Plex failure. func TestRefreshPlexArtists_Interrupted(t *testing.T) { - ctx, stop := context.WithCancel(t.Context()) - defer stop() - plex := &fakePlex{find: stop} - p := NewProcessor(t.TempDir(), "", nil) - p.plex = plex - for _, a := range []string{"C", "A", "B"} { - p.touchedArtists[a] = struct{}{} + refreshed := func(a string) string { + return ` [Plex] Refreshed artist: "` + a + `"` + "\n" + ` [Plex] Media analysis triggered for "` + a + `"` + "\n" } - out := captureStdout(t, func() { p.refreshPlexArtists(ctx) }) - if !slices.Equal(plex.calls, []string{"find A"}) { - t.Errorf("calls = %v, want only the first find", plex.calls) + notRefreshed := func(as ...string) string { + var s string + for _, a := range as { + s += ` [Plex] Not refreshed (interrupted): "` + a + `"` + "\n" + } + return s } - want := " [Plex] Not refreshed (interrupted): \"A\"\n [Plex] Not refreshed (interrupted): \"B\"\n [Plex] Not refreshed (interrupted): \"C\"\n" - if out != want { - t.Errorf("output = %q, want %q", out, want) + for _, tc := range []struct { + at, signal string + calls []string + out string + }{ + {"find A", "stop", []string{"find A", "refresh A", "analyze A"}, refreshed("A") + notRefreshed("B", "C")}, + {"refresh A", "stop", []string{"find A", "refresh A", "analyze A"}, refreshed("A") + notRefreshed("B", "C")}, + {"analyze B", "stop", []string{"find A", "refresh A", "analyze A", "find B", "refresh B", "analyze B"}, refreshed("A") + refreshed("B") + notRefreshed("C")}, + {"find A", "kill", []string{"find A"}, notRefreshed("A", "B", "C")}, + {"refresh A", "kill", []string{"find A", "refresh A"}, notRefreshed("A", "B", "C")}, + {"analyze A", "kill", []string{"find A", "refresh A", "analyze A"}, ` [Plex] Refreshed artist: "A"` + "\n" + ` [Plex] Not analysed (interrupted): "A"` + "\n" + notRefreshed("B", "C")}, + } { + t.Run(tc.signal+" at "+tc.at, func(t *testing.T) { + ctx, stop, kill := newInterruptContext() + defer kill() + hook := stop + if tc.signal == "kill" { + hook = func() { stop(); kill() } + } + plex := &fakePlex{on: map[string]func(){tc.at: hook}} + p := NewProcessor(t.TempDir(), "", nil) + p.plex = plex + for _, a := range []string{"C", "A", "B"} { + p.touchedArtists[a] = struct{}{} + } + out := captureStdout(t, func() { p.refreshPlexArtists(ctx) }) + if !slices.Equal(plex.calls, tc.calls) { + t.Errorf("calls = %v, want %v", plex.calls, tc.calls) + } + if out != tc.out { + t.Errorf("output = %q, want %q", out, tc.out) + } + }) } } @@ -413,7 +452,8 @@ func TestSetAudioTimestamps_KilledIsTheInterrupt(t *testing.T) { } } -// An interrupted run's summary is headed INTERRUPTED, and it exits 130. +// An interrupted run's summary is headed INTERRUPTED, never claims that +// nothing was skipped, lists the videos whose tagging it stopped, and exits 130. func TestFinish(t *testing.T) { cancelled, cancel := context.WithCancel(t.Context()) cancel() @@ -430,6 +470,13 @@ func TestFinish(t *testing.T) { if code != tc.code || !strings.Contains(out, tc.heading) || !strings.Contains(out, "x.mkv") { t.Errorf("exit %d, output %q; want %d under %q", code, out, tc.code, tc.heading) } + out = captureStdout(t, func() { finish(tc.ctx, Stats{}, nil, nil, TagOutcome{Stopped: []string{"s.mkv"}}) }) + if claims := strings.Contains(out, "No music videos were skipped or unmatched."); claims == (tc.code == 130) { + t.Errorf("exit %d: output %q; want the all-clear only when not interrupted", tc.code, out) + } + if !strings.Contains(out, "--- TAGGING INTERRUPTED (1) ---\ns.mkv") { + t.Errorf("output %q doesn't list the stopped video", out) + } } } @@ -460,23 +507,6 @@ func TestSetAudioTimestamps_InterruptedBeforeStart(t *testing.T) { } } -// An interrupt during an artist's refresh leaves the rest unrefreshed. -func TestRefreshPlexArtists_InterruptedAfterFind(t *testing.T) { - ctx, stop := context.WithCancel(t.Context()) - defer stop() - plex := &fakePlex{onRefresh: stop} - p := NewProcessor(t.TempDir(), "", nil) - p.plex = plex - p.touchedArtists["A"], p.touchedArtists["B"] = struct{}{}, struct{}{} - out := captureStdout(t, func() { p.refreshPlexArtists(ctx) }) - if !slices.Equal(plex.calls, []string{"find A", "refresh A", "analyze A"}) { - t.Errorf("calls = %v, want only A's", plex.calls) - } - if !strings.Contains(out, "Not refreshed (interrupted): \"B\"") || strings.Contains(out, "Not refreshed (interrupted): \"A\"") { - t.Errorf("output = %q, want only B listed", out) - } -} - // Once the walk sees the interrupt it reads no further, so even an // unreadable root goes unreported. func TestRun_InterruptedBeforeStartWalksNothing(t *testing.T) { @@ -537,3 +567,113 @@ func TestTagger_KillReachesEveryRead(t *testing.T) { }) } } + +// failingTagger is a fakeTagger whose copy fails on its own (a locked file) +// while the kill fires. +type failingTagger struct { + fakeTagger + kill func() +} + +func (f *failingTagger) CopyTagsToMKV(context.Context, string, string, string) error { + f.kill() + return errors.New("mkvpropedit: exit status 2") +} + +// A copy that fails on its own is a failure, even if the kill fired meanwhile. +func TestCopyTags_FailureDuringKillIsAFailure(t *testing.T) { + ctx, stop, kill := newInterruptContext() + defer kill() + stop() + dir := t.TempDir() + p := NewProcessor(dir, "", nil) + p.tagger = &failingTagger{kill: kill} + mkv := filepath.Join(dir, "01 - Foo - Foo-video.mkv") + captureStdout(t, func() { + p.copyTagsIfConfigured(ctx, mkv, "01 - Foo", "01 - Foo - Foo", "", dir, mkv, map[string]string{"01 - Foo": "01 - Foo.flac"}) + }) + if got := p.Tags(); len(got.Failed) != 1 || len(got.Stopped) != 0 { + t.Errorf("outcome = %+v, want one failure", got) + } +} + +// With input ended (stdin closed), each video offered a rename is skipped and +// listed, as before the interrupt handling; so is one whose ignore-pattern +// prompt finds input ended, and no pattern is saved for it. +func TestRun_EndOfInputSkips(t *testing.T) { + for _, input := range []string{"", "i"} { + t.Run(fmt.Sprintf("input %q", input), func(t *testing.T) { + root := artistDirs(t, misnamed...) + ignoreFile := filepath.Join(t.TempDir(), "ignore.json") + p := NewProcessor(root, ignoreFile, newPrompter(t.Context(), strings.NewReader(input), io.Discard)) + var stats Stats + var skipped []string + out := captureStdout(t, func() { stats, skipped, _ = p.Run(t.Context()) }) + if stats.Skipped != 2 || len(skipped) != 2 || stats.Renamed != 0 { + t.Errorf("stats = %+v, skipped %v; want both skipped", stats, skipped) + } + if !strings.Contains(out, "[SKIP] No answer (EOF); kept original name.") { + t.Errorf("output missing the skip notice:\n%s", out) + } + if _, err := os.Stat(ignoreFile); !errors.Is(err, os.ErrNotExist) { + t.Errorf("ignore file written: %v", err) + } + }) + } +} + +// A rename the first Ctrl+C lands on is finished, tags and all; the next +// video is not started. +func TestRun_InterruptAfterRenameFinishesIt(t *testing.T) { + root := artistDirs(t, misnamed...) + ctx, stop := context.WithCancel(t.Context()) + defer stop() + prompter := &stopAtPrompter{answers: []string{"r", "r"}, stopAt: -1} + p := NewProcessor(root, "", prompter) + tagger := &fakeTagger{} + p.tagger, p.timer = tagger, &fakeFileTimer{} + p.renamer = func(from, to string) error { stop(); return os.Rename(from, to) } + var stats Stats + captureStdout(t, func() { stats, _, _ = p.Run(ctx) }) + renamed := filepath.Join(root, "A", "01 - Foo - Foo-video.mkv") + if stats.Renamed != 1 || !exists(t, root, "A/01 - Foo - Foo-video.mkv") || !exists(t, root, "B/01 - Barr.mkv") { + t.Errorf("stats = %+v; want only A's video renamed", stats) + } + if len(tagger.calls) != 1 || tagger.calls[0].mkvPath != renamed || p.Tags().Copied != 1 { + t.Errorf("copies = %v, outcome %+v; want the renamed video tagged", tagger.calls, p.Tags()) + } + if len(prompter.asked) != 1 { + t.Errorf("asked %d questions, want 1", len(prompter.asked)) + } + if _, ok := p.touchedArtists["A"]; !ok { + t.Error("artist A not marked for the Plex refresh") + } +} + +// The first Ctrl+C stops the run before the next video in the same folder. +func TestRun_InterruptStopsWithinFolder(t *testing.T) { + root := artistDirs(t, "A/01 - Foo.flac", "A/01 - Foo - Foo-video.mkv", "A/02 - Bar.flac", "A/02 - Bar - Bar-video.mkv") + ctx, stop := context.WithCancel(t.Context()) + defer stop() + tagger := &stoppingTagger{stop: stop} + p := NewProcessor(root, "", &stopAtPrompter{stopAt: -1}) + p.tagger = tagger + captureStdout(t, func() { p.Run(ctx) }) + if len(tagger.calls) != 1 { + t.Errorf("copies = %v, want the first video's only", tagger.calls) + } +} + +// The audio pass is skipped once the run is interrupted. +func TestSyncAudio_SkippedAfterInterrupt(t *testing.T) { + root := artistDirs(t, "A/01 - Foo.flac") + ctx, cancel := context.WithCancel(t.Context()) + cancel() + timer := &fakeFileTimer{} + if out := captureStdout(t, func() { syncAudio(ctx, root, time.Time{}, timer, "exiftool", nil) }); out != "" { + t.Errorf("output = %q, want nothing", out) + } + if len(timer.setTimes) != 0 { + t.Errorf("timestamps set: %v", timer.setTimes) + } +} diff --git a/mkv-music/main.go b/mkv-music/main.go index 6d43e2e..2bbc6d7 100644 --- a/mkv-music/main.go +++ b/mkv-music/main.go @@ -94,37 +94,51 @@ func main() { stats, skippedVideos, unmatchedVideos := processor.Run(ctx) - // Audio timestamp pass: set OS file timestamps from embedded date tags. exiftoolPath, exiftoolErr := exec.LookPath("exiftool") + syncAudio(ctx, root, cutoff, &win32FileTimer{}, exiftoolPath, exiftoolErr) + + os.Exit(finish(ctx, stats, skippedVideos, unmatchedVideos, processor.Tags())) +} + +// syncAudio runs the audio timestamp pass, which sets OS file timestamps from +// embedded date tags, unless the run was interrupted first. +func syncAudio(ctx context.Context, root string, cutoff time.Time, timer FileTimer, exiftoolPath string, exiftoolErr error) { switch { - case ctx.Err() != nil: // interrupted: no next step + case ctx.Err() != nil: case exiftoolErr != nil: fmt.Fprintln(os.Stderr, "Warning: exiftool not found in PATH — audio timestamp sync disabled") default: fmt.Printf("\n--- Syncing audio file timestamps in: %s ---\n\n", root) - aStats, _ := SetAudioTimestamps(ctx, root, cutoff, &win32FileTimer{}, exiftoolPath) - fmt.Printf("\nAudio timestamps: %d updated, %d no date, %d failed, %d skipped (old)\n", - aStats.Updated, aStats.NoDate, aStats.Failed, aStats.SkippedOld) + aStats, err := SetAudioTimestamps(ctx, root, cutoff, timer, exiftoolPath) + interrupted := "" + if err != nil { + interrupted = " (interrupted)" + } + fmt.Printf("\nAudio timestamps%s: %d updated, %d no date, %d failed, %d skipped (old)\n", + interrupted, aStats.Updated, aStats.NoDate, aStats.Failed, aStats.SkippedOld) } - - os.Exit(finish(ctx, stats, skippedVideos, unmatchedVideos, processor.Tags())) } -// finish prints the run summary and returns the exit code: 130, under an -// INTERRUPTED heading, once ctx is cancelled. +// finish prints the run summary and returns the exit code: 130 once ctx is +// cancelled. func finish(ctx context.Context, stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) int { - if ctx.Err() != nil { - printRunSummary("INTERRUPTED", stats, skippedVideos, unmatchedVideos, tags) + interrupted := ctx.Err() != nil + printRunSummary(interrupted, stats, skippedVideos, unmatchedVideos, tags) + if interrupted { return 130 } - printRunSummary("Scan Complete", stats, skippedVideos, unmatchedVideos, tags) return 0 } -// printRunSummary prints the end-of-run report under heading: unmatched and -// skipped videos, old files skipped, and the tagging outcome. -func printRunSummary(heading string, stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) { - fmt.Printf("\n--- %s ---\n", heading) +// printRunSummary prints the end-of-run report: unmatched and skipped videos, +// old files skipped, and the tagging outcome. An interrupted run is headed +// INTERRUPTED, and never claims that nothing was skipped. +func printRunSummary(interrupted bool, stats Stats, skippedVideos, unmatchedVideos []string, tags TagOutcome) { + if interrupted { + fmt.Println("\n--- INTERRUPTED ---") + } else { + fmt.Println("\n--- Scan Complete ---") + } if len(unmatchedVideos) > 0 { fmt.Printf("\n--- UNMATCHED MUSIC VIDEOS (%d) ---\n", len(unmatchedVideos)) for _, path := range unmatchedVideos { @@ -137,7 +151,7 @@ func printRunSummary(heading string, stats Stats, skippedVideos, unmatchedVideos fmt.Println(path) } } - if len(unmatchedVideos) == 0 && len(skippedVideos) == 0 { + if len(unmatchedVideos) == 0 && len(skippedVideos) == 0 && !interrupted { fmt.Println("\nNo music videos were skipped or unmatched.") } if stats.SkippedOld > 0 { diff --git a/mkv-music/processor.go b/mkv-music/processor.go index 8dd4109..e8c23ef 100644 --- a/mkv-music/processor.go +++ b/mkv-music/processor.go @@ -33,8 +33,9 @@ type Stats struct { // TagOutcome is a run's tag-copying result. type TagOutcome struct { - Copied int // MKVs whose tags were copied and, when they have a date header, timestamps synced - Failed []string // " (failed: …)" for each MKV a tagging step failed on + Copied int // MKVs whose tags were copied and, when they have a date header, timestamps synced + Failed []string // " (failed: …)" for each MKV a tagging step failed on + Stopped []string // MKVs whose tag copy or timestamp sync the kill stopped } // IgnoreData holds ignore patterns used when fuzzy-matching video filenames to @@ -95,21 +96,28 @@ func (p *Processor) markArtistTouched(dir string) { // refreshPlexArtists triggers a Plex metadata refresh for every artist dir // that was touched during this run. No-op when Plex is not configured. Once -// ctx is cancelled it lists the artists left unrefreshed instead. +// ctx is cancelled it lists the artists left unrefreshed instead. The requests +// run on ctx's kill context, so the first Ctrl+C lets the artist in progress +// finish and the second abandons it. func (p *Processor) refreshPlexArtists(ctx context.Context) { if p.plex == nil || len(p.touchedArtists) == 0 { return } + req := killContext(ctx) artists := slices.Sorted(maps.Keys(p.touchedArtists)) - for i, artist := range artists { - ratingKey, err := "", ctx.Err() - if err == nil { - ratingKey, err = p.plex.FindArtistByTitle(ctx, artist) + notRefreshed := func(from int) { + for _, a := range artists[from:] { + fmt.Printf(" [Plex] Not refreshed (interrupted): %q\n", a) } + } + for i, artist := range artists { if ctx.Err() != nil { - for _, a := range artists[i:] { - fmt.Printf(" [Plex] Not refreshed (interrupted): %q\n", a) - } + notRefreshed(i) + return + } + ratingKey, err := p.plex.FindArtistByTitle(req, artist) + if req.Err() != nil { + notRefreshed(i) return } if err != nil { @@ -120,12 +128,23 @@ func (p *Processor) refreshPlexArtists(ctx context.Context) { } continue } - if err := p.plex.RefreshMetadata(ctx, ratingKey); err != nil { + err = p.plex.RefreshMetadata(req, ratingKey) + if req.Err() != nil { + notRefreshed(i) + return + } + if err != nil { fmt.Printf(" [Plex] Refresh failed for %q: %v\n", artist, err) } else { fmt.Printf(" [Plex] Refreshed artist: %q\n", artist) } - if err := p.plex.AnalyzeMedia(ctx, ratingKey); err != nil { + err = p.plex.AnalyzeMedia(req, ratingKey) + if req.Err() != nil { + fmt.Printf(" [Plex] Not analysed (interrupted): %q\n", artist) + notRefreshed(i + 1) + return + } + if err != nil { fmt.Printf(" [Plex] Analyze failed for %q: %v\n", artist, err) } else { fmt.Printf(" [Plex] Media analysis triggered for %q\n", artist) @@ -619,8 +638,8 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, } titleSuffix := strings.Join(parts, " ") match, err := p.tagger.TagsMatchMKV(ctx, audioFullPath, mkvPath, titleSuffix) - if err != nil && killContext(ctx).Err() != nil { - tagsStopped(mkvPath) + if errors.Is(err, context.Canceled) { + p.tagsStopped(mkvPath, "tags") return } if err == nil && match { @@ -630,8 +649,8 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, return } if err := p.tagger.CopyTagsToMKV(ctx, audioFullPath, mkvPath, titleSuffix); err != nil { - if killContext(ctx).Err() != nil { - tagsStopped(mkvPath) + if errors.Is(err, context.Canceled) { // the kill, before any edit + p.tagsStopped(mkvPath, "tags") return } fmt.Printf(" [ERROR] tag copy failed for %s: %v\n", filepath.Base(mkvPath), err) @@ -647,10 +666,11 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, } } -// tagsStopped reports that the kill stopped reading mkvPath's tags, so they -// were left as they were; the next run copies them. -func tagsStopped(mkvPath string) { - fmt.Printf(" [STOP] Interrupted; tags left unchanged: %s\n", filepath.Base(mkvPath)) +// tagsStopped reports that the kill stopped mkvPath's step ("tags" or +// "timestamps") before it changed anything, and lists mkvPath in the summary. +func (p *Processor) tagsStopped(mkvPath, step string) { + fmt.Printf(" [STOP] Interrupted; %s left unchanged: %s\n", step, filepath.Base(mkvPath)) + p.tags.Stopped = append(p.tags.Stopped, mkvPath) } // recordTagFailure adds mkvPath to the run's tagging failures, naming the @@ -671,8 +691,8 @@ func (p *Processor) syncTimestamps(ctx context.Context, mkvPath string) (failed return nil, false } dt, ok, err := p.tagger.MKVDate(ctx, mkvPath) - if err != nil && killContext(ctx).Err() != nil { - fmt.Printf(" [STOP] Interrupted; timestamps left unchanged: %s\n", filepath.Base(mkvPath)) + if errors.Is(err, context.Canceled) { + p.tagsStopped(mkvPath, "timestamps") return nil, true } if err != nil { @@ -820,7 +840,7 @@ func (p *Processor) processVideo(ctx context.Context, videoDir, videoFile string return promptStopped() } if err != nil { - return "" + return noAnswer(err) } choice = strings.ToLower(strings.TrimSpace(choice)) @@ -860,7 +880,7 @@ func (p *Processor) processVideo(ctx context.Context, videoDir, videoFile string return promptStopped() } if err != nil { - return "" + return noAnswer(err) } if strings.TrimSpace(pattern) == "" { pattern = diff @@ -890,6 +910,13 @@ func (p *Processor) processVideo(ctx context.Context, videoDir, videoFile string return "" } +// noAnswer reports a prompt that got no answer, such as at the end of input, +// and skips the video. +func noAnswer(err error) string { + fmt.Printf(" [SKIP] No answer (%v); kept original name.\n", err) + return "skipped" +} + // promptStopped reports an interrupt at a prompt, whose answer is ignored. func promptStopped() string { fmt.Println(" [STOP] Interrupted; left unchanged.") @@ -897,8 +924,8 @@ func promptStopped() string { } // Run walks root, groups files by directory, and processes each video file. -// Once ctx is cancelled it starts no more files, and skips any it hadn't -// started when the walk was cut short. +// Once ctx is cancelled it starts no more files (a walk cut short processes +// none), and refreshPlexArtists lists the artists it didn't refresh. func (p *Processor) Run(ctx context.Context) (Stats, []string, []string) { var stats Stats var skippedVideos []string @@ -977,6 +1004,12 @@ func (p *Processor) Tags() TagOutcome { // printTagSummary prints a run's tagging outcome and lists the MKVs a tagging // step failed on. Prints nothing when no MKV was copied or failed. func printTagSummary(tags TagOutcome) { + if len(tags.Stopped) > 0 { + fmt.Printf("\n--- TAGGING INTERRUPTED (%d) ---\n", len(tags.Stopped)) + for _, f := range tags.Stopped { + fmt.Println(f) + } + } if len(tags.Failed) > 0 { fmt.Printf("\n--- TAGGING FAILURES (%d) ---\n", len(tags.Failed)) for _, f := range tags.Failed { diff --git a/mkv-music/tag_outcome_test.go b/mkv-music/tag_outcome_test.go index 6982d41..9e2b975 100644 --- a/mkv-music/tag_outcome_test.go +++ b/mkv-music/tag_outcome_test.go @@ -254,7 +254,7 @@ func TestRun_TagOutcome_NonMKV_NotTagged(t *testing.T) { func TestPrintRunSummary_IncludesTagOutcome(t *testing.T) { out := captureStdout(t, func() { - printRunSummary("Scan Complete", Stats{SkippedOld: 2}, []string{`C:\m\skipped.mkv`}, nil, + printRunSummary(false, Stats{SkippedOld: 2}, []string{`C:\m\skipped.mkv`}, nil, TagOutcome{Copied: 1, Failed: []string{`C:\m\b.mkv (failed: tags)`}}) }) want := []string{ diff --git a/mkv-music/tags.go b/mkv-music/tags.go index 093af0f..5d41ef5 100644 --- a/mkv-music/tags.go +++ b/mkv-music/tags.go @@ -17,8 +17,8 @@ import ( // MusicVideoTagger copies tags and cover art from a source audio file to a // destination MKV file, and can check whether the MKV tags already match. -// Each returns the kill context's error once ctx's kill (see command) has -// stopped a read, and CopyTagsToMKV then edits nothing. +// Once ctx's kill (see command) has fired, each may return the kill +// context's error, and CopyTagsToMKV then edits nothing. type MusicVideoTagger interface { // TagsMatchMKV returns true if the MKV at mkvPath already has tags // identical to what CopyTagsToMKV would write from audioPath. From 348624f01a350cd17d21feccb88139734c308041 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 6 Dec 2026 09:20:17 +1300 Subject: [PATCH 3/4] fix(mkv-music): keep a Plex refresh that succeeded before the kill, name the stopped step and the skipped audio pass --- README.md | 2 +- mkv-music/interrupt_run_test.go | 159 ++++++++++++++++++++++++++------ mkv-music/main.go | 3 +- mkv-music/processor.go | 29 +++--- mkv-music/tag_outcome_test.go | 5 + mkv-music/tags.go | 3 +- 6 files changed, 160 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 39fcefb..0f9dcd6 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,7 @@ date header has no timestamps to sync; one already up to date isn't counted), and lists each one whose tag copy or timestamp sync failed, naming the step (`tags`, `date` when the header can't be read, `ctime`, `mtime`). -Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips the audio timestamp sync, lists the artists Plex wasn't asked to refresh, prints the summary headed `INTERRUPTED` and exits 130. A video already past its prompt is finished, as is the Plex refresh of the artist in progress. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress and abandons the Plex request; a tag copy or timestamp sync it stops is skipped and listed under `TAGGING INTERRUPTED` (rerun with a `--cutoff-date` that covers it). `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. With input ended (stdin closed), each prompt skips its video. +Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips or stops the audio timestamp sync, lists the artists it didn't refresh, prints the summary headed `INTERRUPTED` and exits 130. A video already past its prompt is finished, as is the Plex refresh of the artist in progress. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress and abandons the Plex request; a tag copy or timestamp sync it stops is skipped and listed under `TAGGING INTERRUPTED` with the step it stopped (rerun with a `--cutoff-date` that covers it). `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. With input ended (stdin closed), each prompt skips its video. ### Flags diff --git a/mkv-music/interrupt_run_test.go b/mkv-music/interrupt_run_test.go index e650f83..ac04625 100644 --- a/mkv-music/interrupt_run_test.go +++ b/mkv-music/interrupt_run_test.go @@ -204,13 +204,13 @@ func (f *killingTagger) MKVDate(ctx context.Context, mkvPath string) (time.Time, // reported as left unchanged and listed in the summary, for the next run. func TestCopyTags_KilledIsNotAFailure(t *testing.T) { for _, tc := range []struct { - at, notice string - upToDate bool + at, step string + upToDate bool }{ - {"match", "[STOP] Interrupted; tags left unchanged", false}, - {"copy", "[STOP] Interrupted; tags left unchanged", false}, - {"date", "[STOP] Interrupted; timestamps left unchanged", false}, - {"date", "[STOP] Interrupted; timestamps left unchanged", true}, + {"match", "tags", false}, + {"copy", "tags", false}, + {"date", "timestamps", false}, + {"date", "timestamps", true}, } { t.Run(fmt.Sprintf("%s up-to-date=%v", tc.at, tc.upToDate), func(t *testing.T) { ctx, stop, kill := newInterruptContext() @@ -226,14 +226,15 @@ func TestCopyTags_KilledIsNotAFailure(t *testing.T) { out := captureStdout(t, func() { p.copyTagsIfConfigured(ctx, mkv, "01 - Foo", "01 - Foo - Foo", "", dir, mkv, map[string]string{"01 - Foo": "01 - Foo.flac"}) }) - if got := p.Tags(); got.Copied != 0 || len(got.Failed) != 0 || !slices.Equal(got.Stopped, []string{mkv}) { - t.Errorf("outcome = %+v, want neither copied nor failed, and listed as stopped", got) + want := mkv + " (stopped: " + tc.step + ")" + if got := p.Tags(); got.Copied != 0 || len(got.Failed) != 0 || !slices.Equal(got.Stopped, []string{want}) { + t.Errorf("outcome = %+v, want neither copied nor failed, and listed as %q", got, want) } if tc.at == "match" && len(tagger.calls) != 0 { t.Errorf("copied after a killed check: %v", tagger.calls) } - if !strings.Contains(out, tc.notice) { - t.Errorf("output missing %q:\n%s", tc.notice, out) + if notice := "[STOP] Interrupted; " + tc.step + " left unchanged"; !strings.Contains(out, notice) { + t.Errorf("output missing %q:\n%s", notice, out) } }) } @@ -241,10 +242,11 @@ func TestCopyTags_KilledIsNotAFailure(t *testing.T) { // fakePlex records the calls made to it. Like the real client, a call whose // ctx is done sends nothing and returns ctx's error. on runs for each call -// sent, keyed by the call ("refresh A"), before it answers. +// sent, keyed by the call ("refresh A"), before it answers; after runs once the +// call has its answer, so a kill there follows a request that succeeded. type fakePlex struct { - calls []string - on map[string]func() + calls []string + on, after map[string]func() } func (f *fakePlex) call(ctx context.Context, name string) error { @@ -255,7 +257,11 @@ func (f *fakePlex) call(ctx context.Context, name string) error { if hook := f.on[name]; hook != nil { hook() } - return ctx.Err() + err := ctx.Err() + if hook := f.after[name]; hook != nil { + hook() + } + return err } func (f *fakePlex) FindArtistByTitle(ctx context.Context, title string) (string, error) { @@ -272,7 +278,8 @@ func (f *fakePlex) AnalyzeMedia(ctx context.Context, key string) error { // The first Ctrl+C during the Plex refresh lets the artist in progress // finish; the second abandons it. Either way the artists left unrefreshed are -// listed, and nothing is reported as a Plex failure. +// listed, and nothing is reported as a Plex failure. A "kill after" lands just +// after a call succeeded: a refresh or analyze that succeeded still counts. func TestRefreshPlexArtists_Interrupted(t *testing.T) { refreshed := func(a string) string { return ` [Plex] Refreshed artist: "` + a + `"` + "\n" + ` [Plex] Media analysis triggered for "` + a + `"` + "\n" @@ -295,15 +302,24 @@ func TestRefreshPlexArtists_Interrupted(t *testing.T) { {"find A", "kill", []string{"find A"}, notRefreshed("A", "B", "C")}, {"refresh A", "kill", []string{"find A", "refresh A"}, notRefreshed("A", "B", "C")}, {"analyze A", "kill", []string{"find A", "refresh A", "analyze A"}, ` [Plex] Refreshed artist: "A"` + "\n" + ` [Plex] Not analysed (interrupted): "A"` + "\n" + notRefreshed("B", "C")}, + {"find B", "kill", []string{"find A", "refresh A", "analyze A", "find B"}, refreshed("A") + notRefreshed("B", "C")}, + {"refresh B", "kill", []string{"find A", "refresh A", "analyze A", "find B", "refresh B"}, refreshed("A") + notRefreshed("B", "C")}, + {"find A", "kill after", []string{"find A"}, notRefreshed("A", "B", "C")}, + {"refresh A", "kill after", []string{"find A", "refresh A"}, ` [Plex] Refreshed artist: "A"` + "\n" + ` [Plex] Not analysed (interrupted): "A"` + "\n" + notRefreshed("B", "C")}, + {"analyze A", "kill after", []string{"find A", "refresh A", "analyze A"}, refreshed("A") + notRefreshed("B", "C")}, } { t.Run(tc.signal+" at "+tc.at, func(t *testing.T) { ctx, stop, kill := newInterruptContext() defer kill() - hook := stop - if tc.signal == "kill" { - hook = func() { stop(); kill() } + plex := &fakePlex{} + switch tc.signal { + case "stop": + plex.on = map[string]func(){tc.at: stop} + case "kill": + plex.on = map[string]func(){tc.at: func() { stop(); kill() }} + case "kill after": + plex.after = map[string]func(){tc.at: func() { stop(); kill() }} } - plex := &fakePlex{on: map[string]func(){tc.at: hook}} p := NewProcessor(t.TempDir(), "", nil) p.plex = plex for _, a := range []string{"C", "A", "B"} { @@ -634,10 +650,14 @@ func TestRun_InterruptAfterRenameFinishesIt(t *testing.T) { p.tagger, p.timer = tagger, &fakeFileTimer{} p.renamer = func(from, to string) error { stop(); return os.Rename(from, to) } var stats Stats - captureStdout(t, func() { stats, _, _ = p.Run(ctx) }) + var skipped []string + out := captureStdout(t, func() { stats, skipped, _ = p.Run(ctx) }) renamed := filepath.Join(root, "A", "01 - Foo - Foo-video.mkv") - if stats.Renamed != 1 || !exists(t, root, "A/01 - Foo - Foo-video.mkv") || !exists(t, root, "B/01 - Barr.mkv") { - t.Errorf("stats = %+v; want only A's video renamed", stats) + if stats != (Stats{Renamed: 1}) || len(skipped) != 0 || !exists(t, root, "A/01 - Foo - Foo-video.mkv") || !exists(t, root, "B/01 - Barr.mkv") || exists(t, root, "B/01 - Bar - Bar-video.mkv") { + t.Errorf("stats = %+v, skipped %v; want only A's video renamed", stats, skipped) + } + if strings.Contains(out, "[STOP]") { + t.Errorf("output has a stop notice:\n%s", out) } if len(tagger.calls) != 1 || tagger.calls[0].mkvPath != renamed || p.Tags().Copied != 1 { t.Errorf("copies = %v, outcome %+v; want the renamed video tagged", tagger.calls, p.Tags()) @@ -659,21 +679,108 @@ func TestRun_InterruptStopsWithinFolder(t *testing.T) { p := NewProcessor(root, "", &stopAtPrompter{stopAt: -1}) p.tagger = tagger captureStdout(t, func() { p.Run(ctx) }) - if len(tagger.calls) != 1 { + first := filepath.Join(root, "A", "01 - Foo - Foo-video.mkv") + if len(tagger.calls) != 1 || tagger.calls[0].mkvPath != first { t.Errorf("copies = %v, want the first video's only", tagger.calls) } + if got := p.Tags(); got.Copied != 1 || len(got.Stopped) != 0 || len(got.Failed) != 0 { + t.Errorf("outcome = %+v, want one copied", got) + } } -// The audio pass is skipped once the run is interrupted. +// The audio pass is skipped once the run is interrupted, and says so. func TestSyncAudio_SkippedAfterInterrupt(t *testing.T) { root := artistDirs(t, "A/01 - Foo.flac") ctx, cancel := context.WithCancel(t.Context()) cancel() timer := &fakeFileTimer{} - if out := captureStdout(t, func() { syncAudio(ctx, root, time.Time{}, timer, "exiftool", nil) }); out != "" { - t.Errorf("output = %q, want nothing", out) + if out := captureStdout(t, func() { syncAudio(ctx, root, time.Time{}, timer, "exiftool", nil) }); out != "\nAudio timestamp sync skipped (interrupted)\n" { + t.Errorf("output = %q, want only the skip notice", out) } if len(timer.setTimes) != 0 { t.Errorf("timestamps set: %v", timer.setTimes) } } + +// An audio pass the kill stops part-way reports its counts as interrupted. +func TestSyncAudio_KilledMidPass(t *testing.T) { + exiftool, readyFile := helperTool(t, "sleep") + root := artistDirs(t, "A/01 - Foo.mka") + ctx, stop, kill := newInterruptContext() + t.Cleanup(kill) + out := captureStdout(t, func() { + result := make(chan error, 1) + go func() { + syncAudio(ctx, root, time.Time{}, &fakeFileTimer{}, exiftool, nil) + result <- nil + }() + waitReady(t, readyFile, result) + stop() + kill() + _ = awaitErr(t, result) + }) + if want := "\nAudio timestamps (interrupted): 0 updated, 0 no date, 0 failed, 0 skipped (old)\n"; !strings.HasSuffix(out, want) { + t.Errorf("output = %q, want it to end %q", out, want) + } +} + +// dateFailingTagger is a fakeTagger whose date read fails on its own (a +// corrupt header) while the kill fires. +type dateFailingTagger struct { + fakeTagger + kill func() +} + +func (f *dateFailingTagger) MKVDate(context.Context, string) (time.Time, bool, error) { + f.kill() + return time.Time{}, false, errors.New("mkvmerge: exit status 2") +} + +// A date read that fails on its own is a failure, even if the kill fired +// meanwhile: only the kill's own error is a stop. +func TestSyncTimestamps_FailureDuringKillIsAFailure(t *testing.T) { + ctx, stop, kill := newInterruptContext() + defer kill() + stop() + dir := t.TempDir() + p := NewProcessor(dir, "", nil) + p.tagger, p.timer = &dateFailingTagger{kill: kill}, &fakeFileTimer{} + mkv := filepath.Join(dir, "01 - Foo - Foo-video.mkv") + captureStdout(t, func() { + p.copyTagsIfConfigured(ctx, mkv, "01 - Foo", "01 - Foo - Foo", "", dir, mkv, map[string]string{"01 - Foo": "01 - Foo.flac"}) + }) + want := []string{mkv + " (failed: date)"} + if got := p.Tags(); !slices.Equal(got.Failed, want) || len(got.Stopped) != 0 || got.Copied != 0 { + t.Errorf("outcome = %+v, want failed %v", got, want) + } +} + +// errPrompter fails every question with err. +type errPrompter struct { + err error + asked int +} + +func (p *errPrompter) Ask(string) (string, error) { + p.asked++ + return "", p.err +} + +// A prompt that fails other than at the end of input skips its video, names +// the error, and goes on to the next. +func TestRun_PromptErrorSkips(t *testing.T) { + root := artistDirs(t, misnamed...) + prompter := &errPrompter{err: errors.New("read stdin: broken")} + var stats Stats + var skipped []string + out := captureStdout(t, func() { stats, skipped, _ = NewProcessor(root, "", prompter).Run(t.Context()) }) + if stats != (Stats{Skipped: 2}) || len(skipped) != 2 || prompter.asked != 2 { + t.Errorf("stats = %+v, skipped %v, asked %d; want both skipped", stats, skipped, prompter.asked) + } + if !strings.Contains(out, "[SKIP] No answer (read stdin: broken); kept original name.") { + t.Errorf("output missing the skip notice:\n%s", out) + } + if !exists(t, root, "A/01 - Fooo.mkv") || !exists(t, root, "B/01 - Barr.mkv") { + t.Error("a video was renamed") + } +} diff --git a/mkv-music/main.go b/mkv-music/main.go index 2bbc6d7..76ad1a1 100644 --- a/mkv-music/main.go +++ b/mkv-music/main.go @@ -105,8 +105,9 @@ func main() { func syncAudio(ctx context.Context, root string, cutoff time.Time, timer FileTimer, exiftoolPath string, exiftoolErr error) { switch { case ctx.Err() != nil: + fmt.Println("\nAudio timestamp sync skipped (interrupted)") case exiftoolErr != nil: - fmt.Fprintln(os.Stderr, "Warning: exiftool not found in PATH — audio timestamp sync disabled") + fmt.Fprintf(os.Stderr, "Warning: audio timestamp sync disabled: %v\n", exiftoolErr) default: fmt.Printf("\n--- Syncing audio file timestamps in: %s ---\n\n", root) aStats, err := SetAudioTimestamps(ctx, root, cutoff, timer, exiftoolPath) diff --git a/mkv-music/processor.go b/mkv-music/processor.go index e8c23ef..2bf2a65 100644 --- a/mkv-music/processor.go +++ b/mkv-music/processor.go @@ -35,7 +35,7 @@ type Stats struct { type TagOutcome struct { Copied int // MKVs whose tags were copied and, when they have a date header, timestamps synced Failed []string // " (failed: …)" for each MKV a tagging step failed on - Stopped []string // MKVs whose tag copy or timestamp sync the kill stopped + Stopped []string // " (stopped: tags|timestamps)" for each MKV whose step the kill stopped } // IgnoreData holds ignore patterns used when fuzzy-matching video filenames to @@ -128,8 +128,9 @@ func (p *Processor) refreshPlexArtists(ctx context.Context) { } continue } + // A request that succeeded just before the kill still counts. err = p.plex.RefreshMetadata(req, ratingKey) - if req.Err() != nil { + if err != nil && req.Err() != nil { notRefreshed(i) return } @@ -139,7 +140,7 @@ func (p *Processor) refreshPlexArtists(ctx context.Context) { fmt.Printf(" [Plex] Refreshed artist: %q\n", artist) } err = p.plex.AnalyzeMedia(req, ratingKey) - if req.Err() != nil { + if err != nil && req.Err() != nil { fmt.Printf(" [Plex] Not analysed (interrupted): %q\n", artist) notRefreshed(i + 1) return @@ -639,7 +640,7 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, titleSuffix := strings.Join(parts, " ") match, err := p.tagger.TagsMatchMKV(ctx, audioFullPath, mkvPath, titleSuffix) if errors.Is(err, context.Canceled) { - p.tagsStopped(mkvPath, "tags") + p.stepStopped(mkvPath, "tags") return } if err == nil && match { @@ -650,7 +651,7 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, } if err := p.tagger.CopyTagsToMKV(ctx, audioFullPath, mkvPath, titleSuffix); err != nil { if errors.Is(err, context.Canceled) { // the kill, before any edit - p.tagsStopped(mkvPath, "tags") + p.stepStopped(mkvPath, "tags") return } fmt.Printf(" [ERROR] tag copy failed for %s: %v\n", filepath.Base(mkvPath), err) @@ -666,11 +667,11 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, } } -// tagsStopped reports that the kill stopped mkvPath's step ("tags" or +// stepStopped reports that the kill stopped mkvPath's step ("tags" or // "timestamps") before it changed anything, and lists mkvPath in the summary. -func (p *Processor) tagsStopped(mkvPath, step string) { +func (p *Processor) stepStopped(mkvPath, step string) { fmt.Printf(" [STOP] Interrupted; %s left unchanged: %s\n", step, filepath.Base(mkvPath)) - p.tags.Stopped = append(p.tags.Stopped, mkvPath) + p.tags.Stopped = append(p.tags.Stopped, fmt.Sprintf("%s (stopped: %s)", mkvPath, step)) } // recordTagFailure adds mkvPath to the run's tagging failures, naming the @@ -692,7 +693,7 @@ func (p *Processor) syncTimestamps(ctx context.Context, mkvPath string) (failed } dt, ok, err := p.tagger.MKVDate(ctx, mkvPath) if errors.Is(err, context.Canceled) { - p.tagsStopped(mkvPath, "timestamps") + p.stepStopped(mkvPath, "timestamps") return nil, true } if err != nil { @@ -1001,8 +1002,9 @@ func (p *Processor) Tags() TagOutcome { return p.tags } -// printTagSummary prints a run's tagging outcome and lists the MKVs a tagging -// step failed on. Prints nothing when no MKV was copied or failed. +// printTagSummary prints a run's tagging outcome and lists the MKVs whose +// tagging step the kill stopped or that failed. Prints nothing when no MKV was +// copied, stopped or failed. func printTagSummary(tags TagOutcome) { if len(tags.Stopped) > 0 { fmt.Printf("\n--- TAGGING INTERRUPTED (%d) ---\n", len(tags.Stopped)) @@ -1016,7 +1018,10 @@ func printTagSummary(tags TagOutcome) { fmt.Println(f) } } - if tags.Copied > 0 || len(tags.Failed) > 0 { + switch { + case len(tags.Stopped) > 0: + fmt.Printf("\nTags: %d copied, %d failed, %d stopped\n", tags.Copied, len(tags.Failed), len(tags.Stopped)) + case tags.Copied > 0 || len(tags.Failed) > 0: fmt.Printf("\nTags: %d copied, %d failed\n", tags.Copied, len(tags.Failed)) } } diff --git a/mkv-music/tag_outcome_test.go b/mkv-music/tag_outcome_test.go index 9e2b975..3632e29 100644 --- a/mkv-music/tag_outcome_test.go +++ b/mkv-music/tag_outcome_test.go @@ -289,6 +289,11 @@ func TestPrintTagSummary(t *testing.T) { TagOutcome{Copied: 1, Failed: []string{`C:\m\a.mkv (failed: tags)`, `C:\m\b.mkv (failed: mtime)`}}, []string{"--- TAGGING FAILURES (2) ---", `C:\m\a.mkv (failed: tags)`, `C:\m\b.mkv (failed: mtime)`, "Tags: 1 copied, 2 failed"}, }, + { + "only stopped", + TagOutcome{Stopped: []string{`C:\m\a.mkv (stopped: timestamps)`}}, + []string{"--- TAGGING INTERRUPTED (1) ---", `C:\m\a.mkv (stopped: timestamps)`, "Tags: 0 copied, 0 failed, 1 stopped"}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/mkv-music/tags.go b/mkv-music/tags.go index 5d41ef5..5e32e2d 100644 --- a/mkv-music/tags.go +++ b/mkv-music/tags.go @@ -22,7 +22,8 @@ import ( type MusicVideoTagger interface { // TagsMatchMKV returns true if the MKV at mkvPath already has tags // identical to what CopyTagsToMKV would write from audioPath. - // Returns false (not true) on any error so the caller falls back to copying. + // Returns false (not true) on any error. The caller stops on the kill's + // context.Canceled and otherwise falls back to copying. TagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) CopyTagsToMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) error // MKVDate returns the date stored in the MKV container header and true, From 0fdc33d349dc167748c99633dca33e45c82a5257 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 6 Dec 2026 09:29:24 +1300 Subject: [PATCH 4/4] test(mkv-music): pin the exiftool warning and the Tags line; fix round-3 comment wording --- README.md | 2 +- mkv-music/interrupt_run_test.go | 34 +++++++++++++++++++++++++++++---- mkv-music/main.go | 3 ++- mkv-music/processor.go | 7 ++++--- mkv-music/processor_test.go | 18 ++++++++++++++--- mkv-music/tag_outcome_test.go | 3 +++ mkv-music/tags.go | 3 +-- 7 files changed, 56 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0f9dcd6..33ce035 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,7 @@ date header has no timestamps to sync; one already up to date isn't counted), and lists each one whose tag copy or timestamp sync failed, naming the step (`tags`, `date` when the header can't be read, `ctime`, `mtime`). -Ctrl+C stops before the next video, and at a prompt without acting on the answer, then skips or stops the audio timestamp sync, lists the artists it didn't refresh, prints the summary headed `INTERRUPTED` and exits 130. A video already past its prompt is finished, as is the Plex refresh of the artist in progress. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress and abandons the Plex request; a tag copy or timestamp sync it stops is skipped and listed under `TAGGING INTERRUPTED` with the step it stopped (rerun with a `--cutoff-date` that covers it). `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. With input ended (stdin closed), each prompt skips its video. +Ctrl+C stops before the next video, and at a prompt without acting on the answer, then lists the artists it didn't refresh, skips or stops the audio timestamp sync, prints the summary headed `INTERRUPTED` and exits 130. A video already past its prompt is finished, as is the Plex refresh of the artist in progress. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge`, `mkvextract` or `exiftool` in progress and abandons the Plex request; a tag copy or timestamp sync it stops is skipped and listed under `TAGGING INTERRUPTED` with the step it stopped (rerun with a `--cutoff-date` that covers it). `mkvpropedit` edits in place, so it is never killed. From then on only Ctrl+C quits, at once. With input ended (stdin closed), each prompt skips its video. ### Flags diff --git a/mkv-music/interrupt_run_test.go b/mkv-music/interrupt_run_test.go index ac04625..71d85c0 100644 --- a/mkv-music/interrupt_run_test.go +++ b/mkv-music/interrupt_run_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "os" + "os/exec" "path/filepath" "slices" "strings" @@ -279,7 +280,8 @@ func (f *fakePlex) AnalyzeMedia(ctx context.Context, key string) error { // The first Ctrl+C during the Plex refresh lets the artist in progress // finish; the second abandons it. Either way the artists left unrefreshed are // listed, and nothing is reported as a Plex failure. A "kill after" lands just -// after a call succeeded: a refresh or analyze that succeeded still counts. +// after a call succeeded: a refresh or analyze that succeeded still counts (a +// find doesn't: its refresh never goes out). func TestRefreshPlexArtists_Interrupted(t *testing.T) { refreshed := func(a string) string { return ` [Plex] Refreshed artist: "` + a + `"` + "\n" + ` [Plex] Media analysis triggered for "` + a + `"` + "\n" @@ -702,6 +704,30 @@ func TestSyncAudio_SkippedAfterInterrupt(t *testing.T) { } } +// Without a usable exiftool the audio pass is skipped with a warning naming +// the error, unless the run was interrupted, which takes precedence. +func TestSyncAudio_ExiftoolUnavailable(t *testing.T) { + cancelled, cancel := context.WithCancel(t.Context()) + cancel() + for _, tc := range []struct { + ctx context.Context + stdout, stderr string + }{ + {t.Context(), "", "Warning: audio timestamp sync disabled: " + exec.ErrDot.Error() + "\n"}, + {cancelled, "\nAudio timestamp sync skipped (interrupted)\n", ""}, + } { + root := artistDirs(t, "A/01 - Foo.flac") + timer := &fakeFileTimer{} + var stdout string + stderr := captureStderr(t, func() { + stdout = captureStdout(t, func() { syncAudio(tc.ctx, root, time.Time{}, timer, "", exec.ErrDot) }) + }) + if stdout != tc.stdout || stderr != tc.stderr || len(timer.setTimes) != 0 { + t.Errorf("stdout %q, stderr %q, set %v; want %q, %q, nothing set", stdout, stderr, timer.setTimes, tc.stdout, tc.stderr) + } + } +} + // An audio pass the kill stops part-way reports its counts as interrupted. func TestSyncAudio_KilledMidPass(t *testing.T) { exiftool, readyFile := helperTool(t, "sleep") @@ -724,8 +750,8 @@ func TestSyncAudio_KilledMidPass(t *testing.T) { } } -// dateFailingTagger is a fakeTagger whose date read fails on its own (a -// corrupt header) while the kill fires. +// dateFailingTagger is a fakeTagger whose date read fails on its own (output +// it can't parse) while the kill fires. type dateFailingTagger struct { fakeTagger kill func() @@ -733,7 +759,7 @@ type dateFailingTagger struct { func (f *dateFailingTagger) MKVDate(context.Context, string) (time.Time, bool, error) { f.kill() - return time.Time{}, false, errors.New("mkvmerge: exit status 2") + return time.Time{}, false, errors.New("parse mkvmerge output: unexpected end of JSON input") } // A date read that fails on its own is a failure, even if the kill fired diff --git a/mkv-music/main.go b/mkv-music/main.go index 76ad1a1..33e6d2e 100644 --- a/mkv-music/main.go +++ b/mkv-music/main.go @@ -101,7 +101,8 @@ func main() { } // syncAudio runs the audio timestamp pass, which sets OS file timestamps from -// embedded date tags, unless the run was interrupted first. +// embedded date tags. It skips the pass, saying why, when the run was +// interrupted first or exiftool is unavailable. func syncAudio(ctx context.Context, root string, cutoff time.Time, timer FileTimer, exiftoolPath string, exiftoolErr error) { switch { case ctx.Err() != nil: diff --git a/mkv-music/processor.go b/mkv-music/processor.go index 2bf2a65..e3300ba 100644 --- a/mkv-music/processor.go +++ b/mkv-music/processor.go @@ -98,7 +98,8 @@ func (p *Processor) markArtistTouched(dir string) { // that was touched during this run. No-op when Plex is not configured. Once // ctx is cancelled it lists the artists left unrefreshed instead. The requests // run on ctx's kill context, so the first Ctrl+C lets the artist in progress -// finish and the second abandons it. +// finish and the second abandons it, though a refresh or analyze that already +// succeeded still counts. func (p *Processor) refreshPlexArtists(ctx context.Context) { if p.plex == nil || len(p.touchedArtists) == 0 { return @@ -128,7 +129,6 @@ func (p *Processor) refreshPlexArtists(ctx context.Context) { } continue } - // A request that succeeded just before the kill still counts. err = p.plex.RefreshMetadata(req, ratingKey) if err != nil && req.Err() != nil { notRefreshed(i) @@ -668,7 +668,8 @@ func (p *Processor) copyTagsIfConfigured(ctx context.Context, mkvPath, matchKey, } // stepStopped reports that the kill stopped mkvPath's step ("tags" or -// "timestamps") before it changed anything, and lists mkvPath in the summary. +// "timestamps") before that step changed anything, and records it for the +// summary as " (stopped: )". func (p *Processor) stepStopped(mkvPath, step string) { fmt.Printf(" [STOP] Interrupted; %s left unchanged: %s\n", step, filepath.Base(mkvPath)) p.tags.Stopped = append(p.tags.Stopped, fmt.Sprintf("%s (stopped: %s)", mkvPath, step)) diff --git a/mkv-music/processor_test.go b/mkv-music/processor_test.go index 90e7ad0..5510db5 100644 --- a/mkv-music/processor_test.go +++ b/mkv-music/processor_test.go @@ -820,14 +820,26 @@ func TestRun_RenameKeepsFilePatternText(t *testing.T) { // captureStdout returns what fn prints to os.Stdout. func captureStdout(t *testing.T, fn func()) string { + t.Helper() + return captureFile(t, &os.Stdout, fn) +} + +// captureStderr returns what fn prints to os.Stderr. +func captureStderr(t *testing.T, fn func()) string { + t.Helper() + return captureFile(t, &os.Stderr, fn) +} + +// captureFile returns what fn writes to *f, which it swaps for a pipe. +func captureFile(t *testing.T, f **os.File, fn func()) string { t.Helper() r, w, err := os.Pipe() if err != nil { t.Fatal(err) } - orig := os.Stdout - os.Stdout = w - defer func() { os.Stdout = orig }() + orig := *f + *f = w + defer func() { *f = orig }() done := make(chan []byte) go func() { b, _ := io.ReadAll(r); done <- b }() fn() diff --git a/mkv-music/tag_outcome_test.go b/mkv-music/tag_outcome_test.go index 3632e29..fa22cc6 100644 --- a/mkv-music/tag_outcome_test.go +++ b/mkv-music/tag_outcome_test.go @@ -306,6 +306,9 @@ func TestPrintTagSummary(t *testing.T) { t.Errorf("output missing %q:\n%s", w, out) } } + if len(tt.tags.Stopped) == 0 && strings.Contains(out, "stopped") { + t.Errorf("output mentions stopped with nothing stopped:\n%s", out) + } }) } } diff --git a/mkv-music/tags.go b/mkv-music/tags.go index 5e32e2d..deee3d1 100644 --- a/mkv-music/tags.go +++ b/mkv-music/tags.go @@ -262,8 +262,7 @@ func (t *realMusicVideoTagger) MKVDate(ctx context.Context, mkvPath string) (tim // TagsMatchMKV implements MusicVideoTagger. // It reads tags from audioPath and the current tags embedded in mkvPath, -// then compares all text fields and cover art. -// Returns false on any error so the caller falls back to copying. +// then compares all text fields and cover art. Returns false on any error. func (t *realMusicVideoTagger) TagsMatchMKV(ctx context.Context, audioPath, mkvPath, titleSuffix string) (bool, error) { match, err := t.tagsMatchMKV(ctx, audioPath, mkvPath, titleSuffix) if killErr := killContext(ctx).Err(); killErr != nil { // a killed read can look like a match