2023-03-08 13:40:04 +00:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
2023-03-09 11:04:11 +00:00
|
|
|
"bytes"
|
|
|
|
"context"
|
2023-03-08 13:40:04 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2023-03-09 11:04:11 +00:00
|
|
|
"fmt"
|
2023-03-08 13:40:04 +00:00
|
|
|
"io"
|
|
|
|
"os"
|
2023-03-09 11:04:11 +00:00
|
|
|
"os/exec"
|
2023-03-08 13:40:04 +00:00
|
|
|
|
|
|
|
"github.com/golangci/golangci-lint/pkg/printers"
|
|
|
|
"github.com/golangci/golangci-lint/pkg/report"
|
|
|
|
"github.com/golangci/golangci-lint/pkg/result"
|
|
|
|
)
|
|
|
|
|
2023-03-08 15:13:49 +00:00
|
|
|
var ErrNoResult = errors.New("could not read result")
|
2023-03-08 13:40:04 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2023-03-09 11:04:11 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|