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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// 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.

use chrono::{DateTime, Utc};
use derive_builder::Builder;

use crate::api::common::{NameOrId, SortOrder};
use crate::api::endpoint_prelude::*;
use crate::api::ParamValue;

/// Scopes for pipelines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PipelineScope {
    /// Currently running.
    Running,
    /// Created, but blocked on available runners or triggers.
    Pending,
    /// Completed pipelines.
    Finished,
    /// Pipelines for branches.
    Branches,
    /// Pipelines for tags.
    Tags,
}

impl PipelineScope {
    /// The scope as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            PipelineScope::Running => "running",
            PipelineScope::Pending => "pending",
            PipelineScope::Finished => "finished",
            PipelineScope::Branches => "branches",
            PipelineScope::Tags => "tags",
        }
    }
}

impl ParamValue<'static> for PipelineScope {
    fn as_value(&self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

/// The status of a pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PipelineStatus {
    /// Currently running.
    Running,
    /// Ready to run, but no jobs have been claimed by a runner.
    Pending,
    /// Successfully completed.
    Success,
    /// Unsuccessfully completed.
    Failed,
    /// Canceled.
    Canceled,
    /// Skipped.
    Skipped,
    /// Created, but blocked on available runners or triggers.
    Created,
    /// Awaiting manual triggering.
    Manual,
    /// Pipelines which have been scheduled.
    Scheduled,
    /// Pipelines which are being prepared.
    Preparing,
    /// Pipelines waiting for a resource.
    WaitingForResource,
}

impl PipelineStatus {
    /// The status as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            PipelineStatus::Running => "running",
            PipelineStatus::Pending => "pending",
            PipelineStatus::Success => "success",
            PipelineStatus::Failed => "failed",
            PipelineStatus::Canceled => "canceled",
            PipelineStatus::Skipped => "skipped",
            PipelineStatus::Created => "created",
            PipelineStatus::Manual => "manual",
            PipelineStatus::Scheduled => "scheduled",
            PipelineStatus::Preparing => "preparing",
            PipelineStatus::WaitingForResource => "waiting_for_resource",
        }
    }
}

impl ParamValue<'static> for PipelineStatus {
    fn as_value(&self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

/// Keys pipeline results may be ordered by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PipelineOrderBy {
    /// Order by the pipeline ID.
    Id,
    /// Order by the status of the pipeline.
    Status,
    /// Order by the ref the pipeline was triggered for.
    Ref,
    /// When the pipeline was last updated.
    UpdatedAt,
    /// The ID of the user that created the pipeline.
    UserId,
}

#[allow(clippy::derivable_impls)]
impl Default for PipelineOrderBy {
    fn default() -> Self {
        // XXX(rust-1.62): use `#[default]`
        PipelineOrderBy::Id
    }
}

impl PipelineOrderBy {
    /// The ordering as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            PipelineOrderBy::Id => "id",
            PipelineOrderBy::Status => "status",
            PipelineOrderBy::Ref => "ref",
            PipelineOrderBy::UpdatedAt => "updated_at",
            PipelineOrderBy::UserId => "user_id",
        }
    }
}

impl ParamValue<'static> for PipelineOrderBy {
    fn as_value(&self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

/// Ways that pipelines can be created.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PipelineSource {
    /// A pipeline crated by pushing to a repository.
    Push,
    /// A pipeline created through the web interface.
    Web,
    /// A pipeline created by a trigger.
    Trigger,
    /// A pipeline created on a schedule.
    Schedule,
    /// A pipeline created through the API.
    Api,
    /// A pipeline created externally.
    External,
    /// A pipeline created by another pipeline.
    Pipeline,
    /// A pipeline created through a chat.
    Chat,
    /// A pipeline created through the web IDE.
    WebIde,
    /// A pipeline created by a merge request event.
    MergeRequestEvent,
    /// A pipeline created by an external pull request event.
    ExternalPullRequestEvent,
    /// A pipeline created by a parent pipeline.
    ParentPipeline,
    /// A pipeline created by an on-demand DAST scan.
    OnDemandDastScan,
    /// A pipeline created by an on-demand DAST validation.
    OnDemandDastValidation,
    /// A pipeline created by a security orchestration policy.
    SecurityOrchestrationPolicy,
}

impl PipelineSource {
    /// The ordering as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            PipelineSource::Push => "push",
            PipelineSource::Web => "web",
            PipelineSource::Trigger => "trigger",
            PipelineSource::Schedule => "schedule",
            PipelineSource::Api => "api",
            PipelineSource::External => "external",
            PipelineSource::Pipeline => "pipeline",
            PipelineSource::Chat => "chat",
            PipelineSource::WebIde => "web_ide",
            PipelineSource::MergeRequestEvent => "merge_request_event",
            PipelineSource::ExternalPullRequestEvent => "external_pull_request_event",
            PipelineSource::ParentPipeline => "parent_pipeline",
            PipelineSource::OnDemandDastScan => "ondemand_dast_scan",
            PipelineSource::OnDemandDastValidation => "ondemand_dast_validation",
            PipelineSource::SecurityOrchestrationPolicy => "security_orchestration_policy",
        }
    }
}

impl ParamValue<'static> for PipelineSource {
    fn as_value(&self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

/// Query for pipelines within a project.
#[derive(Debug, Builder, Clone)]
#[builder(setter(strip_option))]
pub struct Pipelines<'a> {
    /// The project to query for pipelines.
    #[builder(setter(into))]
    project: NameOrId<'a>,

    /// Filter pipelines by its scope.
    #[builder(default)]
    scope: Option<PipelineScope>,
    /// Filter pipelines by its status.
    #[builder(default)]
    status: Option<PipelineStatus>,
    /// Filter pipelines by the owning ref.
    #[builder(setter(into), default)]
    ref_: Option<Cow<'a, str>>,
    /// Filter pipelines for a given commit SHA.
    #[builder(setter(into), default)]
    sha: Option<Cow<'a, str>>,
    /// Filter pipelines with or without YAML errors.
    #[builder(default)]
    yaml_errors: Option<bool>,
    /// Filter pipelines by the username of the triggering user.
    #[builder(setter(into), default)]
    username: Option<Cow<'a, str>>,

    /// Order results by a given key.
    #[builder(default)]
    order_by: Option<PipelineOrderBy>,
    /// Sort order for resulting pipelines.
    #[builder(default)]
    sort: Option<SortOrder>,

    /// Filter pipelines by the last updated date before this time.
    #[builder(default)]
    updated_before: Option<DateTime<Utc>>,
    /// Filter pipelines by the last updated date after this time.
    #[builder(default)]
    updated_after: Option<DateTime<Utc>>,
    /// How the pipeline was triggered.
    #[builder(default)]
    source: Option<PipelineSource>,
}

impl<'a> Pipelines<'a> {
    /// Create a builder for the endpoint.
    pub fn builder() -> PipelinesBuilder<'a> {
        PipelinesBuilder::default()
    }
}

impl<'a> PipelinesBuilder<'a> {
    /// Filter pipelines by the name of the triggering user.
    #[deprecated(note = "use `username` instead; `name` was never accepted by GitLab")]
    pub fn name<N>(&mut self, _: N) -> &mut Self
    where
        N: Into<Cow<'a, str>>,
    {
        self
    }
}

impl<'a> Endpoint for Pipelines<'a> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("projects/{}/pipelines", self.project).into()
    }

    fn parameters(&self) -> QueryParams {
        let mut params = QueryParams::default();

        params
            .push_opt("scope", self.scope)
            .push_opt("status", self.status)
            .push_opt("ref", self.ref_.as_ref())
            .push_opt("sha", self.sha.as_ref())
            .push_opt("yaml_errors", self.yaml_errors)
            .push_opt("username", self.username.as_ref())
            .push_opt("updated_after", self.updated_after)
            .push_opt("updated_before", self.updated_before)
            .push_opt("source", self.source)
            .push_opt("order_by", self.order_by)
            .push_opt("sort", self.sort);

        params
    }
}

impl<'a> Pageable for Pipelines<'a> {}

#[cfg(test)]
mod tests {
    use chrono::{TimeZone, Utc};

    use crate::api::common::SortOrder;
    use crate::api::projects::pipelines::{
        PipelineOrderBy, PipelineScope, PipelineSource, PipelineStatus, Pipelines,
        PipelinesBuilderError,
    };
    use crate::api::{self, Query};
    use crate::test::client::{ExpectedUrl, SingleTestClient};

    #[test]
    fn pipeline_scope_as_str() {
        let items = &[
            (PipelineScope::Running, "running"),
            (PipelineScope::Pending, "pending"),
            (PipelineScope::Finished, "finished"),
            (PipelineScope::Branches, "branches"),
            (PipelineScope::Tags, "tags"),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn pipeline_status_as_str() {
        let items = &[
            (PipelineStatus::Running, "running"),
            (PipelineStatus::Pending, "pending"),
            (PipelineStatus::Success, "success"),
            (PipelineStatus::Failed, "failed"),
            (PipelineStatus::Canceled, "canceled"),
            (PipelineStatus::Skipped, "skipped"),
            (PipelineStatus::Created, "created"),
            (PipelineStatus::Manual, "manual"),
            (PipelineStatus::Scheduled, "scheduled"),
            (PipelineStatus::Preparing, "preparing"),
            (PipelineStatus::WaitingForResource, "waiting_for_resource"),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn order_by_default() {
        assert_eq!(PipelineOrderBy::default(), PipelineOrderBy::Id);
    }

    #[test]
    fn order_by_as_str() {
        let items = &[
            (PipelineOrderBy::Id, "id"),
            (PipelineOrderBy::Status, "status"),
            (PipelineOrderBy::Ref, "ref"),
            (PipelineOrderBy::UpdatedAt, "updated_at"),
            (PipelineOrderBy::UserId, "user_id"),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn pipeline_source_as_str() {
        let items = &[
            (PipelineSource::Push, "push"),
            (PipelineSource::Web, "web"),
            (PipelineSource::Trigger, "trigger"),
            (PipelineSource::Schedule, "schedule"),
            (PipelineSource::Api, "api"),
            (PipelineSource::External, "external"),
            (PipelineSource::Pipeline, "pipeline"),
            (PipelineSource::Chat, "chat"),
            (PipelineSource::WebIde, "web_ide"),
            (PipelineSource::MergeRequestEvent, "merge_request_event"),
            (
                PipelineSource::ExternalPullRequestEvent,
                "external_pull_request_event",
            ),
            (PipelineSource::ParentPipeline, "parent_pipeline"),
            (PipelineSource::OnDemandDastScan, "ondemand_dast_scan"),
            (
                PipelineSource::OnDemandDastValidation,
                "ondemand_dast_validation",
            ),
            (
                PipelineSource::SecurityOrchestrationPolicy,
                "security_orchestration_policy",
            ),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn project_is_needed() {
        let err = Pipelines::builder().build().unwrap_err();
        crate::test::assert_missing_field!(err, PipelinesBuilderError, "project");
    }

    #[test]
    fn project_is_sufficient() {
        Pipelines::builder().project(1).build().unwrap();
    }

    #[test]
    fn endpoint() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/simple%2Fproject/pipelines")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project("simple/project")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_scope() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("scope", "finished")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .scope(PipelineScope::Finished)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_status() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("status", "failed")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .status(PipelineStatus::Failed)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_ref() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("ref", "master")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .ref_("master")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_sha() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("sha", "0000000000000000000000000000000000000000")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .sha("0000000000000000000000000000000000000000")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_yaml_errors() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("yaml_errors", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .yaml_errors(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_username() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("username", "name")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .username("name")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_updated_before() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("updated_before", "2020-01-01T00:00:00Z")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .updated_before(Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_updated_after() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("updated_after", "2020-01-01T00:00:00Z")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .updated_after(Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_source() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("source", "trigger")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .source(PipelineSource::Trigger)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_order_by() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("order_by", "updated_at")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .order_by(PipelineOrderBy::UpdatedAt)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_sort() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("projects/1/pipelines")
            .add_query_params(&[("sort", "desc")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Pipelines::builder()
            .project(1)
            .sort(SortOrder::Descending)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }
}