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

     1  package reporters
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  
     7  	"github.com/yoheimuta/protolint/linter/report"
     8  )
     9  
    10  const (
    11  	protolintSonarEngineId  string = "protolint"
    12  	protolintSonarIssueType string = "CODE_SMELL"
    13  	severityError           string = "MAJOR"
    14  	severityWarn            string = "MINOR"
    15  	severityNote            string = "INFO"
    16  )
    17  
    18  type SonarReporter struct {
    19  }
    20  
    21  // for details refer to https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/importing-external-issues/generic-issue-import-format/
    22  
    23  type sonarTextRange struct {
    24  	StartLine   int `json:"startLine"`
    25  	StartColumn int `json:"startColumn"`
    26  }
    27  
    28  type sonarLocation struct {
    29  	Message   string         `json:"message"`
    30  	FilePath  string         `json:"filePath"`
    31  	TextRange sonarTextRange `json:"textRange"`
    32  }
    33  
    34  type sonarIssue struct {
    35  	EngineId        string        `json:"engineId"`
    36  	RuleId          string        `json:"ruleId"`
    37  	PrimaryLocation sonarLocation `json:"primaryLocation"`
    38  	Severity        string        `json:"severity"`
    39  	IssueType       string        `json:"issueType"`
    40  }
    41  
    42  func (s SonarReporter) Report(w io.Writer, fs []report.Failure) error {
    43  	var issues []sonarIssue
    44  	for _, f := range fs {
    45  		issue := sonarIssue{
    46  			EngineId:  protolintSonarEngineId,
    47  			RuleId:    f.RuleID(),
    48  			IssueType: protolintSonarIssueType,
    49  			Severity:  getSonarSeverity(f.Severity()),
    50  			PrimaryLocation: sonarLocation{
    51  				Message:  f.Message(),
    52  				FilePath: f.Pos().Filename,
    53  				TextRange: sonarTextRange{
    54  					StartLine:   f.Pos().Line,
    55  					StartColumn: f.Pos().Column,
    56  				},
    57  			},
    58  		}
    59  
    60  		issues = append(issues, issue)
    61  	}
    62  
    63  	bs, err := json.MarshalIndent(issues, "", "  ")
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	_, err = w.Write(bs)
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	return nil
    74  }
    75  
    76  func getSonarSeverity(severity string) string {
    77  	if severity == "warn" {
    78  		return severityWarn
    79  	}
    80  
    81  	if severity == "note" {
    82  		return severityNote
    83  	}
    84  
    85  	return severityError
    86  }