Skip to content

Commit

Permalink
cmd/lint: show JSON errors (#817)
Browse files Browse the repository at this point in the history
Signed-off-by: Charlie Egan <charlie@styra.com>
  • Loading branch information
charlieegan3 authored Jun 10, 2024
1 parent 982d13b commit d0def34
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
19 changes: 18 additions & 1 deletion 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 @@ -313,7 +314,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{}, formatError(params.format, fmt.Errorf("error(s) encountered while linting: %w", err))
}

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

return f, nil
}

func formatError(format string, err error) error {
// currently, JSON and SARIF will get the same generic JSON error format
if format == formatJSON || format == formatSarif {
bs, err := json.MarshalIndent(map[string]interface{}{
"errors": []string{err.Error()},
}, "", " ")
if err != nil {
return fmt.Errorf("failed to format errors for output: %w", err)
}

return fmt.Errorf("%s", string(bs))
}

return err
}
2 changes: 1 addition & 1 deletion e2e/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func TestLintNonExistentDir(t *testing.T) {
if exp, act := "error(s) encountered while linting: errors encountered when reading files to lint: "+
"failed to filter paths:\nstat "+td+filepath.FromSlash("/what/ever")+": no such file or directory\n",
stderr.String(); exp != act {
t.Errorf("expected stderr %q, got %q", exp, act)
t.Errorf("expected stderr\n%q,\ngot\n%q", exp, act)
}
}

Expand Down

0 comments on commit d0def34

Please sign in to comment.