github.com/yoheimuta/protolint@v0.49.8-0.20240515023657-4ecaebb7575d/internal/addon/plugin/externalRule.go (about)

     1  package plugin
     2  
     3  import (
     4  	"path/filepath"
     5  
     6  	"github.com/yoheimuta/protolint/internal/addon/plugin/shared"
     7  
     8  	"github.com/yoheimuta/go-protoparser/v4/parser"
     9  	"github.com/yoheimuta/go-protoparser/v4/parser/meta"
    10  
    11  	"github.com/yoheimuta/protolint/internal/addon/plugin/proto"
    12  	"github.com/yoheimuta/protolint/linter/report"
    13  	"github.com/yoheimuta/protolint/linter/rule"
    14  )
    15  
    16  // externalRule represents a customized rule that works as a plugin.
    17  type externalRule struct {
    18  	id       string
    19  	purpose  string
    20  	client   shared.RuleSet
    21  	severity rule.Severity
    22  }
    23  
    24  func newExternalRule(
    25  	id string,
    26  	purpose string,
    27  	client shared.RuleSet,
    28  	severity rule.Severity,
    29  ) externalRule {
    30  	return externalRule{
    31  		id:       id,
    32  		purpose:  purpose,
    33  		client:   client,
    34  		severity: severity,
    35  	}
    36  }
    37  
    38  // ID returns the ID of this rule.
    39  func (r externalRule) ID() string {
    40  	return r.id
    41  }
    42  
    43  // Purpose returns the purpose of this rule.
    44  func (r externalRule) Purpose() string {
    45  	return r.purpose
    46  }
    47  
    48  // IsOfficial decides whether or not this rule belongs to the official guide.
    49  func (r externalRule) IsOfficial() bool {
    50  	return true
    51  }
    52  
    53  // Severity returns the severity of a rule (note, warning, error)
    54  func (r externalRule) Severity() rule.Severity {
    55  	return r.severity
    56  }
    57  
    58  // Apply applies the rule to the proto.
    59  func (r externalRule) Apply(p *parser.Proto) ([]report.Failure, error) {
    60  	relPath := p.Meta.Filename
    61  	absPath, err := filepath.Abs(relPath)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	resp, err := r.client.Apply(&proto.ApplyRequest{
    67  		Id:   r.id,
    68  		Path: absPath,
    69  	})
    70  	if err != nil {
    71  		return nil, err
    72  	}
    73  
    74  	var fs []report.Failure
    75  	for _, f := range resp.Failures {
    76  		fs = append(fs, report.FailureWithSeverityf(meta.Position{
    77  			Filename: relPath,
    78  			Offset:   int(f.Pos.Offset),
    79  			Line:     int(f.Pos.Line),
    80  			Column:   int(f.Pos.Column),
    81  		}, r.id, string(r.severity), f.Message))
    82  	}
    83  	return fs, nil
    84  }