github.com/yoheimuta/protolint@v0.49.8-0.20240515023657-4ecaebb7575d/internal/cmd/subcmds/list/cmdList.go (about)

     1  package list
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	"github.com/yoheimuta/protolint/internal/addon/plugin/shared"
     8  
     9  	"github.com/yoheimuta/protolint/internal/linter/config"
    10  
    11  	"github.com/yoheimuta/protolint/internal/cmd/subcmds"
    12  	"github.com/yoheimuta/protolint/internal/osutil"
    13  	"github.com/yoheimuta/protolint/linter/autodisable"
    14  	"github.com/yoheimuta/protolint/linter/rule"
    15  )
    16  
    17  // CmdList is a rule list command.
    18  type CmdList struct {
    19  	stdout io.Writer
    20  	stderr io.Writer
    21  	flags  Flags
    22  }
    23  
    24  // NewCmdList creates a new CmdList.
    25  func NewCmdList(
    26  	flags Flags,
    27  	stdout io.Writer,
    28  	stderr io.Writer,
    29  ) *CmdList {
    30  	return &CmdList{
    31  		flags:  flags,
    32  		stdout: stdout,
    33  		stderr: stderr,
    34  	}
    35  }
    36  
    37  // Run lists each rule description.
    38  func (c *CmdList) Run() osutil.ExitCode {
    39  	err := c.run()
    40  	if err != nil {
    41  		return osutil.ExitInternalFailure
    42  	}
    43  	return osutil.ExitSuccess
    44  }
    45  
    46  func (c *CmdList) run() error {
    47  	rules, err := hasIDAndPurposes(c.flags.Plugins)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	for _, r := range rules {
    53  		_, err := fmt.Fprintf(
    54  			c.stdout,
    55  			"%s: %s\n",
    56  			r.ID(),
    57  			r.Purpose(),
    58  		)
    59  		if err != nil {
    60  			return err
    61  		}
    62  	}
    63  	return nil
    64  }
    65  
    66  type hasIDAndPurpose interface {
    67  	rule.HasID
    68  	rule.HasPurpose
    69  }
    70  
    71  func hasIDAndPurposes(plugins []shared.RuleSet) ([]hasIDAndPurpose, error) {
    72  	rs, err := subcmds.NewAllRules(config.RulesOption{}, false, autodisable.Noop, false, plugins)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	var rules []hasIDAndPurpose
    78  	for _, r := range rs {
    79  		rules = append(rules, r)
    80  	}
    81  	return rules, nil
    82  }