-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
85 lines (78 loc) · 2.22 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
package main
import (
"context"
"fmt"
"github.com/codeship/codeship-go"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
)
type buildConfig struct {
OrgName string `yaml:"org_name"`
Projects []project `yaml:"projects"`
}
type project struct {
Name string
Branch string
UUID string
}
func readConfig() (m buildConfig) {
data, err := ioutil.ReadFile("build_trigger.yml")
if err != nil {
log.Fatal("could not read build_trigger.yml in current directory")
}
err = yaml.Unmarshal(data, &m)
if err != nil {
log.Fatal("could not unmarshall config file, Error",err)
}
return
}
func findLatestSHA(p project, org *codeship.Organization) (string, error) {
opt := codeship.PerPage(50)
ctx := context.Background()
builds, _, err := org.ListBuilds(ctx, p.UUID, opt)
if err != nil {
log.Fatalf("Could not list builds %s", err)
}
for _, build := range builds.Builds {
if build.Ref == p.Branch && build.Status == "success" {
return build.CommitSha, nil
}
}
return "", fmt.Errorf("no prior builds to pull from for %s on branch %s", p.Name, p.Branch)
}
func triggerBuild(org *codeship.Organization, p project) {
ctx := context.Background()
//list past builds, trigger last build
latestBuildSha, err := findLatestSHA(p, org)
if err != nil {
log.Printf("Encountered error triggering builf for repo %s, error %s", p.Name, err.Error())
return
}
success, resp, err := org.CreateBuild(ctx, p.UUID, p.Branch, latestBuildSha)
if err != nil {
log.Fatalf("Could not trigger build for %s\n response details:\n %+v, %s", p.Name, resp,err)
}
if success == true {
log.Printf("Build for %s successfully triggered", p.Name)
}
}
func main() {
config := readConfig()
ctx := context.Background()
auth := codeship.NewBasicAuth(os.Getenv("CODESHIP_USERNAME"), os.Getenv("CODESHIP_PASSWORD"))
client, err := codeship.New(auth)
if err != nil {
log.Fatalln("encountered issue authenticating",err.Error())
}
org, err := client.Organization(ctx, config.OrgName)
if err != nil {
log.Fatalf("encountered issue selecting organization %s, Error: %s", config.OrgName, err.Error())
}
println("ORG UUID =", org.UUID)
for _, project := range config.Projects {
log.Printf("Triggering build for %s", project.Name)
triggerBuild(org, project)
}
}