gunk-dev/the-valley

lint.go

sourceb8e46aa6aaccmain's published tip history
1.6 KiB
1package review
2
3import (
4 "bytes"
5 "fmt"
6 "os/exec"
7 "strings"
8)
9
10// LintConfig configures which lint commands to run.
11type LintConfig struct {
12 Commands []string // e.g. ["go vet ./...", "golangci-lint run"]
13}
14
15// LintResult captures the output of a single lint command.
16type LintResult struct {
17 Command string
18 Passed bool
19 Output string
20}
21
22// RunLinters executes each lint command in the given directory and returns results.
23func RunLinters(dir string, commands []string) ([]LintResult, error) {
24 if len(commands) == 0 {
25 return nil, nil
26 }
27
28 var results []LintResult
29 for _, cmdStr := range commands {
30 result, err := runLintCommand(dir, cmdStr)
31 if err != nil {
32 return nil, fmt.Errorf("running %q: %w", cmdStr, err)
33 }
34 results = append(results, result)
35 }
36 return results, nil
37}
38
39func runLintCommand(dir, cmdStr string) (LintResult, error) {
40 if strings.TrimSpace(cmdStr) == "" {
41 return LintResult{Command: cmdStr, Passed: true}, nil
42 }
43
44 cmd := exec.Command("sh", "-c", cmdStr)
45 cmd.Dir = dir
46
47 var stdout, stderr bytes.Buffer
48 cmd.Stdout = &stdout
49 cmd.Stderr = &stderr
50
51 err := cmd.Run()
52 output := stdout.String()
53 if stderr.Len() > 0 {
54 if output != "" {
55 output += "\n"
56 }
57 output += stderr.String()
58 }
59 output = strings.TrimSpace(output)
60
61 passed := err == nil
62 // exec.ExitError means the command ran but returned non-zero — that's a lint failure, not an error.
63 if err != nil {
64 if _, ok := err.(*exec.ExitError); !ok {
65 return LintResult{}, fmt.Errorf("executing %q: %w", cmdStr, err)
66 }
67 }
68
69 return LintResult{
70 Command: cmdStr,
71 Passed: passed,
72 Output: output,
73 }, nil
74}