Skip to content

Commit 177d688

Browse files
committed
feat: use problem matchers for GitHub Action format
1 parent 87db2a3 commit 177d688

File tree

5 files changed

+269
-50
lines changed

5 files changed

+269
-50
lines changed

pkg/printers/github.go

Lines changed: 119 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,102 @@
11
package printers
22

33
import (
4+
"encoding/json"
45
"fmt"
56
"io"
7+
"os"
68
"path/filepath"
79

810
"github.com/golangci/golangci-lint/pkg/result"
911
)
1012

13+
const defaultGitHubSeverity = "error"
14+
15+
const filenameGitHubActionProblemMatchers = "golangci-lint-action-problem-matchers.json"
16+
17+
// GitHubProblemMatchers defines the root of problem matchers.
18+
// - https://github.com/actions/toolkit/blob/main/docs/problem-matchers.md
19+
// - https://github.com/actions/toolkit/blob/main/docs/commands.md#problem-matchers
20+
type GitHubProblemMatchers struct {
21+
Matchers []GitHubMatcher `json:"problemMatcher,omitempty"`
22+
}
23+
24+
// GitHubMatcher defines a problem matcher.
25+
type GitHubMatcher struct {
26+
// Owner an ID field that can be used to remove or replace the problem matcher.
27+
// **required**
28+
Owner string `json:"owner,omitempty"`
29+
// Severity indicates the default severity, either 'warning' or 'error' case-insensitive.
30+
// Defaults to 'error'.
31+
Severity string `json:"severity,omitempty"`
32+
Pattern []GitHubPattern `json:"pattern,omitempty"`
33+
}
34+
35+
// GitHubPattern defines a pattern for a problem matcher.
36+
type GitHubPattern struct {
37+
// Regexp the regexp pattern that provides the groups to match against.
38+
// **required**
39+
Regexp string `json:"regexp,omitempty"`
40+
// File a group number containing the file name.
41+
File int `json:"file,omitempty"`
42+
// FromPath a group number containing a filepath used to root the file (e.g. a project file).
43+
FromPath int `json:"fromPath,omitempty"`
44+
// Line a group number containing the line number.
45+
Line int `json:"line,omitempty"`
46+
// Column a group number containing the column information.
47+
Column int `json:"column,omitempty"`
48+
// Severity a group number containing either 'warning' or 'error' case-insensitive.
49+
// Defaults to `error`.
50+
Severity int `json:"severity,omitempty"`
51+
// Code a group number containing the error code.
52+
Code int `json:"code,omitempty"`
53+
// Message a group number containing the error message.
54+
// **required** at least one pattern must set the message.
55+
Message int `json:"message,omitempty"`
56+
// Loop whether to loop until a match is not found,
57+
// only valid on the last pattern of a multi-pattern matcher.
58+
Loop bool `json:"loop,omitempty"`
59+
}
60+
1161
type GitHub struct {
1262
w io.Writer
1363
}
1464

15-
const defaultGithubSeverity = "error"
16-
17-
// NewGitHub output format outputs issues according to GitHub actions format:
18-
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message
65+
// NewGitHub output format outputs issues according to GitHub actions the problem matcher regexp.
1966
func NewGitHub(w io.Writer) *GitHub {
2067
return &GitHub{w: w}
2168
}
2269

23-
// print each line as: ::error file=app.js,line=10,col=15::Something went wrong
24-
func formatIssueAsGithub(issue *result.Issue) string {
25-
severity := defaultGithubSeverity
70+
func (p *GitHub) Print(issues []result.Issue) error {
71+
// Note: the file with the problem matcher definition should not be removed.
72+
// A sleep can mitigate this problem but this will be flaky.
73+
//
74+
// Error: Unable to process command '::add-matcher::/tmp/golangci-lint-action-problem-matchers.json' successfully.
75+
// Error: Could not find file '/tmp/golangci-lint-action-problem-matchers.json'.
76+
//
77+
filename, err := storeProblemMatcher()
78+
if err != nil {
79+
return err
80+
}
81+
82+
_, _ = fmt.Fprintln(p.w, "::debug::problem matcher definition file: "+filename)
83+
84+
_, _ = fmt.Fprintln(p.w, "::add-matcher::"+filename)
85+
86+
for ind := range issues {
87+
_, err := fmt.Fprintln(p.w, formatIssueAsGitHub(&issues[ind]))
88+
if err != nil {
89+
return err
90+
}
91+
}
92+
93+
_, _ = fmt.Fprintln(p.w, "::remove-matcher owner=golangci-lint-action::")
94+
95+
return nil
96+
}
97+
98+
func formatIssueAsGitHub(issue *result.Issue) string {
99+
severity := defaultGitHubSeverity
26100
if issue.Severity != "" {
27101
severity = issue.Severity
28102
}
@@ -32,21 +106,49 @@ func formatIssueAsGithub(issue *result.Issue) string {
32106
// Otherwise, GitHub won't be able to show the annotations pointing to the file path with backslashes.
33107
file := filepath.ToSlash(issue.FilePath())
34108

35-
ret := fmt.Sprintf("::%s file=%s,line=%d", severity, file, issue.Line())
109+
ret := fmt.Sprintf("%s\t%s:%d:", severity, file, issue.Line())
36110
if issue.Pos.Column != 0 {
37-
ret += fmt.Sprintf(",col=%d", issue.Pos.Column)
111+
ret += fmt.Sprintf("%d:", issue.Pos.Column)
38112
}
39113

40-
ret += fmt.Sprintf("::%s (%s)", issue.Text, issue.FromLinter)
114+
ret += fmt.Sprintf("\t%s (%s)", issue.Text, issue.FromLinter)
41115
return ret
42116
}
43117

44-
func (p *GitHub) Print(issues []result.Issue) error {
45-
for ind := range issues {
46-
_, err := fmt.Fprintln(p.w, formatIssueAsGithub(&issues[ind]))
47-
if err != nil {
48-
return err
49-
}
118+
func storeProblemMatcher() (string, error) {
119+
//nolint:gosec // To be able to clean the file during tests, we need a deterministic filepath.
120+
file, err := os.Create(filepath.Join(os.TempDir(), filenameGitHubActionProblemMatchers))
121+
if err != nil {
122+
return "", err
123+
}
124+
125+
defer file.Close()
126+
127+
err = json.NewEncoder(file).Encode(generateProblemMatcher())
128+
if err != nil {
129+
return "", err
130+
}
131+
132+
return file.Name(), nil
133+
}
134+
135+
func generateProblemMatcher() GitHubProblemMatchers {
136+
return GitHubProblemMatchers{
137+
Matchers: []GitHubMatcher{
138+
{
139+
Owner: "golangci-lint-action",
140+
Severity: "error",
141+
Pattern: []GitHubPattern{
142+
{
143+
Regexp: `^([^\s]+)\s+([^:]+):(\d+):(?:(\d+):)?\s+(.+)$`,
144+
Severity: 1,
145+
File: 2,
146+
Line: 3,
147+
Column: 4,
148+
Message: 5,
149+
},
150+
},
151+
},
152+
},
50153
}
51-
return nil
52154
}

pkg/printers/github_test.go

Lines changed: 115 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@ package printers
22

33
import (
44
"bytes"
5+
"fmt"
56
"go/token"
7+
"os"
8+
"path/filepath"
9+
"regexp"
610
"runtime"
11+
"strings"
712
"testing"
813

914
"github.com/stretchr/testify/assert"
@@ -13,6 +18,10 @@ import (
1318
)
1419

1520
func TestGitHub_Print(t *testing.T) {
21+
if runtime.GOOS != "linux" {
22+
t.Skip("Skipping tests because temp folder depends on OS")
23+
}
24+
1625
issues := []result.Issue{
1726
{
1827
FromLinter: "linter-a",
@@ -43,20 +52,27 @@ func TestGitHub_Print(t *testing.T) {
4352
},
4453
}
4554

55+
t.Cleanup(func() {
56+
_ = os.RemoveAll(filepath.Join(t.TempDir(), filenameGitHubActionProblemMatchers))
57+
})
58+
4659
buf := new(bytes.Buffer)
4760
printer := NewGitHub(buf)
4861

4962
err := printer.Print(issues)
5063
require.NoError(t, err)
5164

52-
expected := `::warning file=path/to/filea.go,line=10,col=4::some issue (linter-a)
53-
::error file=path/to/fileb.go,line=300,col=9::another issue (linter-b)
65+
expected := `::debug::problem matcher definition file: /tmp/golangci-lint-action-problem-matchers.json
66+
::add-matcher::/tmp/golangci-lint-action-problem-matchers.json
67+
warning path/to/filea.go:10:4: some issue (linter-a)
68+
error path/to/fileb.go:300:9: another issue (linter-b)
69+
::remove-matcher owner=golangci-lint-action::
5470
`
5571

5672
assert.Equal(t, expected, buf.String())
5773
}
5874

59-
func Test_formatIssueAsGithub(t *testing.T) {
75+
func Test_formatIssueAsGitHub(t *testing.T) {
6076
sampleIssue := result.Issue{
6177
FromLinter: "sample-linter",
6278
Text: "some issue",
@@ -67,13 +83,13 @@ func Test_formatIssueAsGithub(t *testing.T) {
6783
Column: 4,
6884
},
6985
}
70-
require.Equal(t, "::error file=path/to/file.go,line=10,col=4::some issue (sample-linter)", formatIssueAsGithub(&sampleIssue))
86+
require.Equal(t, "error\tpath/to/file.go:10:4:\tsome issue (sample-linter)", formatIssueAsGitHub(&sampleIssue))
7187

7288
sampleIssue.Pos.Column = 0
73-
require.Equal(t, "::error file=path/to/file.go,line=10::some issue (sample-linter)", formatIssueAsGithub(&sampleIssue))
89+
require.Equal(t, "error\tpath/to/file.go:10:\tsome issue (sample-linter)", formatIssueAsGitHub(&sampleIssue))
7490
}
7591

76-
func Test_formatIssueAsGithub_Windows(t *testing.T) {
92+
func Test_formatIssueAsGitHub_Windows(t *testing.T) {
7793
if runtime.GOOS != "windows" {
7894
t.Skip("Skipping test on non Windows")
7995
}
@@ -88,8 +104,99 @@ func Test_formatIssueAsGithub_Windows(t *testing.T) {
88104
Column: 4,
89105
},
90106
}
91-
require.Equal(t, "::error file=path/to/file.go,line=10,col=4::some issue (sample-linter)", formatIssueAsGithub(&sampleIssue))
107+
require.Equal(t, "error\tpath/to/file.go:10:4:\tsome issue (sample-linter)", formatIssueAsGitHub(&sampleIssue))
92108

93109
sampleIssue.Pos.Column = 0
94-
require.Equal(t, "::error file=path/to/file.go,line=10::some issue (sample-linter)", formatIssueAsGithub(&sampleIssue))
110+
require.Equal(t, "error\tpath/to/file.go:10:\tsome issue (sample-linter)", formatIssueAsGitHub(&sampleIssue))
111+
}
112+
113+
func Test_generateProblemMatcher(t *testing.T) {
114+
pattern := generateProblemMatcher().Matchers[0].Pattern[0]
115+
116+
exp := regexp.MustCompile(pattern.Regexp)
117+
118+
testCases := []struct {
119+
desc string
120+
line string
121+
expected string
122+
}{
123+
{
124+
desc: "error",
125+
line: "error\tpath/to/filea.go:10:4:\tsome issue (sample-linter)",
126+
expected: `File: path/to/filea.go
127+
Line: 10
128+
Column: 4
129+
Severity: error
130+
Message: some issue (sample-linter)`,
131+
},
132+
{
133+
desc: "warning",
134+
line: "warning\tpath/to/fileb.go:1:4:\tsome issue (sample-linter)",
135+
expected: `File: path/to/fileb.go
136+
Line: 1
137+
Column: 4
138+
Severity: warning
139+
Message: some issue (sample-linter)`,
140+
},
141+
{
142+
desc: "no column",
143+
line: "error\t \tpath/to/fileb.go:40:\t Foo bar",
144+
expected: `File: path/to/fileb.go
145+
Line: 40
146+
Column:
147+
Severity: error
148+
Message: Foo bar`,
149+
},
150+
}
151+
152+
for _, test := range testCases {
153+
test := test
154+
t.Run(test.desc, func(t *testing.T) {
155+
t.Parallel()
156+
157+
assert.True(t, exp.MatchString(test.line), test.line)
158+
159+
actual := exp.ReplaceAllString(test.line, createReplacement(&pattern))
160+
161+
assert.Equal(t, test.expected, actual)
162+
})
163+
}
164+
}
165+
166+
func createReplacement(pattern *GitHubPattern) string {
167+
var repl []string
168+
169+
if pattern.File > 0 {
170+
repl = append(repl, fmt.Sprintf("File: $%d", pattern.File))
171+
}
172+
173+
if pattern.FromPath > 0 {
174+
repl = append(repl, fmt.Sprintf("FromPath: $%d", pattern.FromPath))
175+
}
176+
177+
if pattern.Line > 0 {
178+
repl = append(repl, fmt.Sprintf("Line: $%d", pattern.Line))
179+
}
180+
181+
if pattern.Column > 0 {
182+
repl = append(repl, fmt.Sprintf("Column: $%d", pattern.Column))
183+
}
184+
185+
if pattern.Severity > 0 {
186+
repl = append(repl, fmt.Sprintf("Severity: $%d", pattern.Severity))
187+
}
188+
189+
if pattern.Code > 0 {
190+
repl = append(repl, fmt.Sprintf("Code: $%d", pattern.Code))
191+
}
192+
193+
if pattern.Message > 0 {
194+
repl = append(repl, fmt.Sprintf("Message: $%d", pattern.Message))
195+
}
196+
197+
if pattern.Loop {
198+
repl = append(repl, fmt.Sprintf("Loop: $%v", pattern.Loop))
199+
}
200+
201+
return strings.Join(repl, "\n")
95202
}

pkg/printers/printer_test.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,18 +173,22 @@ func TestPrinter_Print_file(t *testing.T) {
173173
func TestPrinter_Print_multiple(t *testing.T) {
174174
logger := logutils.NewStderrLog("skip")
175175

176+
t.Cleanup(func() {
177+
_ = os.RemoveAll(filepath.Join(t.TempDir(), filenameGitHubActionProblemMatchers))
178+
})
179+
176180
var issues []result.Issue
177181
unmarshalFile(t, "in-issues.json", &issues)
178182

179183
data := &report.Data{}
180184
unmarshalFile(t, "in-report-data.json", data)
181185

182-
outputPath := filepath.Join(t.TempDir(), "github-actions.txt")
186+
outputPath := filepath.Join(t.TempDir(), "teamcity.txt")
183187

184188
cfg := &config.Output{
185189
Formats: []config.OutputFormat{
186190
{
187-
Format: "github-actions",
191+
Format: "teamcity",
188192
Path: outputPath,
189193
},
190194
{
@@ -210,7 +214,7 @@ func TestPrinter_Print_multiple(t *testing.T) {
210214
err = p.Print(issues)
211215
require.NoError(t, err)
212216

213-
goldenGitHub, err := os.ReadFile(filepath.Join("testdata", "golden-github-actions.txt"))
217+
goldenGitHub, err := os.ReadFile(filepath.Join("testdata", "golden-teamcity.txt"))
214218
require.NoError(t, err)
215219

216220
actual, err := os.ReadFile(outputPath)

0 commit comments

Comments
 (0)