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 @@ -175,6 +175,8 @@ The tool scans recursively and prints a summary:
Scanned: 120 Fixed: 14 Failed: 0 LangFixes: 9 FlagFixes: 8
```

Ctrl+C stops before the next file or lookup, and at a prompt without acting on the answer, then prints the summary headed `INTERRUPTED` and exits 130. A file already read still gets the fixes that need no answer, and a conversion or trim in progress finishes. A second Ctrl+C, closing the terminal or SIGTERM also kills the `mkvmerge` or `mkvextract` in progress and starts no more edits; a conversion or trim it kills leaves the file as it was. `mkvpropedit` edits in place, so it is never killed. Files the interrupt skips aren't recorded as failures, and an earlier failure stays on the retry list unless the run got all the way through that file. From then on only Ctrl+C quits, at once, which can leave an `mkv-audit-*.tmp` beside the file being converted or trimmed.

### Dependencies

- `mkvmerge` — reads track metadata; also used for container conversion and track trimming remux
Expand Down
36 changes: 36 additions & 0 deletions mkv-audit/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-audit/command_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//go:build !unix && !windows

package main

import (
"os"
"os/exec"
)

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

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

// pipeSignals is empty: there is no SIGPIPE to catch.
var pipeSignals []os.Signal
173 changes: 173 additions & 0 deletions mkv-audit/command_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package main

import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
)

const (
// helperEnv names the helperModes entry a child started by these tests runs.
helperEnv = "MKVAUDIT_TEST_HELPER"
// readyEnv names a file the helper creates once ready, for a child whose
// stdout the test can't read.
readyEnv = "MKVAUDIT_TEST_READY"
)

// helperModes are the children the command tests start: the test binary run
// with helperEnv set, which TestMain hands to the mode instead of the tests.
// Those startHelper runs say "ready" first.
var helperModes = map[string]func(){
// sleep sleeps for a minute or until killed.
"sleep": func() { ready(); time.Sleep(time.Minute) },
}

// ready prints "ready", and creates the file readyEnv names, if any.
func ready() {
fmt.Println("ready")
if path := os.Getenv(readyEnv); path != "" {
if err := os.WriteFile(path, nil, 0o600); err != nil {
fmt.Fprintln(os.Stderr, "write ready file:", err)
os.Exit(1)
}
}
}

func TestMain(m *testing.M) {
if mode := os.Getenv(helperEnv); mode != "" {
helper, ok := helperModes[mode]
if !ok {
fmt.Fprintln(os.Stderr, "unknown helper mode", mode)
os.Exit(2)
}
helper()
os.Exit(0)
}
os.Exit(m.Run())
}

// startHelper runs the helper mode through command and waits for it to say
// "ready", returning its stdout and a channel that gets commandErr's verdict
// once it ends. Cleanup kills it, so a failed test leaves nothing running, and
// logs its stderr if the test failed.
func startHelper(ctx context.Context, t *testing.T, kill func(), mode string) (*bufio.Reader, <-chan error) {
t.Helper()
cmd := command(ctx, os.Args[0])
cmd.Env = append(os.Environ(), helperEnv+"="+mode)
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
var stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = w, &stderr
result := make(chan error, 1)
finished := make(chan struct{})
go func() {
result <- commandErr(ctx, cmd.Run())
w.Close() // EOF for a reader still waiting on a helper that never spoke
close(finished)
}()
t.Cleanup(func() {
kill()
<-finished
r.Close()
if t.Failed() && stderr.Len() > 0 {
t.Logf("helper stderr:\n%s", stderr.String())
}
})
out := bufio.NewReader(r)
if line := readLine(t, out); line != "ready" {
t.Fatalf("helper said %q, want ready", line)
}
return out, result
}

// readLine reads one line from the helper, failing the test on EOF.
func readLine(t *testing.T, r *bufio.Reader) string {
t.Helper()
line, err := r.ReadString('\n')
if err != nil {
t.Fatalf("helper said %q, then %v", line, err)
}
return strings.TrimSpace(line)
}

// wantKilled waits for startHelper's verdict, which must be the kill.
func wantKilled(t *testing.T, result <-chan error) {
t.Helper()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Errorf("commandErr = %v, want context.Canceled", err)
}
case <-time.After(10 * time.Second):
t.Fatal("child still running after the kill")
}
}

// wantRunning fails the test if the helper ends within a short wait.
func wantRunning(t *testing.T, result <-chan error) {
t.Helper()
select {
case err := <-result:
t.Fatalf("child ended after the first interrupt: %v", err)
case <-time.After(300 * time.Millisecond):
}
}

// Without an interrupt context, command's processes are never killed.
func TestKillContext_DefaultNeverCancels(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
if err := killContext(ctx).Err(); err != nil {
t.Errorf("killContext of a cancelled plain context: %v", err)
}
}

// commandErr reports a failure as the kill only once the kill context, not
// ctx, is cancelled, and never turns a success into an error.
func TestCommandErr(t *testing.T) {
failed := errors.New("exit status 1")
cases := []struct {
name string
stop, kill bool
in, want error
}{
{"running", false, false, failed, failed},
{"stopped", true, false, failed, failed},
{"killed", true, true, failed, context.Canceled},
{"killed but succeeded", true, true, nil, nil},
}
for _, tc := range cases {
ctx, stop, kill := newInterruptContext()
if tc.stop {
stop()
}
if tc.kill {
kill()
}
if got := commandErr(ctx, tc.in); !errors.Is(got, tc.want) || (tc.want == nil) != (got == nil) {
t.Errorf("%s: commandErr = %v, want %v", tc.name, got, tc.want)
}
stop()
kill()
}
}

// A child outlives the first interrupt and is killed by the second, which
// commandErr reports as the interrupt.
func TestCommand_SecondInterruptKillsChild(t *testing.T) {
ctx, stop, kill := newInterruptContext()
_, result := startHelper(ctx, t, kill, "sleep")

stop()
wantRunning(t, result)
kill()
wantKilled(t, result)
}
32 changes: 32 additions & 0 deletions mkv-audit/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-audit by default without reaching its isolated
// children, so it catches them and kills the children itself.
var quitSignals = []os.Signal{syscall.SIGTERM, syscall.SIGHUP}

// pipeSignals is SIGPIPE, which ends mkv-audit on a write to a broken stdout or
// stderr unless caught. Caught (not ignored, which the children would inherit), the
// write fails instead.
var pipeSignals = []os.Signal{syscall.SIGPIPE}
Loading