github.com/wolfi-dev/wolfictl@v0.16.11/pkg/cli/lint.go (about)

     1  package cli
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/spf13/cobra"
     8  	"github.com/wolfi-dev/wolfictl/pkg/lint"
     9  )
    10  
    11  type lintOptions struct {
    12  	args      []string
    13  	list      bool
    14  	skipRules []string
    15  }
    16  
    17  func cmdLint() *cobra.Command {
    18  	o := &lintOptions{}
    19  	cmd := &cobra.Command{
    20  		Use:               "lint",
    21  		DisableAutoGenTag: true,
    22  		SilenceUsage:      true,
    23  		SilenceErrors:     true,
    24  		Short:             "Lint the code",
    25  		RunE: func(cmd *cobra.Command, args []string) error {
    26  			// args[0] can be used to get the path to the file to lint or `.` to lint the current directory
    27  			// what if given yaml is not Melange yaml?
    28  			o.args = args
    29  			return o.LintCmd(cmd.Context())
    30  		},
    31  	}
    32  	cmd.Flags().BoolVarP(&o.list, "list", "l", false, "prints the all of available rules and exits")
    33  	cmd.Flags().StringArrayVarP(&o.skipRules, "skip-rule", "", []string{}, "list of rules to skip")
    34  
    35  	cmd.AddCommand(cmdLintYam())
    36  
    37  	return cmd
    38  }
    39  
    40  func (o lintOptions) LintCmd(ctx context.Context) error {
    41  	linter := lint.New(o.makeLintOptions()...)
    42  
    43  	// If the list flag is set, print the list of available rules and exit.
    44  	if o.list {
    45  		linter.PrintRules(ctx)
    46  		return nil
    47  	}
    48  
    49  	// Run the linter.
    50  	result, err := linter.Lint(ctx)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	if result.HasErrors() {
    55  		linter.Print(ctx, result)
    56  		return errors.New("linting failed")
    57  	}
    58  	return nil
    59  }
    60  
    61  func (o lintOptions) makeLintOptions() []lint.Option {
    62  	if len(o.args) == 0 {
    63  		// Lint the current directory by default.
    64  		o.args = []string{"."}
    65  	}
    66  
    67  	return []lint.Option{
    68  		lint.WithPath(o.args[0]),
    69  		lint.WithSkipRules(o.skipRules),
    70  	}
    71  }