-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathactions.go
686 lines (614 loc) · 19.6 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// 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"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
var (
// osExit allows `os.Exit()` to be stubbed during testing.
osExit = os.Exit
)
const (
addMaskCmd = "add-mask"
envCmd = "env"
outputCmd = "output"
pathCmd = "path"
stateCmd = "state"
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
multiLineFileDelim = "_GitHubActionsFileCommandDelimeter_"
multilineFileCmd = "%s<<" + multiLineFileDelim + EOF + "%s" + EOF + multiLineFileDelim // ${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}
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.
//
// On 2022-10-11, GitHub deprecated "::save-state name=<k>::<v>" in favor of
// [environment files].
//
// [environment files]: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
func (c *Action) SaveState(k, v string) {
c.IssueFileCommand(&Command{
Name: stateCmd,
Message: fmt.Sprintf(multilineFileCmd, k, v),
})
}
// 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(multilineFileCmd, k, v),
})
}
// SetOutput sets an output parameter. It panics if it cannot write to the
// output stream.
//
// On 2022-10-11, GitHub deprecated "::set-output name=<k>::<v>" in favor of
// [environment files].
//
// [environment files]: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
func (c *Action) SetOutput(k, v string) {
c.IssueFileCommand(&Command{
Name: outputCmd,
Message: fmt.Sprintf(multilineFileCmd, k, v),
})
}
// 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
// GitHubContext of current workflow.
//
// See: https://docs.github.com/en/actions/learn-github-actions/environment-variables
type GitHubContext struct {
Action string
ActionPath string
ActionRepository string
Actions bool
Actor string
ActorID string
APIURL string
BaseRef string
Env string
EventName string
EventPath string
GraphqlURL string
HeadRef string
Job string
Path string
Ref string
RefName string
RefProtected bool
RefType string
// Repository is the owner and repository name. For example, octocat/Hello-World
// It is not recommended to use this field to acquire the repository name
// but to use the Repo method instead.
Repository string
// RepositoryOwner is the repository owner. For example, octocat
// It is not recommended to use this field to acquire the repository owner
// but to use the Repo method instead.
RepositoryOwner string
RetentionDays int64
RunAttempt int64
RunID int64
RunNumber int64
ServerURL string
SHA string
StepSummary string
TriggeringActor string
Workflow string
Workspace string
// Event is populated by parsing the file at EventPath, if it exists.
Event map[string]any
}
// Repo returns the username of the repository owner and repository name.
func (c *GitHubContext) Repo() (string, string) {
if c == nil {
return "", ""
}
// Based on https://github.com/actions/toolkit/blob/main/packages/github/src/context.ts
if c.Repository != "" {
parts := strings.SplitN(c.Repository, "/", 2)
if len(parts) == 1 {
return parts[0], ""
}
return parts[0], parts[1]
}
// If c.Repository is empty attempt to get the repo from the Event data.
var repoName string
// NOTE: differs from context.ts. Fall back to GITHUB_REPOSITORY_OWNER
ownerName := c.RepositoryOwner
if c.Event != nil {
if repo, ok := c.Event["repository"].(map[string]any); ok {
if name, ok := repo["name"].(string); ok {
repoName = name
}
if owner, ok := repo["owner"].(map[string]any); ok {
if name, ok := owner["name"].(string); ok {
ownerName = name
}
}
}
}
return ownerName, repoName
}
func parseBool(v string) (bool, error) {
if v == "" {
return false, nil
}
return strconv.ParseBool(v)
}
func parseInt(v string) (int64, error) {
if v == "" {
return 0, nil
}
return strconv.ParseInt(v, 10, 64)
}
// Context returns the context of current action with the payload object
// that triggered the workflow
func (c *Action) Context() (*GitHubContext, error) {
var merr error
githubContext := &GitHubContext{
APIURL: "https://api.github.com",
GraphqlURL: "https://api.github.com/graphql",
ServerURL: "https://github.com",
}
if v := c.getenv("GITHUB_ACTION"); v != "" {
githubContext.Action = v
}
if v := c.getenv("GITHUB_ACTION_PATH"); v != "" {
githubContext.ActionPath = v
}
if v := c.getenv("GITHUB_ACTION_REPOSITORY"); v != "" {
githubContext.ActionRepository = v
}
if v, err := parseBool(c.getenv("GITHUB_ACTIONS")); err == nil {
githubContext.Actions = v
} else {
merr = errors.Join(merr, err)
}
if v := c.getenv("GITHUB_ACTOR"); v != "" {
githubContext.Actor = v
}
if v := c.getenv("GITHUB_ACTOR_ID"); v != "" {
githubContext.ActorID = v
}
if v := c.getenv("GITHUB_API_URL"); v != "" {
githubContext.APIURL = v
}
if v := c.getenv("GITHUB_BASE_REF"); v != "" {
githubContext.BaseRef = v
}
if v := c.getenv("GITHUB_ENV"); v != "" {
githubContext.Env = v
}
if v := c.getenv("GITHUB_EVENT_NAME"); v != "" {
githubContext.EventName = v
}
if v := c.getenv("GITHUB_EVENT_PATH"); v != "" {
githubContext.EventPath = v
}
if v := c.getenv("GITHUB_GRAPHQL_URL"); v != "" {
githubContext.GraphqlURL = v
}
if v := c.getenv("GITHUB_HEAD_REF"); v != "" {
githubContext.HeadRef = v
}
if v := c.getenv("GITHUB_JOB"); v != "" {
githubContext.Job = v
}
if v := c.getenv("GITHUB_PATH"); v != "" {
githubContext.Path = v
}
if v := c.getenv("GITHUB_REF"); v != "" {
githubContext.Ref = v
}
if v := c.getenv("GITHUB_REF_NAME"); v != "" {
githubContext.RefName = v
}
if v, err := parseBool(c.getenv("GITHUB_REF_PROTECTED")); err == nil {
githubContext.RefProtected = v
} else {
merr = errors.Join(merr, err)
}
if v := c.getenv("GITHUB_REF_TYPE"); v != "" {
githubContext.RefType = v
}
if v := c.getenv("GITHUB_REPOSITORY"); v != "" {
githubContext.Repository = v
}
if v := c.getenv("GITHUB_REPOSITORY_OWNER"); v != "" {
githubContext.RepositoryOwner = v
}
if v, err := parseInt(c.getenv("GITHUB_RETENTION_DAYS")); err == nil {
githubContext.RetentionDays = v
} else {
merr = errors.Join(merr, err)
}
if v, err := parseInt(c.getenv("GITHUB_RUN_ATTEMPT")); err == nil {
githubContext.RunAttempt = v
} else {
merr = errors.Join(merr, err)
}
if v, err := parseInt(c.getenv("GITHUB_RUN_ID")); err == nil {
githubContext.RunID = v
} else {
merr = errors.Join(merr, err)
}
if v, err := parseInt(c.getenv("GITHUB_RUN_NUMBER")); err == nil {
githubContext.RunNumber = v
} else {
merr = errors.Join(merr, err)
}
if v := c.getenv("GITHUB_SERVER_URL"); v != "" {
githubContext.ServerURL = v
}
if v := c.getenv("GITHUB_SHA"); v != "" {
githubContext.SHA = v
}
if v := c.getenv("GITHUB_STEP_SUMMARY"); v != "" {
githubContext.StepSummary = v
}
if v := c.getenv("GITHUB_TRIGGERING_ACTOR"); v != "" {
githubContext.TriggeringActor = v
}
if v := c.getenv("GITHUB_WORKFLOW"); v != "" {
githubContext.Workflow = v
}
if v := c.getenv("GITHUB_WORKSPACE"); v != "" {
githubContext.Workspace = v
}
if githubContext.EventPath != "" {
eventData, err := os.ReadFile(githubContext.EventPath)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("could not read event file: %w", err)
}
if eventData != nil {
if err := json.Unmarshal(eventData, &githubContext.Event); err != nil {
return nil, fmt.Errorf("failed to unmarshal event payload: %w", err)
}
}
}
return githubContext, merr
}