-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
99 lines (81 loc) · 2.14 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"github.com/google/go-github/v29/github"
"golang.org/x/oauth2"
"os"
"strconv"
"strings"
"time"
)
func main() {
ctx := context.Background()
token := &oauth2.Token{AccessToken: os.Getenv("INPUT_TOKEN")}
ts := oauth2.StaticTokenSource(token)
tc := oauth2.NewClient(ctx, ts)
client := &wrapper{github.NewClient(tc)}
minDeletionSize, _ := strconv.Atoi(os.Getenv("INPUT_MINIMUMDELETIONSIZE"))
minAge, _ := strconv.ParseFloat(os.Getenv("INPUT_MINIMUMAGE"), 64)
name := os.Getenv("INPUT_NAME")
ownerRepo := os.Getenv("INPUT_REPOSITORY")
if len(ownerRepo) == 0 {
ownerRepo = os.Getenv("GITHUB_REPOSITORY")
}
split := strings.SplitN(ownerRepo, "/", 2)
owner := split[0]
repo := split[1]
err := forEachArtifact(ctx, client, owner, repo, func(ctx context.Context, artifact *Artifact, run *WorkflowRun) (bool, error) {
if artifact.SizeInBytes < minDeletionSize {
return false, nil
}
age := time.Now().Sub(artifact.CreatedAt)
if age.Seconds() < minAge {
return false, nil
}
if len(name) > 0 && name != artifact.Name {
return false, nil
}
fmt.Printf("Deleting %s\n", artifact.URL)
resp, err := client.DeleteWorkflowArtifact(ctx, artifact.URL)
if err != nil {
return true, err
}
if resp.StatusCode != 204 {
return true, errors.New(fmt.Sprintf("Unexpected status code deleting artifact: %d", resp.StatusCode))
}
return false, nil
})
if err != nil {
panic(err)
}
}
func forEachArtifact(ctx context.Context, client *wrapper, owner, repo string, iter func(ctx context.Context, artifact *Artifact, run *WorkflowRun) (bool, error)) error {
opt := &github.ListOptions{}
for {
runs, resp, err := client.ListWorkflowRuns(ctx, owner, repo, opt)
if err != nil {
return err
}
for _, run := range runs {
artifacts, _, err := client.ListWorkflowArtifacts(ctx, run.ArtifactsURL, nil)
if err != nil {
return err
}
for _, artifact := range artifacts {
stop, err := iter(ctx, artifact, run)
if err != nil {
return err
}
if stop {
return nil
}
}
}
if resp.NextPage == 0 {
return nil
}
opt.Page = resp.NextPage
}
}