forked from harness/harness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitlab.go
314 lines (261 loc) · 8.87 KB
/
gitlab.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package handler
import (
"database/sql"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"github.com/drone/drone/pkg/database"
. "github.com/drone/drone/pkg/model"
"github.com/drone/drone/pkg/queue"
"github.com/plouc/go-gitlab-client"
)
type GitlabHandler struct {
queue *queue.Queue
apiPath string
}
func NewGitlabHandler(queue *queue.Queue) *GitlabHandler {
return &GitlabHandler{
queue: queue,
apiPath: "/api/v3",
}
}
func (g *GitlabHandler) Add(w http.ResponseWriter, r *http.Request, u *User) error {
settings := database.SettingsMust()
teams, err := database.ListTeams(u.ID)
if err != nil {
return err
}
data := struct {
User *User
Teams []*Team
Settings *Settings
}{u, teams, settings}
// if the user hasn't linked their GitLab account
// render a different template
if len(u.GitlabToken) == 0 {
return RenderTemplate(w, "gitlab_link.html", &data)
}
// otherwise display the template for adding
// a new GitLab repository.
return RenderTemplate(w, "gitlab_add.html", &data)
}
func (g *GitlabHandler) Link(w http.ResponseWriter, r *http.Request, u *User) error {
token := strings.TrimSpace(r.FormValue("token"))
if len(u.GitlabToken) == 0 || token != u.GitlabToken && len(token) > 0 {
u.GitlabToken = token
settings := database.SettingsMust()
gl := gogitlab.NewGitlab(settings.GitlabApiUrl, g.apiPath, u.GitlabToken)
_, err := gl.CurrentUser()
if err != nil {
return fmt.Errorf("Private Token is not valid: %q", err)
}
if err := database.SaveUser(u); err != nil {
return RenderError(w, err, http.StatusBadRequest)
}
}
http.Redirect(w, r, "/new/gitlab", http.StatusSeeOther)
return nil
}
func (g *GitlabHandler) ReLink(w http.ResponseWriter, r *http.Request, u *User) error {
data := struct {
User *User
}{u}
return RenderTemplate(w, "gitlab_link.html", &data)
}
func (g *GitlabHandler) Create(w http.ResponseWriter, r *http.Request, u *User) error {
teamName := r.FormValue("team")
owner := r.FormValue("owner")
name := r.FormValue("name")
repo, err := g.newGitlabRepo(u, owner, name)
if err != nil {
return err
}
if len(teamName) > 0 {
team, err := database.GetTeamSlug(teamName)
if err != nil {
return fmt.Errorf("Unable to find Team %s.", teamName)
}
// user must be an admin member of the team
if ok, _ := database.IsMemberAdmin(u.ID, team.ID); !ok {
return fmt.Errorf("Invalid permission to access Team %s.", teamName)
}
repo.TeamID = team.ID
}
// Save to the database
if err := database.SaveRepo(repo); err != nil {
return fmt.Errorf("Error saving repository to the database. %s", err)
}
return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK)
}
func (g *GitlabHandler) newGitlabRepo(u *User, owner, name string) (*Repo, error) {
settings := database.SettingsMust()
gl := gogitlab.NewGitlab(settings.GitlabApiUrl, g.apiPath, u.GitlabToken)
project, err := gl.Project(ns(owner, name))
if err != nil {
return nil, err
}
var cloneUrl string
if project.Public {
cloneUrl = project.HttpRepoUrl
} else {
cloneUrl = project.SshRepoUrl
}
repo, err := NewRepo(settings.GitlabDomain, owner, name, ScmGit, cloneUrl)
if err != nil {
return nil, err
}
repo.UserID = u.ID
repo.Private = !project.Public
if repo.Private {
// name the key
keyName := fmt.Sprintf("%s@%s", repo.Owner, settings.Domain)
// TODO: (fudanchii) check if we already opted to use UserKey
// create the github key, or update if one already exists
if err := gl.AddProjectDeployKey(ns(owner, name), keyName, repo.PublicKey); err != nil {
return nil, fmt.Errorf("Unable to add Public Key to your GitLab repository.")
}
}
link := fmt.Sprintf("%s://%s/hook/gitlab?id=%s", settings.Scheme, settings.Domain, repo.Slug)
if err := gl.AddProjectHook(ns(owner, name), link, true, false, true); err != nil {
return nil, fmt.Errorf("Unable to add Hook to your GitLab repository.")
}
return repo, err
}
func (g *GitlabHandler) Hook(w http.ResponseWriter, r *http.Request) error {
rID := r.FormValue("id")
repo, err := database.GetRepoSlug(rID)
if err != nil {
return RenderText(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
user, err := database.GetUser(repo.UserID)
if err != nil {
return RenderText(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
payload, _ := ioutil.ReadAll(r.Body)
parsed, err := gogitlab.ParseHook(payload)
if err != nil {
return err
}
if parsed.ObjectKind == "merge_request" {
fmt.Println(string(payload))
if err := g.PullRequestHook(parsed, repo, user); err != nil {
return err
}
return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK)
}
if len(parsed.After) == 0 {
return RenderText(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
_, err = database.GetCommitHash(parsed.After, repo.ID)
if err != nil && err != sql.ErrNoRows {
fmt.Println("commit already exists")
return RenderText(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
}
commit := &Commit{}
commit.RepoID = repo.ID
commit.Branch = parsed.Branch()
commit.Hash = parsed.After
commit.Status = "Pending"
commit.Created = time.Now().UTC()
head := parsed.Head()
commit.Message = head.Message
commit.Timestamp = head.Timestamp
if head.Author != nil {
commit.SetAuthor(head.Author.Email)
} else {
commit.SetAuthor(parsed.UserName)
}
// get the github settings from the database
settings := database.SettingsMust()
// get the drone.yml file from GitHub
client := gogitlab.NewGitlab(settings.GitlabApiUrl, g.apiPath, user.GitlabToken)
buildscript, err := client.RepoRawFile(ns(repo.Owner, repo.Name), commit.Hash, ".drone.yml")
if err != nil {
msg := "No .drone.yml was found in this repository. You need to add one.\n"
if err := saveFailedBuild(commit, msg); err != nil {
return RenderText(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return RenderText(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
// save the commit to the database
if err := database.SaveCommit(commit); err != nil {
return RenderText(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
// save the build to the database
build := &Build{}
build.Slug = "1" // TODO
build.CommitID = commit.ID
build.Created = time.Now().UTC()
build.Status = "Pending"
build.BuildScript = string(buildscript)
if err := database.SaveBuild(build); err != nil {
return RenderText(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
g.queue.Add(&queue.BuildTask{Repo: repo, Commit: commit, Build: build})
// OK!
return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK)
}
func (g *GitlabHandler) PullRequestHook(p *gogitlab.HookPayload, repo *Repo, user *User) error {
obj := p.ObjectAttributes
// Gitlab may trigger multiple hooks upon updating merge requests status
// only build when it was just opened and the merge hasn't been checked yet.
if !(obj.State == "opened" && obj.MergeStatus == "unchecked") {
fmt.Println("Ignore GitLab Merge Requests")
return nil
}
settings := database.SettingsMust()
client := gogitlab.NewGitlab(settings.GitlabApiUrl, g.apiPath, user.GitlabToken)
// GitLab merge-requests hook doesn't include repository data.
// Have to fetch it manually
src, err := client.RepoBranch(strconv.Itoa(obj.SourceProjectId), obj.SourceBranch)
if err != nil {
return err
}
_, err = database.GetCommitHash(src.Commit.Id, repo.ID)
if err != nil && err != sql.ErrNoRows {
fmt.Println("commit already exists")
return err
}
commit := &Commit{}
commit.RepoID = repo.ID
commit.Branch = src.Name
commit.Hash = src.Commit.Id
commit.Status = "Pending"
commit.Created = time.Now().UTC()
commit.PullRequest = strconv.Itoa(obj.IId)
commit.Message = src.Commit.Message
commit.Timestamp = src.Commit.AuthoredDateRaw
commit.SetAuthor(src.Commit.Author.Email)
buildscript, err := client.RepoRawFile(strconv.Itoa(obj.SourceProjectId), commit.Hash, ".drone.yml")
if err != nil {
msg := "No .drone.yml was found in this repository. You need to add one.\n"
if err := saveFailedBuild(commit, msg); err != nil {
return fmt.Errorf("Failed to save build: %q", err)
}
return fmt.Errorf("Error to fetch build script: %q", err)
}
// save the commit to the database
if err := database.SaveCommit(commit); err != nil {
return fmt.Errorf("Failed to save commit: %q", err)
}
// save the build to the database
build := &Build{}
build.Slug = "1" // TODO
build.CommitID = commit.ID
build.Created = time.Now().UTC()
build.Status = "Pending"
build.BuildScript = string(buildscript)
if err := database.SaveBuild(build); err != nil {
return fmt.Errorf("Failed to save build: %q", err)
}
g.queue.Add(&queue.BuildTask{Repo: repo, Commit: commit, Build: build})
return nil
}
// ns namespaces user and repo.
// Returns user%2Frepo
func ns(user, repo string) string {
return fmt.Sprintf("%s%%2F%s", user, repo)
}