gitlab.rs 17.4 KB
Newer Older
1
2
3
4
5
6
7
8
// Copyright 2016 Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

9
10
11
12
extern crate ease;
use self::ease::Error as EaseError;
use self::ease::{Request, Response, Url};

13
14
15
extern crate serde;
use self::serde::Deserialize;

16
extern crate serde_json;
17
use self::serde_json::from_value;
18
19
20
21

extern crate url;
use self::url::percent_encoding::{PATH_SEGMENT_ENCODE_SET, percent_encode};

22
use super::error::Error;
23
use super::types::*;
24

25
26
27
// TODO: Add system hook APIs
// TODO: Add webhook APIs

Ben Boeckel's avatar
Ben Boeckel committed
28
#[derive(Clone)]
Ben Boeckel's avatar
Ben Boeckel committed
29
30
31
/// A representation of the Gitlab API for a single user.
///
/// Separate users should use separate instances of this.
32
33
34
35
36
pub struct Gitlab {
    base_url: Url,
    token: String,
}

Ben Boeckel's avatar
Ben Boeckel committed
37
// The header Gitlab uses to authenticate the user.
38
39
header!{ (GitlabPrivateToken, "PRIVATE-TOKEN") => [String] }

Ben Boeckel's avatar
Ben Boeckel committed
40
/// A JSON value return from Gitlab.
41
pub type GitlabResult<T: Deserialize> = Result<T, Error>;
42

43
44
45
46
47
48
49
50
51
52
53
54
/// Optional information for commit statuses.
pub struct CommitStatusInfo<'a> {
    /// The refname of the commit being tested.
    pub refname: Option<&'a str>,
    /// The name of the status (defaults to `"default"` on the Gitlab side).
    pub name: Option<&'a str>,
    /// A URL to associate with the status.
    pub target_url: Option<&'a str>,
    /// A description of the status check.
    pub description: Option<&'a str>,
}

55
impl Gitlab {
Ben Boeckel's avatar
Ben Boeckel committed
56
57
58
    /// Create a new Gitlab API representation.
    ///
    /// Errors out if `token` is invalid.
Ben Boeckel's avatar
Ben Boeckel committed
59
    pub fn new<T: ToString>(host: &str, token: T) -> GitlabResult<Self> {
Ben Boeckel's avatar
Ben Boeckel committed
60
        Self::_new("https", host, token.to_string())
61
62
63
64
65
66
    }

    /// Create a new non-SSL Gitlab API representation.
    ///
    /// Errors out if `token` is invalid.
    pub fn new_insecure<T: ToString>(host: &str, token: T) -> GitlabResult<Self> {
Ben Boeckel's avatar
Ben Boeckel committed
67
        Self::_new("http", host, token.to_string())
68
69
    }

Ben Boeckel's avatar
Ben Boeckel committed
70
71
72
    fn _new(protocol: &str, host: &str, token: String) -> GitlabResult<Self> {
        let base_url = try!(Url::parse(&format!("{}://{}/api/v3/", protocol, host)));

73
74
        let api = Gitlab {
            base_url: base_url,
75
            token: token,
76
        };
77

78
79
80
        // Ensure the API is working.
        let _: UserFull = try!(api._get("user"));

81
        Ok(api)
82
83
    }

Ben Boeckel's avatar
Ben Boeckel committed
84
    /// The user the API is acting as.
85
    pub fn current_user(&self) -> GitlabResult<UserFull> {
86
87
88
        self._get("user")
    }

89
90
91
92
93
94
95
96
97
98
    /// Get all user accounts
    pub fn users<T: UserResult>(&self) -> GitlabResult<Vec<T>> {
        self._get_paged("users")
    }

    /// Find a user by id.
    pub fn user<T: UserResult>(&self, user: UserId) -> GitlabResult<T> {
        self._get(&format!("users/{}", user))
    }

Ben Boeckel's avatar
Ben Boeckel committed
99
    /// Find a user by username.
100
    pub fn user_by_name<T: UserResult>(&self, name: &str) -> GitlabResult<T> {
Ben Boeckel's avatar
Ben Boeckel committed
101
102
103
104
105
106
        let mut req = try!(self._mkrequest("users"));

        req.param("username", name);

        let mut users = try!(Self::_get_paged_req(req));

107
        users.pop()
108
            .ok_or_else(|| Error::Gitlab("no such user".to_string()))
109
110
    }

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    /// Get all accessible projects.
    pub fn projects(&self) -> GitlabResult<Vec<Project>> {
        self._get_paged("projects")
    }

    /// Get all owned projects.
    pub fn owned_projects(&self) -> GitlabResult<Vec<Project>> {
        self._get_paged("projects/owned")
    }

    /// Get all projects.
    ///
    /// Requires administrator privileges.
    pub fn all_projects(&self) -> GitlabResult<Vec<Project>> {
        self._get_paged("projects/all")
    }

    /// Find a project by id.
    pub fn project(&self, project: ProjectId) -> GitlabResult<Project> {
        self._get(&format!("projects/{}", project))
131
132
    }

Ben Boeckel's avatar
Ben Boeckel committed
133
    /// Find a project by name.
134
    pub fn project_by_name(&self, name: &str) -> GitlabResult<Project> {
135
136
        self._get(&format!("projects/{}",
                           percent_encode(name.as_bytes(), PATH_SEGMENT_ENCODE_SET)))
137
138
    }

139
140
141
142
    /// Get a project's hooks.
    pub fn hooks(&self, project: ProjectId) -> GitlabResult<Vec<Hook>> {
        self._get_paged(&format!("projects/{}/hooks", project))
    }
143

144
145
146
147
148
    /// Get a project hook.
    pub fn hook(&self, project: ProjectId, hook: HookId) -> GitlabResult<Hook> {
        self._get(&format!("projects/{}/hooks/{}", project, hook))
    }

Ben Boeckel's avatar
Ben Boeckel committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    fn bool_param_value(value: bool) -> &'static str {
        if value {
            "true"
        } else {
            "false"
        }
    }

    fn set_event_flags(request: &mut Request, events: WebhookEvents) {
        request
            .param("build_events", Self::bool_param_value(events.build()))
            .param("issues_events", Self::bool_param_value(events.issues()))
            .param("merge_requests_events", Self::bool_param_value(events.merge_requests()))
            .param("note_events", Self::bool_param_value(events.note()))
            .param("pipeline_events", Self::bool_param_value(events.pipeline()))
            .param("push_events", Self::bool_param_value(events.push()))
            .param("wiki_page_events", Self::bool_param_value(events.wiki_page()));
    }

    /// Add a project hook.
    pub fn add_hook(&self, project: ProjectId, url: &str, events: WebhookEvents) -> GitlabResult<Hook> {
        let mut req = try!(self._mkrequest(&format!("projects/{}/hooks", project)));
        Self::set_event_flags(&mut req, events);

173
174
        req.param("url", url);

175
        Self::_post_req(req)
Ben Boeckel's avatar
Ben Boeckel committed
176
177
    }

178
179
180
181
182
183
    /// Get the team members of a group.
    pub fn group_members(&self, group: GroupId) -> GitlabResult<Vec<Member>> {
        self._get_paged(&format!("groups/{}/members", group))
    }

    /// Get a team member of a group.
Ben Boeckel's avatar
Ben Boeckel committed
184
    pub fn group_member(&self, group: GroupId, user: UserId) -> GitlabResult<Member> {
185
186
187
        self._get(&format!("groups/{}/members/{}", group, user))
    }

188
    /// Get the team members of a project.
189
    pub fn project_members(&self, project: ProjectId) -> GitlabResult<Vec<Member>> {
190
191
192
193
        self._get_paged(&format!("projects/{}/members", project))
    }

    /// Get a team member of a project.
Ben Boeckel's avatar
Ben Boeckel committed
194
    pub fn project_member(&self, project: ProjectId, user: UserId) -> GitlabResult<Member> {
195
196
197
        self._get(&format!("projects/{}/members/{}", project, user))
    }

198
199
200
    /// Add a user to a project.
    pub fn add_user_to_project(&self, project: ProjectId, user: UserId, access: AccessLevel)
                               -> GitlabResult<Member> {
201
202
203
204
205
206
207
208
        let user_str = format!("{}", user);
        let access_str = format!("{}", access);

        let mut req = try!(self._mkrequest(&format!("projects/{}/members", project)));

        req.param("user", &user_str)
            .param("access", &access_str);

209
        Self::_post_req(req)
210
211
212
    }

    /// Get branches for a project.
Ben Boeckel's avatar
Ben Boeckel committed
213
    pub fn branches(&self, project: ProjectId) -> GitlabResult<Vec<RepoBranch>> {
214
215
216
217
        self._get_paged(&format!("projects/{}/branches", project))
    }

    /// Get a branch.
Ben Boeckel's avatar
Ben Boeckel committed
218
    pub fn branch(&self, project: ProjectId, branch: &str) -> GitlabResult<RepoBranch> {
219
220
221
        self._get(&format!("projects/{}/repository/branches/{}",
                           project,
                           percent_encode(branch.as_bytes(), PATH_SEGMENT_ENCODE_SET)))
222
223
224
225
    }

    /// Get a commit.
    pub fn commit(&self, project: ProjectId, commit: &str) -> GitlabResult<RepoCommitDetail> {
226
        self._get(&format!("projects/{}/repository/commits/{}", project, commit))
227
228
229
    }

    /// Get comments on a commit.
Ben Boeckel's avatar
Ben Boeckel committed
230
231
    pub fn commit_comments(&self, project: ProjectId, commit: &str)
                           -> GitlabResult<Vec<CommitNote>> {
232
        self._get_paged(&format!("projects/{}/repository/commits/{}/comments", project, commit))
233
234
235
    }

    /// Get comments on a commit.
Ben Boeckel's avatar
Ben Boeckel committed
236
237
    pub fn create_commit_comment(&self, project: ProjectId, commit: &str, body: &str)
                                 -> GitlabResult<CommitNote> {
238
        let mut req = try!(self._mkrequest(&format!("projects/{}/repository/commits/{}/comment",
Ben Boeckel's avatar
Ben Boeckel committed
239
240
                                                    project,
                                                    commit)));
241
242
243

        req.param("note", body);

244
        Self::_post_req(req)
245
246
247
248
    }

    /// Get comments on a commit.
    pub fn create_commit_line_comment(&self, project: ProjectId, commit: &str, body: &str,
Ben Boeckel's avatar
Ben Boeckel committed
249
250
                                      path: &str, line: u64)
                                      -> GitlabResult<CommitNote> {
251
        let line_str = format!("{}", line);
Ben Boeckel's avatar
Ben Boeckel committed
252
        let line_type = LineType::New;
253

254
        let mut req = try!(self._mkrequest(&format!("projects/{}/repository/commits/{}/comment",
Ben Boeckel's avatar
Ben Boeckel committed
255
256
                                                    project,
                                                    commit)));
257
258
259
260

        req.param("note", body)
            .param("path", path)
            .param("line", &line_str)
261
            .param("line_type", line_type.as_str());
262

263
        Self::_post_req(req)
264
265
266
    }

    /// Get the statuses of a commit.
Ben Boeckel's avatar
Ben Boeckel committed
267
268
    pub fn commit_statuses(&self, project: ProjectId, commit: &str)
                           -> GitlabResult<Vec<CommitStatus>> {
269
        self._get_paged(&format!("projects/{}/repository/commits/{}/statuses", project, commit))
270
271
272
    }

    /// Get the statuses of a commit.
Ben Boeckel's avatar
Ben Boeckel committed
273
274
    pub fn commit_all_statuses(&self, project: ProjectId, commit: &str)
                               -> GitlabResult<Vec<CommitStatus>> {
275
        let mut req = try!(self._mkrequest(&format!("projects/{}/repository/commits/{}/statuses",
Ben Boeckel's avatar
Ben Boeckel committed
276
277
                                                    project,
                                                    commit)));
278
279
280
281

        req.param("all", "true");

        Self::_get_paged_req(req)
282
283
    }

Ben Boeckel's avatar
Ben Boeckel committed
284
    /// Create a status message for a commit.
Ben Boeckel's avatar
Ben Boeckel committed
285
    pub fn create_commit_status(&self, project: ProjectId, sha: &str, state: StatusState,
Ben Boeckel's avatar
Ben Boeckel committed
286
287
                                info: &CommitStatusInfo)
                                -> GitlabResult<CommitStatus> {
288
        let path = &format!("projects/{}/statuses/{}", project, sha);
289
290
        let mut req = try!(self._mkrequest(path));

291
        req.param("state", state.as_str());
292

293
294
295
296
297
        info.refname.map(|v| req.param("ref", v));
        info.name.map(|v| req.param("name", v));
        info.target_url.map(|v| req.param("target_url", v));
        info.description.map(|v| req.param("description", v));

298
        Self::_post_req(req)
299
300
    }

Ben Boeckel's avatar
Ben Boeckel committed
301
302
303
304
305
306
    /// Get the issues for a project.
    pub fn issues(&self, project: ProjectId) -> GitlabResult<Vec<Issue>> {
        self._get_paged(&format!("projects/{}/issues", project))
    }

    /// Get issues.
Ben Boeckel's avatar
Ben Boeckel committed
307
    pub fn issue(&self, project: ProjectId, issue: IssueId) -> GitlabResult<Issue> {
Ben Boeckel's avatar
Ben Boeckel committed
308
309
310
311
        self._get(&format!("projects/{}/issues/{}", project, issue))
    }

    /// Get the notes from a issue.
Ben Boeckel's avatar
Ben Boeckel committed
312
313
    pub fn issue_notes(&self, project: ProjectId, issue: IssueId) -> GitlabResult<Vec<Note>> {
        self._get_paged(&format!("projects/{}/issues/{}/notes", project, issue))
Ben Boeckel's avatar
Ben Boeckel committed
314
315
316
    }

    /// Create a note on a issue.
Ben Boeckel's avatar
Ben Boeckel committed
317
    pub fn create_issue_note(&self, project: ProjectId, issue: IssueId, content: &str)
Ben Boeckel's avatar
Ben Boeckel committed
318
                             -> GitlabResult<Note> {
Ben Boeckel's avatar
Ben Boeckel committed
319
        let path = &format!("projects/{}/issues/{}/notes", project, issue);
Ben Boeckel's avatar
Ben Boeckel committed
320

Ben Boeckel's avatar
Ben Boeckel committed
321
322
323
324
325
        let mut req = try!(self._mkrequest(path));

        req.param("body", content);

        Self::_post_req(req)
Ben Boeckel's avatar
Ben Boeckel committed
326
327
    }

328
329
330
331
332
333
    /// Get the merge requests for a project.
    pub fn merge_requests(&self, project: ProjectId) -> GitlabResult<Vec<MergeRequest>> {
        self._get_paged(&format!("projects/{}/merge_requests", project))
    }

    /// Get merge requests.
Ben Boeckel's avatar
Ben Boeckel committed
334
335
    pub fn merge_request(&self, project: ProjectId, merge_request: MergeRequestId)
                         -> GitlabResult<MergeRequest> {
336
337
338
        self._get(&format!("projects/{}/merge_requests/{}", project, merge_request))
    }

339
340
    /// Get the issues that will be closed when a merge request is merged.
    pub fn merge_request_closes_issues(&self, project: ProjectId, merge_request: MergeRequestId)
341
                                       -> GitlabResult<Vec<IssueReference>> {
342
343
344
345
346
        self._get_paged(&format!("projects/{}/merge_requests/{}/closes_issues",
                                 project,
                                 merge_request))
    }

347
    /// Get the notes from a merge request.
Ben Boeckel's avatar
Ben Boeckel committed
348
349
350
351
352
    pub fn merge_request_notes(&self, project: ProjectId, merge_request: MergeRequestId)
                               -> GitlabResult<Vec<Note>> {
        self._get_paged(&format!("projects/{}/merge_requests/{}/notes",
                                 project,
                                 merge_request))
353
354
    }

355
356
357
358
359
360
361
362
363
364
365
366
    /// Award a merge request note with an award.
    pub fn award_merge_request_note(&self, project: ProjectId, merge_request: MergeRequestId,
                                    note: NoteId, award: &str) -> GitlabResult<AwardEmoji> {
        let path = &format!("projects/{}/merge_requests/{}/notes/{}/award_emoji",
                            project, merge_request, note);
        let mut req = try!(self._mkrequest(path));

        req.param("name", award);

        Self::_post_req(req)
    }

367
368
369
370
371
372
373
374
375
    /// Get the awards for a merge request note.
    pub fn merge_request_note_awards(&self, project: ProjectId, merge_request: MergeRequestId,
                                     note: NoteId) -> GitlabResult<Vec<AwardEmoji>> {
        self._get_paged(&format!("projects/{}/merge_requests/{}/notes/{}/award_emoji",
                                 project,
                                 merge_request,
                                 note))
    }

376
    /// Create a note on a merge request.
Ben Boeckel's avatar
Ben Boeckel committed
377
378
379
380
381
382
    pub fn create_merge_request_note(&self, project: ProjectId, merge_request: MergeRequestId,
                                     content: &str)
                                     -> GitlabResult<Note> {
        let path = &format!("projects/{}/merge_requests/{}/notes",
                            project,
                            merge_request);
383

384
385
386
387
388
        let mut req = try!(self._mkrequest(path));

        req.param("body", content);

        Self::_post_req(req)
389
390
    }

Ben Boeckel's avatar
Ben Boeckel committed
391
    // Create a request with the proper common metadata for authentication.
392
393
394
395
    //
    // This method exists because we want to store the current user in the structure, but we don't
    // have a `self` before we create the structure. Making it `Option<>` is a little silly and
    // refactoring this out is worth the cleaner API.
Ben Boeckel's avatar
Ben Boeckel committed
396
    fn _mkrequest1(base_url: &Url, token: &str, url: &str) -> GitlabResult<Request> {
397
        let full_url = try!(base_url.join(url));
398
399
        let mut req = Request::new(full_url);

400
401
        debug!(target: "gitlab", "api call {}", url);

402
        req.header(GitlabPrivateToken(token.to_string()));
403
404
405
406

        Ok(req)
    }

407
408
409
410
411
    // Create a request with the proper common metadata for authentication.
    fn _mkrequest(&self, url: &str) -> GitlabResult<Request> {
        Self::_mkrequest1(&self.base_url, &self.token, url)
    }

Ben Boeckel's avatar
Ben Boeckel committed
412
    // Refactored code which talks to Gitlab and transforms error messages properly.
413
414
    fn _comm<F, T>(req: Request, f: F) -> GitlabResult<T>
        where F: FnOnce(Request) -> Result<Response, EaseError>,
415
              T: Deserialize,
416
    {
417
        match f(req) {
418
            Ok(rsp) => {
419
                let v = try!(rsp.from_json().map_err(Error::Ease));
420
421
422

                Ok(try!(from_value::<T>(v)))
            },
423
            Err(err) => {
424
425
426
                if let EaseError::UnsuccessfulResponse(rsp) = err {
                    Err(Error::from_gitlab(try!(rsp.from_json())))
                } else {
427
                    Err(Error::Ease(err))
428
429
430
431
432
                }
            },
        }
    }

433
434
    fn _get_req<T: Deserialize>(req: Request) -> GitlabResult<T> {
        Self::_comm(req, |mut req| req.get())
435
436
    }

437
    fn _get<T: Deserialize>(&self, url: &str) -> GitlabResult<T> {
438
        Self::_get_req(try!(self._mkrequest(url)))
439
440
    }

441
442
    fn _post_req<T: Deserialize>(req: Request) -> GitlabResult<T> {
        Self::_comm(req, |mut req| req.post())
443
444
    }

445
    fn _post<T: Deserialize>(&self, url: &str) -> GitlabResult<T> {
446
        Self::_post_req(try!(self._mkrequest(url)))
447
448
    }

Ben Boeckel's avatar
Ben Boeckel committed
449
450
    fn _put_req<T: Deserialize>(req: Request) -> GitlabResult<T> {
        Self::_comm(req, |mut req| req.put())
451
452
    }

453
    fn _put<T: Deserialize>(&self, url: &str) -> GitlabResult<T> {
Ben Boeckel's avatar
Ben Boeckel committed
454
        Self::_put_req(try!(self._mkrequest(url)))
455
456
    }

457
458
    fn _get_paged_req<T: Deserialize>(req: Request) -> GitlabResult<Vec<T>> {
        let mut page_num = 1;
459
460
461
        let per_page = 100;
        let per_page_str = &format!("{}", per_page);

462
        let mut results: Vec<T> = vec![];
463
464

        loop {
465
            let page_str = &format!("{}", page_num);
Ben Boeckel's avatar
Ben Boeckel committed
466
            let mut page_req = req.clone();
467
            page_req.param("page", page_str)
Ben Boeckel's avatar
Ben Boeckel committed
468
                .param("per_page", per_page_str);
469
            let page = try!(Self::_get_req::<Vec<T>>(page_req));
470
            let page_len = page.len();
471

472
            results.extend(page.into_iter());
473

474
475
476
477
            // Gitlab used to have issues returning paginated results; these have been fixed since,
            // but if it is needed, the bug manifests as Gitlab returning *all* results instead of
            // just the requested results. This can cause an infinite loop here if the number of
            // total results is exactly equal to `per_page`.
478
            if page_len != per_page {
479
                break;
480
            }
481
            page_num += 1;
482
483
        }

484
        Ok(results)
485
    }
Ben Boeckel's avatar
Ben Boeckel committed
486

Ben Boeckel's avatar
Ben Boeckel committed
487
    // Handle paginated queries. Returns all results.
488
    fn _get_paged<T: Deserialize>(&self, url: &str) -> GitlabResult<Vec<T>> {
Ben Boeckel's avatar
Ben Boeckel committed
489
490
        Self::_get_paged_req(try!(self._mkrequest(url)))
    }
491
}