aboutsummaryrefslogtreecommitdiff
path: root/cmd/krino/explain.go
blob: 09145b9c9664d8fcae6bb470faa0deed5745a688 (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
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"strings"

	"krino/internal/cond"
	"krino/internal/engine"
	"krino/internal/xdg"
)

func init() { commands["explain"] = cmdExplain }

// cmdExplain evaluates every rule of FILE's directory against it and shows
// each test's result.
func cmdExplain(g *globals, args []string, stdout, stderr io.Writer) int {
	fs := flagSet("explain", g)
	if code, ok := parse(fs, args, stdout, stderr); !ok {
		return code
	}
	if fs.NArg() != 1 {
		return usageError(stderr, "usage: krino explain FILE")
	}
	if code, refused := refuseUnusedFlags(g, stderr, "explain", false); refused {
		return code
	}
	minAge, setMinAge, err := minAgeOverride(g)
	if err != nil {
		return usageError(stderr, err.Error())
	}

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

	x, err := e.Explain(context.Background(), xdg.Expand(fs.Arg(0)))
	if err != nil {
		fmt.Fprintf(stderr, "krino: %v\n", err)
		return 2
	}

	fmt.Fprintf(stdout, "%s  (directory %s)\n", display(xdg.Abbrev(x.File.Path)), x.Dir.Name)
	if x.Skip != "" {
		fmt.Fprintf(stdout, "krino would not look at this file: %s\n", x.Skip)
	}
	if x.Excluded != "" {
		fmt.Fprintf(stdout, "krino would set this file aside: %s\n", x.Excluded)
	}
	fmt.Fprintln(stdout)
	for _, xt := range x.Excludes {
		status := "no"
		if xt.Match {
			status = "MATCH"
		}
		fmt.Fprintf(stdout, "%s: %s\n", xt.Text, status)
		printTrace(stdout, xt.Trace)
	}
	for _, rt := range x.Rules {
		if rt.Stopped != "" {
			fmt.Fprintf(stdout, "rule %s: not evaluated, %s\n", rt.Rule.Name, rt.Stopped)
			continue
		}
		status := "no"
		switch {
		case rt.Match:
			status = "MATCH"
		case rt.Trace != nil && rt.Trace.Unknown:
			status = "undecided"
		}
		fmt.Fprintf(stdout, "rule %s: %s\n", rt.Rule.Name, status)
		printTrace(stdout, rt.Trace)
	}
	if x.NoDelete != "" {
		fmt.Fprintf(stdout, "\nkrino would skip deleting this file: %s\n", display(x.NoDelete))
	}
	return 0
}

// printTrace writes t's Format output with every line prefixed by two
// spaces.
func printTrace(w io.Writer, t *cond.Trace) {
	var buf bytes.Buffer
	displayTrace(t).Format(&buf)
	for _, line := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") {
		fmt.Fprintf(w, "  %s\n", line)
	}
}