Skip to content

Commit 3de4a05

Browse files
committed
reflactor: do some optimizations to githubactions
Signed-off-by: Daniel Hu <[email protected]>
1 parent 59cf87e commit 3de4a05

File tree

6 files changed

+144
-161
lines changed

6 files changed

+144
-161
lines changed

internal/pkg/githubactions/githubactions.go

Lines changed: 117 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -4,118 +4,168 @@ import (
44
"context"
55
"fmt"
66
"log"
7+
"net/http"
78

89
"github.com/google/go-github/v40/github"
10+
"github.com/mitchellh/mapstructure"
911
"github.com/spf13/viper"
1012
"golang.org/x/oauth2"
1113
)
1214

13-
func generateGitHubWorkflowFileByName(f string) string {
14-
return fmt.Sprintf("%s/%s", ".github/workflows", f)
15+
// Options is the struct for configurations of the githubactions plugin.
16+
type Options struct {
17+
Owner string
18+
Repo string
19+
Language *Language
20+
Branch string
1521
}
1622

17-
func getGitHubToken() string {
18-
err := viper.BindEnv("github_token")
19-
if err != nil {
20-
log.Fatalf("ENV var GITHUB_TOKEN is needed")
21-
}
22-
23-
token, ok := viper.Get("github_token").(string)
24-
if !ok {
25-
log.Fatalf("ENV var GITHUB_TOKEN is needed")
26-
}
27-
28-
return token
23+
// Language is the struct containing details of a programming language specified in the GitHub Actions workflow.
24+
type Language struct {
25+
Name string
26+
Version string
2927
}
3028

31-
func getGitHubClient(ctx *context.Context) *github.Client {
32-
token := getGitHubToken()
33-
ts := oauth2.StaticTokenSource(
34-
&oauth2.Token{AccessToken: token},
35-
)
36-
tc := oauth2.NewClient(*ctx, ts)
37-
return github.NewClient(tc)
29+
type GithubActions struct {
30+
ctx context.Context
31+
client *github.Client
32+
options *Options
3833
}
3934

40-
func fileExists(params *Param) bool {
41-
_, _, resp, err := params.client.Repositories.GetContents(
42-
*params.ctx,
43-
params.options.Owner,
44-
params.options.Repo,
45-
generateGitHubWorkflowFileByName(params.workflow.workflowFileName),
46-
&github.RepositoryContentGetOptions{})
35+
func NewGithubActions(options *map[string]interface{}) (*GithubActions, error) {
36+
ctx := context.Background()
4737

38+
var opt Options
39+
err := mapstructure.Decode(*options, &opt)
4840
if err != nil {
49-
if resp.StatusCode == 401 {
50-
log.Fatal("invalid GitHub credentials in GITHUB_TOKEN ENV var")
51-
} else if resp.StatusCode != 404 {
52-
log.Fatal(err)
53-
}
41+
return nil, err
5442
}
5543

56-
if resp.StatusCode == 200 {
57-
return true
44+
client, err := getGitHubClient(ctx)
45+
if err != nil {
46+
return nil, err
5847
}
59-
return false
6048

49+
return &GithubActions{
50+
ctx: ctx,
51+
client: client,
52+
options: &opt,
53+
}, nil
6154
}
6255

63-
func createFile(params *Param) (bool, error) {
64-
if fileExists(params) {
65-
log.Printf("github actions workflow %s already exists\n", params.workflow.workflowFileName)
66-
return true, nil
56+
func (ga *GithubActions) AddWorkflow(workflow Workflow) error {
57+
exists, err := ga.fileExists(workflow.workflowFileName)
58+
if err != nil {
59+
return err
60+
}
61+
if exists {
62+
log.Printf("github actions workflow %s already exists\n", workflow.workflowFileName)
63+
return nil
6764
}
6865

6966
// Note: the file needs to be absent from the repository as you are not
7067
// specifying a SHA reference here.
7168
opts := &github.RepositoryContentFileOptions{
72-
Message: github.String(params.workflow.commitMessage),
73-
Content: []byte(params.workflow.workflowContent),
69+
Message: github.String(workflow.commitMessage),
70+
Content: []byte(workflow.workflowContent),
7471
Branch: github.String("master"),
7572
}
7673

77-
log.Printf("creating github actions workflow %s...\n", params.workflow.workflowFileName)
78-
_, _, err := params.client.Repositories.CreateFile(
79-
*params.ctx,
80-
params.options.Owner,
81-
params.options.Repo,
82-
generateGitHubWorkflowFileByName(params.workflow.workflowFileName),
74+
log.Printf("creating github actions workflow %s...\n", workflow.workflowFileName)
75+
_, _, err = ga.client.Repositories.CreateFile(
76+
ga.ctx,
77+
ga.options.Owner,
78+
ga.options.Repo,
79+
generateGitHubWorkflowFileByName(workflow.workflowFileName),
8380
opts)
8481

8582
if err != nil {
86-
log.Println(err.Error())
87-
return false, err
83+
log.Println(err)
84+
return err
8885
}
89-
log.Printf("github actions workflow %s created\n", params.workflow.workflowFileName)
90-
return true, nil
86+
log.Printf("github actions workflow %s created\n", workflow.workflowFileName)
87+
return nil
9188
}
9289

93-
func removeFile(params *Param) (bool, error) {
94-
if !fileExists(params) {
95-
log.Printf("github actions workflow %s already removed\n", params.workflow.workflowFileName)
96-
return true, nil
90+
func (ga *GithubActions) DeleteWorkflow(workflow Workflow) error {
91+
exists, err := ga.fileExists(workflow.workflowFileName)
92+
if err != nil {
93+
return err
94+
}
95+
if !exists {
96+
log.Printf("github actions workflow %s already removed\n", workflow.workflowFileName)
97+
return nil
9798
}
9899

99100
// Note: the file needs to be absent from the repository as you are not
100101
// specifying a SHA reference here.
101102
opts := &github.RepositoryContentFileOptions{
102-
Message: github.String(params.workflow.commitMessage),
103-
Content: []byte(params.workflow.workflowContent),
103+
Message: github.String(workflow.commitMessage),
104+
Content: []byte(workflow.workflowContent),
104105
Branch: github.String("master"),
105106
}
106107

107-
log.Printf("deleting github actions workflow %s...\n", params.workflow.workflowFileName)
108-
_, _, err := params.client.Repositories.DeleteFile(
109-
*params.ctx,
110-
params.options.Owner,
111-
params.options.Repo,
112-
generateGitHubWorkflowFileByName(params.workflow.workflowFileName),
108+
log.Printf("deleting github actions workflow %s...\n", workflow.workflowFileName)
109+
_, _, err = ga.client.Repositories.DeleteFile(
110+
ga.ctx,
111+
ga.options.Owner,
112+
ga.options.Repo,
113+
generateGitHubWorkflowFileByName(workflow.workflowFileName),
113114
opts)
114115

115116
if err != nil {
116-
log.Println(err.Error())
117+
log.Println(err)
118+
return err
119+
}
120+
log.Printf("github actions workflow %s removed\n", workflow.workflowFileName)
121+
return nil
122+
}
123+
124+
func generateGitHubWorkflowFileByName(f string) string {
125+
return fmt.Sprintf(".github/workflows/%s", f)
126+
}
127+
128+
func (ga *GithubActions) fileExists(filename string) (bool, error) {
129+
_, _, resp, err := ga.client.Repositories.GetContents(
130+
ga.ctx,
131+
ga.options.Owner,
132+
ga.options.Repo,
133+
generateGitHubWorkflowFileByName(filename),
134+
&github.RepositoryContentGetOptions{},
135+
)
136+
137+
if resp.StatusCode == http.StatusNotFound {
138+
return false, nil
139+
}
140+
141+
if err != nil {
117142
return false, err
118143
}
119-
log.Printf("github actions workflow %s removed\n", params.workflow.workflowFileName)
120-
return true, nil
144+
145+
if resp.StatusCode == http.StatusOK {
146+
return true, nil
147+
}
148+
return false, fmt.Errorf("got some error is not expected")
149+
}
150+
151+
func getGitHubToken() string {
152+
err := viper.BindEnv("github_token")
153+
if err != nil {
154+
log.Println("ENV var GITHUB_TOKEN is needed")
155+
return ""
156+
}
157+
158+
return viper.GetString("github_token")
159+
}
160+
161+
func getGitHubClient(ctx context.Context) (*github.Client, error) {
162+
token := getGitHubToken()
163+
if token == "" {
164+
return nil, fmt.Errorf("failed to initialize GitHub token")
165+
}
166+
ts := oauth2.StaticTokenSource(
167+
&oauth2.Token{AccessToken: token},
168+
)
169+
tc := oauth2.NewClient(ctx, ts)
170+
return github.NewClient(tc), nil
121171
}
Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,23 @@
11
package githubactions
22

3-
import (
4-
"context"
5-
"log"
6-
7-
"github.com/mitchellh/mapstructure"
8-
)
9-
103
var workflows = []Workflow{
114
{"pr builder by DevStream", "pr-builder.yml", prBuilder},
125
{"master builder by DevStream", "master-builder.yml", masterBuilder},
136
}
147

158
// Install sets up GitHub Actions workflows.
169
func Install(options *map[string]interface{}) (bool, error) {
17-
ctx := context.Background()
18-
19-
var opt Options
20-
err := mapstructure.Decode(*options, &opt)
10+
githubActions, err := NewGithubActions(options)
2111
if err != nil {
22-
log.Fatalln(err)
12+
return false, err
2313
}
2414

2515
for _, pipeline := range workflows {
26-
_, errCreate := createFile(&Param{
27-
&ctx,
28-
getGitHubClient(&ctx),
29-
&opt,
30-
&pipeline,
31-
})
32-
if errCreate != nil {
33-
return false, errCreate
16+
err := githubActions.AddWorkflow(pipeline)
17+
if err != nil {
18+
return false, err
3419
}
3520
}
21+
3622
return true, nil
3723
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package githubactions
2+
3+
// Workflow is the struct for a GitHub Actions workflow.
4+
type Workflow struct {
5+
commitMessage string
6+
workflowFileName string
7+
workflowContent string
8+
}

internal/pkg/githubactions/params.go

Lines changed: 0 additions & 36 deletions
This file was deleted.
Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,23 @@
11
package githubactions
22

3-
import (
4-
"context"
5-
"github.com/mitchellh/mapstructure"
6-
)
7-
83
// Reinstall remove and set up GitHub Actions workflows.
94
func Reinstall(options *map[string]interface{}) (bool, error) {
10-
ctx := context.Background()
11-
12-
var opt Options
13-
err := mapstructure.Decode(*options, &opt)
5+
githubActions, err := NewGithubActions(options)
146
if err != nil {
157
return false, err
168
}
179

1810
for _, pipeline := range workflows {
19-
param := &Param{
20-
&ctx,
21-
getGitHubClient(&ctx),
22-
&opt,
23-
&pipeline,
24-
}
25-
_, errRemove := removeFile(param)
26-
if errRemove != nil {
27-
return false, errRemove
11+
err := githubActions.DeleteWorkflow(pipeline)
12+
if err != nil {
13+
return false, err
2814
}
2915

30-
_, errCreate := createFile(param)
31-
if errCreate != nil {
32-
return false, errCreate
16+
err = githubActions.AddWorkflow(pipeline)
17+
if err != nil {
18+
return false, err
3319
}
3420
}
21+
3522
return true, nil
3623
}

0 commit comments

Comments
 (0)