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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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

| Flag | Description |
Expand Down
44 changes: 28 additions & 16 deletions mkv-music/audio_timestamps.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main

import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
Expand All @@ -27,11 +27,16 @@ 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; 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 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 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()
}
if err != nil {
fmt.Printf("[AUDIO] Skipping unreadable %s: %v\n", path, err)
return nil
Expand All @@ -50,7 +55,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++
Expand All @@ -65,21 +73,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",
Expand All @@ -89,23 +98,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 {
Expand Down
36 changes: 36 additions & 0 deletions mkv-music/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package main

import (
"context"
"os/exec"
)

// killKey keys the kill context a ctx carries for command: cancelling ctx lets
// command's processes finish, and cancelling the kill context kills them.
type killKey struct{}

// killContext is the kill context ctx carries, or one never cancelled.
func killContext(ctx context.Context) context.Context {
if kill, ok := ctx.Value(killKey{}).(context.Context); ok {
return kill
}
return context.WithoutCancel(ctx)
}

// command returns a Cmd for name that the terminal's Ctrl+C doesn't reach
// (isolate). Only ctx's kill context kills it: ctx's own cancellation and
// deadline never do.
func command(ctx context.Context, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(killContext(ctx), name, args...)
isolate(cmd)
return cmd
}

// commandErr is err from running a command, or the kill context's error once
// that is cancelled: any failure is then reported as the kill, its likely cause.
func commandErr(ctx context.Context, err error) error {
if killErr := killContext(ctx).Err(); err != nil && killErr != nil {
return killErr
}
return err
}
17 changes: 17 additions & 0 deletions mkv-music/command_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//go:build !unix && !windows

package main

import (
"os"
"os/exec"
)

// isolate does nothing where there are no process groups.
func isolate(*exec.Cmd) {}

// quitSignals is empty: without isolate, children get the same signals.
var quitSignals []os.Signal

// pipeSignals is empty: there is no SIGPIPE to catch.
var pipeSignals []os.Signal
184 changes: 184 additions & 0 deletions mkv-music/command_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
32 changes: 32 additions & 0 deletions mkv-music/command_unix.go
Original file line number Diff line number Diff line change
@@ -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}
Loading