This repository has been archived by the owner on Mar 30, 2021. It is now read-only.
/
actions.go
81 lines (64 loc) · 1.75 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
package gh
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/eikc/gapp/internal/authentication"
"github.com/google/go-github/v30/github"
"golang.org/x/oauth2"
)
type ActionsClient struct {
client *github.Client
pkeys map[string]*github.PublicKey
}
func (c *ActionsClient) Dispatch(ctx context.Context, owner, repo, event string, payload []byte) error {
raw := json.RawMessage(payload)
req := github.DispatchRequestOptions{
EventType: event,
ClientPayload: &raw,
}
_, _, err := c.client.Repositories.Dispatch(ctx, owner, repo, req)
return err
}
type SecretParams struct {
Name string
Value string
PkeyId string
}
func NewActionsClient(ctx context.Context, user authentication.User) *ActionsClient {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: user.Token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
return &ActionsClient{
client: client,
pkeys: map[string]*github.PublicKey{},
}
}
func (c *ActionsClient) GetPublicKey(ctx context.Context, owner, repo string) ([]byte, string, error) {
repoUrl := fmt.Sprintf("%s/%s", owner, repo)
val, ok := c.pkeys[repoUrl]
if !ok {
key, _, err := c.client.Actions.GetPublicKey(ctx, owner, repo)
if err != nil {
return nil, "", err
}
c.pkeys[repoUrl] = key
val = key
}
decoded, err := base64.StdEncoding.DecodeString(*val.Key)
if err != nil {
return nil, "", err
}
return decoded, *val.KeyID, nil
}
func (c *ActionsClient) AddOrUpdateSecret(ctx context.Context, owner, repo string, secret SecretParams) error {
_, err := c.client.Actions.CreateOrUpdateSecret(ctx, owner, repo, &github.EncryptedSecret{
Name: secret.Name,
KeyID: secret.PkeyId,
EncryptedValue: secret.Value,
})
return err
}