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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
use mermaid::{generate_mermaid_stages_diagram, YamlParser};
use yaml::load_yaml;

use crate::api_traits::{Cicd, CicdJob, CicdRunner, Timestamp};
use crate::cli::cicd::{JobOptions, PipelineOptions, RunnerOptions};
use crate::config::Config;
use crate::display::{Column, DisplayBody};
use crate::remote::{GetRemoteCliArgs, ListBodyArgs, ListRemoteCliArgs};
use crate::{display, error, remote, Result};
use std::fmt::Display;
use std::io::{Read, Write};
use std::sync::Arc;

pub mod mermaid;
pub mod yaml;

use super::common::{
    self, num_cicd_pages, num_cicd_resources, num_job_pages, num_job_resources, num_runner_pages,
    num_runner_resources,
};

#[derive(Builder, Clone, Debug)]
pub struct Pipeline {
    id: i64,
    pub status: String,
    web_url: String,
    branch: String,
    sha: String,
    created_at: String,
    updated_at: String,
    duration: u64,
}

impl Pipeline {
    pub fn builder() -> PipelineBuilder {
        PipelineBuilder::default()
    }
}

impl Timestamp for Pipeline {
    fn created_at(&self) -> String {
        self.created_at.clone()
    }
}

impl From<Pipeline> for DisplayBody {
    fn from(p: Pipeline) -> DisplayBody {
        DisplayBody {
            columns: vec![
                Column::new("ID", p.id.to_string()),
                Column::new("URL", p.web_url),
                Column::new("Branch", p.branch),
                Column::new("SHA", p.sha),
                Column::new("Created at", p.created_at),
                Column::new("Updated at", p.updated_at),
                Column::new("Duration", p.duration.to_string()),
                Column::new("Status", p.status),
            ],
        }
    }
}

#[derive(Builder, Clone)]
pub struct PipelineBodyArgs {
    pub from_to_page: Option<ListBodyArgs>,
}

impl PipelineBodyArgs {
    pub fn builder() -> PipelineBodyArgsBuilder {
        PipelineBodyArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct LintFilePathArgs {
    pub path: String,
}

impl LintFilePathArgs {
    pub fn builder() -> LintFilePathArgsBuilder {
        LintFilePathArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct LintResponse {
    pub valid: bool,
    #[builder(default)]
    pub merged_yaml: String,
    pub errors: Vec<String>,
}

impl LintResponse {
    pub fn builder() -> LintResponseBuilder {
        LintResponseBuilder::default()
    }
}

pub struct YamlBytes<'a>(&'a [u8]);

impl YamlBytes<'_> {
    pub fn new(data: &[u8]) -> YamlBytes {
        YamlBytes(data)
    }
}

impl Display for YamlBytes<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = String::from_utf8_lossy(self.0);
        write!(f, "{}", s)
    }
}

#[derive(Builder, Clone)]
pub struct Runner {
    pub id: i64,
    pub active: bool,
    pub description: String,
    pub ip_address: String,
    pub name: String,
    pub online: bool,
    pub paused: bool,
    pub is_shared: bool,
    pub runner_type: String,
    pub status: String,
}

impl Runner {
    pub fn builder() -> RunnerBuilder {
        RunnerBuilder::default()
    }
}

impl From<Runner> for DisplayBody {
    fn from(r: Runner) -> DisplayBody {
        DisplayBody {
            columns: vec![
                Column::new("ID", r.id.to_string()),
                Column::new("Active", r.active.to_string()),
                Column::new("Description", r.description),
                Column::new("IP Address", r.ip_address),
                Column::new("Name", r.name),
                Column::new("Paused", r.paused.to_string()),
                Column::new("Shared", r.is_shared.to_string()),
                Column::new("Type", r.runner_type),
                Column::new("Online", r.online.to_string()),
                Column::new("Status", r.status.to_string()),
            ],
        }
    }
}

impl Timestamp for Runner {
    fn created_at(&self) -> String {
        // There is no created_at field for runners, set it to UNIX epoch
        "1970-01-01T00:00:00Z".to_string()
    }
}

/// Used when getting runner details. Adds extra fields to the runner struct.
#[derive(Builder, Clone)]
pub struct RunnerMetadata {
    pub id: i64,
    pub run_untagged: bool,
    pub tag_list: Vec<String>,
    pub version: String,
    pub architecture: String,
    pub platform: String,
    pub contacted_at: String,
    pub revision: String,
}

impl RunnerMetadata {
    pub fn builder() -> RunnerMetadataBuilder {
        RunnerMetadataBuilder::default()
    }
}

impl From<RunnerMetadata> for DisplayBody {
    fn from(r: RunnerMetadata) -> DisplayBody {
        DisplayBody {
            columns: vec![
                Column::new("ID", r.id.to_string()),
                Column::new("Run untagged", r.run_untagged.to_string()),
                Column::new("Tags", r.tag_list.join(", ")),
                Column::new("Architecture", r.architecture),
                Column::new("Platform", r.platform),
                Column::new("Contacted at", r.contacted_at),
                Column::new("Version", r.version),
                Column::new("Revision", r.revision),
            ],
        }
    }
}

#[derive(Builder, Clone)]
pub struct RunnerListCliArgs {
    pub status: RunnerStatus,
    #[builder(default)]
    pub tags: Option<String>,
    #[builder(default)]
    pub all: bool,
    pub list_args: ListRemoteCliArgs,
}

impl RunnerListCliArgs {
    pub fn builder() -> RunnerListCliArgsBuilder {
        RunnerListCliArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct RunnerListBodyArgs {
    pub list_args: Option<ListBodyArgs>,
    pub status: RunnerStatus,
    #[builder(default)]
    pub tags: Option<String>,
    #[builder(default)]
    pub all: bool,
}

impl RunnerListBodyArgs {
    pub fn builder() -> RunnerListBodyArgsBuilder {
        RunnerListBodyArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct RunnerMetadataGetCliArgs {
    pub id: i64,
    pub get_args: GetRemoteCliArgs,
}

impl RunnerMetadataGetCliArgs {
    pub fn builder() -> RunnerMetadataGetCliArgsBuilder {
        RunnerMetadataGetCliArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct RunnerPostDataCliArgs {
    pub description: Option<String>,
    pub tags: Option<String>,
    pub kind: RunnerType,
    #[builder(default)]
    pub run_untagged: bool,
    #[builder(default)]
    pub project_id: Option<i64>,
    #[builder(default)]
    pub group_id: Option<i64>,
}

impl RunnerPostDataCliArgs {
    pub fn builder() -> RunnerPostDataCliArgsBuilder {
        RunnerPostDataCliArgsBuilder::default()
    }
}

fn create_runner<W: Write>(
    remote: Arc<dyn CicdRunner>,
    cli_args: RunnerPostDataCliArgs,
    mut writer: W,
) -> Result<()> {
    let response = remote.create(cli_args)?;
    writeln!(writer, "{}", response)?;
    Ok(())
}

#[derive(Builder, Clone)]
pub struct RunnerRegistrationResponse {
    pub id: i64,
    pub token: String,
    pub token_expiration: String,
}

impl RunnerRegistrationResponse {
    pub fn builder() -> RunnerRegistrationResponseBuilder {
        RunnerRegistrationResponseBuilder::default()
    }
}

impl Display for RunnerRegistrationResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Runner ID: [{}], Runner Token: [{}], Token Expiration: [{}]",
            self.id, self.token, self.token_expiration
        )
    }
}

#[derive(Clone, PartialEq, Debug)]
pub enum RunnerType {
    Instance,
    Group,
    Project,
}

impl Display for RunnerType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RunnerType::Instance => write!(f, "instance_type"),
            RunnerType::Group => write!(f, "group_type"),
            RunnerType::Project => write!(f, "project_type"),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum RunnerStatus {
    Online,
    Offline,
    Stale,
    NeverContacted,
    All,
}

impl Display for RunnerStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RunnerStatus::Online => write!(f, "online"),
            RunnerStatus::Offline => write!(f, "offline"),
            RunnerStatus::Stale => write!(f, "stale"),
            RunnerStatus::NeverContacted => write!(f, "never_contacted"),
            RunnerStatus::All => write!(f, "all"),
        }
    }
}

#[derive(Builder, Clone)]
pub struct Job {
    id: i64,
    name: String,
    branch: String,
    url: String,
    author_name: String,
    commit_sha: String,
    pipeline_id: i64,
    runner_tags: Vec<String>,
    stage: String,
    status: String,
    created_at: String,
    started_at: String,
    finished_at: String,
    duration: String,
}

impl Job {
    pub fn builder() -> JobBuilder {
        JobBuilder::default()
    }
}

impl From<Job> for DisplayBody {
    fn from(j: Job) -> DisplayBody {
        DisplayBody {
            columns: vec![
                Column::new("ID", j.id.to_string()),
                Column::new("Name", j.name),
                Column::new("Author Name", j.author_name),
                Column::new("Branch", j.branch),
                Column::new("Commit SHA", j.commit_sha),
                Column::new("Pipeline ID", j.pipeline_id.to_string()),
                Column::new("URL", j.url),
                Column::new("Runner Tags", j.runner_tags.join(", ")),
                Column::new("Stage", j.stage),
                Column::new("Status", j.status),
                Column::new("Created At", j.created_at),
                Column::new("Started At", j.started_at),
                Column::new("Finished At", j.finished_at),
                Column::new("Duration", j.duration.to_string()),
            ],
        }
    }
}

impl Timestamp for Job {
    fn created_at(&self) -> String {
        self.created_at.clone()
    }
}

// Technically no need to encapsulate the common ListRemoteCliArgs but we might
// need to add pipeline_id to retrieve jobs from a specific pipeline.
#[derive(Builder, Clone)]
pub struct JobListCliArgs {
    pub list_args: ListRemoteCliArgs,
}

impl JobListCliArgs {
    pub fn builder() -> JobListCliArgsBuilder {
        JobListCliArgsBuilder::default()
    }
}

#[derive(Builder, Clone)]
pub struct JobListBodyArgs {
    pub list_args: Option<ListBodyArgs>,
}

impl JobListBodyArgs {
    pub fn builder() -> JobListBodyArgsBuilder {
        JobListBodyArgsBuilder::default()
    }
}

pub fn execute(
    options: PipelineOptions,
    config: Arc<Config>,
    domain: String,
    path: String,
) -> Result<()> {
    match options {
        PipelineOptions::Lint(args) => {
            let remote = remote::get_cicd(domain, path, config, false)?;
            let file = std::fs::File::open(args.path)?;
            let body = read_ci_file(file)?;
            lint_ci_file(remote, &body, false, std::io::stdout())
        }
        PipelineOptions::MergedCi => {
            let remote = remote::get_cicd(domain, path, config, false)?;
            let file = std::fs::File::open(".gitlab-ci.yml")?;
            let body = read_ci_file(file)?;
            lint_ci_file(remote, &body, true, std::io::stdout())
        }
        PipelineOptions::Chart(args) => {
            let file = std::fs::File::open(".gitlab-ci.yml")?;
            let body = read_ci_file(file)?;
            let parser = YamlParser::new(load_yaml(&String::from_utf8_lossy(&body)));
            let chart = generate_mermaid_stages_diagram(parser, args)?;
            println!("{}", chart);
            Ok(())
        }
        PipelineOptions::List(cli_args) => {
            let remote = remote::get_cicd(domain, path, config, cli_args.get_args.refresh_cache)?;
            if cli_args.num_pages {
                return num_cicd_pages(remote, std::io::stdout());
            } else if cli_args.num_resources {
                return num_cicd_resources(remote, std::io::stdout());
            }
            let from_to_args = remote::validate_from_to_page(&cli_args)?;
            let body_args = PipelineBodyArgs::builder()
                .from_to_page(from_to_args)
                .build()?;
            list_pipelines(remote, body_args, cli_args, std::io::stdout())
        }
        PipelineOptions::Jobs(options) => match options {
            JobOptions::List(cli_args) => {
                let remote = remote::get_cicd_job(
                    domain,
                    path,
                    config,
                    cli_args.list_args.get_args.refresh_cache,
                )?;
                let from_to_args = remote::validate_from_to_page(&cli_args.list_args)?;
                let body_args = JobListBodyArgs::builder().list_args(from_to_args).build()?;
                if cli_args.list_args.num_pages {
                    return num_job_pages(remote, body_args, std::io::stdout());
                }
                if cli_args.list_args.num_resources {
                    return num_job_resources(remote, body_args, std::io::stdout());
                }
                list_jobs(remote, body_args, cli_args, std::io::stdout())
            }
        },
        PipelineOptions::Runners(options) => match options {
            RunnerOptions::List(cli_args) => {
                let remote = remote::get_cicd_runner(
                    domain,
                    path,
                    config,
                    cli_args.list_args.get_args.refresh_cache,
                )?;
                let from_to_args = remote::validate_from_to_page(&cli_args.list_args)?;
                let tags = cli_args.tags.clone();
                let body_args = RunnerListBodyArgs::builder()
                    .list_args(from_to_args)
                    .status(cli_args.status)
                    .tags(tags)
                    .all(cli_args.all)
                    .build()?;
                if cli_args.list_args.num_pages {
                    return num_runner_pages(remote, body_args, std::io::stdout());
                }
                if cli_args.list_args.num_resources {
                    return num_runner_resources(remote, body_args, std::io::stdout());
                }
                list_runners(remote, body_args, cli_args, std::io::stdout())
            }
            RunnerOptions::Get(cli_args) => {
                let remote =
                    remote::get_cicd_runner(domain, path, config, cli_args.get_args.refresh_cache)?;
                get_runner_details(remote, cli_args, std::io::stdout())
            }
            RunnerOptions::Create(cli_args) => {
                let remote = remote::get_cicd_runner(domain, path, config, false)?;
                create_runner(remote, cli_args, std::io::stdout())
            }
        },
    }
}

fn get_runner_details<W: Write>(
    remote: Arc<dyn CicdRunner>,
    cli_args: RunnerMetadataGetCliArgs,
    mut writer: W,
) -> Result<()> {
    let runner = remote.get(cli_args.id)?;
    display::print(&mut writer, vec![runner], cli_args.get_args)?;
    Ok(())
}

fn list_runners<W: Write>(
    remote: Arc<dyn CicdRunner>,
    body_args: RunnerListBodyArgs,
    cli_args: RunnerListCliArgs,
    mut writer: W,
) -> Result<()> {
    common::list_runners(remote, body_args, cli_args, &mut writer)
}

fn list_jobs<W: Write>(
    remote: Arc<dyn CicdJob>,
    body_args: JobListBodyArgs,
    cli_args: JobListCliArgs,
    mut writer: W,
) -> Result<()> {
    common::list_jobs(remote, body_args, cli_args, &mut writer)
}

fn list_pipelines<W: Write>(
    remote: Arc<dyn Cicd>,
    body_args: PipelineBodyArgs,
    cli_args: ListRemoteCliArgs,
    mut writer: W,
) -> Result<()> {
    common::list_pipelines(remote, body_args, cli_args, &mut writer)
}

fn read_ci_file<R: Read>(mut reader: R) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    reader.read_to_end(&mut buf)?;
    Ok(buf)
}

fn lint_ci_file<W: Write>(
    remote: Arc<dyn Cicd>,
    body: &[u8],
    display_merged_ci_yaml: bool,
    mut writer: W,
) -> Result<()> {
    let response = remote.lint(YamlBytes::new(body))?;
    if response.valid {
        if display_merged_ci_yaml {
            let lines = response.merged_yaml.split('\n');
            for line in lines {
                if line.is_empty() {
                    continue;
                }
                writeln!(writer, "{}", line)?;
            }
            return Ok(());
        }
        writeln!(writer, "File is valid.")?;
    } else {
        for error in response.errors {
            writeln!(writer, "{}", error)?;
        }
        return Err(error::gen("Linting failed."));
    }
    Ok(())
}

#[cfg(test)]
mod test {
    use std::io::Cursor;

    use super::*;
    use crate::{api_traits::NumberDeltaErr, error};

    #[derive(Clone, Builder)]
    struct PipelineMock {
        #[builder(default = "vec![]")]
        pipelines: Vec<Pipeline>,
        #[builder(default = "false")]
        error: bool,
        #[builder(setter(into, strip_option), default)]
        num_pages: Option<u32>,
        #[builder(default)]
        gitlab_ci_merged_yaml: String,
    }

    impl PipelineMock {
        pub fn builder() -> PipelineMockBuilder {
            PipelineMockBuilder::default()
        }
    }

    impl Cicd for PipelineMock {
        fn list(&self, _args: PipelineBodyArgs) -> Result<Vec<Pipeline>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            let pp = self.pipelines.clone();
            Ok(pp)
        }

        fn get_pipeline(&self, _id: i64) -> Result<Pipeline> {
            let pp = self.pipelines.clone();
            Ok(pp[0].clone())
        }

        fn num_pages(&self) -> Result<Option<u32>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            return Ok(self.num_pages);
        }

        fn num_resources(&self) -> Result<Option<crate::api_traits::NumberDeltaErr>> {
            todo!()
        }

        fn lint(&self, _body: YamlBytes) -> Result<LintResponse> {
            if self.error {
                return Ok(LintResponse::builder()
                    .valid(false)
                    .errors(vec!["YAML Error".to_string()])
                    .build()
                    .unwrap());
            }
            Ok(LintResponse::builder()
                .valid(true)
                .errors(vec![])
                .merged_yaml(self.gitlab_ci_merged_yaml.clone())
                .build()
                .unwrap())
        }
    }

    #[test]
    fn test_list_pipelines() {
        let pp_remote = PipelineMock::builder()
            .pipelines(vec![
                Pipeline::builder()
                    .id(123)
                    .status("success".to_string())
                    .web_url("https://gitlab.com/owner/repo/-/pipelines/123".to_string())
                    .branch("master".to_string())
                    .sha("1234567890abcdef".to_string())
                    .created_at("2020-01-01T00:00:00Z".to_string())
                    .updated_at("2020-01-01T00:01:00Z".to_string())
                    .duration(60)
                    .build()
                    .unwrap(),
                Pipeline::builder()
                    .id(456)
                    .status("failed".to_string())
                    .web_url("https://gitlab.com/owner/repo/-/pipelines/456".to_string())
                    .branch("master".to_string())
                    .sha("1234567890abcdef".to_string())
                    .created_at("2020-01-01T00:00:00Z".to_string())
                    .updated_at("2020-01-01T00:01:01Z".to_string())
                    .duration(61)
                    .build()
                    .unwrap(),
            ])
            .build()
            .unwrap();
        let mut buf = Vec::new();
        let body_args = PipelineBodyArgs::builder()
            .from_to_page(None)
            .build()
            .unwrap();
        let cli_args = ListRemoteCliArgs::builder().build().unwrap();
        list_pipelines(Arc::new(pp_remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!(
            String::from_utf8(buf).unwrap(),
            "ID|URL|Branch|SHA|Created at|Updated at|Duration|Status\n\
             123|https://gitlab.com/owner/repo/-/pipelines/123|master|1234567890abcdef|2020-01-01T00:00:00Z|2020-01-01T00:01:00Z|60|success\n\
             456|https://gitlab.com/owner/repo/-/pipelines/456|master|1234567890abcdef|2020-01-01T00:00:00Z|2020-01-01T00:01:01Z|61|failed\n")
    }

    #[test]
    fn test_list_pipelines_empty_warns_message() {
        let pp_remote = PipelineMock::builder().build().unwrap();
        let mut buf = Vec::new();

        let body_args = PipelineBodyArgs::builder()
            .from_to_page(None)
            .build()
            .unwrap();
        let cli_args = ListRemoteCliArgs::builder().build().unwrap();
        list_pipelines(Arc::new(pp_remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!("No resources found.\n", String::from_utf8(buf).unwrap(),)
    }

    #[test]
    fn test_pipelines_empty_with_flush_option_no_warn_message() {
        let pp_remote = PipelineMock::builder().build().unwrap();
        let mut buf = Vec::new();
        let body_args = PipelineBodyArgs::builder()
            .from_to_page(None)
            .build()
            .unwrap();
        let cli_args = ListRemoteCliArgs::builder().flush(true).build().unwrap();
        list_pipelines(Arc::new(pp_remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!("", String::from_utf8(buf).unwrap(),)
    }

    #[test]
    fn test_list_pipelines_error() {
        let pp_remote = PipelineMock::builder().error(true).build().unwrap();
        let mut buf = Vec::new();
        let body_args = PipelineBodyArgs::builder()
            .from_to_page(None)
            .build()
            .unwrap();
        let cli_args = ListRemoteCliArgs::builder().build().unwrap();
        assert!(list_pipelines(Arc::new(pp_remote), body_args, cli_args, &mut buf).is_err());
    }

    #[test]
    fn test_list_number_of_pipelines_pages() {
        let pp_remote = PipelineMock::builder().num_pages(3 as u32).build().unwrap();
        let mut buf = Vec::new();
        num_cicd_pages(Arc::new(pp_remote), &mut buf).unwrap();
        assert_eq!("3\n", String::from_utf8(buf).unwrap(),)
    }

    #[test]
    fn test_no_pages_available() {
        let pp_remote = PipelineMock::builder().build().unwrap();
        let mut buf = Vec::new();
        num_cicd_pages(Arc::new(pp_remote), &mut buf).unwrap();
        assert_eq!(
            "Number of pages not available.\n",
            String::from_utf8(buf).unwrap(),
        )
    }

    #[test]
    fn test_number_of_pages_error() {
        let pp_remote = PipelineMock::builder().error(true).build().unwrap();
        let mut buf = Vec::new();
        assert!(num_cicd_pages(Arc::new(pp_remote), &mut buf).is_err());
    }

    #[test]
    fn test_list_pipelines_no_headers() {
        let pp_remote = PipelineMock::builder()
            .pipelines(vec![
                Pipeline::builder()
                    .id(123)
                    .status("success".to_string())
                    .web_url("https://gitlab.com/owner/repo/-/pipelines/123".to_string())
                    .branch("master".to_string())
                    .sha("1234567890abcdef".to_string())
                    .created_at("2020-01-01T00:00:00Z".to_string())
                    .updated_at("2020-01-01T00:01:00Z".to_string())
                    .duration(60)
                    .build()
                    .unwrap(),
                Pipeline::builder()
                    .id(456)
                    .status("failed".to_string())
                    .web_url("https://gitlab.com/owner/repo/-/pipelines/456".to_string())
                    .branch("master".to_string())
                    .sha("1234567890abcdef".to_string())
                    .created_at("2020-01-01T00:00:00Z".to_string())
                    .updated_at("2020-01-01T00:01:00Z".to_string())
                    .duration(60)
                    .build()
                    .unwrap(),
            ])
            .build()
            .unwrap();
        let mut buf = Vec::new();
        let body_args = PipelineBodyArgs::builder()
            .from_to_page(None)
            .build()
            .unwrap();
        let cli_args = ListRemoteCliArgs::builder()
            .get_args(
                GetRemoteCliArgs::builder()
                    .no_headers(true)
                    .build()
                    .unwrap(),
            )
            .build()
            .unwrap();
        list_pipelines(Arc::new(pp_remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!(
            "123|https://gitlab.com/owner/repo/-/pipelines/123|master|1234567890abcdef|2020-01-01T00:00:00Z|2020-01-01T00:01:00Z|60|success\n\
             456|https://gitlab.com/owner/repo/-/pipelines/456|master|1234567890abcdef|2020-01-01T00:00:00Z|2020-01-01T00:01:00Z|60|failed\n",
            String::from_utf8(buf).unwrap(),
        )
    }

    #[derive(Builder, Clone)]
    struct RunnerMock {
        #[builder(default = "vec![]")]
        runners: Vec<Runner>,
        #[builder(default)]
        error: bool,
        #[builder(default)]
        one_runner: Option<RunnerMetadata>,
    }

    impl RunnerMock {
        pub fn builder() -> RunnerMockBuilder {
            RunnerMockBuilder::default()
        }
    }

    impl CicdRunner for RunnerMock {
        fn list(&self, _args: RunnerListBodyArgs) -> Result<Vec<Runner>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            let rr = self.runners.clone();
            Ok(rr)
        }

        fn get(&self, _id: i64) -> Result<RunnerMetadata> {
            let rr = self.one_runner.as_ref().unwrap();
            Ok(rr.clone())
        }

        fn num_pages(&self, _args: RunnerListBodyArgs) -> Result<Option<u32>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            Ok(None)
        }

        fn num_resources(
            &self,
            _args: RunnerListBodyArgs,
        ) -> Result<Option<crate::api_traits::NumberDeltaErr>> {
            todo!()
        }

        fn create(&self, _args: RunnerPostDataCliArgs) -> Result<RunnerRegistrationResponse> {
            Ok(RunnerRegistrationResponse::builder()
                .id(1)
                .token("token".to_string())
                .token_expiration("2020-01-01T00:00:00Z".to_string())
                .build()
                .unwrap())
        }
    }

    #[test]
    fn test_list_runners() {
        let runners = vec![
            Runner::builder()
                .id(1)
                .active(true)
                .description("Runner 1".to_string())
                .ip_address("10.0.0.1".to_string())
                .name("runner1".to_string())
                .online(true)
                .status("online".to_string())
                .paused(false)
                .is_shared(true)
                .runner_type("shared".to_string())
                .build()
                .unwrap(),
            Runner::builder()
                .id(2)
                .active(true)
                .description("Runner 2".to_string())
                .ip_address("10.0.0.2".to_string())
                .name("runner2".to_string())
                .online(true)
                .status("online".to_string())
                .paused(false)
                .is_shared(true)
                .runner_type("shared".to_string())
                .build()
                .unwrap(),
        ];
        let remote = RunnerMock::builder().runners(runners).build().unwrap();
        let mut buf = Vec::new();
        let body_args = RunnerListBodyArgs::builder()
            .list_args(None)
            .status(RunnerStatus::Online)
            .build()
            .unwrap();
        let cli_args = RunnerListCliArgs::builder()
            .status(RunnerStatus::Online)
            .list_args(ListRemoteCliArgs::builder().build().unwrap())
            .build()
            .unwrap();
        list_runners(Arc::new(remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!(
            "ID|Active|Description|IP Address|Name|Paused|Shared|Type|Online|Status\n\
             1|true|Runner 1|10.0.0.1|runner1|false|true|shared|true|online\n\
             2|true|Runner 2|10.0.0.2|runner2|false|true|shared|true|online\n",
            String::from_utf8(buf).unwrap()
        )
    }

    #[test]
    fn test_no_runners_warn_user_with_message() {
        let remote = RunnerMock::builder().build().unwrap();
        let mut buf = Vec::new();
        let body_args = RunnerListBodyArgs::builder()
            .list_args(None)
            .status(RunnerStatus::Online)
            .build()
            .unwrap();
        let cli_args = RunnerListCliArgs::builder()
            .status(RunnerStatus::Online)
            .list_args(ListRemoteCliArgs::builder().build().unwrap())
            .build()
            .unwrap();
        list_runners(Arc::new(remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!("No resources found.\n", String::from_utf8(buf).unwrap())
    }

    #[test]
    fn test_no_runners_found_with_flush_option_no_warn_message() {
        let remote = RunnerMock::builder().build().unwrap();
        let mut buf = Vec::new();
        let body_args = RunnerListBodyArgs::builder()
            .list_args(None)
            .status(RunnerStatus::Online)
            .build()
            .unwrap();
        let cli_args = RunnerListCliArgs::builder()
            .status(RunnerStatus::Online)
            .list_args(ListRemoteCliArgs::builder().flush(true).build().unwrap())
            .build()
            .unwrap();
        list_runners(Arc::new(remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!("", String::from_utf8(buf).unwrap())
    }

    #[test]
    fn test_get_gitlab_runner_metadata() {
        let runner_metadata = RunnerMetadata::builder()
            .id(1)
            .run_untagged(true)
            .tag_list(vec!["tag1".to_string(), "tag2".to_string()])
            .version("13.0.0".to_string())
            .architecture("amd64".to_string())
            .platform("linux".to_string())
            .contacted_at("2020-01-01T00:00:00Z".to_string())
            .revision("1234567890abcdef".to_string())
            .build()
            .unwrap();
        let remote = RunnerMock::builder()
            .one_runner(Some(runner_metadata))
            .build()
            .unwrap();
        let mut buf = Vec::new();
        let cli_args = RunnerMetadataGetCliArgs::builder()
            .id(1)
            .get_args(GetRemoteCliArgs::builder().build().unwrap())
            .build()
            .unwrap();
        get_runner_details(Arc::new(remote), cli_args, &mut buf).unwrap();
        assert_eq!(
            "ID|Run untagged|Tags|Architecture|Platform|Contacted at|Version|Revision\n\
             1|true|tag1, tag2|amd64|linux|2020-01-01T00:00:00Z|13.0.0|1234567890abcdef\n",
            String::from_utf8(buf).unwrap()
        )
    }

    fn gen_gitlab_ci_body() -> Vec<u8> {
        b"image: alpine\n\
          stages:\n\
            - build\n\
            - test\n\
          build:\n\
            stage: build\n\
            script:\n\
              - echo \"Building\"\n\
          test:\n\
            stage: test\n\
            script:\n\
              - echo \"Testing\"\n"
            .to_vec()
    }

    #[test]
    fn test_read_gitlab_ci_file_contents() {
        let expected_body = gen_gitlab_ci_body();
        let buf = Cursor::new(&expected_body);
        let body = read_ci_file(buf).unwrap();
        assert_eq!(*expected_body, *body);
    }

    #[test]
    fn test_lint_ci_file_success() {
        let mock_cicd = Arc::new(PipelineMock::builder().build().unwrap());
        let mut writer = Vec::new();
        let result = lint_ci_file(mock_cicd, &gen_gitlab_ci_body(), false, &mut writer);
        assert!(result.is_ok());
        assert_eq!(String::from_utf8(writer).unwrap(), "File is valid.\n");
    }

    #[test]
    fn test_lint_ci_file_has_errors_prints_errors() {
        let mock_cicd = Arc::new(PipelineMock::builder().error(true).build().unwrap());
        let mut writer = Vec::new();
        let result = lint_ci_file(mock_cicd, &gen_gitlab_ci_body(), false, &mut writer);
        assert!(result.is_err());
        assert_eq!(String::from_utf8(writer).unwrap(), "YAML Error\n");
    }

    #[test]
    fn test_get_merged_yaml_from_lint_response() {
        let response = LintResponse::builder()
            .valid(true)
            .merged_yaml("image: alpine\nstages:\n  - build\n  - test\nbuild:\n  stage: build\n  script:\n  - echo \"Building\"\ntest:\n  stage: test\n  script:\n  - echo \"Testing\"\n".to_string())
            .errors(vec![])
            .build()
            .unwrap();
        let mut writer = Vec::new();
        let mock_cicd = Arc::new(
            PipelineMock::builder()
                .gitlab_ci_merged_yaml(response.merged_yaml)
                .build()
                .unwrap(),
        );

        let result = lint_ci_file(mock_cicd, &gen_gitlab_ci_body(), true, &mut writer);
        assert!(result.is_ok());
        let merged_gitlab_ci = r#"image: alpine
stages:
  - build
  - test
build:
  stage: build
  script:
  - echo "Building"
test:
  stage: test
  script:
  - echo "Testing"
"#;
        assert_eq!(merged_gitlab_ci, String::from_utf8(writer).unwrap());
    }

    #[derive(Builder)]
    struct JobMock {
        #[builder(default)]
        jobs: Vec<Job>,
        #[builder(default)]
        error: bool,
        #[builder(default)]
        num_pages: Option<u32>,
    }

    impl JobMock {
        pub fn builder() -> JobMockBuilder {
            JobMockBuilder::default()
        }
    }

    impl CicdJob for JobMock {
        fn list(&self, _args: JobListBodyArgs) -> Result<Vec<Job>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            let jj = self.jobs.clone();
            Ok(jj)
        }

        fn num_pages(&self, _args: JobListBodyArgs) -> Result<Option<u32>> {
            if self.error {
                return Err(error::gen("Error"));
            }
            Ok(self.num_pages)
        }

        fn num_resources(&self, _args: JobListBodyArgs) -> Result<Option<NumberDeltaErr>> {
            todo!()
        }
    }

    #[test]
    fn test_list_pipeline_jobs() {
        let jobs = vec![
            Job::builder()
                .id(1)
                .name("job1".to_string())
                .branch("main".to_string())
                .author_name("user1".to_string())
                .commit_sha("1234567890abcdef".to_string())
                .pipeline_id(1)
                .url("https://gitlab.com/owner/repo/-/jobs/1".to_string())
                .runner_tags(vec!["tag1".to_string(), "tag2".to_string()])
                .stage("build".to_string())
                .status("success".to_string())
                .created_at("2020-01-01T00:00:00Z".to_string())
                .started_at("2020-01-01T00:01:00Z".to_string())
                .finished_at("2020-01-01T00:01:30Z".to_string())
                .duration("25".to_string())
                .build()
                .unwrap(),
            Job::builder()
                .id(2)
                .name("job2".to_string())
                .branch("main".to_string())
                .author_name("user2".to_string())
                .commit_sha("1234567890abcdef".to_string())
                .pipeline_id(1)
                .url("https://gitlab.com/owner/repo/-/jobs/2".to_string())
                .runner_tags(vec!["tag1".to_string(), "tag2".to_string()])
                .stage("test".to_string())
                .status("failed".to_string())
                .created_at("2020-01-01T00:00:00Z".to_string())
                .started_at("2020-01-01T00:01:00Z".to_string())
                .finished_at("2020-01-01T00:01:30Z".to_string())
                .duration("30".to_string())
                .build()
                .unwrap(),
        ];
        let remote = JobMock::builder().jobs(jobs).build().unwrap();
        let mut buf = Vec::new();
        let body_args = JobListBodyArgs::builder().list_args(None).build().unwrap();
        let cli_args = JobListCliArgs::builder()
            .list_args(ListRemoteCliArgs::builder().build().unwrap())
            .build()
            .unwrap();
        list_jobs(Arc::new(remote), body_args, cli_args, &mut buf).unwrap();
        assert_eq!(
"ID|Name|Author Name|Branch|Commit SHA|Pipeline ID|URL|Runner Tags|Stage|Status|Created At|Started At|Finished At|Duration\n1|job1|user1|main|1234567890abcdef|1|https://gitlab.com/owner/repo/-/jobs/1|tag1, tag2|build|success|2020-01-01T00:00:00Z|2020-01-01T00:01:00Z|2020-01-01T00:01:30Z|25\n2|job2|user2|main|1234567890abcdef|1|https://gitlab.com/owner/repo/-/jobs/2|tag1, tag2|test|failed|2020-01-01T00:00:00Z|2020-01-01T00:01:00Z|2020-01-01T00:01:30Z|30\n",
            String::from_utf8(buf).unwrap()
        );
    }

    #[test]
    fn test_create_new_runner() {
        let remote = RunnerMock::builder().build().unwrap();
        let mut buf = Vec::new();
        let cli_args = RunnerPostDataCliArgs::builder()
            .description(Some("Runner 1".to_string()))
            .tags(Some("tag1,tag2".to_string()))
            .kind(RunnerType::Instance)
            .build()
            .unwrap();
        create_runner(Arc::new(remote), cli_args, &mut buf).unwrap();
        assert_eq!(
            "Runner ID: [1], Runner Token: [token], Token Expiration: [2020-01-01T00:00:00Z]\n",
            String::from_utf8(buf).unwrap()
        )
    }
}