forked from blippar/git2etcd
/
main.go
220 lines (198 loc) · 5.68 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
220
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
log "github.com/Sirupsen/logrus"
etcd "github.com/coreos/etcd/client"
"github.com/google/go-github/github"
"github.com/spf13/viper"
"golang.org/x/net/context"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
const (
_sep = string(os.PathSeparator)
)
var (
flagConfigPath = flag.String("conf_dir", "", "Path to look for a config file. (directory)")
gitRepo *git.Repository
etcdClient etcd.KeysAPI
)
func main() {
flag.Parse()
setConfig(*flagConfigPath)
// etcd Client connection
if err := etcdConnect(); err != nil {
log.WithError(err).Fatal("Couldn't connect to etcd")
}
// Git repository opening/cloning
if err := openOrCloneRepo(); err != nil {
log.WithError(err).Fatal("Couldn't find repo or clone it")
}
go func(repo *git.Repository) {
syncCycle := time.Duration(viper.GetInt("repo.synccycle")) * time.Second
if syncCycle > 0 {
for {
select {
case <-time.After(syncCycle):
if err := syncRepo(repo); err != nil {
log.WithError(err).Warn("Couldn't sync automatically")
}
}
}
} else {
log.Info("No sync cycle")
}
}(gitRepo)
// HTTP serving
http.HandleFunc("/"+viper.GetString("host.hook"), hookHandler)
http.HandleFunc("/sync", syncHandler)
http.HandleFunc("/status", statusHandler)
log.Fatal(http.ListenAndServe(viper.GetString("host.listen")+":"+viper.GetString("host.port"), nil))
}
func setConfig(path string) {
// Default values
viper.SetDefault("host.listen", "")
viper.SetDefault("host.port", "4242")
viper.SetDefault("host.hook", "hook")
viper.SetDefault("repo.path", "data/")
viper.SetDefault("repo.url", "https://github.com/blippar/git2etcd.git")
viper.SetDefault("repo.branch", "master")
viper.SetDefault("repo.synccycle", 3600)
viper.SetDefault("etcd.hosts", []string{"http://127.0.0.1:2379"})
// Getting config from file
viper.SetConfigName("config")
viper.AddConfigPath("/etc/git2etcd/")
viper.AddConfigPath("$HOME/.git2etcd")
viper.AddConfigPath(".")
if len(path) > 0 {
viper.AddConfigPath(path)
}
err := viper.ReadInConfig()
if err != nil {
log.WithError(err).Warn("Couldn't read config file. Will use defaults.")
}
// Setting environment config
viper.SetEnvPrefix("g2e")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
_, err := etcdClient.Get(context.Background(), "/", nil)
if err != nil && err == etcd.ErrClusterUnavailable {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func syncHandler(w http.ResponseWriter, r *http.Request) {
if err := syncRepo(gitRepo); err != nil {
http.Error(w, "Couldn't sync repo: "+err.Error(), http.StatusInternalServerError)
}
}
func hookHandler(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-GitHub-Event") == "ping" {
log.Info("Ping received")
} else if r.Header.Get("X-GitHub-Event") == "push" {
treatPushEvent(w, r)
} else {
// handle other events than push.
}
}
func treatPushEvent(w http.ResponseWriter, r *http.Request) {
var event github.PushEvent
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.WithError(err).Error("Couldn't read request body")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = json.Unmarshal(body, &event); err != nil {
log.WithError(err).Error("Couldn't Unmarshal json payload")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Info("Push received from ", *event.Repo.FullName)
added := make(map[string]bool)
modified := make(map[string]bool)
removed := make(map[string]bool)
for _, commit := range event.Commits {
for _, ca := range commit.Added {
added[ca] = true
}
for _, cm := range commit.Modified {
modified[cm] = true
}
for _, cr := range commit.Removed {
removed[cr] = true
}
}
wt, err := gitRepo.Worktree()
if err != nil {
log.WithError(err).Error("Couldn't get repo's WorkTree")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = wt.Pull(nil); err != nil {
log.WithError(err).Error("Couldn't pull repo's HEAD")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Info("Repository head is now ", *event.After)
commit, err := gitRepo.CommitObject(plumbing.NewHash(*event.After))
if err != nil {
log.WithError(err).Error("Couldn't get HEAD's commit")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tree, err := commit.Tree()
if err != nil {
log.WithError(err).Error("Couldn't get HEAD's tree")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
treatAdded(added, tree)
treatModified(modified, tree)
treatRemoved(removed, tree)
}
func treatAdded(added map[string]bool, tree *object.Tree) {
for file := range added {
_, err := tree.File(file)
if err != nil {
log.WithError(err).Warn("Couldn't get file: ", file)
continue
}
if err := etcdCreate(file); err != nil {
log.WithError(err).Warn("Couldn't create key")
}
}
}
func treatModified(modified map[string]bool, tree *object.Tree) {
for file := range modified {
_, err := tree.File(file)
if err != nil {
log.WithError(err).Warn("Couldn't get file: ", file)
continue
}
if err := etcdSet(file); err != nil {
log.WithError(err).Warn("Couldn't set key")
}
}
}
func treatRemoved(removed map[string]bool, tree *object.Tree) {
for file := range removed {
_, err := tree.File(file)
if err != nil {
log.WithError(err).Warn("Couldn't get file: ", file)
continue
}
if err := etcdDelete(file); err != nil {
log.WithError(err).Warn("Couldn't delete key")
}
}
}