gitlab.rs 49.6 KB
Newer Older
1
2
3
4
5
6
// 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.

Ben Boeckel's avatar
Ben Boeckel committed
7
8
9
10
11
#[rustversion::since(1.38)]
use std::any;
use std::borrow::Borrow;
use std::fmt::{self, Debug, Display};

12
use crates::itertools::Itertools;
13
use crates::percent_encoding::{utf8_percent_encode, AsciiSet, PercentEncode, CONTROLS};
14
15
use crates::reqwest::header::{self, HeaderValue};
use crates::reqwest::{self, Client, RequestBuilder, Url};
16
use crates::serde::de::Error as SerdeError;
17
use crates::serde::de::{DeserializeOwned, Unexpected};
18
use crates::serde::ser::Serialize;
Ben Boeckel's avatar
Ben Boeckel committed
19
use crates::serde::{Deserialize, Deserializer, Serializer};
20
use crates::serde_json;
21
use crates::thiserror::Error;
22

23
use types::*;
24

25
26
27
28
29
30
31
32
33
34
35
36
37
const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'<')
    .add(b'>')
    .add(b'`')
    .add(b'?')
    .add(b'{')
    .add(b'}')
    .add(b'%')
    .add(b'/');

38
#[derive(Debug, Error)]
39
// TODO #[non_exhaustive]
40
41
42
43
44
45
pub enum TokenError {
    #[error("header value error: {}", source)]
    HeaderValue {
        #[from]
        source: header::InvalidHeaderValue,
    },
46
47
48
49
50
51
    /// This is here to force `_` matching right now.
    ///
    /// **DO NOT USE**
    #[doc(hidden)]
    #[error("unreachable...")]
    _NonExhaustive,
52
53
54
55
}

type TokenResult<T> = Result<T, TokenError>;

56
57
58
59
60
61
62
63
64
65
66
/// A Gitlab API token
///
/// Gitlab supports two kinds of tokens
#[derive(Debug, Clone)]
enum Token {
    /// A personal access token, obtained through Gitlab user settings
    Private(String),
    /// An OAuth2 token, obtained through the OAuth2 flow
    OAuth2(String),
}

67
impl Token {
Miha Čančula's avatar
Miha Čančula committed
68
    /// Sets the appropirate header on the request.
69
70
71
    ///
    /// Depending on the token type, this will be either the Private-Token header
    /// or the Authorization header.
Miha Čančula's avatar
Miha Čančula committed
72
    /// Returns an error if the token string cannot be parsed as a header value.
73
    pub fn set_header(&self, req: RequestBuilder) -> TokenResult<RequestBuilder> {
74
75
        Ok(match self {
            Token::Private(token) => {
76
                let mut token_header_value = HeaderValue::from_str(&token)?;
77
78
79
80
81
                token_header_value.set_sensitive(true);
                req.header("PRIVATE-TOKEN", token_header_value)
            },
            Token::OAuth2(token) => {
                let value = format!("Bearer {}", token);
82
                let mut token_header_value = HeaderValue::from_str(&value)?;
83
84
85
86
87
88
89
                token_header_value.set_sensitive(true);
                req.header("Authorization", token_header_value)
            },
        })
    }
}

90
#[derive(Debug, Error)]
91
// TODO #[non_exhaustive]
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
pub enum GitlabError {
    #[error("failed to parse url: {}", source)]
    UrlParse {
        #[from]
        source: reqwest::UrlError,
    },
    #[error("no such user: {}", user)]
    NoSuchUser { user: String },
    #[error("error setting token header: {}", source)]
    TokenError {
        #[from]
        source: TokenError,
    },
    #[error("communication with gitlab: {}", source)]
    Communication {
        #[from]
        source: reqwest::Error,
    },
    #[error("gitlab HTTP error: {}", status)]
    Http { status: reqwest::StatusCode },
    #[error("could not parse JSON response: {}", source)]
    Json {
        #[source]
        source: serde_json::Error,
    },
    #[error("gitlab server error: {}", msg)]
    Gitlab { msg: String },
    #[error("could not parse {} data from JSON: {}", typename.unwrap_or("<unknown>"), source)]
    DataType {
        #[source]
        source: serde_json::Error,
        typename: Option<&'static str>,
    },
125
126
127
128
129
130
    /// This is here to force `_` matching right now.
    ///
    /// **DO NOT USE**
    #[doc(hidden)]
    #[error("unreachable...")]
    _NonExhaustive,
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
}

impl GitlabError {
    fn no_such_user(user: &str) -> Self {
        GitlabError::NoSuchUser {
            user: user.into(),
        }
    }

    fn http(status: reqwest::StatusCode) -> Self {
        GitlabError::Http {
            status,
        }
    }

    fn json(source: serde_json::Error) -> Self {
        GitlabError::Json {
            source,
        }
    }

    fn from_gitlab(value: serde_json::Value) -> Self {
        let msg = value
            .pointer("/message")
            .or_else(|| value.pointer("/error"))
            .and_then(|s| s.as_str())
            .unwrap_or_else(|| "<unknown error>");

        GitlabError::Gitlab {
            msg: msg.into(),
        }
    }

    #[rustversion::since(1.38)]
    fn data_type<T>(source: serde_json::Error) -> Self {
        GitlabError::DataType {
            source,
            typename: Some(any::type_name::<T>()),
        }
    }

    #[rustversion::before(1.38)]
    fn data_type<T>(source: serde_json::Error) -> Self {
        GitlabError::DataType {
            source,
            typename: None,
        }
    }
}

type GitlabResult<T> = Result<T, GitlabError>;

Ben Boeckel's avatar
Ben Boeckel committed
183
184
185
/// A representation of the Gitlab API for a single user.
///
/// Separate users should use separate instances of this.
186
pub struct Gitlab {
187
188
    /// The client to use for API calls.
    client: Client,
Ben Boeckel's avatar
Ben Boeckel committed
189
    /// The base URL to use for API calls.
190
    base_url: Url,
Ben Boeckel's avatar
Ben Boeckel committed
191
    /// The secret token to use when communicating with Gitlab.
192
    token: Token,
193
194
}

Ben Boeckel's avatar
Ben Boeckel committed
195
impl Debug for Gitlab {
Ben Boeckel's avatar
Ben Boeckel committed
196
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197
198
199
        f.debug_struct("Gitlab")
            .field("base_url", &self.base_url)
            .finish()
Ben Boeckel's avatar
Ben Boeckel committed
200
201
202
    }
}

203
/// Optional information for commit statuses.
204
#[derive(Debug)]
205
206
207
208
209
210
211
212
213
214
215
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>,
}

216
/// Optional information for merge requests.
217
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218
219
220
221
222
223
224
225
pub enum MergeRequestStateFilter {
    /// Get the opened/reopened merge requests.
    Opened,
    /// Get the closes merge requests.
    Closed,
    /// Get the merged merge requests.
    Merged,
}
226
227
228
229
230
231

enum_serialize!(MergeRequestStateFilter -> "state",
    Opened => "opened",
    Closed => "closed",
    Merged => "merged",
);
232

233
impl Gitlab {
Ben Boeckel's avatar
Ben Boeckel committed
234
235
    /// Create a new Gitlab API representation.
    ///
236
    /// The `token` should be a valid [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html).
Ben Boeckel's avatar
Ben Boeckel committed
237
    /// Errors out if `token` is invalid.
238
    pub fn new<H, T>(host: H, token: T) -> GitlabResult<Self>
Ben Boeckel's avatar
Ben Boeckel committed
239
240
241
    where
        H: AsRef<str>,
        T: ToString,
242
    {
243
        Self::new_impl("https", host.as_ref(), Token::Private(token.to_string()))
244
245
246
247
248
    }

    /// Create a new non-SSL Gitlab API representation.
    ///
    /// Errors out if `token` is invalid.
249
    pub fn new_insecure<H, T>(host: H, token: T) -> GitlabResult<Self>
Ben Boeckel's avatar
Ben Boeckel committed
250
251
252
    where
        H: AsRef<str>,
        T: ToString,
253
    {
254
255
256
257
258
259
260
        Self::new_impl("http", host.as_ref(), Token::Private(token.to_string()))
    }

    /// Create a new Gitlab API representation.
    ///
    /// The `token` should be a valid [OAuth2 token](https://docs.gitlab.com/ee/api/oauth2.html).
    /// Errors out if `token` is invalid.
261
    pub fn with_oauth2<H, T>(host: H, token: T) -> GitlabResult<Self>
262
263
264
265
266
267
268
269
270
271
272
    where
        H: AsRef<str>,
        T: ToString,
    {
        Self::new_impl("https", host.as_ref(), Token::OAuth2(token.to_string()))
    }

    /// Create a new non-SSL Gitlab API representation.
    ///
    /// The `token` should be a valid [OAuth2 token](https://docs.gitlab.com/ee/api/oauth2.html).
    /// Errors out if `token` is invalid.
273
    pub fn with_oauth2_insecure<H, T>(host: H, token: T) -> GitlabResult<Self>
274
275
276
277
278
    where
        H: AsRef<str>,
        T: ToString,
    {
        Self::new_impl("http", host.as_ref(), Token::OAuth2(token.to_string()))
279
280
    }

Ben Boeckel's avatar
Ben Boeckel committed
281
    /// Internal method to create a new Gitlab client.
282
283
    fn new_impl(protocol: &str, host: &str, token: Token) -> GitlabResult<Self> {
        let base_url = Url::parse(&format!("{}://{}/api/v4/", protocol, host))?;
Ben Boeckel's avatar
Ben Boeckel committed
284

285
        let api = Gitlab {
Ben Boeckel's avatar
Ben Boeckel committed
286
            client: Client::new(),
287
288
            base_url,
            token,
289
        };
290

291
        // Ensure the API is working.
Ben Boeckel's avatar
Ben Boeckel committed
292
        let _: UserPublic = api.current_user()?;
293

294
        Ok(api)
295
296
    }

297
298
    /// Create a new Gitlab API client builder.
    pub fn builder<H, T>(host: H, token: T) -> GitlabBuilder
Ben Boeckel's avatar
Ben Boeckel committed
299
300
301
    where
        H: ToString,
        T: ToString,
302
303
304
305
    {
        GitlabBuilder::new(host, token)
    }

Ben Boeckel's avatar
Ben Boeckel committed
306
    /// The user the API is acting as.
307
    pub fn current_user(&self) -> GitlabResult<UserPublic> {
308
        self.get_with_param("user", query_param_slice![])
309
310
    }

311
    /// Get all user accounts
312
    pub fn users<T, I, K, V>(&self, params: I) -> GitlabResult<Vec<T>>
Ben Boeckel's avatar
Ben Boeckel committed
313
314
    where
        T: UserResult,
315
316
317
318
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
Ben Boeckel's avatar
Ben Boeckel committed
319
    {
320
        self.get_paged_with_param("users", params)
321
322
323
    }

    /// Find a user by id.
324
    pub fn user<T, I, K, V>(&self, user: UserId, params: I) -> GitlabResult<T>
Ben Boeckel's avatar
Ben Boeckel committed
325
326
    where
        T: UserResult,
327
328
329
330
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
Ben Boeckel's avatar
Ben Boeckel committed
331
    {
332
        self.get_with_param(format!("users/{}", user), params)
333
334
    }

Ben Boeckel's avatar
Ben Boeckel committed
335
    /// Find a user by username.
336
    pub fn user_by_name<T, N>(&self, name: N) -> GitlabResult<T>
Ben Boeckel's avatar
Ben Boeckel committed
337
338
339
    where
        T: UserResult,
        N: AsRef<str>,
340
341
    {
        let mut users = self.get_paged_with_param("users", &[("username", name.as_ref())])?;
Ben Boeckel's avatar
Ben Boeckel committed
342
343
        users
            .pop()
344
            .ok_or_else(|| GitlabError::no_such_user(name.as_ref()))
345
346
    }

347
    /// Get all accessible projects.
348
    pub fn projects<I, K, V>(&self, params: I) -> GitlabResult<Vec<Project>>
349
350
351
352
353
354
355
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.get_paged_with_param("projects", params)
356
357
358
    }

    /// Get all owned projects.
359
    pub fn owned_projects(&self) -> GitlabResult<Vec<Project>> {
360
        self.get_paged_with_param("projects", &[("owned", "true")])
361
362
363
    }

    /// Find a project by id.
364
    pub fn project<I, K, V>(&self, project: ProjectId, params: I) -> GitlabResult<Project>
365
366
367
368
369
370
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
371
        self.get_with_param(format!("projects/{}", project), params)
372
373
    }

374
    /// A URL-safe name for projects.
375
    fn url_name(name: &str) -> PercentEncode {
376
377
378
        utf8_percent_encode(name, PATH_SEGMENT_ENCODE_SET)
    }

Ben Boeckel's avatar
Ben Boeckel committed
379
    /// Find a project by name.
380
    pub fn project_by_name<N, I, K, V>(&self, name: N, params: I) -> GitlabResult<Project>
Ben Boeckel's avatar
Ben Boeckel committed
381
382
    where
        N: AsRef<str>,
383
384
385
386
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
387
    {
388
        self.get_with_param(
389
            format!("projects/{}", Self::url_name(name.as_ref())),
390
391
            params,
        )
392
393
    }

Bijan Chokoufe's avatar
Bijan Chokoufe committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
    /// Get all accessible environments.
    pub fn environments<I, K, V>(
        &self,
        project: ProjectId,
        params: I,
    ) -> GitlabResult<Vec<Environment>>
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.get_paged_with_param(format!("projects/{}/environments", project), params)
    }

    pub fn environment<I, K, V>(
        &self,
        project: ProjectId,
        environment: EnvironmentId,
        params: I,
    ) -> GitlabResult<Environment>
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.get_with_param(
            format!("projects/{}/environments/{}", project, environment),
            params,
        )
    }

427
    /// Get all accessible groups.
428
    pub fn groups<I, K, V>(&self, params: I) -> GitlabResult<Vec<Group>>
429
430
431
432
433
434
435
436
437
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.get_paged_with_param("groups", params)
    }

438
439
440
441
442
443
    /// Find a group by its name.
    pub fn group_by_name<N>(&self, name: N) -> GitlabResult<Group>
    where
        N: AsRef<str>,
    {
        let param: &[(&str, &str)] = &[];
Andrew Chin's avatar
Andrew Chin committed
444
        self.get_with_param(format!("groups/{}", Self::url_name(name.as_ref())), param)
445
446
    }

447
    /// Get a project's hooks.
448
    pub fn hooks<I, K, V>(&self, project: ProjectId, params: I) -> GitlabResult<Vec<ProjectHook>>
449
450
451
452
453
454
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
455
        self.get_paged_with_param(format!("projects/{}/hooks", project), params)
456
    }
457

458
    /// Get a project hook.
459
460
461
462
463
464
    pub fn hook<I, K, V>(
        &self,
        project: ProjectId,
        hook: HookId,
        params: I,
    ) -> GitlabResult<ProjectHook>
465
466
467
468
469
470
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
471
        self.get_with_param(format!("projects/{}/hooks/{}", project, hook), params)
472
473
    }

Ben Boeckel's avatar
Ben Boeckel committed
474
    /// Convert a boolean parameter into an HTTP request value.
Ben Boeckel's avatar
Ben Boeckel committed
475
476
477
478
479
480
481
482
    fn bool_param_value(value: bool) -> &'static str {
        if value {
            "true"
        } else {
            "false"
        }
    }

Ben Boeckel's avatar
Ben Boeckel committed
483
    /// HTTP parameters required to register to a project.
Makoto Nakashima's avatar
Makoto Nakashima committed
484
    fn event_flags(events: WebhookEvents) -> Vec<(&'static str, &'static str)> {
Ben Boeckel's avatar
Ben Boeckel committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
        vec![
            ("job_events", Self::bool_param_value(events.job())),
            ("issues_events", Self::bool_param_value(events.issues())),
            (
                "confidential_issues_events",
                Self::bool_param_value(events.confidential_issues()),
            ),
            (
                "merge_requests_events",
                Self::bool_param_value(events.merge_requests()),
            ),
            ("note_events", Self::bool_param_value(events.note())),
            ("pipeline_events", Self::bool_param_value(events.pipeline())),
            ("push_events", Self::bool_param_value(events.push())),
            (
                "wiki_page_events",
                Self::bool_param_value(events.wiki_page()),
            ),
        ]
Ben Boeckel's avatar
Ben Boeckel committed
504
505
506
    }

    /// Add a project hook.
Ben Boeckel's avatar
Ben Boeckel committed
507
508
509
510
511
    pub fn add_hook<U>(
        &self,
        project: ProjectId,
        url: U,
        events: WebhookEvents,
512
    ) -> GitlabResult<ProjectHook>
Ben Boeckel's avatar
Ben Boeckel committed
513
514
    where
        U: AsRef<str>,
515
    {
Makoto Nakashima's avatar
Makoto Nakashima committed
516
        let mut flags = Self::event_flags(events);
517
        flags.push(("url", url.as_ref()));
Ben Boeckel's avatar
Ben Boeckel committed
518

519
        self.post_with_param(format!("projects/{}/hooks", project), &flags)
Ben Boeckel's avatar
Ben Boeckel committed
520
521
    }

522
    /// Get the team members of a group.
523
    pub fn group_members<I, K, V>(&self, group: GroupId, params: I) -> GitlabResult<Vec<Member>>
524
525
526
527
528
529
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
530
        self.get_paged_with_param(format!("groups/{}/members", group), params)
531
532
533
    }

    /// Get a team member of a group.
534
535
536
537
538
539
    pub fn group_member<I, K, V>(
        &self,
        group: GroupId,
        user: UserId,
        params: I,
    ) -> GitlabResult<Member>
540
541
542
543
544
545
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
546
        self.get_with_param(format!("groups/{}/members/{}", group, user), params)
547
548
    }

549
    /// Get the team members of a project.
550
551
552
553
554
    pub fn project_members<I, K, V>(
        &self,
        project: ProjectId,
        params: I,
    ) -> GitlabResult<Vec<Member>>
555
556
557
558
559
560
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
561
        self.get_paged_with_param(format!("projects/{}/members", project), params)
562
563
564
    }

    /// Get a team member of a project.
565
566
567
568
569
    pub fn project_member<I, K, V>(
        &self,
        project: ProjectId,
        user: UserId,
        params: I,
570
    ) -> GitlabResult<Member>
571
572
573
574
575
576
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
577
        self.get_with_param(format!("projects/{}/members/{}", project, user), params)
578
579
    }

580
    /// Add a user to a project.
Ben Boeckel's avatar
Ben Boeckel committed
581
582
583
584
585
    pub fn add_user_to_project(
        &self,
        project: ProjectId,
        user: UserId,
        access: AccessLevel,
586
    ) -> GitlabResult<Member> {
587
588
589
        let user_str = format!("{}", user);
        let access_str = format!("{}", access);

Ben Boeckel's avatar
Ben Boeckel committed
590
        self.post_with_param(
591
            format!("projects/{}/members", project),
Ben Boeckel's avatar
Ben Boeckel committed
592
593
            &[("user", &user_str), ("access", &access_str)],
        )
594
595
    }

596
    /// Add a user to a project.
Ben Boeckel's avatar
Ben Boeckel committed
597
598
599
600
601
    pub fn add_user_to_project_by_name<P>(
        &self,
        project: P,
        user: UserId,
        access: AccessLevel,
602
    ) -> GitlabResult<Member>
Ben Boeckel's avatar
Ben Boeckel committed
603
604
    where
        P: AsRef<str>,
605
606
607
608
    {
        let user_str = format!("{}", user);
        let access_str = format!("{}", access);

Ben Boeckel's avatar
Ben Boeckel committed
609
        self.post_with_param(
610
            format!("projects/{}/members", Self::url_name(project.as_ref())),
611
            &[("user_id", &user_str), ("access_level", &access_str)],
Ben Boeckel's avatar
Ben Boeckel committed
612
        )
613
614
    }

615
    /// Get branches for a project.
616
    pub fn branches<I, K, V>(&self, project: ProjectId, params: I) -> GitlabResult<Vec<RepoBranch>>
617
618
619
620
621
622
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
623
        self.get_paged_with_param(format!("projects/{}/branches", project), params)
624
625
626
    }

    /// Get a branch.
627
628
629
630
631
632
    pub fn branch<B, I, K, V>(
        &self,
        project: ProjectId,
        branch: B,
        params: I,
    ) -> GitlabResult<RepoBranch>
Ben Boeckel's avatar
Ben Boeckel committed
633
634
    where
        B: AsRef<str>,
635
636
637
638
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
639
    {
640
        self.get_with_param(
641
            format!(
642
643
644
645
646
647
                "projects/{}/repository/branches/{}",
                project,
                Self::url_name(branch.as_ref()),
            ),
            params,
        )
648
649
650
    }

    /// Get a commit.
651
    pub fn commit<C>(&self, project: ProjectId, commit: C) -> GitlabResult<RepoCommitDetail>
Ben Boeckel's avatar
Ben Boeckel committed
652
653
    where
        C: AsRef<str>,
654
    {
Brad King's avatar
Brad King committed
655
        self.get_with_param(
656
            format!(
Ben Boeckel's avatar
Ben Boeckel committed
657
658
659
660
661
662
                "projects/{}/repository/commits/{}",
                project,
                commit.as_ref(),
            ),
            &[("stats", "true")],
        )
663
664
665
    }

    /// Get comments on a commit.
666
667
668
669
670
    pub fn commit_comments<C, I, K, V>(
        &self,
        project: ProjectId,
        commit: C,
        params: I,
671
    ) -> GitlabResult<Vec<CommitNote>>
Ben Boeckel's avatar
Ben Boeckel committed
672
673
    where
        C: AsRef<str>,
674
675
676
677
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
678
    {
679
        self.get_paged_with_param(
680
            format!(
681
682
683
684
685
686
                "projects/{}/repository/commits/{}/comments",
                project,
                commit.as_ref(),
            ),
            params,
        )
687
688
689
    }

    /// Get comments on a commit.
Ben Boeckel's avatar
Ben Boeckel committed
690
691
692
693
694
    pub fn create_commit_comment<C, B>(
        &self,
        project: ProjectId,
        commit: C,
        body: B,
695
    ) -> GitlabResult<CommitNote>
Ben Boeckel's avatar
Ben Boeckel committed
696
697
698
    where
        C: AsRef<str>,
        B: AsRef<str>,
699
    {
Ben Boeckel's avatar
Ben Boeckel committed
700
        self.post_with_param(
701
            format!(
Ben Boeckel's avatar
Ben Boeckel committed
702
703
704
705
706
707
                "projects/{}/repository/commits/{}/comment",
                project,
                commit.as_ref(),
            ),
            &[("note", body.as_ref())],
        )
708
709
    }

710
    /// Get comments on a commit.
Ben Boeckel's avatar
Ben Boeckel committed
711
712
713
714
715
    pub fn create_commit_comment_by_name<P, C, B>(
        &self,
        project: P,
        commit: C,
        body: B,
716
    ) -> GitlabResult<CommitNote>
Ben Boeckel's avatar
Ben Boeckel committed
717
718
719
720
    where
        P: AsRef<str>,
        C: AsRef<str>,
        B: AsRef<str>,
721
    {
Ben Boeckel's avatar
Ben Boeckel committed
722
        self.post_with_param(
723
            format!(
Ben Boeckel's avatar
Ben Boeckel committed
724
725
726
727
728
729
                "projects/{}/repository/commits/{}/comment",
                Self::url_name(project.as_ref()),
                commit.as_ref(),
            ),
            &[("note", body.as_ref())],
        )
730
731
    }

732
    /// Get comments on a commit.
Ben Boeckel's avatar
Ben Boeckel committed
733
734
735
736
737
738
739
    pub fn create_commit_line_comment(
        &self,
        project: ProjectId,
        commit: &str,
        body: &str,
        path: &str,
        line: u64,
740
    ) -> GitlabResult<CommitNote> {
741
        let line_str = format!("{}", line);
Ben Boeckel's avatar
Ben Boeckel committed
742
        let line_type = LineType::New;
743

Ben Boeckel's avatar
Ben Boeckel committed
744
        self.post_with_param(
745
            format!("projects/{}/repository/commits/{}/comment", project, commit),
Ben Boeckel's avatar
Ben Boeckel committed
746
747
748
749
750
751
752
            &[
                ("note", body),
                ("path", path),
                ("line", &line_str),
                ("line_type", line_type.as_str()),
            ],
        )
753
754
    }

755
    /// Get the latest statuses of a commit.
756
    pub fn commit_latest_statuses<C, I, K, V>(
Ben Boeckel's avatar
Ben Boeckel committed
757
758
759
        &self,
        project: ProjectId,
        commit: C,
760
        params: I,
761
    ) -> GitlabResult<Vec<CommitStatus>>
Ben Boeckel's avatar
Ben Boeckel committed
762
763
    where
        C: AsRef<str>,
764
765
766
767
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
768
    {
769
        self.get_paged_with_param(
770
            format!(
771
772
773
774
775
776
                "projects/{}/repository/commits/{}/statuses",
                project,
                commit.as_ref(),
            ),
            params,
        )
777
778
    }

779
    /// Get the latest statuses of a commit.
780
    pub fn commit_latest_statuses_by_name<P, C, I, K, V>(
Ben Boeckel's avatar
Ben Boeckel committed
781
782
783
        &self,
        project: P,
        commit: C,
784
        params: I,
785
    ) -> GitlabResult<Vec<CommitStatus>>
Ben Boeckel's avatar
Ben Boeckel committed
786
787
788
    where
        P: AsRef<str>,
        C: AsRef<str>,
789
790
791
792
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
793
    {
794
        self.get_paged_with_param(
795
            format!(
796
797
798
799
800
801
                "projects/{}/repository/commits/{}/statuses",
                Self::url_name(project.as_ref()),
                commit.as_ref(),
            ),
            params,
        )
802
803
    }

804
    /// Get the all statuses of a commit.
805
806
807
808
809
    pub fn commit_all_statuses<C>(
        &self,
        project: ProjectId,
        commit: C,
    ) -> GitlabResult<Vec<CommitStatus>>
Ben Boeckel's avatar
Ben Boeckel committed
810
811
    where
        C: AsRef<str>,
812
    {
Ben Boeckel's avatar
Ben Boeckel committed
813
        self.get_paged_with_param(
814
            format!(
Ben Boeckel's avatar
Ben Boeckel committed
815
816
817
818
819
820
                "projects/{}/repository/commits/{}/statuses",
                project,
                commit.as_ref(),
            ),
            &[("all", "true")],
        )
821
822
    }

823
    /// Get the latest builds of a commit.
824
825
826
827
828
    pub fn commit_latest_builds<C, I, K, V>(
        &self,
        project: ProjectId,
        commit: C,
        params: I,
829
    ) -> GitlabResult<Vec<Job>>
Ben Boeckel's avatar
Ben Boeckel committed
830
831
    where
        C: AsRef<str>,
832
833
834
835
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
836
    {
837
        self.get_paged_with_param(
838
            format!(
839
840
841
842
843
844
                "projects/{}/repository/commits/{}/builds",
                project,
                commit.as_ref(),
            ),
            params,
        )
Makoto Nakashima's avatar
Makoto Nakashima committed
845
846
    }

847
    /// Get the all builds of a commit.
848
    pub fn commit_all_builds<C>(&self, project: ProjectId, commit: C) -> GitlabResult<Vec<Job>>
Ben Boeckel's avatar
Ben Boeckel committed
849
850
    where
        C: AsRef<str>,
851
    {
Ben Boeckel's avatar
Ben Boeckel committed
852
        self.get_paged_with_param(
853
            format!(
Ben Boeckel's avatar
Ben Boeckel committed
854
855
856
857
858
859
                "projects/{}/repository/commits/{}/builds",
                project,
                commit.as_ref(),
            ),
            &[("all", "true")],
        )
Makoto Nakashima's avatar
Makoto Nakashima committed
860
861
    }

Ben Boeckel's avatar
Ben Boeckel committed
862
    /// Create a status message for a commit.
Ben Boeckel's avatar
Ben Boeckel committed
863
864
865
866
867
868
    pub fn create_commit_status<S>(
        &self,
        project: ProjectId,
        sha: S,
        state: StatusState,
        info: &CommitStatusInfo,
869
    ) -> GitlabResult<CommitStatus>
Ben Boeckel's avatar
Ben Boeckel committed
870
871
    where
        S: AsRef<str>,
872
    {
873
        let path = format!("projects/{}/statuses/{}", project, sha.as_ref());
874

Makoto Nakashima's avatar
Makoto Nakashima committed
875
        let mut params = vec![("state", state.as_str())];
876

877
878
879
880
881
882
883
884
885
886
887
888
        if let Some(v) = info.refname {
            params.push(("ref", v))
        }
        if let Some(v) = info.name {
            params.push(("name", v))
        }
        if let Some(v) = info.target_url {
            params.push(("target_url", v))
        }
        if let Some(v) = info.description {
            params.push(("description", v))
        }
889

890
        self.post_with_param(path, &params)
891
892
    }

893
    /// Create a status message for a commit.
Ben Boeckel's avatar
Ben Boeckel committed
894
895
896
897
898
899
    pub fn create_commit_status_by_name<P, S>(
        &self,
        project: P,
        sha: S,
        state: StatusState,
        info: &CommitStatusInfo,
900
    ) -> GitlabResult<CommitStatus>
Ben Boeckel's avatar
Ben Boeckel committed
901
902
903
    where
        P: AsRef<str>,
        S: AsRef<str>,
904
    {
905
        let path = format!(
Ben Boeckel's avatar
Ben Boeckel committed
906
907
908
909
            "projects/{}/statuses/{}",
            Self::url_name(project.as_ref()),
            sha.as_ref(),
        );
910
911
912

        let mut params = vec![("state", state.as_str())];

913
914
915
916
917
918
919
920
921
922
923
924
        if let Some(v) = info.refname {
            params.push(("ref", v))
        }
        if let Some(v) = info.name {
            params.push(("name", v))
        }
        if let Some(v) = info.target_url {
            params.push(("target_url", v))
        }
        if let Some(v) = info.description {
            params.push(("description", v))
        }
925

926
        self.post_with_param(path, &params)
927
928
    }

929
    /// Get the labels for a project.
930
    pub fn labels(&self, project: ProjectId) -> GitlabResult<Vec<Label>> {
931
        self.get_paged(format!("projects/{}/labels", project))
932
    }
933
934

    /// Get the labels with open/closed/merge requests count
935
    pub fn labels_with_counts(&self, project: ProjectId) -> GitlabResult<Vec<Label>> {
Ben Boeckel's avatar
Ben Boeckel committed
936
        self.get_paged_with_param(
937
            format!("projects/{}/labels", project),
938
            &[("with_counts", "true")],
Ben Boeckel's avatar
Ben Boeckel committed
939
        )
940
    }
941
942

    /// Get label by ID.
943
    pub fn label(&self, project: ProjectId, label: LabelId) -> GitlabResult<Label> {
944
        self.get(format!("projects/{}/labels/{}", project, label))
945
946
    }

Ben Boeckel's avatar
Ben Boeckel committed
947
    /// Get the issues for a project.
948
    pub fn issues<I, K, V>(&self, project: ProjectId, params: I) -> GitlabResult<Vec<Issue>>
949
950
951
952
953
954
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
955
        self.get_paged_with_param(format!("projects/{}/issues", project), params)
Ben Boeckel's avatar
Ben Boeckel committed
956
957
958
    }

    /// Get issues.
959
960
961
962
963
    pub fn issue<I, K, V>(
        &self,
        project: ProjectId,
        issue: IssueInternalId,
        params: I,
964
    ) -> GitlabResult<Issue>
965
966
967
968
969
970
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
971
        self.get_with_param(format!("projects/{}/issues/{}", project, issue), params)
Ben Boeckel's avatar
Ben Boeckel committed
972
973
974
    }

    /// Get the notes from a issue.
975
976
977
978
979
    pub fn issue_notes<I, K, V>(
        &self,
        project: ProjectId,
        issue: IssueInternalId,
        params: I,
980
    ) -> GitlabResult<Vec<Note>>
981
982
983
984
985
986
987
    where
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.get_paged_with_param(
988
            format!("projects/{}/issues/{}/notes", project, issue),
989
990
            params,
        )
Ben Boeckel's avatar
Ben Boeckel committed
991
992
    }

993
    /// Get the notes from a issue.
994
995
996
997
998
    pub fn issue_notes_by_name<P, I, K, V>(
        &self,
        project: P,
        issue: IssueInternalId,
        params: I,
999
    ) -> GitlabResult<Vec<Note>>
Ben Boeckel's avatar
Ben Boeckel committed
1000
1001
    where
        P: AsRef<str>,
1002
1003
1004
1005
        I: IntoIterator,
        I::Item: Borrow<(K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
1006
    {
1007
        self.get_paged_with_param(
1008
            format!(
1009
1010
1011
1012
1013
1014
                "projects/{}/issues/{}/notes",
                Self::url_name(project.as_ref()),
                issue,
            ),
            params,
        )
1015
1016
    }

1017
    /// Create a new label
1018
    pub fn create_label(&self, project: ProjectId, label: Label) -> GitlabResult<Label> {
1019
        let path = format!("projects/{}/labels", project);
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036

        let mut params: Vec<(&str, String)> = Vec::new();

        params.push(("name", label.name));
        params.push(("color", label.color.value()));

        if let Some(d) = label.description {
            params.push(("description", d));
        }

        if let Some(p) = label.priority {
            params.push(("priority", p.to_string()));
        }

        self.post_with_param(path, &params)
    }

VC's avatar
VC committed
1037
    /// Create a new milestone
1038
1039
1040
1041
1042
    pub fn create_milestone(
        &self,
        project: ProjectId,
        milestone: Milestone,
    ) -> GitlabResult<Milestone> {
1043
        let path = format!("projects/{}/milestones", project);
VC's avatar
VC committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063

        let mut params: Vec<(&str, String)> = Vec::new();

        params.push(("title", milestone.title));

        if let Some(d) = milestone.description {
            params.push(("description", d));
        }

        if let Some(d) = milestone.due_date {
            params.push(("due_date", d.to_string()))
        }

        if let Some(s) = milestone.start_date {
            params.push(("start_date", s.to_string()))
        }

        self.post_with_param(path, &params)
    }

VC's avatar
VC committed
1064
    /// Create a new issue
1065
    pub fn create_issue(&self, project: ProjectId, issue: Issue) -> GitlabResult<Issue> {
1066
        let path = format!("projects/{}/issues", project);
VC's avatar
VC committed
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082

        let mut params: Vec<(&str, String)> = Vec::new();

        if issue.iid.value() != 0 {
            params.push(("iid", issue.iid.value().to_string()));
        }

        params.push(("title", issue.title));

        if let Some(d) = issue.description {
            params.push(("description", d));
        }

        params.push(("confidential", issue.confidential.to_string()));

        if let Some(v) = issue.assignees {
Ben Boeckel's avatar
Ben Boeckel committed
1083
1084
1085
1086
            params.extend(
                v.into_iter()
                    .map(|x| ("assignee_ids[]", x.id.value().to_string())),
            );
VC's avatar
VC committed
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
        }

        if let Some(m) = issue.milestone {
            params.push(("milestone_id", m.id.value().to_string()))
        }

        if !issue.labels.is_empty() {
            params.push(("labels", issue.labels.join(",")));
        }

        params.push(("created_at", issue.created_at.to_string()));

        if let Some(d) = issue.due_date {
            params.push(("due_date", d.to_string()))
        }

        self.post_with_param(path, &params)
    }

Andrew Chin's avatar
Andrew Chin committed
1106
1107
1108
1109
1110
    /// Get the resource label events from an issue.
    pub fn issue_label_events(
        &self,
        project: ProjectId,
        issue: IssueInternalId,
1111
    ) -> GitlabResult<Vec<ResourceLabelEvent>> {
1112
        self.get_paged(format!(
Ben Boeckel's avatar
Ben Boeckel committed
1113
1114
1115
            "projects/{}/issues/{}/resource_label_events",
            project, issue,
        ))
Andrew Chin's avatar
Andrew Chin committed
1116
1117
    }

Ben Boeckel's avatar
Ben Boeckel committed
1118
    /// Create a note on a issue.