summaryrefslogtreecommitdiff
path: root/internal/cli/corpus.go
blob: 15a140c2fbc43876099bb6f23f1eb6612db408ee (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
package cli

import (
	"encoding/json"
	"fmt"
	"io"
	"path/filepath"
	"strings"

	"github.com/lukaszkasprzak/lectio/internal/bible"
	"github.com/lukaszkasprzak/lectio/internal/config"
)

// runCorpusCheck handles --corpus-check <code|path>: validates a bible
// corpus's sidecar + text (bible.CheckCorpus) and prints the report, plain or
// (with asJSON) as JSON. It exits 1 if the report has any errors, 0
// otherwise -- coverage warnings never fail the check.
//
// arg is either a bare corpus code, resolved against the user corpora dir
// (config.CorporaDir(), which overrides the embedded built-ins the same way
// normal rendering does), or a path to a <code>.tsv file -- its directory
// becomes the user corpora dir for this run and its basename (minus ".tsv")
// the code. The path form lets a corpus be validated before it is copied
// into internal/bible/corpora/ (see scripts/corpus-validate.sh, make
// add-corpus).
func runCorpusCheck(arg string, asJSON bool, stdout, stderr io.Writer) int {
	code := arg
	if strings.Contains(arg, "/") || strings.HasSuffix(arg, ".tsv") {
		dir := filepath.Dir(arg)
		code = strings.TrimSuffix(filepath.Base(arg), ".tsv")
		bible.SetUserCorporaDir(dir)
	} else if dir, err := config.CorporaDir(); err == nil {
		bible.SetUserCorporaDir(dir)
	}

	report := bible.CheckCorpus(code)

	if asJSON {
		enc := json.NewEncoder(stdout)
		enc.SetIndent("", "  ")
		if err := enc.Encode(report); err != nil {
			fmt.Fprintln(stderr, "lectio:", err)
			return 1
		}
	} else {
		printCorpusReport(stdout, report)
	}

	if !report.OK() {
		return 1
	}
	return 0
}

// printCorpusReport renders a CorpusReport as plain text: one line per
// error/warning, then a summary line.
func printCorpusReport(w io.Writer, r bible.CorpusReport) {
	for _, e := range r.Errors {
		fmt.Fprintf(w, "ERROR: %s\n", e)
	}
	for _, wm := range r.Warnings {
		fmt.Fprintf(w, "WARNING: %s\n", wm)
	}
	if r.OK() {
		fmt.Fprintf(w, "ok: %s (%d warning(s))\n", r.Code, len(r.Warnings))
	} else {
		fmt.Fprintf(w, "FAIL: %s (%d error(s), %d warning(s))\n", r.Code, len(r.Errors), len(r.Warnings))
	}
}