Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: rule type #119

Merged
merged 6 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 7 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,37 +108,23 @@ Our linter allows addition of custom lint rules beyond the default golangci-lint

4. Once the RFC is approved, proceed with the implementation:

a. Implement the `LintRule` interface for your new rule:
a. Create a new variable of type `LintRule` for your new rule:

```go
type NewRule struct{}
NewRule = LintRule{severity: tt.SeverityWarning, check: lints.RunNewRule}

func (r *NewRule) Check(filename string, node *ast.File) ([]types.Issue, error) {
func RunNewRule(filename string, node *ast.File, fset *token.FileSet, severity tt.Severity) ([]types.Issue, error) {
// Implement your lint rule logic here
// return a slice of Issues and any error encountered
}
```

b. Register your new rule in the `registerAllRules` and maybe `registerDefaultRules` method of the `Engine` struct in `internal/engine.go`:
b. Add your rule to `allRules` mapping:

```go
func (e *Engine) registerDefaultRules() {
e.rules = append(e.rules,
&GolangciLintRule{},
// ...
&NewRule{}, // Add your new rule here
)
}
```

```go
func (e *Engine) registerAllRules() {
e.rules = append(e.rules,
&GolangciLintRule{},
// ...
&NewRule{}, // Add your new rule here
)
}
var allRules = ruleMap{
"new-rule": NewRule,
}
```

5. (Optional) If your rule requires special formatting, create a new formatter in the `formatter` package:
Expand Down
6 changes: 6 additions & 0 deletions cmd/tlin/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -381,8 +382,13 @@ func createTempFileWithContent(t *testing.T, content string) string {
return tempFile.Name()
}

var mu sync.Mutex

func captureOutput(t *testing.T, f func()) string {
t.Helper()
mu.Lock()
defer mu.Unlock()

oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
Expand Down
65 changes: 10 additions & 55 deletions internal/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,41 +30,19 @@ func NewEngine(rootDir string, source []byte, rules map[string]tt.ConfigRule) (*
return engine, nil
}

// Define the ruleConstructor type
type ruleConstructor func() LintRule

// Define the ruleMap type
type ruleMap map[string]ruleConstructor

// Create a map to hold the mappings of rule names to their constructors
var allRuleConstructors = ruleMap{
"golangci-lint": NewGolangciLintRule,
"early-return-opportunity": NewEarlyReturnOpportunityRule,
"simplify-slice-range": NewSimplifySliceExprRule,
"unnecessary-type-conversion": NewUnnecessaryConversionRule,
"emit-format": NewEmitFormatRule,
"cycle-detection": NewDetectCycleRule,
"unused-package": NewGnoSpecificRule,
"repeated-regex-compilation": NewRepeatedRegexCompilationRule,
"useless-break": NewUselessBreakRule,
"defer-issues": NewDeferRule,
"const-error-declaration": NewConstErrorDeclarationRule,
}

func (e *Engine) applyRules(rules map[string]tt.ConfigRule) {
e.rules = make(map[string]LintRule)
e.registerDefaultRules()

// Iterate over the rules and apply severity
for key, rule := range rules {
r := e.findRule(key)
if r == nil {
newRuleCstr := allRuleConstructors[key]
if newRuleCstr == nil {
r, ok := e.findRule(key)
if !ok {
newRule, exists := allRules[key]
if !exists {
// Unknown rule, continue to the next one
continue
}
newRule := newRuleCstr()
newRule.SetSeverity(rule.Severity)
e.rules[key] = newRule
} else {
Expand All @@ -77,28 +55,22 @@ func (e *Engine) applyRules(rules map[string]tt.ConfigRule) {
}

func (e *Engine) registerDefaultRules() {
// iterate over allRuleConstructors and add them to the rules map if severity is not off
for key, newRuleCstr := range allRuleConstructors {
newRule := newRuleCstr()
// iterate over allRules and add them to the rules map if severity is not off
for key, newRule := range allRules {
if newRule.Severity() != tt.SeverityOff {
newRule.SetName(key)
e.rules[key] = newRule
}
}
}

func (e *Engine) findRule(name string) LintRule {
if rule, ok := e.rules[name]; ok {
return rule
}
return nil
func (e *Engine) findRule(name string) (LintRule, bool) {
rule, exists := e.rules[name]
return rule, exists
}

// Run applies all lint rules to the given file and returns a slice of Issues.
func (e *Engine) Run(filename string) ([]tt.Issue, error) {
if strings.HasSuffix(filename, ".mod") {
return e.runModCheck(filename)
}

tempFile, err := e.prepareFile(filename)
if err != nil {
return nil, err
Expand Down Expand Up @@ -204,23 +176,6 @@ func (e *Engine) prepareFile(filename string) (string, error) {
return filename, nil
}

func (e *Engine) runModCheck(filename string) ([]tt.Issue, error) {
var allIssues []tt.Issue
for _, rule := range e.rules {
if e.ignoredRules[rule.Name()] {
continue
}
if modRule, ok := rule.(ModRule); ok {
issues, err := modRule.CheckMod(filename)
if err != nil {
return nil, fmt.Errorf("error checking .mod file: %w", err)
}
allIssues = append(allIssues, issues...)
}
}
return allIssues, nil
}

func (e *Engine) cleanupTemp(temp string) {
if temp != "" && strings.HasPrefix(filepath.Base(temp), "temp_") {
_ = os.Remove(temp)
Expand Down
2 changes: 1 addition & 1 deletion internal/lints/default_golangci.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type golangciOutput struct {
} `json:"Issues"`
}

func RunGolangciLint(filename string, severity tt.Severity) ([]tt.Issue, error) {
func RunGolangciLint(filename string, _ *ast.File, _ *token.FileSet, severity tt.Severity) ([]tt.Issue, error) {
cmd := exec.Command("golangci-lint", "run", "--config=./.golangci.yml", "--out-format=json", filename)
output, _ := cmd.CombinedOutput()

Expand Down
2 changes: 1 addition & 1 deletion internal/lints/gno_analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Dependency struct {

type Dependencies map[string]*Dependency

func DetectGnoPackageImports(filename string, severity tt.Severity) ([]tt.Issue, error) {
func DetectGnoPackageImports(filename string, _ *ast.File, _ *token.FileSet, severity tt.Severity) ([]tt.Issue, error) {
file, deps, err := analyzeFile(filename)
if err != nil {
return nil, fmt.Errorf("error analyzing file: %w", err)
Expand Down
2 changes: 1 addition & 1 deletion internal/lints/regex_lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func multipleRepeats() {
node, err := parser.ParseFile(fset, tempFile, nil, parser.ParseComments)
require.NoError(t, err)

issues, err := DetectRepeatedRegexCompilation(tempFile, node, types.SeverityError)
issues, err := DetectRepeatedRegexCompilation(tempFile, node, fset, types.SeverityError)
require.NoError(t, err)

assert.Len(t, issues, tt.expected)
Expand Down
2 changes: 1 addition & 1 deletion internal/lints/repeated_regex_compilation.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var RepeatedRegexCompilationAnalyzer = &analysis.Analyzer{
Run: runRepeatedRegexCompilation,
}

func DetectRepeatedRegexCompilation(filename string, node *ast.File, severity tt.Severity) ([]tt.Issue, error) {
func DetectRepeatedRegexCompilation(filename string, node *ast.File, _ *token.FileSet, severity tt.Severity) ([]tt.Issue, error) {
imports := extractImports(node, func(path string) bool {
return path == "regexp"
})
Expand Down
Loading
Loading