Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for JSON output writing #14

Merged
merged 7 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 60 additions & 15 deletions cmd/gocognit/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package main

import (
"errors"
"flag"
"fmt"
"go/parser"
Expand All @@ -40,19 +41,33 @@ Flags:
-top N show the top N most complex functions only
-avg show the average complexity over all functions,
not depending on whether -over or -top are set
-format string
which format to use, supported formats: [text json json-pretty] (default "text")
The output fields for each line are:
<complexity> <package> <function> <file:row:column>
`

func usage() {
fmt.Fprint(os.Stderr, usageDoc)
_, _ = fmt.Fprint(os.Stderr, usageDoc)
os.Exit(2)
}

const (
defaultValueIndicator = -1
textFormat = "text"
jsonFormat = "json"
jsonPrettyFormat = "json-pretty"
)

var (
over = flag.Int("over", 0, "show functions with complexity > N only")
top = flag.Int("top", -1, "show the top N most complex functions only")
avg = flag.Bool("avg", false, "show the average complexity")
supportedFormats = []string{
textFormat, jsonFormat, jsonPrettyFormat,
}

over = flag.Int("over", defaultValueIndicator, "show functions with complexity > N only")
top = flag.Int("top", defaultValueIndicator, "show the top N most complex functions only")
avg = flag.Bool("avg", false, "show the average complexity")
format = flag.String("format", textFormat, fmt.Sprintf("which format to use, supported formats: %v", supportedFormats))
)

func main() {
Expand All @@ -71,7 +86,10 @@ func main() {
}

sort.Sort(byComplexity(stats))
written := writeStats(os.Stdout, stats)
written, err := writeStats(os.Stdout, stats)
if err != nil {
log.Fatal(err)
}

if *avg {
showAverage(stats)
Expand Down Expand Up @@ -149,17 +167,44 @@ func analyzeDir(dirname string, stats []gocognit.Stat) ([]gocognit.Stat, error)
return stats, nil
}

func writeStats(w io.Writer, sortedStats []gocognit.Stat) int {
for i, stat := range sortedStats {
if i == *top {
return i
}
if stat.Complexity <= *over {
return i
}
fmt.Fprintln(w, stat)
var errFormatNotDefined = errors.New(fmt.Sprintf("Format is not valid, use a supported format %v", supportedFormats))

func writeStats(w io.Writer, sortedStats []gocognit.Stat) (int, error) {
filter := gocognit.Filter{}
if *top != defaultValueIndicator {
// top filter
filter.AddFilter(gocognit.NewTopFilter(*top))
}
return len(sortedStats)

if *over != defaultValueIndicator {
// over filter
filter.AddFilter(gocognit.NewComplexityFilter(*over))
}

var formatter gocognit.Formatter

switch *format {
case textFormat:
formatter = gocognit.NewTextFormatter(w)
break
case jsonFormat:
formatter = gocognit.NewJsonFormatter(w, false)
break
case jsonPrettyFormat:
formatter = gocognit.NewJsonFormatter(w, true)
break
default:
return 0, errFormatNotDefined
}

filtered := filter.Apply(sortedStats)

err := formatter.Format(filtered)
if err != nil {
return 0, err
}

return len(sortedStats), nil
}

func showAverage(stats []gocognit.Stat) {
Expand Down
47 changes: 47 additions & 0 deletions filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package gocognit

type FilterFunc func(stat Stat, index int) bool

func NewTopFilter(top int) FilterFunc {
return func(_ Stat, i int) bool {
return i < top
}
}

func NewComplexityFilter(over int) FilterFunc {
return func(stat Stat, _ int) bool {
return stat.Complexity > over
}
}

type Filter struct {
filterFuncs []FilterFunc
}

func (f *Filter) Apply(original []Stat) []Stat {
filtered := make([]Stat, 0, len(original))

// loop all stats
for i, stat := range original {
keep := true

// loop all filters
for _, filter := range f.filterFuncs {
keep = filter(stat, i)

if !keep {
break
}
}

if keep {
filtered = append(filtered, stat)
}
}

return filtered
}

func (f *Filter) AddFilter(filterFunc FilterFunc) {
f.filterFuncs = append(f.filterFuncs, filterFunc)
}
5 changes: 5 additions & 0 deletions formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package gocognit

type Formatter interface {
Format([]Stat) error
}
uudashr marked this conversation as resolved.
Show resolved Hide resolved
25 changes: 25 additions & 0 deletions formatter_json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package gocognit

import (
"encoding/json"
"io"
)

type JsonFormatter struct {
writer io.Writer
withIndentation bool
}

func NewJsonFormatter(writer io.Writer, withIndentation bool) JsonFormatter {
return JsonFormatter{writer, withIndentation}
}

func (t JsonFormatter) Format(stats []Stat) error {
encoder := json.NewEncoder(t.writer)

if t.withIndentation {
encoder.SetIndent("", "\t")
}

return encoder.Encode(stats)
}
27 changes: 27 additions & 0 deletions formatter_text.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gocognit

import (
"fmt"
"io"
)

type TextFormatter struct {
writer io.Writer
}

func NewTextFormatter(writer io.Writer) TextFormatter {
return TextFormatter{writer: writer}
}

func (t TextFormatter) Format(stats []Stat) error {

for _, stat := range stats {
_, err := fmt.Fprintln(t.writer, stat)

if err != nil {
return err
}
}

return nil
}