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 }