summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/logging.go
blob: 89201974fee79cefc6539613832055d22aa7a18d (plain)
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
package pkglint

import (
	"bytes"
	"io"
	"netbsd.org/pkglint/histogram"
	"netbsd.org/pkglint/textproc"
	"strings"
)

type Logger struct {
	Opts LoggerOpts

	out *SeparatorWriter
	err *SeparatorWriter

	suppressDiag bool
	suppressExpl bool
	prevLine     *Line

	verbose   bool // allow duplicate diagnostics, even in the same line
	logged    Once
	explained Once
	histo     *histogram.Histogram

	errors                int
	warnings              int
	notes                 int
	explanationsAvailable bool
	autofixAvailable      bool
}

type LoggerOpts struct {
	ShowAutofix,
	Autofix,
	Explain,
	ShowSource,
	GccOutput,
	Quiet bool
}

type LogLevel struct {
	TraditionalName string
	GccName         string
}

var (
	Fatal           = &LogLevel{"FATAL", "fatal"}
	Error           = &LogLevel{"ERROR", "error"}
	Warn            = &LogLevel{"WARN", "warning"}
	Note            = &LogLevel{"NOTE", "note"}
	AutofixLogLevel = &LogLevel{"AUTOFIX", "autofix"}
)

// Explain outputs an explanation for the preceding diagnostic
// if the --explain option is given. Otherwise it just records
// that an explanation is available.
func (l *Logger) Explain(explanation ...string) {
	if l.suppressExpl {
		l.suppressExpl = false
		return
	}

	l.explanationsAvailable = true
	if !l.Opts.Explain {
		return
	}

	if !l.explained.FirstTimeSlice(explanation...) {
		return
	}

	// The explanation should fit nicely on a screen that is 80
	// characters wide. The explanation is indented using a tab, and
	// there should be a little margin at the right. The resulting
	// number comes remarkably close to the line width recommended
	// by typographers, which is 66.
	const explanationWidth = 80 - 8 - 4

	l.prevLine = nil
	l.out.Separate()
	wrapped := wrap(explanationWidth, explanation...)
	for _, explanationLine := range wrapped {
		if explanationLine != "" {
			l.out.Write("\t")
		}
		l.out.WriteLine(escapePrintable(explanationLine))
	}
	l.out.WriteLine("")
}

// Diag logs a diagnostic. These are filtered by the --only command line option,
// and duplicates are suppressed unless the --log-verbose command line option is given.
//
// See Logf for logging arbitrary messages.
func (l *Logger) Diag(line *Line, level *LogLevel, format string, args ...interface{}) {
	if l.IsAutofix() {
		// In these two cases, the only interesting diagnostics are those that can
		// be fixed automatically. These are logged by Autofix.Apply.
		l.suppressExpl = true
		return
	}

	if !l.Relevant(format) {
		return
	}

	filename := line.Filename
	linenos := line.Linenos()
	msg := sprintf(format, args...)
	if !l.FirstTime(filename, linenos, msg) {
		l.suppressDiag = false
		return
	}

	if l.Opts.ShowSource {
		if line != l.prevLine {
			l.out.Separate()
		}
		l.showSource(line)
	}

	l.Logf(level, filename, linenos, format, msg)
}

func (l *Logger) FirstTime(filename Path, linenos, msg string) bool {
	if l.verbose {
		return true
	}

	if !l.logged.FirstTimeSlice(filename.Clean().String(), linenos, msg) {
		l.suppressDiag = true
		l.suppressExpl = true
		return false
	}

	return true
}

// Relevant decides and remembers whether the given diagnostic is relevant and should be logged.
//
// The result of the decision affects all log items until Relevant is called for the next time.
func (l *Logger) Relevant(format string) bool {
	relevant := l.shallBeLogged(format)
	l.suppressDiag = !relevant
	l.suppressExpl = !relevant
	return relevant
}

// shallBeLogged tests whether a diagnostic with the given format should
// be logged.
//
// It only inspects the --only arguments; duplicates are handled in Logger.Logf.
func (l *Logger) shallBeLogged(format string) bool {
	if len(G.Opts.LogOnly) == 0 {
		return true
	}

	for _, substr := range G.Opts.LogOnly {
		if contains(format, substr) {
			return true
		}
	}
	return false
}

func (l *Logger) showSource(line *Line) {
	if !G.Logger.Opts.ShowSource {
		return
	}

	if !l.IsAutofix() {
		if line == l.prevLine {
			return
		}
		l.prevLine = line
	}

	out := l.out
	writeLine := func(prefix, line string) {
		out.Write(prefix)
		out.Write(escapePrintable(line))
		if !hasSuffix(line, "\n") {
			out.Write("\n")
		}
	}

	printDiff := func(rawLines []*RawLine) {
		prefix := ">\t"
		for _, rawLine := range rawLines {
			if rawLine.textnl != rawLine.orignl {
				prefix = "\t" // Make it look like an actual diff
			}
		}

		for _, rawLine := range rawLines {
			if rawLine.textnl != rawLine.orignl {
				writeLine("-\t", rawLine.orignl)
				if rawLine.textnl != "" {
					writeLine("+\t", rawLine.textnl)
				}
			} else {
				writeLine(prefix, rawLine.orignl)
			}
		}
	}

	if !l.IsAutofix() {
		l.out.Separate()
	}
	if line.autofix != nil {
		for _, before := range line.autofix.linesBefore {
			writeLine("+\t", before)
		}
		printDiff(line.raw)
		for _, after := range line.autofix.linesAfter {
			writeLine("+\t", after)
		}
	} else {
		printDiff(line.raw)
	}
	if l.IsAutofix() {
		l.out.Separate()
	}
}

// IsAutofix returns whether one of the --show-autofix or --autofix options is active.
func (l *Logger) IsAutofix() bool { return l.Opts.Autofix || l.Opts.ShowAutofix }

func (l *Logger) Logf(level *LogLevel, filename Path, lineno, format, msg string) {
	if l.suppressDiag {
		l.suppressDiag = false
		return
	}

	if G.Testing && format != AutofixFormat {
		if textproc.Alpha.Contains(format[0]) {
			assertf(
				textproc.Upper.Contains(format[0]),
				"Diagnostic %q must start with an uppercase letter.",
				format)
		}

		if !hasSuffix(format, ": %s") && !hasSuffix(format, ". %s") {
			assertf(hasSuffix(format, "."), "Diagnostic format %q must end in a period.", format)
		}
	}

	if filename != "" {
		filename = cleanpath(filename)
	}
	if G.Opts.Profiling && format != AutofixFormat && level != Fatal {
		l.histo.Add(format, 1)
	}

	out := l.out
	if level == Fatal {
		out = l.err
	}

	filenameSep := condStr(filename != "", ": ", "")
	effLineno := condStr(filename != "", lineno, "")
	linenoSep := condStr(effLineno != "", ":", "")
	var diag string
	if l.Opts.GccOutput {
		diag = sprintf("%s%s%s%s%s: %s\n", filename, linenoSep, effLineno, filenameSep, level.GccName, msg)
	} else {
		diag = sprintf("%s%s%s%s%s: %s\n", level.TraditionalName, filenameSep, filename, linenoSep, effLineno, msg)
	}
	out.Write(escapePrintable(diag))

	switch level {
	case Fatal:
		panic(pkglintFatal{})
	case Error:
		l.errors++
	case Warn:
		l.warnings++
	case Note:
		l.notes++
	}
}

// TechErrorf logs a technical error on the error output.
//
// location must be a slash-separated filename, such as the one in
// Location.Filename. It may be followed by the usual ":123" for line numbers.
//
// For diagnostics, use Logf instead.
func (l *Logger) TechErrorf(location Path, format string, args ...interface{}) {
	msg := sprintf(format, args...)
	var diag string
	if l.Opts.GccOutput {
		diag = sprintf("%s: %s: %s\n", location, Error.GccName, msg)
	} else {
		diag = sprintf("%s: %s: %s\n", Error.TraditionalName, location, msg)
	}
	l.err.Write(escapePrintable(diag))
}

func (l *Logger) ShowSummary(args []string) {
	if l.Opts.Quiet || l.Opts.Autofix {
		return
	}

	if l.Opts.ShowSource {
		l.out.Separate()
	}

	if l.errors != 0 || l.warnings != 0 {
		num := func(n int, singular, plural string) string {
			if n == 0 {
				return ""
			} else if n == 1 {
				return sprintf("%d %s", n, singular)
			} else {
				return sprintf("%d %s", n, plural)
			}
		}

		l.out.Write(sprintf("%s found.\n",
			joinSkipEmptyCambridge("and",
				num(l.errors, "error", "errors"),
				num(l.warnings, "warning", "warnings"),
				num(l.notes, "note", "notes"))))
	} else {
		l.out.WriteLine("Looks fine.")
	}

	commandLine := func(arg string) string {
		argv := append([]string{args[0], arg}, args[1:]...)
		for i := range argv {
			argv[i] = shquote(argv[i])
		}
		return strings.Join(argv, " ")
	}

	if l.explanationsAvailable && !l.Opts.Explain {
		l.out.WriteLine(sprintf("(Run \"%s\" to show explanations.)", commandLine("-e")))
	}
	if l.autofixAvailable {
		if !l.Opts.ShowAutofix {
			l.out.WriteLine(sprintf("(Run \"%s\" to show what can be fixed automatically.)", commandLine("-fs")))
		}
		l.out.WriteLine(sprintf("(Run \"%s\" to automatically fix some issues.)", commandLine("-F")))
	}
}

// SeparatorWriter writes output, occasionally separated by an
// empty line. This is used for separating the diagnostics when
// --source is combined with --show-autofix, where each
// log message consists of multiple lines.
type SeparatorWriter struct {
	out   io.Writer
	state uint8 // 0 = beginning of line, 1 = in line, 2 = separator wanted, 3 = paragraph
	line  bytes.Buffer
}

func NewSeparatorWriter(out io.Writer) *SeparatorWriter {
	assertNotNil(out)
	return &SeparatorWriter{out, 3, bytes.Buffer{}}
}

func (wr *SeparatorWriter) WriteLine(text string) {
	wr.Write(text)
	wr.write('\n')
}

func (wr *SeparatorWriter) Write(text string) {
	for _, b := range []byte(text) {
		wr.write(b)
	}
}

// Separate remembers to output an empty line before the next character.
//
// The writer must not be in the middle of a line.
func (wr *SeparatorWriter) Separate() {
	assert(wr.state != 1)
	if wr.state < 2 {
		wr.state = 2
	}
}

func (wr *SeparatorWriter) write(b byte) {
	if b == '\n' {
		if wr.state == 1 {
			wr.state = 0
		} else {
			wr.state = 3
		}
		wr.line.WriteByte('\n')
		wr.Flush()
		return
	}

	if wr.state == 2 {
		wr.line.WriteByte('\n')
		wr.Flush()
	}
	wr.state = 1
	wr.line.WriteByte(b)
}

func (wr *SeparatorWriter) Flush() {
	_, _ = io.Copy(wr.out, &wr.line)
	wr.line.Reset()
}