simpleci 0.1.0

A simple tool to run CICD pipelines locally
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
use colored::*;
use serde_yaml::Value;
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::process::exit;
// use std::process::Command;

// Main objects
////////////////////////////////////////
// Creation of the Pipeline object    //
////////////////////////////////////////
#[derive(Debug)]
pub struct Pipeline {
    // Pipeline object has 3 forms (PipelineTypes): a simple script, a list of jobs and a list of stages.
    pipeline_type: PipelineType,
    stages: Vec<Stage>,
    jobs: Vec<Job>,
    script: Script,
    variables: HashMap<String, String>,
}

impl Pipeline {
    ////////////////////////////////////////
    //     Implement Pipeline::new()      //
    ////////////////////////////////////////
    pub fn new(pipeline_file: &str) -> Pipeline {
        // Extract data from file
        let pipeline_data = get_pipeline_data(pipeline_file);
        // determine pipeline type
        match get_pipeline_type(pipeline_data.clone()) {
            ////////////////////////////////////////
            // Create a Script with pipeline data //
            ////////////////////////////////////////
            PipelineType::Script => {
                let script_data = get_script(pipeline_data.clone()).unwrap();
                let new_pipeline = Pipeline {
                    pipeline_type: PipelineType::Script,
                    stages: vec![],                   // empty
                    jobs: vec![],                     // empty
                    script: Script::new(script_data), // Create the script object
                    variables: get_variables(pipeline_data),
                };
                return new_pipeline;
            }
            ////////////////////////////////////////
            // Create jobs with pipeline data     //
            ////////////////////////////////////////
            PipelineType::Jobs => {
                let mut pipeline_jobs: Vec<Job> = vec![];
                let pipeline_variables = get_variables(pipeline_data.clone());
                // Get jobs liste (sequence)
                let jobs_data = get_jobs(pipeline_data.clone()).unwrap();
                // Loop over pipeline data to gather jobs scripts
                let mut a = 0;
                loop {
                    // get next job if exists
                    if jobs_data.get(a).is_some() {
                        // get job name
                        let job_name = jobs_data.get(a).unwrap().as_str().unwrap().to_owned();
                        let job_script = if get_job_or_stage(
                            pipeline_data.clone(),
                            job_name.clone(),
                        )
                        .is_some()
                        {
                            get_job_or_stage(pipeline_data.clone(), job_name.clone()).unwrap()
                        } else {
                            break;
                        };
                        pipeline_jobs.push(Job::new(
                            job_name.clone(),
                            job_script.clone(),
                            pipeline_variables.clone(),
                        ));
                    } else {
                        break;
                    }
                    a += 1;
                }
                let new_pipeline = Pipeline {
                    pipeline_type: PipelineType::Jobs,
                    stages: vec![], // empty
                    jobs: pipeline_jobs,
                    script: Script { data: vec![] }, // empty
                    variables: pipeline_variables,
                };
                return new_pipeline;
            }
            ////////////////////////////////////////
            // Create stages with pipeline data   //
            ////////////////////////////////////////
            PipelineType::Stages => {
                let mut pipeline_stages: Vec<Stage> = vec![];
                let pipeline_variables = get_variables(pipeline_data.clone());
                // Get stages liste (sequence)
                let stages_data = get_stages(pipeline_data.clone()).unwrap();
                let mut a = 0;
                loop {
                    if stages_data.get(a).is_some() {
                        let stage_name = stages_data.get(a).unwrap().as_str().unwrap().to_owned();
                        pipeline_stages.push(Stage::new(
                            stage_name,
                            pipeline_data.clone(),
                            pipeline_variables.clone(),
                        ));
                    } else {
                        break;
                    }
                    a += 1;
                }

                let new_pipeline = Pipeline {
                    pipeline_type: PipelineType::Stages,
                    stages: pipeline_stages,
                    jobs: vec![],                    // empty
                    script: Script { data: vec![] }, // empty
                    variables: pipeline_variables,
                };
                return new_pipeline;
            }
            PipelineType::Null => panic!("Error in pipeline format!"),
        }
    }
    ////////////////////////////////////////////////
    //     Implement Pipeline::exec_pipeline()    //
    ////////////////////////////////////////////////
    pub fn exec_pipeline(&self) -> &str {
        match self.pipeline_type {
            PipelineType::Script => {
                println!("{}", "###############################".green());
                self.script.exec(self.variables.clone());
                println!("{}", "###############################\n".green());
                return "Le script s'est éxécuté";
            }
            PipelineType::Jobs => {
                for a in 0..self.jobs.len() {
                    println!("{}", "###############################".green());
                    self.jobs[a].exec();
                    println!("{}", "###############################\n".green());
                }
                return "Le script (job) s'est éxécuté";
            }
            PipelineType::Stages => {
                for a in 0..self.stages.len() {
                    println!("{}", "###############################".green());
                    println!(
                        ">>> Execution du stage '{}'",
                        self.stages[a].get_name().to_string().blue()
                    );
                    self.stages[a].exec();
                    println!("{}", "###############################\n".green());
                }
                return "Le script (stage) s'est éxécuté";
            }
            PipelineType::Null => panic!("Error in pipeline format!"),
        }
    }
}

////////////////////////////////////////
// Creation of the Script object      //
////////////////////////////////////////
#[derive(Debug)]
pub struct Script {
    data: Vec<String>,
}
impl Script {
    pub fn new(script_data: Value) -> Script {
        // add command to script data until no command is left
        let mut a = 0;
        let mut commands: Vec<String> = vec![];
        loop {
            let next_command = get_command(script_data.clone(), a);
            if next_command.is_some() {
                commands.push(next_command.unwrap());
            } else {
                break;
            }
            a += 1;
        }
        let new_script = Script { data: commands };
        return new_script;
    }
    pub fn exec(&self, variables: HashMap<String, String>) -> bool {
        let mut script_string = "".to_owned(); // Initialize script
        script_string += "set -ebuxo pipefail\n"; // Make script fail when needed
        script_string += "exec 2>&1\n"; // Redirect stderr

        //add variables
        for (key, value) in variables {
            script_string += "export ";
            script_string += key.as_str();
            script_string += "=";
            script_string += value.as_str();
            script_string += "\n";
        }

        // add commands
        for command in self.data.iter() {
            script_string += "\n";
            script_string += command;
        }

        // exec command
        let res = exec_command(script_string);
        if res.0 == true {
            let res1 = res.1.clone();
            let parts = res1.split("\n");
            for part in parts {
                // Handle the absence of first character
                if part.chars().nth(0).is_some() {
                    // Color commands
                    if part.chars().nth(0).unwrap() == '+' {
                        println!("{}", part.blue())
                    } else {
                        println!("{}", part)
                    }
                }
            }
            return true;
        } else {
            let res2 = res.2.clone();
            let parts = res2.split("\n");
            for part in parts {
                // Handle the absence of first character
                if part.chars().nth(0).is_some() {
                    // Color commands
                    if part.chars().nth(0).unwrap() == '+' {
                        println!("{}", part.on_red().cyan())
                    } else {
                        println!("{}", part.on_red())
                    }
                }
            }
            return false;
        }
    }
}

////////////////////////////////////////
// Creation of the Job object         //
////////////////////////////////////////
#[derive(Debug)]
pub struct Job {
    name: String,
    scripts: Script,
    variables: HashMap<String, String>,
}
impl Job {
    pub fn new(
        job_name: String,
        job_data: Value,
        herited_variables: HashMap<String, String>,
    ) -> Job {
        // merge the 2 dicts
        let mut all_vars = herited_variables;
        for (key, value) in get_variables(job_data.clone()).iter() {
            all_vars.insert(key.to_owned(), value.to_owned());
        }
        return Job {
            name: job_name,
            scripts: Script::new(job_data.get("script").unwrap().to_owned()),
            variables: all_vars,
        };
    }
    pub fn exec(&self) {
        println!("> Execution du job '{}'", self.name.to_owned().green());
        self.scripts.exec(self.variables.clone());
        // self.scripts.print_exec();
    }
}

////////////////////////////////////////
// Creation of the Stage object       //
////////////////////////////////////////
#[derive(Debug)]
pub struct Stage {
    name: String,
    jobs: Vec<Job>,
    // variables: HashMap<String, String>, // this attribute has no use for now
}
impl Stage {
    // args: nom du stage, data pipeline
    pub fn new(
        stage_name: String,
        pipeline_data: Value,
        herited_variables: HashMap<String, String>,
    ) -> Stage {
        // Create jobs vector
        let mut stage_jobs: Vec<Job> = vec![];
        // Get jobs liste (sequence)
        let stage_data = if get_job_or_stage(pipeline_data.clone(), stage_name.clone()).is_some() {
            get_job_or_stage(pipeline_data.clone(), stage_name.clone()).unwrap()
        } else {
            panic!(
                "The stage '{}' doesn't exists in pipeline",
                stage_name.as_str().red()
            );
        };
        // merge the 2 vars dicts
        let mut all_vars = herited_variables;
        for (key, value) in get_variables(stage_data.clone()).iter() {
            all_vars.insert(key.to_owned(), value.to_owned());
        }
        let jobs_data = if get_jobs(stage_data.clone()).is_some() {
            get_jobs(stage_data.clone()).unwrap()
        } else {
            panic!("Jobs not found for stage '{}", stage_name.as_str().red())
        };
        // Loop over stage data to gather jobs scripts
        let mut a = 0;
        loop {
            // get next job if exists
            if jobs_data.get(a).is_some() {
                // get job name
                let job_name = jobs_data.get(a).unwrap().as_str().unwrap().to_owned();
                let job_script =
                    if get_job_or_stage(pipeline_data.clone(), job_name.clone()).is_some() {
                        get_job_or_stage(pipeline_data.clone(), job_name.clone()).unwrap()
                    } else {
                        a += 1;
                        continue;
                    };
                stage_jobs.push(Job::new(
                    job_name.clone(),
                    job_script.clone(),
                    all_vars.clone(), // TODO
                ));
            } else {
                break;
            }
            a += 1;
        }
        return Stage {
            name: stage_name,
            jobs: stage_jobs,
            // variables: all_vars, // this attribute has no use for now
        };
    }
    pub fn get_name(&self) -> String {
        return self.name.clone();
    }
    pub fn exec(&self) {
        for job in self.jobs.iter() {
            job.exec();
        }
    }
}

////////////////////////////////////////
// Functions                          //
////////////////////////////////////////
// Get functions
pub fn get_variables<'t>(data: Value) -> HashMap<String, String> {
    let variables = data.get("variables");
    if variables.is_some() {
        //assert parsed vars is not null
        if variables.unwrap().is_mapping() {
            //assert it's a mapping
            let mut map = HashMap::new();
            for var in variables.unwrap().to_owned().as_mapping().unwrap().iter() {
                let key = var.0.as_str().unwrap().to_owned();
                let value = var.1.as_str().unwrap().to_owned();
                map.insert(key, value);
            }
            return map;
        } else {
            println!(
                "{}",
                "Variables data is incorrect! (not a dictionnay)".red()
            );
            exit(1)
        }
    } else {
        return HashMap::new();
    }
}

pub fn get_script<'t>(data: Value) -> Option<Value> {
    let script = data.get("script");
    match script {
        Some(_) => return Option::Some(script.unwrap().to_owned()),
        None => return Option::None,
    }
}

pub fn get_command<'t>(script: Value, i: usize) -> Option<std::string::String> {
    let command = script.get(i);
    if command.is_some() {
        return Option::Some(command.unwrap().as_str().unwrap().to_owned());
    } else {
        return Option::None;
    }
}

pub fn get_jobs<'t>(data: Value) -> Option<Value> {
    let jobs = data.get("jobs");
    match jobs {
        Some(_) => return Option::Some(jobs.unwrap().to_owned()),
        None => return Option::None,
    }
}

pub fn get_stages<'t>(pipeline: Value) -> Option<Value> {
    let stages = pipeline.get("stages");
    match stages {
        Some(_) => return Option::Some(stages.unwrap().to_owned()),
        None => return Option::None,
    }
}

pub fn get_job_or_stage<'t>(pipeline: Value, job_or_stage_name: String) -> Option<Value> {
    let stages = pipeline.get(job_or_stage_name);
    match stages {
        Some(_) => return Option::Some(stages.unwrap().to_owned()),
        None => return Option::None,
    }
}
// Get raw pipeline data
pub fn get_pipeline_data<'t>(file: &str) -> Value {
    let content = fs::read_to_string(file).expect("Could not read the pipeline file");
    let pipeline: Value = serde_yaml::from_str(&content).unwrap();
    return pipeline;
}

pub fn exec_command(
    command: std::string::String,
) -> (bool, std::string::String, std::string::String) {
    let command_args = OsString::from(command.as_str());
    let mut command_base = std::process::Command::new("bash");
    // TODO: captuer la sortie, passer toute la commande
    let command_executed = command_base
        .arg("-c")
        .arg(command_args)
        .output()
        .expect("Error in command: '{command}'");

    let command_success = command_executed.status.success();

    let command_stdout = std::str::from_utf8(&command_executed.stdout[..])
        .unwrap()
        .to_owned();

    let command_stderr = std::str::from_utf8(&command_executed.stdout[..])
        .unwrap()
        .to_owned();

    return (command_success, command_stdout, command_stderr);
}

#[derive(Debug)]
pub enum PipelineType {
    Null,
    Stages,
    Jobs,
    Script,
}

pub fn get_pipeline_type(pipeline_data: Value) -> PipelineType {
    let stages = get_stages(pipeline_data.clone());
    let jobs = get_jobs(pipeline_data.clone());
    let script = get_script(pipeline_data.clone());

    let pipeline_type_found: PipelineType;
    if stages.is_some() {
        pipeline_type_found = PipelineType::Stages;
    } else if jobs.is_some() {
        pipeline_type_found = PipelineType::Jobs;
    } else if script.is_some() {
        pipeline_type_found = PipelineType::Script;
    } else {
        pipeline_type_found = PipelineType::Null
    }
    return pipeline_type_found;
}

pub fn main_exec(myfile: &str) {
    println!("this file will be used: {}", myfile)
}
pub fn main_start() {
    println!("Start: Not implemented yet!")
}
pub fn main_stop() {
    println!("Stop: Not implemented yet!")
}
pub fn main_init() {
    println!("Init: Not implemented yet!")
}
pub fn main_clean() {
    println!("Clean: Not implemented yet!")
}