local-ci 0.20.0

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
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
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
//! The result of a run: its state, the short text report, and the JSON file.

use crate::complete::{Completeness, Verdict};
use crate::exec::{tail, JobResult, JobTime, Outcome, StepResult, UnitResult};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Skipped {
    pub workflow: String,
    pub reason: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct RunResult {
    pub version: String,
    pub sha: String,
    pub base: String,
    pub changed_files: usize,
    /// `changes` (what the changes trigger) or `all` (paths filters ignored).
    pub mode: String,
    pub state: String,
    pub description: String,
    pub secs: f64,
    pub run_dir: PathBuf,
    pub setup: Vec<StepResult>,
    pub units: Vec<UnitResult>,
    pub skipped_workflows: Vec<Skipped>,
    pub not_covered: Vec<String>,
    pub warnings: Vec<String>,
    /// How the CPU was divided between the jobs, when it was (see [`crate::cpu`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpu: Option<crate::cpu::Share>,
    /// Whether the units, jobs and steps of the plan are all in this result
    /// (see [`crate::complete`]). `state` is `success` only when they are and
    /// nothing was left out.
    pub completeness: Completeness,
}

/// What `local-ci status` needs back from a saved result.
#[derive(Debug, Deserialize)]
pub struct Saved {
    pub sha: String,
    pub state: String,
    pub description: String,
}

/// What printing needs to know about the host: the directory output leaves
/// off workflow paths, and the home directory shown as `~`.
#[derive(Debug, Clone)]
pub struct Style {
    /// The first `workflows-dirs` entry of `.local-ci.toml`, else `.github/workflows`.
    pub workflows_dir: String,
    pub home: Option<String>,
}

/// How a workflow is named in output: the file name for the default directory
/// `dir` (`.github/workflows/`, or the first one `.local-ci.toml` names), the
/// path for any other, so equal file names stay apart.
pub fn short<'a>(dir: &str, f: &'a str) -> &'a str {
    short_in(dir, f)
}

fn short_in<'a>(dir: &str, f: &'a str) -> &'a str {
    f.strip_prefix(dir)
        .and_then(|r| r.strip_prefix('/'))
        .unwrap_or(f)
}

/// `p` with `home` at its start shown as `~`.
pub fn tilde(p: &Path, home: Option<&str>) -> String {
    let s = p.to_string_lossy().into_owned();
    match home {
        Some(h) if !h.is_empty() && s.starts_with(h) => format!("~{}", &s[h.len()..]),
        _ => s,
    }
}

fn dur(secs: f64) -> String {
    let s = secs.round() as u64;
    if s >= 60 {
        format!("{}m{:02}s", s / 60, s % 60)
    } else {
        format!("{s}s")
    }
}

/// ` (ran 2m20s · waited slot 5m00s, queue 40s)` for a job that waited a second
/// or more for something; empty otherwise.
fn waits(t: Option<&JobTime>) -> String {
    let Some(t) = t else { return String::new() };
    let list: Vec<String> = [
        ("lock", t.wait_lock_secs),
        ("slot", t.wait_slot_secs),
        ("queue", t.wait_queue_secs),
        ("parallel", t.wait_parallel_secs),
    ]
    .iter()
    .filter(|(_, s)| *s >= 1.0)
    .map(|(n, s)| format!("{n} {}", dur(*s)))
    .collect();
    if list.is_empty() {
        return String::new();
    }
    format!(" (ran {} · waited {})", dur(t.work_secs), list.join(", "))
}

pub struct Counts {
    pub pass: usize,
    pub fail: usize,
    pub error: usize,
    pub skip: usize,
}

pub fn counts(units: &[UnitResult]) -> Counts {
    let mut c = Counts {
        pass: 0,
        fail: 0,
        error: 0,
        skip: 0,
    };
    for j in units.iter().flat_map(|u| &u.jobs) {
        match j.outcome {
            Outcome::Pass => c.pass += 1,
            Outcome::Fail => c.fail += 1,
            Outcome::Error(_) => c.error += 1,
            Outcome::Skip(_) => c.skip += 1,
        }
    }
    c
}

/// Jobs whose result was reused instead of run.
pub fn cached_jobs(units: &[UnitResult]) -> usize {
    units
        .iter()
        .filter(|u| u.cached.is_some())
        .map(|u| u.jobs.len())
        .sum()
}

/// success / failure / error from what ran, the same table the commit status
/// uses. This looks only at the results that are there; [`final_state`] adds
/// whether they are all there.
pub fn state(setup: &[StepResult], units: &[UnitResult]) -> &'static str {
    let c = counts(units);
    if setup.iter().any(|s| s.outcome == Outcome::Fail) || c.fail > 0 {
        "failure"
    } else if setup.iter().any(|s| matches!(s.outcome, Outcome::Error(_))) || c.error > 0 {
        "error"
    } else {
        "success"
    }
}

/// The state of a run: a failure is a failure and an error an error whatever
/// else is missing; otherwise `success` only for a complete result, `no_work`
/// for a plan with nothing to run, `incomplete` when parts that cannot be
/// reproduced here were left out, and `error` when the result lacks (or has
/// twice, or has too much of) what the plan expects.
pub fn final_state(base: &'static str, c: &Completeness) -> &'static str {
    if base != "success" {
        return base;
    }
    match c.verdict {
        Verdict::Complete => "success",
        Verdict::NoWork => "no_work",
        Verdict::Incomplete => "incomplete",
        Verdict::Invalid => "error",
    }
}

/// The state a commit status can have for a run state. `success` is posted
/// only for a complete run, and for a run that had nothing to run (a commit
/// that triggers no workflow still has to be able to pass a required check,
/// as before; its description says `no_work`). Anything else that is not a
/// failure is an `error`: it was not checked.
pub fn github_state(state: &str) -> &'static str {
    match state {
        "success" | "no_work" => "success",
        "failure" => "failure",
        _ => "error",
    }
}

/// Whether a skip is something local-ci cannot reproduce (as opposed to a
/// step that is not needed here, like a checkout of the commit or a cache).
pub(crate) fn not_reproduced(reason: &str) -> bool {
    reason == "uses secrets"
        || reason == "artifact"
        || reason.starts_with("action ")
        || reason == "installs system packages"
        || reason == "pushes, publishes or deploys"
}

/// Steps and jobs that were skipped because they cannot be reproduced here.
pub fn not_covered(units: &[UnitResult], dir: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for j in units.iter().flat_map(|u| &u.jobs) {
        if let Outcome::Skip(r) = &j.outcome {
            if r.contains("not supported") || crate::os_legs::is_not_run_reason(r) {
                out.push(format!("{} › {}: {r}", short(dir, &j.workflow), j.display));
            }
        }
        for s in &j.steps {
            if let Outcome::Skip(r) = &s.outcome {
                if not_reproduced(r) {
                    out.push(format!(
                        "{} › {} › {}: {r}",
                        short(dir, &j.workflow),
                        j.display,
                        s.label
                    ));
                }
            }
        }
    }
    out
}

pub fn warnings(setup: &[StepResult], units: &[UnitResult]) -> Vec<String> {
    let mut out: Vec<String> = setup
        .iter()
        .filter_map(|s| s.note.clone())
        .filter(|n| n.starts_with("ignore-env"))
        .collect();
    // a step's note may hold several, told apart by "; "
    for j in units.iter().flat_map(|u| &u.jobs) {
        for st in &j.steps {
            for n in st.note.iter().flat_map(|n| n.split("; ")) {
                if n.starts_with("wants ") {
                    out.push(format!("{}: {n}", st.label));
                } else if n.starts_with("job output ") {
                    out.push(format!("{}: {n}", j.job));
                } else if n.starts_with("warning: ") {
                    out.push(format!("{}: {n}", st.label));
                }
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// The result of a run over `units`, worked out from what ran and checked
/// against `fp`, which must be the whole plan (units whose result was reused
/// are in `units` too, with `cached` set), not the part of it that was run.
pub fn assemble(
    fp: &crate::frozen::FrozenPlan,
    run_dir: PathBuf,
    setup: Vec<StepResult>,
    units: Vec<UnitResult>,
    secs: f64,
) -> anyhow::Result<RunResult> {
    fp.require_git_source()?;
    let dir = fp.config.default_workflows_dir.as_str();
    let base = state(&setup, &units);
    let not_covered = not_covered(&units, dir);
    let mut result = RunResult {
        version: env!("CARGO_PKG_VERSION").into(),
        sha: fp
            .source
            .execution_commit
            .clone()
            .expect("Git execution requires a commit"),
        base: fp
            .source
            .base
            .clone()
            .expect("Git execution requires a base"),
        changed_files: fp.changed_files.len(),
        mode: if fp.filters.all { "all" } else { "changes" }.into(),
        state: base.into(),
        description: String::new(),
        secs,
        run_dir,
        warnings: warnings(&setup, &units),
        setup,
        units,
        skipped_workflows: fp
            .skipped
            .iter()
            .map(|s| Skipped {
                workflow: s.workflow.clone(),
                reason: s.reason.clone(),
            })
            .collect(),
        not_covered,
        cpu: None,
        completeness: Completeness {
            verdict: Verdict::Complete,
            expected_units: 0,
            expected_jobs: 0,
            from_cache: 0,
            missing: vec![],
            duplicate: vec![],
            unexpected: vec![],
            invalid: vec![],
            incomplete: vec![],
        },
    };
    result.completeness = crate::complete::validate_run_result(fp, &result);
    let state = final_state(base, &result.completeness);
    result.state = state.into();
    result.description = description(
        state,
        &result.units,
        result.completeness.verdict == Verdict::NoWork,
        &result.completeness.incomplete,
        result.completeness.problems().len(),
        dir,
    );
    Ok(result)
}

pub fn description(
    state: &str,
    units: &[UnitResult],
    no_work: bool,
    not_covered: &[String],
    problems: usize,
    dir: &str,
) -> String {
    if no_work {
        return "no_work: no workflow triggered by these changes".into();
    }
    let c = counts(units);
    let mut wfs: Vec<&str> = units.iter().map(|u| short(dir, &u.workflow)).collect();
    wfs.dedup();
    let mut d = format!(
        "{state}: pass {} / fail {} / error {} / skip {}",
        c.pass, c.fail, c.error, c.skip
    );
    if !not_covered.is_empty() {
        d.push_str(&format!(", {} not covered", not_covered.len()));
        // the first two names, so the status says what was left out
        let names: Vec<String> = not_covered
            .iter()
            .take(2)
            .map(|e| {
                let n = e.split(": ").next().unwrap_or(e);
                let n = n.rsplit(" › ").next().unwrap_or(n);
                n.chars().take(24).collect()
            })
            .collect();
        d.push_str(&format!(" ({}", names.join(", ")));
        d.push_str(if not_covered.len() > 2 { ", ...)" } else { ")" });
    }
    if problems > 0 {
        d.push_str(&format!(", {problems} result problems"));
    }
    let cached = cached_jobs(units);
    if cached > 0 {
        d.push_str(&format!(", {cached} cached"));
    }
    let list = wfs.join(",");
    if d.len() + list.len() + 3 <= 140 {
        d = format!("{list}: {d}");
    }
    d.chars().take(140).collect()
}

fn failed_step(j: &JobResult) -> Option<&StepResult> {
    j.steps
        .iter()
        .find(|s| {
            s.outcome == Outcome::Fail
                && !s
                    .note
                    .iter()
                    .flat_map(|note| note.split("; "))
                    .any(|segment| segment == "continue-on-error")
        })
        .or_else(|| {
            j.steps
                .iter()
                .find(|s| matches!(s.outcome, Outcome::Error(_)))
        })
}

/// "paths not matched: a.yml, b.yml; only schedule: c.yml"
pub fn group_skipped(skipped: &[Skipped], dir: &str) -> String {
    let mut groups: Vec<(&str, Vec<&str>)> = Vec::new();
    for sk in skipped {
        match groups.iter_mut().find(|(reason, _)| *reason == sk.reason) {
            Some((_, files)) => files.push(short(dir, &sk.workflow)),
            None => groups.push((&sk.reason, vec![short(dir, &sk.workflow)])),
        }
    }
    groups
        .iter()
        .map(|(reason, files)| format!("{reason}: {}", files.join(", ")))
        .collect::<Vec<_>>()
        .join("; ")
}

/// `  [ran on macOS, not Linux (runs-on ubuntu-latest)]` for a job that ran on
/// another OS than its `runs-on` names.
fn os_tag(j: &JobResult) -> String {
    j.os_note
        .as_ref()
        .map(|n| format!("  [{n}]"))
        .unwrap_or_default()
}

/// `cpu    budget 12 · 3 jobs at once · 4 threads each`
fn cpu_line(c: &crate::cpu::Share) -> String {
    format!(
        "cpu    budget {} · {} jobs at once · {} thread{} each",
        c.budget,
        c.jobs_at_once,
        c.threads_per_job,
        if c.threads_per_job == 1 { "" } else { "s" }
    )
}

pub fn print(r: &RunResult, tail_lines: usize, style: &Style) {
    let dir = style.workflows_dir.as_str();
    println!(
        "local-ci {} · {} vs {} · {} file{} changed · {} · logs {}",
        r.version,
        &r.sha[..7],
        r.base,
        r.changed_files,
        if r.changed_files == 1 { "" } else { "s" },
        if r.mode == "all" {
            "all checks"
        } else {
            "triggered by the changes"
        },
        tilde(&r.run_dir, style.home.as_deref())
    );
    if let Some(line) = r.cpu.as_ref().map(cpu_line) {
        println!("{line}");
    }
    let bc = crate::build_cache::summary(
        r.units
            .iter()
            .flat_map(|u| &u.jobs)
            .filter_map(|j| j.build_cache.as_ref()),
    );
    if !bc.is_empty() {
        println!("{bc}");
    }
    let setup_bad: Vec<&StepResult> = r
        .setup
        .iter()
        .filter(|s| s.outcome != Outcome::Pass)
        .collect();
    if !r.setup.is_empty() {
        let secs: f64 = r.setup.iter().map(|s| s.secs).sum();
        if setup_bad.is_empty() {
            println!(
                "setup  ok  {} step{} {}",
                r.setup.len(),
                if r.setup.len() == 1 { "" } else { "s" },
                dur(secs)
            );
        } else {
            println!("setup  FAILED at {}", setup_bad[0].label);
        }
    }
    let mut skipped_jobs = Vec::new();
    for (u, j) in r
        .units
        .iter()
        .flat_map(|u| u.jobs.iter().map(move |j| (u, j)))
    {
        let name = format!("{} › {}", short(dir, &j.workflow), j.display);
        match &j.outcome {
            Outcome::Pass => match &u.cached {
                Some(from) => println!("PASS   {name}  cached ({from}){}", os_tag(j)),
                None => println!(
                    "PASS   {name}  {}{}{}",
                    dur(j.secs),
                    waits(j.time.as_ref()),
                    os_tag(j)
                ),
            },
            Outcome::Fail => {
                let s = failed_step(j);
                let what = s
                    .map(|s| format!(" › {} (exit {})", s.label, s.exit.unwrap_or(-1)))
                    .unwrap_or_default();
                println!(
                    "FAIL   {name}{what}  {}{}{}",
                    dur(j.secs),
                    waits(j.time.as_ref()),
                    os_tag(j)
                );
            }
            Outcome::Error(e) => println!(
                "ERROR  {name}  {}{}",
                e.lines().next().unwrap_or(""),
                os_tag(j)
            ),
            Outcome::Skip(reason) => skipped_jobs.push(format!("{} ({reason})", j.display)),
        }
    }
    if !skipped_jobs.is_empty() {
        println!("SKIP   {}", skipped_jobs.join(", "));
    }
    if !r.skipped_workflows.is_empty() {
        println!(
            "not triggered ({})",
            group_skipped(&r.skipped_workflows, dir)
        );
    }
    if r.completeness.verdict == Verdict::NoWork {
        println!("NO WORK  no workflow is triggered by these changes (nothing was checked)");
    }
    let problems = r.completeness.problems();
    if !problems.is_empty() {
        println!("INCOMPLETE RESULT  {}", problems.join("; "));
    }
    if !r.completeness.incomplete.is_empty() {
        println!(
            "not covered{}: {}",
            if r.state == "incomplete" {
                " (so this is not a pass)"
            } else {
                ""
            },
            r.completeness.incomplete.join("; ")
        );
    }
    if !r.warnings.is_empty() {
        println!("warnings: {}", r.warnings.join("; "));
    }
    // details of what went wrong
    let mut details: Vec<(String, &StepResult)> = setup_bad
        .iter()
        .map(|s| ("setup".to_string(), *s))
        .collect();
    for j in r.units.iter().flat_map(|u| &u.jobs) {
        if matches!(j.outcome, Outcome::Fail | Outcome::Error(_)) {
            if let Some(s) = failed_step(j) {
                details.push((format!("{} › {}", short(dir, &j.workflow), j.display), s));
            } else if let Outcome::Error(e) = &j.outcome {
                if e.lines().count() > 1 {
                    println!(
                        "\n── ERROR {} › {}\n{}",
                        short(dir, &j.workflow),
                        j.display,
                        indent(e.lines().skip(1).map(String::from).collect())
                    );
                }
            }
        }
    }
    for (where_, s) in details {
        let what = match &s.outcome {
            Outcome::Error(e) => format!("error: {e}"),
            _ => format!("exit {}", s.exit.unwrap_or(-1)),
        };
        println!("\n── {where_} › {} ({what})", s.label);
        if let Some(log) = &s.log {
            let t = tail(log, tail_lines);
            if t.is_empty() {
                println!("   (no output)");
            } else {
                println!("{}", indent(t));
            }
            println!("   log: {}", tilde(log, style.home.as_deref()));
        }
    }
    let c = counts(&r.units);
    let cached = cached_jobs(&r.units);
    println!(
        "\nresult: {} · pass {} / fail {} / error {} / skip {}{} · {}",
        r.state,
        c.pass,
        c.fail,
        c.error,
        c.skip,
        if cached > 0 {
            format!(" ({cached} cached)")
        } else {
            String::new()
        },
        dur(r.secs)
    );
}

fn indent(lines: Vec<String>) -> String {
    lines
        .iter()
        .map(|l| format!("   {l}"))
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn job(outcome: Outcome) -> JobResult {
        JobResult {
            workflow: ".github/workflows/ci.yml".into(),
            job: "j".into(),
            display: "j".into(),
            outcome,
            secs: 1.0,
            steps: vec![],
            cancelled: false,
            time: None,
            build_cache: None,
            os_note: None,
        }
    }

    #[test]
    fn failed_step_ignores_only_the_continue_on_error_note_segment() {
        for note in [
            None,
            Some("warning: cleanup incomplete: query failed"),
            Some("job output key holds the GitHub token: not passed on"),
            Some("warning: continue-on-error"),
            Some("not-continue-on-error"),
        ] {
            let mut result = job(Outcome::Fail);
            result.steps.push(StepResult {
                label: "tests".into(),
                outcome: Outcome::Fail,
                exit: Some(1),
                secs: 0.0,
                log: None,
                note: note.map(String::from),
            });
            assert_eq!(failed_step(&result).unwrap().label, "tests");
        }
        for note in [
            "continue-on-error",
            "continue-on-error; warning: cleanup incomplete: query failed",
            "warning: cleanup incomplete: query failed; continue-on-error",
        ] {
            let mut result = job(Outcome::Pass);
            result.steps.push(StepResult {
                label: "allowed failure".into(),
                outcome: Outcome::Fail,
                exit: Some(1),
                secs: 0.0,
                log: None,
                note: Some(note.into()),
            });
            assert!(failed_step(&result).is_none());
        }
    }

    #[test]
    fn states() {
        let u = |o: Vec<Outcome>| {
            vec![UnitResult {
                unit: None,
                workflow: "ci.yml".into(),
                jobs: o.into_iter().map(job).collect(),
                waited_secs: 0.0,
                copy_secs: None,
                cached: None,
                outcomes: vec![],
            }]
        };
        assert_eq!(
            state(
                &[],
                &u(vec![Outcome::Pass, Outcome::Skip("if: false".into())])
            ),
            "success"
        );
        assert_eq!(
            state(
                &[],
                &u(vec![Outcome::Pass, Outcome::Error("docker".into())])
            ),
            "error"
        );
        assert_eq!(
            state(
                &[],
                &u(vec![Outcome::Fail, Outcome::Error("docker".into())])
            ),
            "failure"
        );
        let d = description(
            "success",
            &u(vec![Outcome::Pass]),
            false,
            &[
                "ci.yml › deploy › Push image: pushes, publishes or deploys".into(),
                "ci.yml › deploy › Install jq: installs system packages".into(),
                "x".into(),
            ],
            0,
            ".github/workflows",
        );
        assert_eq!(
            d,
            "ci.yml: success: pass 1 / fail 0 / error 0 / skip 0, 3 not covered (Push image, Install jq, ...)"
        );
        assert!(d.len() <= 140);
    }

    #[test]
    fn waits_are_named_only_when_there_were_some() {
        let t = |lock, slot, queue, parallel| JobTime {
            work_secs: 140.0,
            wait_lock_secs: lock,
            wait_slot_secs: slot,
            wait_queue_secs: queue,
            wait_parallel_secs: parallel,
            ..JobTime::default()
        };
        assert_eq!(waits(None), "");
        assert_eq!(waits(Some(&t(0.0, 0.4, 0.0, 0.2))), "");
        assert_eq!(
            waits(Some(&t(0.0, 300.0, 40.0, 0.0))),
            " (ran 2m20s · waited slot 5m00s, queue 40s)"
        );
        assert_eq!(
            waits(Some(&t(2.0, 0.0, 0.0, 3.0))),
            " (ran 2m20s · waited lock 2s, parallel 3s)"
        );
    }

    #[test]
    fn durations() {
        assert_eq!(dur(5.2), "5s");
        assert_eq!(dur(125.0), "2m05s");
    }

    #[test]
    fn workflow_names_leave_off_the_default_dir() {
        assert_eq!(
            short_in(".github/workflows", ".github/workflows/ci.yml"),
            "ci.yml"
        );
        assert_eq!(short_in(".ci/workflows", ".ci/workflows/ci.yml"), "ci.yml");
        assert_eq!(
            short_in(".ci/workflows", ".github/workflows/ci.yml"),
            ".github/workflows/ci.yml"
        );
        assert_eq!(
            short_in(".ci/workflows", "ci/local/m.yml"),
            "ci/local/m.yml"
        );
        // a sibling that only shares the prefix keeps its path
        assert_eq!(
            short_in(".ci/workflows", ".ci/workflows-old/ci.yml"),
            ".ci/workflows-old/ci.yml"
        );
    }
}