-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
236 lines (228 loc) · 7.16 KB
/
Copy pathgithub.go
File metadata and controls
236 lines (228 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// github.go reports a run into GitHub when agentci runs inside GitHub Actions:
// one check run per rule, with the findings as annotations on the changed
// lines, plus the job summary. Everything here is best effort. A missing
// permission costs one stderr line and never the exit code.
package main
import (
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/sadfun/agentci/providers"
)
type github struct {
api, repo, token string
sha string // commit the check runs attach to
client *http.Client
checks map[string]int64 // rule file -> check run id
}
// newGitHub returns a reporter when running in GitHub Actions, or nil. With a
// token it opens one in-progress check run per rule right away, so the pull
// request lists them while the agent works.
func newGitHub(rules []Rule) *github {
if os.Getenv("GITHUB_ACTIONS") == "" {
return nil
}
g := &github{
api: strings.TrimSuffix(cmp.Or(os.Getenv("GITHUB_API_URL"), "https://api.github.com"), "/"),
repo: os.Getenv("GITHUB_REPOSITORY"),
token: os.Getenv("GITHUB_TOKEN"),
sha: os.Getenv("GITHUB_SHA"),
client: &http.Client{Timeout: 30 * time.Second},
checks: map[string]int64{},
}
// On pull_request events GITHUB_SHA is the temporary merge commit. The
// checks must go on the pull request's own head commit.
if p := os.Getenv("GITHUB_EVENT_PATH"); p != "" {
var ev struct {
PullRequest struct {
Head struct {
SHA string `json:"sha"`
} `json:"head"`
} `json:"pull_request"`
}
if b, err := os.ReadFile(p); err == nil && json.Unmarshal(b, &ev) == nil {
g.sha = cmp.Or(ev.PullRequest.Head.SHA, g.sha)
}
}
if g.token == "" || g.repo == "" || g.sha == "" {
return g
}
for _, r := range rules {
var res struct {
ID int64 `json:"id"`
}
// GitHub lists the check as "<workflow name> / <rule>", so the rule
// name alone is the whole name.
err := g.call(http.MethodPost, "/check-runs", map[string]any{
"name": r.Name,
"head_sha": g.sha,
"status": "in_progress",
"started_at": time.Now().UTC().Format(time.RFC3339),
}, &res)
if err != nil {
fmt.Fprintf(os.Stderr, "agentci: github: per-rule checks unavailable: %v\n", err)
break
}
g.checks[r.File] = res.ID
}
return g
}
// complete closes the rule's check run with its verdict, summary, findings
// and annotations. It reports whether GitHub now shows the result, so the
// caller can skip the duplicate ::error annotations.
func (g *github) complete(o outcome) bool {
id, ok := g.checks[o.rule.File]
if !ok {
return false
}
var ann []map[string]any
var findings []string
for _, f := range o.res.Findings {
findings = append(findings, findingLine(f, o.rule.Name))
if f.File == "" || f.Line <= 0 || len(ann) == 50 { // 50 is GitHub's limit per request
continue
}
ann = append(ann, map[string]any{
"path": f.File, "start_line": f.Line, "end_line": f.Line,
"annotation_level": "failure", "title": "agentci: " + o.rule.Name, "message": oneLine(f.Message),
})
}
duration := o.dur.Round(time.Second)
conclusion := "success"
title := fmt.Sprintf("PASS (%s)", duration)
summary := strings.TrimSpace(o.res.Summary)
var text string
switch {
case o.err != nil:
conclusion = "failure"
if errors.Is(o.err, context.Canceled) {
conclusion = "cancelled"
}
summary = oneLine(o.err.Error())
title = fmt.Sprintf("ERROR (%s): %s", duration, truncate(summary, 120))
text = lastLines(o.transcript, 30)
case !o.res.Pass:
conclusion = "failure"
title = fmt.Sprintf("FAIL (%s): %s", duration, plural(len(findings), "finding"))
text = strings.Join(findings, "\n")
}
out := map[string]any{"title": title, "summary": summary}
if text != "" {
out["text"] = "```\n" + text + "\n```"
}
if len(ann) > 0 {
out["annotations"] = ann
}
err := g.call(http.MethodPatch, "/check-runs/"+strconv.FormatInt(id, 10), map[string]any{
"status": "completed",
"conclusion": conclusion,
"completed_at": time.Now().UTC().Format(time.RFC3339),
"output": out,
}, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "agentci: github: could not complete the %s check: %v\n", o.rule.Name, err)
return false
}
return true
}
// finish appends the report to the job summary shown on the run page.
func (g *github) finish(outcomes []outcome, verdict string) {
p := os.Getenv("GITHUB_STEP_SUMMARY")
if p == "" {
return
}
f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
return
}
defer f.Close()
fmt.Fprintf(f, "**%s**\n\n", verdict)
var findings []string
for _, o := range outcomes {
d := o.dur.Round(time.Second)
switch {
case o.err != nil:
fmt.Fprintf(f, "- **ERROR** %s (%s): %s\n", o.rule.Name, d, oneLine(o.err.Error()))
case o.res.Pass:
fmt.Fprintf(f, "- **PASS** %s (%s)\n", o.rule.Name, d)
default:
fmt.Fprintf(f, "- **FAIL** %s (%s): %s\n", o.rule.Name, d, oneLine(o.res.Summary))
}
for _, finding := range o.res.Findings {
findings = append(findings, findingLine(finding, o.rule.Name))
}
}
if len(findings) > 0 {
fmt.Fprintf(f, "\n```\n%s\n```\n", strings.Join(findings, "\n"))
}
}
// annotation formats a GitHub workflow command that becomes an annotation on
// the job, the fallback when check runs are unavailable.
func annotation(r Rule, f providers.Finding, message string) string {
escape := strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A", ":", "%3A", ",", "%2C").Replace
props := "title=" + escape("agentci: "+r.Name)
if f.File != "" {
props = "file=" + escape(f.File) + ",line=" + strconv.Itoa(max(f.Line, 1)) + "," + props
}
// oneLine removes CR and LF, leaving only percent signs to escape in data.
return "::error " + props + "::" + strings.ReplaceAll(oneLine(message), "%", "%25")
}
// call performs one GitHub REST request against this repository. path is
// relative to /repos/{owner}/{repo}.
func (g *github) call(method, path string, body, out any) error {
b, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest(method, g.api+"/repos/"+g.repo+path, bytes.NewReader(b))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+g.token)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2026-03-10")
req.Header.Set("User-Agent", "agentci")
req.Header.Set("Content-Type", "application/json")
resp, err := g.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
var e struct {
Message string `json:"message"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
json.Unmarshal(data, &e)
msg := e.Message
for _, x := range e.Errors {
if x.Message != "" {
msg += "; " + x.Message
}
}
msg = cmp.Or(msg, http.StatusText(resp.StatusCode))
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusNotFound {
msg += ` (check the workflow's "checks: write" permission)`
}
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, msg)
}
if out != nil && len(data) > 0 {
return json.Unmarshal(data, out)
}
return nil
}