Skip to content

Commit

Permalink
cmd/lint: show JSON errors
Browse files Browse the repository at this point in the history
Signed-off-by: Charlie Egan <charlie@styra.com>
  • Loading branch information
charlieegan3 authored and anderseknert committed Jun 10, 2024
1 parent c2ec08f commit 355ddd3
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions cmd/lint.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"encoding/json"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -100,8 +101,10 @@ func init() {

rep, err := lint(args, params)
if err != nil {
log.SetOutput(os.Stderr)
log.Println(err)
if !errors.Is(err, &alreadyReportedError{}) {
log.SetOutput(os.Stderr)
log.Println(err)
}

return exit(1)
}
Expand Down Expand Up @@ -313,7 +316,7 @@ func lint(args []string, params *lintCommandParams) (report.Report, error) {

result, err := regal.Lint(ctx)
if err != nil {
return report.Report{}, fmt.Errorf("error(s) encountered while linting: %w", err)
return report.Report{}, reportErrors(params.format, outputWriter, err)
}

rep, err := getReporter(params.format, outputWriter)
Expand Down Expand Up @@ -360,3 +363,34 @@ func getWriterForOutputFile(filename string) (io.Writer, error) {

return f, nil
}

// alreadyReportedError is an error type that is used to signal that an error has already been reported
// and should not shown again, however it should still trigger the error exit code.
type alreadyReportedError struct{}

func (*alreadyReportedError) Error() string {
return "error already reported"
}

func reportErrors(format string, outputWriter io.Writer, err error) error {
// currently, JSON and SARIF will get the same generic JSON error format
if format == formatJSON || format == formatSarif {
enc := json.NewEncoder(outputWriter)
enc.SetIndent("", " ")

if err = enc.Encode(map[string]interface{}{
"errors": []string{err.Error()},
}); err != nil {
return fmt.Errorf("failed to encode error in %s: %w", format, err)
}

return &alreadyReportedError{}
}

_, err = outputWriter.Write([]byte(fmt.Sprintf("error(s) encountered while linting: %s\n", err)))
if err != nil {
return fmt.Errorf("failed to write error to output: %w", err)
}

return &alreadyReportedError{}
}

0 comments on commit 355ddd3

Please sign in to comment.