forked from drone-plugins/drone-downstream
/
main.go
111 lines (93 loc) · 2.47 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
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"os"
"strings"
"github.com/drone/drone-go/drone"
"github.com/drone/drone-go/plugin"
)
// Params stores the git clone parameters used to
// configure and customzie the git clone behavior.
type Params struct {
Repos []string `json:"repositories"`
Server string `json:"server"`
Token string `json:"token"`
Fork bool `json:"fork"`
}
var (
buildDate string
)
func main() {
fmt.Printf("Drone Downstream Plugin built at %s\n", buildDate)
v := new(Params)
s := new(drone.System)
plugin.Param("system", s)
plugin.Param("vargs", v)
plugin.MustParse()
// if no server url is provided we can default
// to the hosted Drone service.
if len(v.Token) == 0 {
fmt.Println("Error: you must provide your Drone access token.")
os.Exit(1)
}
if v.Server == "" {
v.Server = s.Link
}
// create the drone client
client := drone.NewClientToken(v.Server, v.Token)
for _, entry := range v.Repos {
// parses the repository name in owner/name@branch format
owner, name, branch := parseRepoBranch(entry)
if len(owner) == 0 || len(name) == 0 {
fmt.Printf("Error: unable to parse repository name %s.\n", entry)
os.Exit(1)
}
if v.Fork {
// get the latest build for the specified repository
build, err := client.BuildLast(owner, name, branch)
if err != nil {
fmt.Printf("Error: unable to get latest build for %s.\n", entry)
os.Exit(1)
}
// start a new build
_, err = client.BuildFork(owner, name, build.Number)
if err != nil {
fmt.Printf("Error: unable to trigger a new build for %s.\n", entry)
os.Exit(1)
}
fmt.Printf("Starting new build %d for %s\n", build.Number, entry)
} else {
// get the latest build for the specified repository
build, err := client.BuildLast(owner, name, branch)
if err != nil {
fmt.Printf("Error: unable to get latest build for %s.\n", entry)
os.Exit(1)
}
// rebuild the latest build
_, err = client.BuildStart(owner, name, build.Number)
if err != nil {
fmt.Printf("Error: unable to trigger build for %s.\n", entry)
os.Exit(1)
}
fmt.Printf("Restarting build %d for %s\n", build.Number, entry)
}
}
}
func parseRepoBranch(repo string) (string, string, string) {
var (
owner string
name string
branch string
)
parts := strings.Split(repo, "@")
if len(parts) == 2 {
branch = parts[1]
repo = parts[0]
}
parts = strings.Split(repo, "/")
if len(parts) == 2 {
owner = parts[0]
name = parts[1]
}
return owner, name, branch
}