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

     1  package rules
     2  
     3  import (
     4  	"github.com/yoheimuta/go-protoparser/v4/parser"
     5  
     6  	"github.com/yoheimuta/protolint/linter/report"
     7  	"github.com/yoheimuta/protolint/linter/rule"
     8  	"github.com/yoheimuta/protolint/linter/visitor"
     9  )
    10  
    11  // EnumsHaveCommentRule verifies that all enums have a comment.
    12  type EnumsHaveCommentRule struct {
    13  	RuleWithSeverity
    14  	// Golang style comments should begin with the name of the thing being described.
    15  	// See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences
    16  	shouldFollowGolangStyle bool
    17  }
    18  
    19  // NewEnumsHaveCommentRule creates a new EnumsHaveCommentRule.
    20  func NewEnumsHaveCommentRule(
    21  	severity rule.Severity,
    22  	shouldFollowGolangStyle bool,
    23  ) EnumsHaveCommentRule {
    24  	return EnumsHaveCommentRule{
    25  		RuleWithSeverity:        RuleWithSeverity{severity: severity},
    26  		shouldFollowGolangStyle: shouldFollowGolangStyle,
    27  	}
    28  }
    29  
    30  // ID returns the ID of this rule.
    31  func (r EnumsHaveCommentRule) ID() string {
    32  	return "ENUMS_HAVE_COMMENT"
    33  }
    34  
    35  // Purpose returns the purpose of this rule.
    36  func (r EnumsHaveCommentRule) Purpose() string {
    37  	return "Verifies that all enums have a comment."
    38  }
    39  
    40  // IsOfficial decides whether or not this rule belongs to the official guide.
    41  func (r EnumsHaveCommentRule) IsOfficial() bool {
    42  	return false
    43  }
    44  
    45  // Apply applies the rule to the proto.
    46  func (r EnumsHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) {
    47  	v := &enumsHaveCommentVisitor{
    48  		BaseAddVisitor:          visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())),
    49  		shouldFollowGolangStyle: r.shouldFollowGolangStyle,
    50  	}
    51  	return visitor.RunVisitor(v, proto, r.ID())
    52  }
    53  
    54  type enumsHaveCommentVisitor struct {
    55  	*visitor.BaseAddVisitor
    56  	shouldFollowGolangStyle bool
    57  }
    58  
    59  // VisitEnum checks the enum.
    60  func (v *enumsHaveCommentVisitor) VisitEnum(enum *parser.Enum) bool {
    61  	n := enum.EnumName
    62  	if v.shouldFollowGolangStyle && !hasGolangStyleComment(enum.Comments, n) {
    63  		v.AddFailuref(enum.Meta.Pos, `Enum %q should have a comment of the form "// %s ..."`, n, n)
    64  	} else if !hasComments(enum.Comments, enum.InlineComment, enum.InlineCommentBehindLeftCurly) {
    65  		v.AddFailuref(enum.Meta.Pos, `Enum %q should have a comment`, n)
    66  	}
    67  	return true
    68  }