Peter Kurfer
c1c1667d9f
lint-pr runs golangci-lint, captures the result and uses it directly without temporary files It also allows to automatically retrieve the PRs base commit and run golangci-lint only against changes in the current PR
86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package commands
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
|
|
"github.com/golangci/golangci-lint/pkg/printers"
|
|
"github.com/golangci/golangci-lint/pkg/report"
|
|
"github.com/golangci/golangci-lint/pkg/result"
|
|
)
|
|
|
|
var ErrNoResult = errors.New("could not read result")
|
|
|
|
func ReadResultsFile(filePath string) (report *report.Data, issues []result.Issue, err error) {
|
|
if filePath == "" {
|
|
return nil, nil, ErrNoResult
|
|
}
|
|
|
|
f, err := os.Open(filePath)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
defer func() {
|
|
err = errors.Join(err, f.Close())
|
|
}()
|
|
|
|
return ReadResults(f)
|
|
}
|
|
|
|
func ReadResults(reader io.Reader) (*report.Data, []result.Issue, error) {
|
|
decoder := json.NewDecoder(reader)
|
|
var printerResult printers.JSONResult
|
|
if err := decoder.Decode(&printerResult); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
return printerResult.Report, printerResult.Issues, nil
|
|
}
|
|
|
|
func RunGolangCiLint(ctx context.Context, extraFlags []string) (*report.Data, []result.Issue, error) {
|
|
const defaultArgsLen = 3
|
|
golangCiLintArgs := make([]string, 1, defaultArgsLen+len(extraFlags))
|
|
golangCiLintArgs[0] = "run"
|
|
golangCiLintArgs = append(golangCiLintArgs, extraFlags...)
|
|
golangCiLintArgs = append(golangCiLintArgs, "--issues-exit-code=0", "--out-format=json")
|
|
|
|
golangCiLintArgs = append(golangCiLintArgs, extraFlags...)
|
|
|
|
cmd := exec.CommandContext(
|
|
ctx,
|
|
"golangci-lint",
|
|
golangCiLintArgs...,
|
|
)
|
|
|
|
stderrBuf := bytes.NewBuffer(nil)
|
|
|
|
cmd.Stderr = stderrBuf
|
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
var printerResult printers.JSONResult
|
|
|
|
if err := json.NewDecoder(stdout).Decode(&printerResult); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
if err := cmd.Wait(); err != nil {
|
|
return nil, nil, fmt.Errorf("stderr: %s - %w", stderrBuf.String(), err)
|
|
}
|
|
|
|
return printerResult.Report, printerResult.Issues, nil
|
|
}
|