/
deployment.go
76 lines (68 loc) · 1.91 KB
/
deployment.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
package github
import (
"context"
"fmt"
"regexp"
"strconv"
"github.com/google/go-github/v58/github"
)
type Deployment struct {
Repository Repository
Id int64
}
var patternDeploymentURL = regexp.MustCompile(`^https://api\.github\.com/repos/(.+?)/(.+?)/deployments/(\d+)$`)
// ParseDeploymentURL parses the URL.
// For example, https://api.github.com/repos/int128/sandbox/deployments/422988781
func ParseDeploymentURL(s string) *Deployment {
m := patternDeploymentURL.FindStringSubmatch(s)
if len(m) != 4 {
return nil
}
id, err := strconv.ParseInt(m[3], 10, 64)
if err != nil {
return nil
}
return &Deployment{
Repository: Repository{Owner: m[1], Name: m[2]},
Id: int64(id),
}
}
type DeploymentStatus struct {
State string
Description string
LogURL string
EnvironmentURL string
}
func (c *client) CreateDeploymentStatus(ctx context.Context, d Deployment, ds DeploymentStatus) error {
r := github.DeploymentStatusRequest{
State: github.String(ds.State),
Description: github.String(ds.Description),
}
if ds.LogURL != "" {
r.LogURL = github.String(ds.LogURL)
}
if ds.EnvironmentURL != "" {
r.EnvironmentURL = github.String(ds.EnvironmentURL)
}
_, _, err := c.rest.Repositories.CreateDeploymentStatus(ctx, d.Repository.Owner, d.Repository.Name, d.Id, &r)
if err != nil {
return fmt.Errorf("GitHub API error: %w", err)
}
return nil
}
func (c *client) FindLatestDeploymentStatus(ctx context.Context, d Deployment) (*DeploymentStatus, error) {
r, _, err := c.rest.Repositories.ListDeploymentStatuses(ctx, d.Repository.Owner, d.Repository.Name, d.Id, nil)
if err != nil {
return nil, fmt.Errorf("GitHub API error: %w", err)
}
if len(r) == 0 {
return nil, nil
}
ds := r[0]
return &DeploymentStatus{
State: ds.GetState(),
Description: ds.GetDescription(),
LogURL: ds.GetLogURL(),
EnvironmentURL: ds.GetEnvironmentURL(),
}, nil
}