This repository has been archived by the owner on Oct 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
219 lines (191 loc) · 5.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
"github.com/google/go-github/github"
"github.com/nicolai86/github-rebase-bot/processors"
"github.com/nicolai86/github-rebase-bot/repo"
"golang.org/x/oauth2"
)
var (
token string
repos repositories
mergeLabel string
)
type repositories []repository
func (rs repositories) Find(owner, name string) *repository {
for i := range rs {
if rs[i].Owner == owner && rs[i].Name == name {
return &rs[i]
}
}
return nil
}
func (hps *repositories) String() string {
return fmt.Sprint(*hps)
}
func (hps *repositories) Set(str string) error {
for _, hp := range strings.Split(str, ",") {
var h repository
if err := h.Set(hp); err != nil {
return err
}
*hps = append(*hps, h)
}
return nil
}
type repository struct {
processors.Repository
hook *github.Hook
}
func (h *repository) String() string {
return fmt.Sprintf("%s/%s#%s", h.Owner, h.Name, h.Mainline)
}
func (h *repository) Set(str string) error {
var parts = strings.Split(str, "/")
if len(parts) != 2 {
return fmt.Errorf("Invalid repository %q. Must be owner/name", str)
}
h.Owner = parts[0]
parts = strings.Split(parts[1], "#")
h.Name = parts[0]
if len(parts) == 2 {
h.Mainline = parts[1]
}
if h.Mainline == "" {
h.Mainline = "master"
}
return nil
}
func main() {
var publicDNS string
flag.StringVar(&token, "github-token", "", "auth token for GH")
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
var addr string
flag.Var(&repos, "repos", "github repos (owner/repo separated by commas)")
flag.StringVar(&publicDNS, "public-dns", "", "publicly accessible dns endpoint for webhook push")
flag.StringVar(&mergeLabel, "merge-label", "", "which label is checked to kick off the merge process")
flag.StringVar(&addr, "addr", "", "address to listen on")
flag.Parse()
if token == "" {
log.Fatal("Missing github token.")
}
if len(repos) == 0 {
log.Fatal("Missing repositories.")
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
client := github.NewClient(tc)
user, _, err := client.Users.Get(context.Background(), "")
if err != nil {
log.Fatalf("resolving github user failed: %v", err)
}
username := *user.Login
log.Printf("Bot started for user %s.\n", username)
log.Printf("Using %q as merge-label.\n", mergeLabel)
if err := exec.Command("git", "config", "--global", "user.name", "rebase bot").Run(); err != nil {
log.Fatal("git config --global user.name failed: %q", err)
}
if err := exec.Command("git", "config", "--global", "user.email", "[email protected]").Run(); err != nil {
log.Fatal("git config --global user.email failed: %q", err)
}
for i, r := range repos {
url := fmt.Sprintf("https://%[email protected]/%s/%s.git", token, r.Owner, r.Name)
c, err := repo.Prepare(url, r.Mainline)
if err != nil {
log.Fatalf("prepare failed: %v", err)
}
repos[i].Cache = c
}
// On ^C, or SIGTERM handle exit.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
mux := http.NewServeMux()
for _, repo := range repos {
mux.HandleFunc(fmt.Sprintf("/events/%s/%s", repo.Owner, repo.Name), prHandler(repo, client))
}
srv := &http.Server{
Addr: addr,
Handler: mux,
}
log.Printf("Listening on %q\n", addr)
go func() {
srv.ListenAndServe()
}()
var h *github.Hook
if publicDNS != "" {
for i, repo := range repos {
h, err = registerHook(client, publicDNS, repo.Owner, repo.Name)
if err != nil {
log.Fatal(err)
}
repos[i].hook = h
}
}
sig := <-c
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
srv.Shutdown(ctx)
cancel()
log.Printf("Received %s, exiting.", sig.String())
if h != nil {
for _, repo := range repos {
client.Repositories.DeleteHook(context.Background(), repo.Owner, repo.Name, *repo.hook.ID)
}
}
}
func createHook(client *github.Client, publicDNS, owner, repo, hookTarget string) (*github.Hook, error) {
hook, _, err := client.Repositories.CreateHook(context.Background(), owner, repo, &github.Hook{
Name: github.String("web"),
Active: github.Bool(true),
Config: map[string]interface{}{
"url": hookTarget,
"content_type": "json",
},
Events: []string{"*"},
})
return hook, err
}
func lookupHook(client *github.Client, owner, repo, hookTarget string) (*github.Hook, error) {
hooks, _, err := client.Repositories.ListHooks(context.Background(), owner, repo, &github.ListOptions{})
if err != nil {
return nil, err
}
var h *github.Hook
for _, hook := range hooks {
if url, ok := hook.Config["url"].(string); ok {
if strings.Contains(url, hookTarget) {
h = hook
break
}
}
}
return h, nil
}
func registerHook(client *github.Client, publicDNS, owner, repo string) (*github.Hook, error) {
hookTarget := fmt.Sprintf("%s/events/%s/%s", publicDNS, owner, repo)
hook, err := lookupHook(client, owner, repo, hookTarget)
if err != nil {
return nil, err
}
if hook == nil {
hook, err = createHook(client, publicDNS, owner, repo, hookTarget)
if err != nil {
return nil, err
}
}
return hook, nil
}