rust-actions 0.2.1

BDD testing framework with GitHub Actions YAML syntax
Documentation
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
use crate::expr::{evaluate_assertion, evaluate_value, ExprContext, JobOutputs};
use crate::hooks::HookRegistry;
use crate::matrix::{expand_matrix, format_matrix_suffix, MatrixCombination};
use crate::parser::{parse_workflow_file, parse_workflows, Job, Step, Workflow};
use crate::registry::{ErasedStepFn, StepRegistry};
use crate::workflow_registry::{is_file_ref, parse_file_ref, WorkflowRegistry};
use crate::world::World;
use crate::{Error, Result};
use colored::Colorize;
use serde_json::Value;
use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use std::path::PathBuf;
use std::time::{Duration, Instant};

#[derive(Debug, Clone)]
pub enum StepResult {
    Passed(Duration),
    Failed(Duration, String),
    Skipped,
}

impl StepResult {
    pub fn is_passed(&self) -> bool {
        matches!(self, StepResult::Passed(_))
    }

    pub fn is_failed(&self) -> bool {
        matches!(self, StepResult::Failed(_, _))
    }
}

#[derive(Debug)]
pub struct JobResult {
    pub name: String,
    pub matrix_suffix: String,
    pub steps: Vec<(String, StepResult)>,
    pub outputs: JobOutputs,
    pub duration: Duration,
}

impl JobResult {
    pub fn passed(&self) -> bool {
        self.steps.iter().all(|(_, r)| r.is_passed())
    }

    pub fn steps_passed(&self) -> usize {
        self.steps.iter().filter(|(_, r)| r.is_passed()).count()
    }

    pub fn steps_failed(&self) -> usize {
        self.steps.iter().filter(|(_, r)| r.is_failed()).count()
    }
}

#[derive(Debug)]
pub struct WorkflowResult {
    pub name: String,
    pub jobs: Vec<JobResult>,
    pub duration: Duration,
}

impl WorkflowResult {
    pub fn passed(&self) -> bool {
        self.jobs.iter().all(|j| j.passed())
    }

    pub fn jobs_passed(&self) -> usize {
        self.jobs.iter().filter(|j| j.passed()).count()
    }

    pub fn jobs_failed(&self) -> usize {
        self.jobs.iter().filter(|j| !j.passed()).count()
    }

    pub fn total_steps_passed(&self) -> usize {
        self.jobs.iter().map(|j| j.steps_passed()).sum()
    }

    pub fn total_steps_failed(&self) -> usize {
        self.jobs.iter().map(|j| j.steps_failed()).sum()
    }
}

pub struct RustActions<W: World + 'static> {
    workflows_path: PathBuf,
    single_workflow: Option<PathBuf>,
    steps: StepRegistry,
    hooks: HookRegistry<W>,
    session_id: String,
    _phantom: PhantomData<W>,
}

impl<W: World + 'static> RustActions<W> {
    pub fn new() -> Self {
        let mut steps = StepRegistry::new();
        steps.collect_for::<W>();

        let session_id = uuid::Uuid::new_v4().to_string().replace("-", "")[..8].to_string();

        Self {
            workflows_path: PathBuf::from("tests/workflows"),
            single_workflow: None,
            steps,
            hooks: HookRegistry::new(),
            session_id,
            _phantom: PhantomData,
        }
    }

    pub fn workflows(mut self, path: impl Into<PathBuf>) -> Self {
        self.workflows_path = path.into();
        self
    }

    pub fn features(self, path: impl Into<PathBuf>) -> Self {
        self.workflows(path)
    }

    pub fn workflow(mut self, path: impl Into<PathBuf>) -> Self {
        self.single_workflow = Some(path.into());
        self
    }

    pub fn register_step(mut self, name: impl Into<String>, func: ErasedStepFn) -> Self {
        self.steps.register(name, func);
        self
    }

    pub async fn run(self) {
        std::env::set_var("RUST_ACTIONS_SESSION_ID", &self.session_id);

        let registry = if self.single_workflow.is_some() {
            None
        } else {
            match WorkflowRegistry::build(&self.workflows_path) {
                Ok(r) => Some(r),
                Err(e) => {
                    eprintln!(
                        "{} Failed to build workflow registry: {}",
                        "Error:".red().bold(),
                        e
                    );
                    std::process::exit(1);
                }
            }
        };

        let workflows: Vec<(PathBuf, Workflow)> = if let Some(ref path) = self.single_workflow {
            match parse_workflow_file(path) {
                Ok(w) => vec![w],
                Err(e) => {
                    eprintln!("{} Failed to parse workflow: {}", "Error:".red().bold(), e);
                    std::process::exit(1);
                }
            }
        } else {
            match parse_workflows(&self.workflows_path) {
                Ok(w) => w.into_iter().filter(|(_, w)| !w.is_reusable()).collect(),
                Err(e) => {
                    eprintln!(
                        "{} Failed to parse workflows: {}",
                        "Error:".red().bold(),
                        e
                    );
                    std::process::exit(1);
                }
            }
        };

        self.hooks.run_before_all().await;

        let mut all_results = Vec::new();
        let mut total_passed = 0;
        let mut total_failed = 0;

        for (path, workflow) in workflows {
            let result = self.run_workflow(&path, workflow, registry.as_ref()).await;
            total_passed += result.jobs_passed();
            total_failed += result.jobs_failed();
            all_results.push(result);
        }

        self.hooks.run_after_all().await;

        println!();
        let total_jobs = total_passed + total_failed;
        let total_steps_passed: usize = all_results.iter().map(|r| r.total_steps_passed()).sum();
        let total_steps_failed: usize = all_results.iter().map(|r| r.total_steps_failed()).sum();
        let total_steps = total_steps_passed + total_steps_failed;

        if total_failed == 0 {
            println!(
                "{} {} ({} passed)",
                format!("{} jobs", total_jobs).green(),
                "✓".green(),
                total_passed
            );
        } else {
            println!(
                "{} ({} passed, {} failed)",
                format!("{} jobs", total_jobs).yellow(),
                total_passed,
                total_failed
            );
        }

        println!(
            "{} ({} passed, {} failed)",
            format!("{} steps", total_steps),
            total_steps_passed,
            total_steps_failed
        );

        if total_failed > 0 {
            std::process::exit(1);
        }
    }

    async fn run_workflow(
        &self,
        _path: &PathBuf,
        workflow: Workflow,
        registry: Option<&WorkflowRegistry>,
    ) -> WorkflowResult {
        let start = Instant::now();
        println!("\n{} {}", "Workflow:".bold(), workflow.name);

        let job_order = match toposort_jobs(&workflow.jobs) {
            Ok(order) => order,
            Err(e) => {
                eprintln!("{} {}", "Error:".red().bold(), e);
                return WorkflowResult {
                    name: workflow.name,
                    jobs: vec![],
                    duration: start.elapsed(),
                };
            }
        };

        let mut job_outputs: HashMap<String, JobOutputs> = HashMap::new();
        let mut job_results = Vec::new();

        for job_name in job_order {
            let job = &workflow.jobs[&job_name];

            if let Some(uses) = &job.uses {
                if is_file_ref(uses) {
                    if let Some(reg) = registry {
                        match self
                            .run_file_ref_job(&job_name, uses, job, reg, &job_outputs)
                            .await
                        {
                            Ok(result) => {
                                job_outputs.insert(job_name.clone(), result.outputs.clone());
                                job_results.push(result);
                            }
                            Err(e) => {
                                eprintln!(
                                    "  {} {} ({})",
                                    "✗".red(),
                                    job_name,
                                    e
                                );
                            }
                        }
                    }
                    continue;
                }
            }

            let matrix_combos = job
                .strategy
                .as_ref()
                .map(|s| expand_matrix(s))
                .unwrap_or_else(|| vec![HashMap::new()]);

            for matrix_values in matrix_combos {
                let result = self
                    .run_job(&job_name, job, &workflow.env, &job_outputs, &matrix_values)
                    .await;
                job_outputs.insert(job_name.clone(), result.outputs.clone());
                job_results.push(result);
            }
        }

        WorkflowResult {
            name: workflow.name,
            jobs: job_results,
            duration: start.elapsed(),
        }
    }

    async fn run_file_ref_job(
        &self,
        job_name: &str,
        uses: &str,
        _job: &Job,
        registry: &WorkflowRegistry,
        parent_outputs: &HashMap<String, JobOutputs>,
    ) -> Result<JobResult> {
        let start = Instant::now();
        let file_path = parse_file_ref(uses)?;
        let ref_workflow = registry.resolve_file_ref(uses)?;

        println!(
            "  {} {} (via @file:{})",
            "Job:".dimmed(),
            job_name,
            file_path
        );

        let mut combined_outputs = JobOutputs::new();

        let ref_job_order = toposort_jobs(&ref_workflow.jobs)?;

        let mut ref_job_outputs: HashMap<String, JobOutputs> = HashMap::new();
        let mut all_step_results = Vec::new();

        for ref_job_name in ref_job_order {
            let ref_job = &ref_workflow.jobs[&ref_job_name];

            let mut world = match W::new().await {
                Ok(w) => w,
                Err(_) => {
                    return Ok(JobResult {
                        name: job_name.to_string(),
                        matrix_suffix: String::new(),
                        steps: vec![],
                        outputs: JobOutputs::new(),
                        duration: start.elapsed(),
                    });
                }
            };

            let mut ctx = ExprContext::new();
            ctx.env = ref_workflow.env.clone();

            for (dep_name, dep_outputs) in &ref_job_outputs {
                ctx.needs.insert(dep_name.clone(), dep_outputs.clone());
            }
            for (dep_name, dep_outputs) in parent_outputs {
                ctx.needs.insert(dep_name.clone(), dep_outputs.clone());
            }

            #[allow(unused_variables)]
            let step_outputs: HashMap<String, Value> = HashMap::new();

            for step in &ref_job.steps {
                let result = self.run_step(&mut world, step, &mut ctx).await;
                let step_name = step.name.clone().unwrap_or_else(|| step.uses.clone());

                match &result {
                    StepResult::Passed(_) => {
                        println!("    {} {}", "✓".green(), step_name);
                    }
                    StepResult::Failed(_, msg) => {
                        println!("    {} {}", "✗".red(), step_name);
                        println!("      {}: {}", "Error".red(), msg);
                    }
                    StepResult::Skipped => {
                        println!("    {} {} (skipped)", "â—‹".dimmed(), step_name);
                    }
                }

                all_step_results.push((step_name, result));
            }

            let mut ref_job_output = JobOutputs::new();
            for (key, expr) in &ref_job.outputs {
                if let Ok(value) = evaluate_value(&Value::String(expr.clone()), &ctx) {
                    ref_job_output.insert(key.clone(), value);
                }
            }
            ref_job_outputs.insert(ref_job_name.clone(), ref_job_output.clone());
        }

        if let Some(trigger) = &ref_workflow.on {
            if let Some(call_config) = &trigger.workflow_call {
                for (key, output_def) in &call_config.outputs {
                    let mut eval_ctx = ExprContext::new();
                    for (job_name, outputs) in &ref_job_outputs {
                        eval_ctx.jobs.insert(job_name.clone(), outputs.clone());
                    }
                    if let Ok(value) =
                        evaluate_value(&Value::String(output_def.value.clone()), &eval_ctx)
                    {
                        combined_outputs.insert(key.clone(), value);
                    }
                }
            }
        }

        Ok(JobResult {
            name: job_name.to_string(),
            matrix_suffix: String::new(),
            steps: all_step_results,
            outputs: combined_outputs,
            duration: start.elapsed(),
        })
    }

    async fn run_job(
        &self,
        job_name: &str,
        job: &Job,
        workflow_env: &HashMap<String, String>,
        parent_outputs: &HashMap<String, JobOutputs>,
        matrix_values: &MatrixCombination,
    ) -> JobResult {
        let start = Instant::now();
        let matrix_suffix = format_matrix_suffix(matrix_values);

        let mut world = match W::new().await {
            Ok(w) => w,
            Err(e) => {
                println!(
                    "  {} {}{} (world init failed: {})",
                    "✗".red(),
                    job_name,
                    matrix_suffix,
                    e
                );
                return JobResult {
                    name: job_name.to_string(),
                    matrix_suffix,
                    steps: vec![],
                    outputs: JobOutputs::new(),
                    duration: start.elapsed(),
                };
            }
        };

        self.hooks.run_before_scenario(&mut world).await;

        let mut ctx = ExprContext::new();
        ctx.env = workflow_env.clone();
        ctx.env.extend(job.env.clone());
        ctx.matrix = matrix_values.clone();

        for need in job.needs.as_vec() {
            if let Some(outputs) = parent_outputs.get(&need) {
                ctx.needs.insert(need.clone(), outputs.clone());
            }
        }

        let mut step_results = Vec::new();
        let mut should_skip = false;

        for step in &job.steps {
            let step_name = step.name.clone().unwrap_or_else(|| step.uses.clone());

            if should_skip {
                step_results.push((step_name, StepResult::Skipped));
                continue;
            }

            self.hooks.run_before_step(&mut world, step).await;

            let result = self.run_step(&mut world, step, &mut ctx).await;

            self.hooks.run_after_step(&mut world, step, &result).await;

            if result.is_failed() && !step.continue_on_error {
                should_skip = true;
            }

            step_results.push((step_name, result));
        }

        self.hooks.run_after_scenario(&mut world).await;

        let duration = start.elapsed();
        let all_passed = step_results.iter().all(|(_, r)| r.is_passed());

        if all_passed {
            println!(
                "  {} {}{} ({:?})",
                "✓".green(),
                job_name,
                matrix_suffix,
                duration
            );
        } else {
            println!(
                "  {} {}{} ({:?})",
                "✗".red(),
                job_name,
                matrix_suffix,
                duration
            );
        }

        for (name, result) in &step_results {
            match result {
                StepResult::Passed(_) => {
                    println!("    {} {}", "✓".green(), name);
                }
                StepResult::Failed(_, msg) => {
                    println!("    {} {}", "✗".red(), name);
                    println!("      {}: {}", "Error".red(), msg);
                }
                StepResult::Skipped => {
                    println!("    {} {} (skipped)", "â—‹".dimmed(), name);
                }
            }
        }

        let mut outputs = JobOutputs::new();
        for (key, expr) in &job.outputs {
            if let Ok(value) = evaluate_value(&Value::String(expr.clone()), &ctx) {
                outputs.insert(key.clone(), value);
            }
        }

        JobResult {
            name: job_name.to_string(),
            matrix_suffix,
            steps: step_results,
            outputs,
            duration,
        }
    }

    async fn run_step(&self, world: &mut W, step: &Step, ctx: &mut ExprContext) -> StepResult {
        let start = Instant::now();

        for assertion in &step.pre_assert {
            match evaluate_assertion(assertion, ctx) {
                Ok(true) => {}
                Ok(false) => {
                    return StepResult::Failed(
                        start.elapsed(),
                        format!("Pre-assertion failed: {}", assertion),
                    );
                }
                Err(e) => {
                    return StepResult::Failed(
                        start.elapsed(),
                        format!("Pre-assertion error: {}", e),
                    );
                }
            }
        }

        let step_fn = match self.steps.get(&step.uses) {
            Some(f) => f,
            None => {
                return StepResult::Failed(
                    start.elapsed(),
                    format!("Step not found: {}", step.uses),
                );
            }
        };

        let evaluated_args = match step
            .with
            .iter()
            .map(|(k, v)| evaluate_value(v, ctx).map(|ev| (k.clone(), ev)))
            .collect::<Result<HashMap<_, _>>>()
        {
            Ok(args) => args,
            Err(e) => {
                return StepResult::Failed(
                    start.elapsed(),
                    format!("Args evaluation failed: {}", e),
                );
            }
        };

        let world_any: &mut dyn Any = world;
        let outputs = match step_fn(world_any, evaluated_args).await {
            Ok(outputs) => outputs,
            Err(e) => return StepResult::Failed(start.elapsed(), e.to_string()),
        };

        if let Some(id) = &step.id {
            ctx.steps.insert(id.clone(), outputs.clone());
        }

        if !step.post_assert.is_empty() {
            let assert_ctx = ctx.with_outputs(outputs);

            for assertion in &step.post_assert {
                match evaluate_assertion(assertion, &assert_ctx) {
                    Ok(true) => {}
                    Ok(false) => {
                        return StepResult::Failed(
                            start.elapsed(),
                            format!("Post-assertion failed: {}", assertion),
                        );
                    }
                    Err(e) => {
                        return StepResult::Failed(
                            start.elapsed(),
                            format!("Post-assertion error: {}", e),
                        );
                    }
                }
            }
        }

        StepResult::Passed(start.elapsed())
    }
}

impl<W: World + 'static> Default for RustActions<W> {
    fn default() -> Self {
        Self::new()
    }
}

fn toposort_jobs(jobs: &HashMap<String, Job>) -> Result<Vec<String>> {
    let mut result = Vec::new();
    let mut visited = HashSet::new();
    let mut temp_visited = HashSet::new();

    fn visit(
        name: &str,
        jobs: &HashMap<String, Job>,
        visited: &mut HashSet<String>,
        temp_visited: &mut HashSet<String>,
        result: &mut Vec<String>,
        path: &mut Vec<String>,
    ) -> Result<()> {
        if temp_visited.contains(name) {
            path.push(name.to_string());
            return Err(Error::CircularDependency {
                chain: path.join(" -> "),
            });
        }

        if visited.contains(name) {
            return Ok(());
        }

        temp_visited.insert(name.to_string());
        path.push(name.to_string());

        if let Some(job) = jobs.get(name) {
            for dep in job.needs.as_vec() {
                if !jobs.contains_key(&dep) {
                    return Err(Error::JobDependencyNotFound {
                        job: name.to_string(),
                        dependency: dep.clone(),
                    });
                }
                visit(&dep, jobs, visited, temp_visited, result, path)?;
            }
        }

        path.pop();
        temp_visited.remove(name);
        visited.insert(name.to_string());
        result.push(name.to_string());

        Ok(())
    }

    let job_names: Vec<String> = jobs.keys().cloned().collect();
    for name in &job_names {
        let mut path = Vec::new();
        visit(name, jobs, &mut visited, &mut temp_visited, &mut result, &mut path)?;
    }

    Ok(result)
}