-
Notifications
You must be signed in to change notification settings - Fork 34
/
actions.go
451 lines (395 loc) · 13.2 KB
/
actions.go
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Copyright 2020 The Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package githubactions provides an SDK for authoring GitHub Actions in Go. It
// has no external dependencies and provides a Go-like interface for interacting
// with GitHub Actions' build system.
package githubactions
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var (
// osExit allows `os.Exit()` to be stubbed during testing.
osExit = os.Exit
)
const (
addMaskCmd = "add-mask"
setOutputCmd = "set-output"
saveStateCmd = "save-state"
pathCmd = "path" // used when issuing the file command
envCmd = "env" // used when issuing the file command
envCmdMsgFmt = "%s<<%s" + EOF + "%s" + EOF + "%s" // ${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}
envCmdDelimiter = "_GitHubActionsFileCommandDelimeter_"
addMatcherCmd = "add-matcher"
removeMatcherCmd = "remove-matcher"
groupCmd = "group"
endGroupCmd = "endgroup"
stepSummaryCmd = "step-summary"
debugCmd = "debug"
noticeCmd = "notice"
warningCmd = "warning"
errorCmd = "error"
errFileCmdFmt = "unable to write command to the environment file: %s"
)
// New creates a new wrapper with helpers for outputting information in GitHub
// actions format.
func New(opts ...Option) *Action {
a := &Action{
w: os.Stdout,
getenv: os.Getenv,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
for _, opt := range opts {
if opt == nil {
continue
}
a = opt(a)
}
return a
}
// Action is an internal wrapper around GitHub Actions' output and magic
// strings.
type Action struct {
w io.Writer
fields CommandProperties
getenv GetenvFunc
httpClient *http.Client
}
// IssueCommand issues a new GitHub actions Command. It panics if it cannot
// write to the output stream.
func (c *Action) IssueCommand(cmd *Command) {
if _, err := fmt.Fprint(c.w, cmd.String()+EOF); err != nil {
panic(fmt.Errorf("failed to issue command: %w", err))
}
}
// IssueFileCommand issues a new GitHub actions Command using environment files.
// It panics if writing to the file fails.
//
// https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#environment-files
//
// The TypeScript equivalent function:
//
// https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/file-command.ts#L10-L23
//
// IssueFileCommand currently ignores the 'CommandProperties' field provided
// with the 'Command' argument as it's scope is unclear in the current
// TypeScript implementation.
func (c *Action) IssueFileCommand(cmd *Command) {
if err := c.issueFileCommand(cmd); err != nil {
panic(err)
}
}
// issueFileCommand is an internal-only helper that issues the command and
// returns an error to make testing easier.
func (c *Action) issueFileCommand(cmd *Command) (retErr error) {
e := strings.ReplaceAll(cmd.Name, "-", "_")
e = strings.ToUpper(e)
e = "GITHUB_" + e
filepath := c.getenv(e)
msg := []byte(cmd.Message + EOF)
f, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
retErr = fmt.Errorf(errFileCmdFmt, err)
return
}
defer func() {
if err := f.Close(); err != nil && retErr == nil {
retErr = err
}
}()
if _, err := f.Write(msg); err != nil {
retErr = fmt.Errorf(errFileCmdFmt, err)
return
}
return
}
// AddMask adds a new field mask for the given string "p". After called, future
// attempts to log "p" will be replaced with "***" in log output. It panics if
// it cannot write to the output stream.
func (c *Action) AddMask(p string) {
// ::add-mask::<p>
c.IssueCommand(&Command{
Name: addMaskCmd,
Message: p,
})
}
// AddMatcher adds a new matcher with the given file path. It panics if it
// cannot write to the output stream.
func (c *Action) AddMatcher(p string) {
// ::add-matcher::<p>
c.IssueCommand(&Command{
Name: addMatcherCmd,
Message: p,
})
}
// RemoveMatcher removes a matcher with the given owner name. It panics if it
// cannot write to the output stream.
func (c *Action) RemoveMatcher(o string) {
// ::remove-matcher owner=<o>::
c.IssueCommand(&Command{
Name: removeMatcherCmd,
Properties: CommandProperties{
"owner": o,
},
})
}
// AddPath adds the string "p" to the path for the invocation. It panics if it
// cannot write to the output file.
//
// https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#adding-a-system-path
// https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
func (c *Action) AddPath(p string) {
c.IssueFileCommand(&Command{
Name: pathCmd,
Message: p,
})
}
// SaveState saves state to be used in the "finally" post job entry point. It
// panics if it cannot write to the output stream.
func (c *Action) SaveState(k, v string) {
// ::save-state name=<k>::<v>
c.IssueCommand(&Command{
Name: saveStateCmd,
Message: v,
Properties: CommandProperties{
"name": k,
},
})
}
// GetInput gets the input by the given name. It returns the empty string if the
// input is not defined.
func (c *Action) GetInput(i string) string {
e := strings.ReplaceAll(i, " ", "_")
e = strings.ToUpper(e)
e = "INPUT_" + e
return strings.TrimSpace(c.getenv(e))
}
// Group starts a new collapsable region up to the next ungroup invocation. It
// panics if it cannot write to the output stream.
func (c *Action) Group(t string) {
// ::group::<t>
c.IssueCommand(&Command{
Name: groupCmd,
Message: t,
})
}
// EndGroup ends the current group. It panics if it cannot write to the output
// stream.
func (c *Action) EndGroup() {
// ::endgroup::
c.IssueCommand(&Command{
Name: endGroupCmd,
})
}
// AddStepSummary writes the given markdown to the job summary. If a job summary
// already exists, this value is appended.
//
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary
// https://github.blog/2022-05-09-supercharging-github-actions-with-job-summaries/
func (c *Action) AddStepSummary(markdown string) {
c.IssueFileCommand(&Command{
Name: stepSummaryCmd,
Message: markdown,
})
}
// AddStepSummaryTemplate adds a summary template by parsing the given Go
// template using html/template with the given input data. See AddStepSummary
// for caveats.
//
// This primarily exists as a convenience function that renders a template.
func (c *Action) AddStepSummaryTemplate(tmpl string, data any) error {
t, err := template.New("").Parse(tmpl)
if err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
var b bytes.Buffer
if err := t.Execute(&b, data); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
c.AddStepSummary(b.String())
return nil
}
// SetEnv sets an environment variable. It panics if it cannot write to the
// output file.
//
// https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
// https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
func (c *Action) SetEnv(k, v string) {
c.IssueFileCommand(&Command{
Name: envCmd,
Message: fmt.Sprintf(envCmdMsgFmt, k, envCmdDelimiter, v, envCmdDelimiter),
})
}
// SetOutput sets an output parameter. It panics if it cannot write to the
// output stream.
func (c *Action) SetOutput(k, v string) {
// ::set-output name=<k>::<v>
c.IssueCommand(&Command{
Name: setOutputCmd,
Message: v,
Properties: CommandProperties{
"name": k,
},
})
}
// Debugf prints a debug-level message. It follows the standard fmt.Printf
// arguments, appending an OS-specific line break to the end of the message. It
// panics if it cannot write to the output stream.
func (c *Action) Debugf(msg string, args ...any) {
// ::debug <c.fields>::<msg, args>
c.IssueCommand(&Command{
Name: debugCmd,
Message: fmt.Sprintf(msg, args...),
Properties: c.fields,
})
}
// Noticef prints a notice-level message. It follows the standard fmt.Printf
// arguments, appending an OS-specific line break to the end of the message. It
// panics if it cannot write to the output stream.
func (c *Action) Noticef(msg string, args ...any) {
// ::notice <c.fields>::<msg, args>
c.IssueCommand(&Command{
Name: noticeCmd,
Message: fmt.Sprintf(msg, args...),
Properties: c.fields,
})
}
// Warningf prints a warning-level message. It follows the standard fmt.Printf
// arguments, appending an OS-specific line break to the end of the message. It
// panics if it cannot write to the output stream.
func (c *Action) Warningf(msg string, args ...any) {
// ::warning <c.fields>::<msg, args>
c.IssueCommand(&Command{
Name: warningCmd,
Message: fmt.Sprintf(msg, args...),
Properties: c.fields,
})
}
// Errorf prints a error-level message. It follows the standard fmt.Printf
// arguments, appending an OS-specific line break to the end of the message. It
// panics if it cannot write to the output stream.
func (c *Action) Errorf(msg string, args ...any) {
// ::error <c.fields>::<msg, args>
c.IssueCommand(&Command{
Name: errorCmd,
Message: fmt.Sprintf(msg, args...),
Properties: c.fields,
})
}
// Fatalf prints a error-level message and exits. This is equivalent to Errorf
// followed by os.Exit(1).
func (c *Action) Fatalf(msg string, args ...any) {
c.Errorf(msg, args...)
osExit(1)
}
// Infof prints message to stdout without any level annotations. It follows the
// standard fmt.Printf arguments, appending an OS-specific line break to the end
// of the message. It panics if it cannot write to the output stream.
func (c *Action) Infof(msg string, args ...any) {
if _, err := fmt.Fprintf(c.w, msg+EOF, args...); err != nil {
panic(fmt.Errorf("failed to write info command: %w", err))
}
}
// WithFieldsSlice includes the provided fields in log output. "f" must be a
// slice of k=v pairs. The given slice will be sorted. It panics if any of the
// string in the given slice does not construct a valid 'key=value' pair.
func (c *Action) WithFieldsSlice(f []string) *Action {
m := make(CommandProperties)
for _, s := range f {
pair := strings.SplitN(s, "=", 2)
if len(pair) < 2 {
panic(fmt.Sprintf("%q is not a proper k=v pair!", s))
}
m[pair[0]] = pair[1]
}
return c.WithFieldsMap(m)
}
// WithFieldsMap includes the provided fields in log output. The fields in "m"
// are automatically converted to k=v pairs and sorted.
func (c *Action) WithFieldsMap(m map[string]string) *Action {
return &Action{
w: c.w,
fields: m,
getenv: c.getenv,
httpClient: c.httpClient,
}
}
// idTokenResponse is the response from minting an ID token.
type idTokenResponse struct {
Value string `json:"value,omitempty"`
}
// GetIDToken returns the GitHub OIDC token from the GitHub Actions runtime.
func (c *Action) GetIDToken(ctx context.Context, audience string) (string, error) {
requestURL := c.getenv("ACTIONS_ID_TOKEN_REQUEST_URL")
if requestURL == "" {
return "", fmt.Errorf("missing ACTIONS_ID_TOKEN_REQUEST_URL in environment")
}
requestToken := c.getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
if requestToken == "" {
return "", fmt.Errorf("missing ACTIONS_ID_TOKEN_REQUEST_TOKEN in environment")
}
u, err := url.Parse(requestURL)
if err != nil {
return "", fmt.Errorf("failed to parse request URL: %w", err)
}
if audience != "" {
q := u.Query()
q.Set("audience", audience)
u.RawQuery = q.Encode()
}
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return "", fmt.Errorf("failed to create HTTP request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+requestToken)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to make HTTP request: %w", err)
}
defer resp.Body.Close()
// This has moved to the io package in Go 1.16, but we still support up to Go
// 1.13 for now.
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1000))
if err != nil {
return "", fmt.Errorf("failed to read response body: %w", err)
}
body = bytes.TrimSpace(body)
if resp.StatusCode != 200 {
return "", fmt.Errorf("non-successful response from minting OIDC token: %s", body)
}
var tokenResp idTokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return "", fmt.Errorf("failed to process response as JSON: %w", err)
}
return tokenResp.Value, nil
}
// Getenv retrieves the value of the environment variable named by the key.
// It uses an internal function that can be set with `WithGetenv`.
func (c *Action) Getenv(key string) string {
return c.getenv(key)
}
// GetenvFunc is an abstraction to make tests feasible for commands that
// interact with environment variables.
type GetenvFunc func(key string) string