|
| 1 | +package actionlint_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + |
| 8 | + "github.com/rhysd/actionlint" |
| 9 | +) |
| 10 | + |
| 11 | +// A rule type to check every steps have their names. |
| 12 | +type RuleStepName struct { |
| 13 | + // Embedding RuleBase struct implements the minimal Rule interface. |
| 14 | + actionlint.RuleBase |
| 15 | +} |
| 16 | + |
| 17 | +// Reimplement methods in RuleBase. Visit* methods are called on checking workflows. |
| 18 | +func (r *RuleStepName) VisitStep(n *actionlint.Step) error { |
| 19 | + // Implement your own check |
| 20 | + if n.Name == nil { |
| 21 | + // RuleBase provides methods to report errors. See RuleBase.Error and RuleBase.Errorf. |
| 22 | + r.Error(n.Pos, "every step must have its name") |
| 23 | + } |
| 24 | + return nil |
| 25 | +} |
| 26 | + |
| 27 | +func NewRuleStepName() *RuleStepName { |
| 28 | + return &RuleStepName{ |
| 29 | + RuleBase: actionlint.NewRuleBase("step-name", "Checks every step has their own name"), |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +func ExampleLinter_yourOwnRule() { |
| 34 | + // The function set at OnRulesCreated is called after rule instances are created. You can |
| 35 | + // add/remove some rules and return the modified slice. This function is called on linting |
| 36 | + // each workflow files. |
| 37 | + o := &actionlint.LinterOptions{ |
| 38 | + OnRulesCreated: func(rules []actionlint.Rule) []actionlint.Rule { |
| 39 | + rules = append(rules, NewRuleStepName()) |
| 40 | + return rules |
| 41 | + }, |
| 42 | + } |
| 43 | + |
| 44 | + l, err := actionlint.NewLinter(os.Stdout, o) |
| 45 | + if err != nil { |
| 46 | + panic(err) |
| 47 | + } |
| 48 | + |
| 49 | + f := filepath.Join("testdata", "ok", "minimal.yaml") |
| 50 | + |
| 51 | + // First return value is an array of lint errors found in the workflow file. |
| 52 | + errs, err := l.LintFile(f, nil) |
| 53 | + if err != nil { |
| 54 | + panic(err) |
| 55 | + } |
| 56 | + |
| 57 | + fmt.Println(len(errs), "lint errors found by actionlint") |
| 58 | + |
| 59 | + // Output: |
| 60 | + // testdata/ok/minimal.yaml:6:9: every step must have its name [step-name] |
| 61 | + // | |
| 62 | + // 6 | - run: echo |
| 63 | + // | ^~~~ |
| 64 | + // 1 lint errors found by actionlint |
| 65 | +} |
0 commit comments