github.com/yoheimuta/protolint@v0.49.8-0.20240515023657-4ecaebb7575d/internal/linter/report/reporters/jsonReporter.go (about)

     1  package reporters
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  
     8  	"github.com/yoheimuta/protolint/linter/report"
     9  )
    10  
    11  // JSONReporter prints failures as a single JSON struct, allowing
    12  // for simple machine-readable output.
    13  //
    14  // The format is:
    15  //
    16  //	 {
    17  //			"lints":
    18  //				[
    19  //					{"filename": FILENAME, "line": LINE, "column": COL, "message": MESSAGE, "rule": RULE}
    20  //				],
    21  //	 }
    22  type JSONReporter struct{}
    23  
    24  type lintJSON struct {
    25  	Filename string `json:"filename"`
    26  	Line     int    `json:"line"`
    27  	Column   int    `json:"column"`
    28  	Message  string `json:"message"`
    29  	Rule     string `json:"rule"`
    30  }
    31  
    32  type outJSON struct {
    33  	Lints []lintJSON `json:"lints"`
    34  }
    35  
    36  // Report writes failures to w.
    37  func (r JSONReporter) Report(w io.Writer, fs []report.Failure) error {
    38  	out := outJSON{}
    39  	for _, failure := range fs {
    40  		out.Lints = append(out.Lints, lintJSON{
    41  			Filename: failure.Pos().Filename,
    42  			Line:     failure.Pos().Line,
    43  			Column:   failure.Pos().Column,
    44  			Message:  failure.Message(),
    45  			Rule:     failure.RuleID(),
    46  		})
    47  	}
    48  
    49  	bs, err := json.MarshalIndent(out, "", "  ")
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	_, err = fmt.Fprintln(w, string(bs))
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	return nil
    60  }