aboutsummaryrefslogtreecommitdiff
path: root/cmd/krino/sort.go
blob: 5e52f8427d2f6c6821e2a97174b448b187c95e25 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"os/signal"
	"sort"
	"strings"
	"syscall"
	"unicode/utf8"

	"golang.org/x/term"

	"krino/internal/engine"
	"krino/internal/journal"
	"krino/internal/lock"
	"krino/internal/plan"
	"krino/internal/scan"
	"krino/internal/xdg"
)

// stdin is os.Stdin, threaded through this seam rather than referenced
// directly: cmdSort's terminal check, installSignalHandler and reviewDir
// all read it, and a test must never depend on what the ambient test
// binary's stdin happens to be (fix round 2026-09-12/item 4). If it were
// ever a real terminal, code that only worked by assuming otherwise would
// fall through to the interactive prompt and block the test suite on a
// keypress - the same kind of hang the lock-cancellation test was built to
// never risk. Tests point this at something guaranteed non-terminal
// (commands_test.go's home helper) instead of relying on a claim about
// what go test does with stdin.
var stdin = os.Stdin

// zeroOutcome is the per-directory outcome line for a directory that had
// nothing applied to it - either because nothing was actionable, or
// because the user chose [s] or [q] - so the same wording is not retyped
// (and cannot drift) across the three places it applies.
const zeroOutcome = "0 applied · 0 failed · 0 declined"

// cmdSort plans and, from Task 7, applies the included directories: flags
// are checked before any config is read, a bad config stops the whole run
// before scanning (spec §11), and one journal.Writer, run id and
// plan.Claims cover every directory in the run. See docs/design.md
// §8.2-§8.4 and §11 for the flow this follows.
func cmdSort(g *globals, names []string, stdout, stderr io.Writer) int {
	if g.yes && g.dry {
		return usageError(stderr, "-y and -n cannot be used together")
	}
	if g.json && !g.dry {
		return usageError(stderr, "--json is only valid with -n")
	}
	minAge, setMinAge, err := minAgeOverride(g)
	if err != nil {
		return usageError(stderr, err.Error())
	}

	e, errs := engine.Load(mainFile(g), names...)
	if len(errs) > 0 {
		printDiags(stderr, errs)
		return 2
	}
	if setMinAge {
		applyMinAge(e, minAge)
	}
	e.CacheDir = cacheDir()
	p := palette{on: colourOn(g, stdout)}

	// Spec §8.4: with neither -y nor -n, krino asks; asking a non-terminal
	// stdin would just hang (or read garbage), so it refuses instead.
	if !g.yes && !g.dry && !term.IsTerminal(int(stdin.Fd())) {
		return usageError(stderr, "refusing to prompt: stdin is not a terminal (use -y or -n)")
	}

	// Ruling 5: internal/tui deliberately does not trap signals - a package
	// that installs process-wide handlers as a side effect of reading one
	// key would surprise every caller. It lands here because cmdSort must
	// install one anyway: spec §11 says Ctrl-C finishes the current step,
	// logs it, and stops, which means the ctx passed to Apply below must be
	// cancelled on SIGINT. The same handler also restores the terminal on
	// SIGTERM, which - unlike a keyboard Ctrl-C during tui.ReadKey's raw
	// read (ISIG is off, so that never even reaches us as a signal) - can
	// land mid-read with no defer left to run.
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	stopSignals := installSignalHandler(cancel)
	defer stopSignals()

	// Ruling 2: journal.Open creates $XDG_STATE_HOME/krino/ and an empty
	// krino.log as a side effect of merely being called, so a dry run must
	// never call it at all - not open it and clean up afterwards. -n is
	// known from the flags before the loop starts, so the gate is exactly
	// that, nothing per-directory. One Writer and one run id cover every
	// directory in the run (Task 5's undo depends on a single run id
	// spanning all of them).
	var j *journal.Writer
	var run string
	if !g.dry {
		var err error
		j, err = journal.Open(e.Config.LogFile())
		if err != nil {
			fmt.Fprintf(stderr, "krino: %v\n", err)
			return 1
		}
		defer func() {
			if cerr := j.Close(); cerr != nil {
				fmt.Fprintf(stderr, "krino: %v\n", cerr)
			}
		}()
		run = journal.NewRunID(e.Now())
	}

	exit := 0
	printed := false
	jsonDirs := []plan.JSONDir{} // never nil: the document's "dirs" must marshal as [], not null
	// A3: one Claims for the whole run, shared across every directory's
	// Plan call below, so two directories that both plan a move to the
	// same destination resolve the collision at planning time instead of
	// each independently believing it owns that path.
	claims := plan.NewClaims()

	for _, d := range e.Dirs {
		// Spec §3/§11: a second krino on the same directory waits for the
		// lock, or fails immediately with -y, so a cron job never piles up
		// behind a stuck run. lock.Acquire takes ctx precisely so that wait
		// is not unbounded in practice (fix round 2026-09-12/item 1): a
		// signal cancels it and Acquire returns ctx.Err() promptly instead
		// of polling forever.
		l, err := lock.Acquire(ctx, e.Config.LockFile(d.Name), !g.yes)
		if err != nil {
			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
				// Interrupted while waiting for the lock: an interrupt, not
				// a failure - the ctx.Err() check at the end of this
				// function already turns this into exit 130, and nothing
				// further should even be attempted.
				break
			}
			fmt.Fprintf(stderr, "krino: %s: %v\n", d.Name, err)
			exit = 1
			continue
		}

		quit := func() bool {
			defer func() {
				if rerr := l.Release(); rerr != nil {
					fmt.Fprintf(stderr, "krino: %s: %v\n", d.Name, rerr)
				}
			}()

			if fi, err := os.Stat(d.Root); err != nil || !fi.IsDir() {
				fmt.Fprintf(stderr, "krino: skipping %s: %s is not a directory\n", d.Name, xdg.Abbrev(d.Root))
				exit = 1
				return false
			}
			dp, err := e.Plan(ctx, d, claims)
			if err != nil {
				fmt.Fprintf(stderr, "krino: skipping %s: %v\n", d.Name, err)
				exit = 1
				return false
			}

			if !g.json {
				if printed {
					fmt.Fprintln(stdout)
				}
				printed = true
				fmt.Fprintln(stdout, p.bold(fmt.Sprintf("krino: %s  %s", d.Name, xdg.Abbrev(d.Root))))
			}
			// C3: directory-level warnings go to stderr after the header
			// line above, not before it, so on a terminal they read as
			// describing the directory just named instead of floating above it.
			for _, w := range dp.Result.Warnings {
				fmt.Fprintf(stderr, "krino: %s: %s\n", d.Name, display(w))
			}
			if g.json {
				// --json is only ever reached with -n (checked above), and
				// Ruling 7 is explicit that JSON must never be paged, so
				// this returns before any of the paging/review code below.
				jsonDirs = append(jsonDirs, plan.NewJSONDir(d.Name, d.Root, dp.Chains, dp.Result.Warnings))
				return false
			}

			// Ruling 6: the plan goes through tui.Page - taller than the
			// terminal, it is shown through $PAGER and the prompt follows
			// once the pager exits (spec §8.2) - for -n as much as for the
			// interactive and -y paths; a dry run that scrolls 200 files
			// off the top of the terminal is exactly the case the pager
			// exists for. printPlan is reused as-is (render.go), never
			// re-rendered here.
			var buf bytes.Buffer
			printPlan(&buf, dp, g.verbose, p, widthPolicy(stdout))
			if err := show(g, stdout, buf.String()); err != nil {
				fmt.Fprintf(stderr, "krino: %s: %v\n", d.Name, err)
				exit = 1
				return false
			}

			if g.dry {
				return false
			}

			actionable := actionableChains(dp.Chains)
			if len(actionable) == 0 {
				// Nothing to decide: neither -y nor the interactive menu
				// has anything useful to do here, so neither is asked.
				fmt.Fprintln(stdout, zeroOutcome)
				return false
			}

			var approved map[string]bool
			var replaced map[string]plan.Kind
			var action rune
			if g.yes {
				approved, action = approveAll(actionable), 'a'
			} else {
				var rerr error
				approved, replaced, action, rerr = reviewDir(stdout, actionable, d.Root, p)
				if rerr != nil {
					fmt.Fprintf(stderr, "krino: %s: %v\n", d.Name, rerr)
					exit = 1
					return false
				}
			}

			switch action {
			case 's':
				// Spec §8.2: [s] applies nothing in this directory and
				// moves on - no Apply call at all, so nothing is logged
				// for it either (Ruling 1: this is a chosen outcome, not a
				// failure, and must not set exit 1).
				fmt.Fprintln(stdout, zeroOutcome)
				return false
			case 'q':
				// Spec §8.2: [q] stops krino; directories already applied
				// this run stay applied. Nothing is applied here either,
				// and no further directory is even planned.
				fmt.Fprintln(stdout, zeroOutcome)
				return true
			}

			// [t] and [d] in review: the file gets the one step chosen
			// there instead of the chain its rules planned.
			dp.Chains = replaceChains(dp.Chains, replaced)
			// [w]: apply what was decided, log nothing for the files never
			// reached, and stop krino once this directory is applied.
			toApply, notReviewed := dp, 0
			if action == 'w' {
				reviewed := *dp
				reviewed.Chains = reviewedChains(dp.Chains, approved)
				toApply = &reviewed
				notReviewed = len(actionable) - len(reviewedChains(actionable, approved))
			}
			res, aerr := e.Apply(ctx, toApply, approved, j, run)
			if aerr != nil {
				if errors.Is(aerr, context.Canceled) || errors.Is(aerr, context.DeadlineExceeded) {
					// Interrupted mid-apply (fix round 2026-09-12/item 2):
					// treated exactly like the cancelled lock wait above -
					// not a failure ("context canceled" is a Go-ism, not
					// something to show a user who just pressed Ctrl-C),
					// and no further directory is even attempted. The
					// ctx.Err() check at the end of this function already
					// turns this into exit 130.
					return true
				}
				fmt.Fprintf(stderr, "krino: %s: %v\n", d.Name, aerr)
				exit = 1
				return false
			}
			fmt.Fprintln(stdout, withNotReviewed(outcome(p, res.Applied, res.Failed, res.Declined), notReviewed))
			// Ruling 1: only an actual step failure makes the run exit 1
			// here - a directory the user declined or skipped must not.
			if res.Failed > 0 {
				exit = 1
			}
			return action == 'w'
		}()

		if quit {
			break
		}
	}

	if g.json {
		b, err := json.MarshalIndent(plan.NewJSON(jsonDirs), "", "  ")
		if err != nil {
			// Unreachable in practice: every field the document carries
			// marshals cleanly (strings, times, ints).
			fmt.Fprintf(stderr, "krino: %v\n", err)
			return 1
		}
		stdout.Write(jsonSafe(b))
		fmt.Fprintln(stdout)
	}

	// Spec §11: 130 interrupted takes priority over whatever exit already
	// accumulated - ctx is only ever cancelled by installSignalHandler, and
	// package main's own cancel() (deferred above) has not run yet here.
	if ctx.Err() != nil {
		return 130
	}
	return exit
}

// actionableChains returns the chains of dp.Chains that have at least one
// step that will actually run (chainActing, render.go) - fix wave item 4 /
// Minor 5: this used to be a separate len(c.Steps) > 0 check, which
// disagreed with render.go's countActing over a chain every one of whose
// steps is skipped, so a directory could report "0 to act on" and then
// still offer such a chain for approval. Converged on chainActing, this is
// now also stricter than the filter engine.Apply's own forward-path loop
// applies (internal/engine/apply.go's Apply, still len(c.Steps) > 0): an
// all-skipped chain is simply never a candidate for approval here, so it
// can never reach Apply with approved == true, and Apply's own loop -
// unchanged - logs it as declined exactly like any other file this review
// never approved (tallyFile then counts it there, not as a fall-through).
func actionableChains(chains []plan.Chain) []plan.Chain {
	var out []plan.Chain
	for _, c := range chains {
		if chainActing(c) {
			out = append(out, c)
		}
	}
	return out
}

// installSignalHandler arranges for SIGINT and SIGTERM to cancel cancel
// and, if stdin is a terminal, restore it to the state it was in when this
// was called (Ruling 5). The returned func stops the handler and must be
// called once the run is over, or its goroutine and signal registration
// outlive cmdSort.
//
// Fix round 2026-09-12/item 2: the handler loops rather than servicing one
// signal and exiting. A single-shot select left signal.Notify's
// registration in place (which suppresses Go's default terminate) with no
// goroutine left reading the channel, so a second Ctrl-C landed in the
// buffered channel unread and a third was dropped outright - together with
// lock.Acquire's own fix, that made a run waiting on a held lock ignore
// every Ctrl-C and every SIGTERM forever, with no escape but another
// shell's kill -9. Looping fixes the common case (ctx cancellation reaches
// something that is actually checking it, e.g. a waiting lock.Acquire or
// Apply between files) and the second signal is also the user's guarantee
// of an exit even when it does not: by then a clean shutdown has already
// been asked for once and not delivered, so it restores the terminal once
// more (harmless if already restored) and exits immediately with the same
// 130 spec §11 already uses for "interrupted".
func installSignalHandler(cancel context.CancelFunc) func() {
	fd := int(stdin.Fd())
	var saved *term.State
	if term.IsTerminal(fd) {
		saved, _ = term.GetState(fd) // best-effort: nothing to restore if this fails
	}

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
	done := make(chan struct{})
	go func() {
		signals := 0
		for {
			select {
			case <-sig:
				cancel()
				if saved != nil {
					term.Restore(fd, saved)
				}
				signals++
				if signals >= 2 {
					// Deliberate exception to "the lock is released on
					// every path" (fix round 2026-09-12/item 3, by
					// design, documented on review): every deferred
					// cleanup in cmdSort - including the held directory's
					// lock.Release - is skipped here. That is intentional:
					// this is the user's escape hatch when a clean
					// shutdown was already asked for once (the first
					// signal) and not delivered, so trying to unwind
					// cleanly a second time is exactly what would make the
					// hatch unreliable. It is safe to skip that unwind:
					// journal.Append flushes each line as it writes, so
					// nothing buffered is lost by exiting immediately, and
					// an abandoned lock file is reclaimed automatically by
					// Task 4's stale-pid takeover the next time anything
					// tries to acquire it (lock.go's tryAcquire).
					os.Exit(130)
				}
			case <-done:
				return
			}
		}
	}()
	return func() {
		signal.Stop(sig)
		close(done)
	}
}

// warnLine is one file's warning, for the warnings section.
type warnLine struct {
	rel  string
	text string
}

// collectWarnings gathers every file's warnings into a single list sorted
// by Rel across matched and unmatched files alike: a reader scans this
// section by file name and has no way to tell which group a file fell
// into, so grouping by match state is invisible structure that would only
// show up as an odd order. A file's own warnings (when it has more than
// one) stay in the order they were recorded: its match warnings (if any)
// first, then its chain warnings (B2) - match happens before planning, so
// that is also the order they were actually produced in. chains supplies
// the chain-level warnings (e.g. "moved more than once"), keyed by
// Chain.File.Rel; every chain's file is necessarily also in r.Matched (only
// matched files ever reach plan.Build), so it is visited exactly once here.
func collectWarnings(r *engine.Result, chains []plan.Chain) []warnLine {
	files := make([]engine.FileMatch, 0, len(r.Matched)+len(r.Unmatched))
	files = append(files, r.Matched...)
	files = append(files, r.Unmatched...)
	sort.Slice(files, func(i, j int) bool { return files[i].File.Rel < files[j].File.Rel })

	chainWarnings := make(map[string][]string, len(chains))
	for _, c := range chains {
		if len(c.Warnings) > 0 {
			chainWarnings[c.File.Rel] = c.Warnings
		}
	}

	var out []warnLine
	for _, fm := range files {
		for _, w := range fm.Warnings {
			out = append(out, warnLine{fm.File.Rel, w})
		}
		for _, w := range chainWarnings[fm.File.Rel] {
			out = append(out, warnLine{fm.File.Rel, w})
		}
	}
	return out
}

// warnedCount counts the distinct files behind lines: B2's "N warnings" in
// the counts line must count a file once even when it carries both a match
// warning and a chain warning, not once per warning line.
func warnedCount(lines []warnLine) int {
	seen := make(map[string]bool, len(lines))
	for _, l := range lines {
		seen[l.rel] = true
	}
	return len(seen)
}

// printWarnings lists one line per warning, Rel padded to the widest shown
// (capped at 40), each line styled with p's warning colour. width wraps a
// long line with its continuation indented four columns (0 never wraps).
func printWarnings(w io.Writer, lines []warnLine, p palette, width int) {
	rels := make([]string, len(lines))
	for i, l := range lines {
		rels[i] = display(l.rel)
	}
	relW := relWidth(rels)
	for _, l := range lines {
		for _, piece := range wrapped("  ", padCell(display(l.rel), relW)+"  "+display(l.text), 4, width, p.warn) {
			fmt.Fprintln(w, piece)
		}
	}
}

// printSkipped lists each skipped file, Rel padded to the widest shown
// (capped at 40), then its reason.
func printSkipped(w io.Writer, skipped []scan.Skipped) {
	rels := make([]string, len(skipped))
	for i, s := range skipped {
		rels[i] = display(s.Rel)
	}
	width := relWidth(rels)
	for _, s := range skipped {
		fmt.Fprintf(w, "  %s  %s\n", padCell(display(s.Rel), width), s.Reason.String())
	}
}

// skipReasonOrder is plan 2's reviewed order for the skip reasons the last
// line reports, before "unmatched".
var skipReasonOrder = []scan.Reason{scan.Ignored, scan.Busy, scan.TooNew, scan.TooBig, scan.Symlink, scan.NotRegular, scan.Unreadable}

// skipSummaryLine builds the "not acted on: N ignored · N busy · ... · N
// unmatched" line per spec §8.2's item format ("<count> <label>", not
// "<label>: <count>"), only the non-zero counts, or "" when every count is
// zero. Ordering is plan 2's reviewed skipReasonOrder, with "unmatched"
// last: the spec's own worked example shows only three of the seven
// categories and states no ordering rule, so its incidental order is not
// adopted, only its item format and unmatched's trailing position.
func skipSummaryLine(r *engine.Result, chains []plan.Chain, verbose bool) string {
	counts := map[scan.Reason]int{}
	for _, s := range r.Skipped {
		counts[s.Reason]++
	}

	var parts []string
	for _, reason := range skipReasonOrder {
		if n := counts[reason]; n > 0 {
			parts = append(parts, fmt.Sprintf("%d %s", n, reason.String()))
		}
	}
	// excluded and allSkipped (chainOutcomes) close the same arithmetic gap:
	// without them, a file matching only an action-less rule, or one whose
	// every step was skipped, is neither "to act on", unmatched, nor a walk
	// skip, so it appears nowhere.
	excluded, allSkipped := chainOutcomes(chains)
	if excluded > 0 {
		parts = append(parts, fmt.Sprintf("%d excluded", excluded))
	}
	if allSkipped > 0 {
		parts = append(parts, fmt.Sprintf("%d all steps skipped", allSkipped))
	}
	if n := len(r.Unmatched); n > 0 {
		parts = append(parts, fmt.Sprintf("%d unmatched", n))
	}
	if len(parts) == 0 {
		return ""
	}
	line := "not acted on: " + strings.Join(parts, " · ")
	if !verbose {
		line += "   (-v lists them)"
	}
	return line
}

// chainOutcomes counts two of skipSummaryLine's categories over chains:
// excluded is chains with no steps at all (a file that matched only rules
// carrying no actions - spec §4.5: "a rule with only (stop) is an
// exclusion"); allSkipped is chains with at least one step, none of them
// unskipped (every step's Skip is set). Neither is "to act on", neither is
// unmatched, and neither is a walk skip, so without these two counts they
// appear nowhere: the real downloads folder reported "267 scanned · 172 to
// act on" and said nothing at all about the other 95. With them the
// arithmetic always closes - scanned = to act on + excluded + all steps
// skipped + unmatched + walk skips - as spec §8.2's own example does.
func chainOutcomes(chains []plan.Chain) (excluded, allSkipped int) {
	for _, c := range chains {
		if len(c.Steps) == 0 {
			excluded++
			continue
		}
		if !chainActing(c) {
			allSkipped++
		}
	}
	return excluded, allSkipped
}

// relWidth returns the column width for a list of Rel names: the widest in
// runes (C4: not bytes, or a name carrying diacritics misaligns its
// column), capped at 40.
func relWidth(rels []string) int {
	w := 0
	for _, s := range rels {
		if n := utf8.RuneCountInString(s); n > w {
			w = n
		}
	}
	if w > 40 {
		w = 40
	}
	return w
}

// padCell pads s to width w (runes, not bytes) with trailing spaces; s
// already at or beyond w is left unpadded.
func padCell(s string, w int) string {
	n := utf8.RuneCountInString(s)
	if n >= w {
		return s
	}
	return s + strings.Repeat(" ", w-n)
}