aboutsummaryrefslogtreecommitdiff
path: root/internal/report/report.go
blob: a97039ea7ad7565df20c3c9362adb972f8f5aa61 (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
package report

import (
	"encoding/json"
	"fmt"
	"github.com/Fuwn/kivia/internal/analyze"
	"github.com/Fuwn/kivia/internal/collect"
	"io"
	"strings"
)

func Render(writer io.Writer, result analyze.Result, format string, includeContext bool) error {
	switch strings.ToLower(format) {
	case "json":
		return renderJSON(writer, result, includeContext)
	case "text", "":
		return renderText(writer, result, includeContext)
	default:
		return fmt.Errorf("Unsupported output format %q. Use \"text\" or \"json\".", format)
	}
}

func renderText(writer io.Writer, result analyze.Result, includeContext bool) error {
	if len(result.Violations) == 0 {
		_, err := fmt.Fprintln(writer, "No naming violations found.")

		return err
	}

	for _, violation := range result.Violations {
		if _, err := fmt.Fprintf(writer, "%s:%d:%d %s %q: %s\n",
			violation.Identifier.File,
			violation.Identifier.Line,
			violation.Identifier.Column,
			violation.Identifier.Kind,
			violation.Identifier.Name,
			violation.Reason,
		); err != nil {
			return err
		}

		if includeContext {
			contextParts := make([]string, 0, 3)

			if violation.Identifier.Context.Type != "" {
				contextParts = append(contextParts, "type="+violation.Identifier.Context.Type)
			}

			if violation.Identifier.Context.ValueExpression != "" {
				contextParts = append(contextParts, "value="+violation.Identifier.Context.ValueExpression)
			}

			if violation.Identifier.Context.EnclosingFunction != "" {
				contextParts = append(contextParts, "function="+violation.Identifier.Context.EnclosingFunction)
			}

			if len(contextParts) > 0 {
				if _, err := fmt.Fprintf(writer, "  context: %s\n", strings.Join(contextParts, ", ")); err != nil {
					return err
				}
			}
		}
	}

	return nil
}

func renderJSON(writer io.Writer, result analyze.Result, includeContext bool) error {
	if !includeContext {
		for index := range result.Violations {
			result.Violations[index].Identifier.Context = collect.Context{}
		}
	}

	encoder := json.NewEncoder(writer)

	encoder.SetIndent("", "  ")

	return encoder.Encode(result)
}