shipslip 0.6.2

Deploy Laravel apps over SSH with a preview, a deploy lock, and a receipt.
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
//! The release map: for each checkout and environment, which code the saved
//! receipts say is on the server. Reads only local files.
//!
//! A commit is only reported with a recorded or observed fact behind it:
//! the fast-forward step's own status, a rerun's checked-out commit, or the
//! server HEAD read after a failed step. Nothing here opens `.lock` files.

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use super::history::{entries_in, Entry};
use super::{io_error, read_receipt, safe_component, Badge, Receipt, ReceiptError, ReceiptStatus};
use super::{Flag, ReceiptStepStatus, ReceiptSummary};
use crate::git::{Comparison, Git};
use crate::{DeployOutcome, RunPlan};

/// Receipts of one cell read before it settles on "no code change".
pub const WALK_LIMIT: usize = 20;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Overview {
    pub repos: Vec<RepoRow>,
    /// Files or directories that could not be read; the rest is still shown.
    pub problems: Vec<Problem>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoRow {
    pub repo_root: String,
    /// `None` for a checkout known only from the trust store.
    pub project: Option<String>,
    pub label: String,
    /// The checkout is no longer on disk.
    pub path_missing: bool,
    pub envs: Vec<EnvCell>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvCell {
    pub env: String,
    /// An approval record exists. It does not mean the current config is
    /// still trusted, which is never checked here.
    pub approved: bool,
    pub code: CodeState,
    /// The newest readable run of any kind.
    pub last_attempt: Option<AttemptSummary>,
    /// The run that decided `code`, when one did. It can be older than
    /// `last_attempt`.
    pub code_run: Option<AttemptSummary>,
    pub stale_hint: Option<StaleHint>,
    /// `ssh_alias:path` of the newest readable run.
    pub target: Option<String>,
    /// Another checkout ran on the same `ssh_alias:path` after this cell's
    /// last run, so its code may have replaced this one.
    pub newer_elsewhere: Option<NewerElsewhere>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewerElsewhere {
    pub repo_root: String,
    pub env: String,
    pub run_id: String,
    pub started_at_ms: u128,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CodeState {
    /// From the receipt's own facts.
    Recorded {
        sha: String,
        /// The run finished and succeeded.
        complete: bool,
        evidence: Evidence,
        run_id: String,
        at_ms: u128,
    },
    /// The server HEAD read after a failed or unknown step.
    Observed {
        sha: String,
        dirty: Option<bool>,
        /// The commit the run was deploying.
        expected: String,
        run_id: String,
        /// How that run ended, if it did.
        outcome: Option<DeployOutcome>,
        at_ms: u128,
    },
    /// The code may have changed, but nothing recorded says to what.
    NotKnown {
        run_id: Option<String>,
        reason: NotKnownReason,
    },
    NeverDeployed,
    /// None of this many runs on the current target changed the code.
    NoCodeChangeInLast {
        records: usize,
    },
    /// Runs exist only for an older `ssh_alias:path`.
    TargetChanged {
        run_id: String,
        target: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Evidence {
    /// The fast-forward step succeeded.
    FastForward,
    /// A rerun or from-step run checked that the target was checked out.
    CheckedOutAtStart,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotKnownReason {
    /// The fast-forward started but did not end `Ok`.
    StepZero(ReceiptStepStatus),
    /// A deploy receipt without a fast-forward step.
    NoStepZero,
    /// None of the cell's receipts could be read.
    Unreadable,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttemptSummary {
    pub run_id: String,
    pub started_at_ms: u128,
    pub run_plan: RunPlan,
    pub badge: Badge,
    /// [`Receipt::next_steps`], already escaped.
    pub next_steps: Vec<String>,
    /// The receipt file.
    pub path: PathBuf,
}

impl AttemptSummary {
    fn of(receipt: &Receipt, path: &Path) -> Self {
        Self {
            run_id: receipt.run_id.clone(),
            started_at_ms: receipt.started_at_ms,
            run_plan: receipt.run_plan,
            badge: receipt.badge(),
            next_steps: receipt.next_steps(),
            path: path.to_path_buf(),
        }
    }

    fn needs_attention(&self) -> bool {
        let badge = &self.badge;
        badge.unfinished
            || matches!(
                badge.outcome,
                Some(
                    DeployOutcome::FailedAtStep { .. }
                        | DeployOutcome::StoppedAfterStep { .. }
                        | DeployOutcome::StoppedInMaintenance(_)
                        | DeployOutcome::Unknown { .. }
                )
            )
            || badge.flags.iter().any(|flag| {
                matches!(
                    flag,
                    Flag::NewErrors(_) | Flag::SmokeFailed(_) | Flag::AppLeftDown
                )
            })
    }
}

impl EnvCell {
    /// Whether the cell shows something the user should look at: a run
    /// that did not succeed, code that is not known or not complete, a
    /// record that may be out of date, or new errors after a run.
    pub fn needs_attention(&self) -> bool {
        let code = match &self.code {
            CodeState::Recorded { complete, .. } => !complete,
            CodeState::Observed { .. } | CodeState::NotKnown { .. } => true,
            CodeState::NeverDeployed
            | CodeState::NoCodeChangeInLast { .. }
            | CodeState::TargetChanged { .. } => false,
        };
        code || self.stale_hint.is_some()
            || self.newer_elsewhere.is_some()
            || self
                .code_run
                .iter()
                .chain(&self.last_attempt)
                .any(AttemptSummary::needs_attention)
    }
}

/// A receipt newer than the one that decided the cell could not be read, so
/// the cell may be out of date.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StaleHint {
    /// One of this checkout's receipts.
    NewestUnreadable { path: PathBuf },
    /// A file in the same directory whose checkout cannot be told.
    UnattributedNewer { path: PathBuf },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
    pub path: PathBuf,
    pub message: String,
    pub kind: ProblemKind,
    /// The cells this problem may make out of date. Empty when it cannot
    /// be tied to any, e.g. for the trust store.
    pub cells: Vec<CellRef>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProblemKind {
    Trust,
    ProjectDir,
    Receipt,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CellRef {
    pub repo_root: String,
    pub env: String,
}

/// Where a problem was found, to work out the cells it touches.
struct Scope {
    project_dir: PathBuf,
    /// Encoded env name; `None` for the whole project directory.
    env: Option<String>,
}

impl Problem {
    fn from_error(fallback: &Path, error: &ReceiptError, kind: ProblemKind) -> Self {
        let path = match error {
            ReceiptError::Io { path, .. } | ReceiptError::Parse { path, .. } => path.clone(),
            _ => fallback.to_path_buf(),
        };
        Self {
            path,
            message: error.to_string(),
            kind,
            cells: Vec::new(),
        }
    }
}

/// One receipt file attributed to a checkout.
struct Own {
    project_dir: PathBuf,
    started_at_ms: u128,
    path: PathBuf,
}

#[derive(Default)]
struct RowBuild {
    project: Option<String>,
    /// Keyed by the encoded env name.
    envs: BTreeMap<String, CellBuild>,
}

#[derive(Default)]
struct CellBuild {
    raw_env: Option<String>,
    approved: bool,
    owns: Vec<Own>,
}

/// Builds the release map. Only an existing receipts root that cannot be
/// read is an error; anything else unreadable becomes a [`Problem`].
pub fn overview(receipts_root: &Path, trust_path: &Path) -> Result<Overview, ReceiptError> {
    let mut problems: Vec<(Problem, Option<Scope>)> = Vec::new();
    let mut rows: BTreeMap<String, RowBuild> = BTreeMap::new();
    // Files no checkout can claim, by (project dir, encoded env).
    let mut unattributed: BTreeMap<(PathBuf, String), Vec<(u128, PathBuf)>> = BTreeMap::new();

    for project_dir in project_dirs(receipts_root)? {
        let (entries, dir_problems) = entries_in(&project_dir);
        problems.extend(dir_problems.iter().map(|error| {
            let problem = Problem::from_error(&project_dir, error, ProblemKind::ProjectDir);
            // An unreadable env directory only touches that env's cells.
            let env = problem
                .path
                .strip_prefix(&project_dir)
                .ok()
                .and_then(|rest| rest.iter().next())
                .map(|env| env.to_string_lossy().into_owned());
            let scope = Scope {
                project_dir: project_dir.clone(),
                env,
            };
            (problem, Some(scope))
        }));
        for entry in entries {
            let Entry {
                env,
                started_at_ms: Some(started_at_ms),
                path,
                ..
            } = entry
            else {
                // Not a `<ms>-<run_id>.json` receipt, e.g. legacy history.
                continue;
            };
            match read_summary(&path) {
                Ok(summary) => {
                    let row = rows.entry(summary.repo_root).or_default();
                    if row.project.is_none() {
                        row.project = summary.project;
                    }
                    row.envs.entry(env).or_default().owns.push(Own {
                        project_dir: project_dir.clone(),
                        started_at_ms,
                        path,
                    });
                }
                Err(error) => {
                    let scope = Scope {
                        project_dir: project_dir.clone(),
                        env: Some(env.clone()),
                    };
                    problems.push((
                        Problem::from_error(&path, &error, ProblemKind::Receipt),
                        Some(scope),
                    ));
                    unattributed
                        .entry((project_dir.clone(), env))
                        .or_default()
                        .push((started_at_ms, path));
                }
            }
        }
    }

    match crate::config::approved_envs(trust_path) {
        Ok(approved) => {
            for (repo_root, envs) in approved {
                let row = rows.entry(repo_root).or_default();
                for env in envs {
                    let cell = row.envs.entry(safe_component(&env)).or_default();
                    cell.approved = true;
                    cell.raw_env = Some(env);
                }
            }
        }
        Err(error) => problems.push((
            Problem {
                path: trust_path.to_path_buf(),
                message: error.to_string(),
                kind: ProblemKind::Trust,
                cells: Vec::new(),
            },
            None,
        )),
    }

    // Which cells read receipts from each project dir and env.
    let mut readers: BTreeMap<(PathBuf, String), Vec<CellRef>> = BTreeMap::new();

    let mut repos: Vec<RepoRow> = rows
        .into_iter()
        .map(|(repo_root, row)| {
            let mut envs: Vec<EnvCell> = Vec::new();
            for (key, cell) in row.envs {
                let dirs: Vec<PathBuf> = cell
                    .owns
                    .iter()
                    .map(|own| own.project_dir.clone())
                    .collect();
                let built = build_cell(&key, cell, &unattributed);
                for dir in dirs {
                    let refs = readers.entry((dir, key.clone())).or_default();
                    let cell_ref = CellRef {
                        repo_root: repo_root.clone(),
                        env: built.env.clone(),
                    };
                    if !refs.contains(&cell_ref) {
                        refs.push(cell_ref);
                    }
                }
                envs.push(built);
            }
            envs.sort_by(|a, b| a.env.cmp(&b.env));
            let label = row.project.clone().unwrap_or_else(|| {
                Path::new(&repo_root)
                    .file_name()
                    .map(|name| name.to_string_lossy().into_owned())
                    .unwrap_or_else(|| repo_root.clone())
            });
            RepoRow {
                path_missing: !Path::new(&repo_root).is_dir(),
                project: row.project,
                label,
                repo_root,
                envs,
            }
        })
        .collect();
    repos.sort_by(|a, b| {
        a.label
            .cmp(&b.label)
            .then_with(|| a.repo_root.cmp(&b.repo_root))
    });
    mark_newer_elsewhere(&mut repos);
    let problems = problems
        .into_iter()
        .map(|(mut problem, scope)| {
            if let Some(scope) = scope {
                let mut cells: Vec<CellRef> = readers
                    .iter()
                    .filter(|((dir, env), _)| {
                        *dir == scope.project_dir && scope.env.as_ref().is_none_or(|key| key == env)
                    })
                    .flat_map(|(_, refs)| refs.iter().cloned())
                    .collect();
                cells.sort();
                cells.dedup();
                problem.cells = cells;
            }
            problem
        })
        .collect();
    Ok(Overview { repos, problems })
}

/// Cells are per checkout, but two checkouts can deploy to one server path.
fn mark_newer_elsewhere(repos: &mut [RepoRow]) {
    let mut runs: BTreeMap<String, Vec<NewerElsewhere>> = BTreeMap::new();
    for row in repos.iter() {
        for cell in &row.envs {
            if let (Some(target), Some(attempt)) = (&cell.target, &cell.last_attempt) {
                runs.entry(target.clone())
                    .or_default()
                    .push(NewerElsewhere {
                        repo_root: row.repo_root.clone(),
                        env: cell.env.clone(),
                        run_id: attempt.run_id.clone(),
                        started_at_ms: attempt.started_at_ms,
                    });
            }
        }
    }
    for row in repos.iter_mut() {
        for cell in &mut row.envs {
            let (Some(target), Some(attempt)) = (&cell.target, &cell.last_attempt) else {
                continue;
            };
            cell.newer_elsewhere = runs
                .get(target)
                .into_iter()
                .flatten()
                .filter(|other| {
                    other.repo_root != row.repo_root && other.started_at_ms > attempt.started_at_ms
                })
                .max_by_key(|other| other.started_at_ms)
                .cloned();
        }
    }
}

fn project_dirs(root: &Path) -> Result<Vec<PathBuf>, ReceiptError> {
    let entries = match fs::read_dir(root) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(source) => return Err(io_error(root, source)),
    };
    let mut dirs = Vec::new();
    for entry in entries {
        let path = entry.map_err(|source| io_error(root, source))?.path();
        if path.is_dir() {
            dirs.push(path);
        }
    }
    dirs.sort();
    Ok(dirs)
}

fn read_summary(path: &Path) -> Result<ReceiptSummary, ReceiptError> {
    let bytes = fs::read(path).map_err(|source| io_error(path, source))?;
    serde_json::from_slice(&bytes).map_err(|source| ReceiptError::Parse {
        path: path.to_path_buf(),
        source,
    })
}

fn build_cell(
    key: &str,
    mut cell: CellBuild,
    unattributed: &BTreeMap<(PathBuf, String), Vec<(u128, PathBuf)>>,
) -> EnvCell {
    // A renamed project leaves one checkout's receipts in two directories.
    cell.owns.sort_by(|a, b| {
        b.started_at_ms
            .cmp(&a.started_at_ms)
            .then_with(|| b.path.cmp(&a.path))
    });
    let walk = walk(&cell.owns);
    let mut stale_hint = walk.stale_hint;
    if stale_hint.is_none() {
        // Any unclaimed file newer than the deciding run may be this
        // checkout's newest receipt.
        stale_hint = cell
            .owns
            .iter()
            .map(|own| &own.project_dir)
            .filter_map(|dir| unattributed.get(&(dir.clone(), key.to_string())))
            .flatten()
            .filter(|(started, _)| walk.decided_at_ms.is_none_or(|decided| *started > decided))
            .max_by_key(|(started, _)| *started)
            .map(|(_, path)| StaleHint::UnattributedNewer { path: path.clone() });
    }
    EnvCell {
        env: walk.env.or(cell.raw_env).unwrap_or_else(|| key.to_string()),
        approved: cell.approved,
        code: walk.code,
        last_attempt: walk.last_attempt,
        code_run: walk.code_run,
        stale_hint,
        target: walk.target,
        newer_elsewhere: None,
    }
}

struct Walk {
    code: CodeState,
    last_attempt: Option<AttemptSummary>,
    code_run: Option<AttemptSummary>,
    stale_hint: Option<StaleHint>,
    target: Option<String>,
    env: Option<String>,
    /// Start time of the run that decided `code`.
    decided_at_ms: Option<u128>,
}

/// Newest first, the first run on the current target that moved or
/// observed the code decides the cell.
fn walk(owns: &[Own]) -> Walk {
    let mut result = Walk {
        code: CodeState::NeverDeployed,
        last_attempt: None,
        code_run: None,
        stale_hint: None,
        target: None,
        env: None,
        decided_at_ms: None,
    };
    let mut current: Option<(String, String)> = None;
    let mut counted = 0;
    let mut unreadable = 0;
    let mut first_on_target: Option<String> = None;
    let mut saw_other_target = false;
    for own in owns {
        if counted == WALK_LIMIT {
            result.code = CodeState::NoCodeChangeInLast { records: counted };
            return result;
        }
        let receipt = match read_receipt(&own.path) {
            Ok(receipt) => receipt,
            Err(_) => {
                // Listed as a problem by `slip receipts`; here it only marks
                // the cell as possibly stale.
                result
                    .stale_hint
                    .get_or_insert(StaleHint::NewestUnreadable {
                        path: own.path.clone(),
                    });
                unreadable += 1;
                continue;
            }
        };
        let target = (
            receipt.target.ssh_alias.clone(),
            receipt.target.path.clone(),
        );
        if current.is_none() {
            result.target = Some(format!("{}:{}", target.0, target.1));
            result.env = Some(receipt.target.env.clone());
            result.last_attempt = Some(AttemptSummary::of(&receipt, &own.path));
            current = Some(target.clone());
        }
        if current.as_ref() != Some(&target) {
            saw_other_target = true;
            continue;
        }
        counted += 1;
        first_on_target = Some(receipt.run_id.clone());
        if let Some(code) = code_of(&receipt) {
            result.code = code;
            result.code_run = Some(AttemptSummary::of(&receipt, &own.path));
            result.decided_at_ms = Some(receipt.started_at_ms);
            return result;
        }
    }
    result.code = match (current, first_on_target) {
        (Some((alias, path)), Some(run_id)) if saw_other_target => CodeState::TargetChanged {
            run_id,
            target: format!("{alias}:{path}"),
        },
        (Some(_), _) => CodeState::NoCodeChangeInLast { records: counted },
        (None, _) if unreadable > 0 => CodeState::NotKnown {
            run_id: None,
            reason: NotKnownReason::Unreadable,
        },
        (None, _) => CodeState::NeverDeployed,
    };
    result
}

/// What one run says about the server's code, or `None` when it did not
/// change it.
fn code_of(receipt: &Receipt) -> Option<CodeState> {
    let run_id = receipt.run_id.clone();
    let at_ms = receipt.finished_at_ms.unwrap_or(receipt.started_at_ms);
    if let Some(head) = &receipt.server_head_at_end {
        return Some(CodeState::Observed {
            sha: head.clone(),
            dirty: receipt.tree_dirty,
            expected: receipt.target_sha.clone(),
            run_id,
            outcome: receipt.outcome.clone(),
            at_ms,
        });
    }
    let complete =
        receipt.status == ReceiptStatus::Final && receipt.outcome == Some(DeployOutcome::Succeeded);
    let recorded = |evidence| CodeState::Recorded {
        sha: receipt.target_sha.clone(),
        complete,
        evidence,
        run_id: run_id.clone(),
        at_ms,
    };
    match receipt.run_plan {
        RunPlan::Deploy => {
            let Some(step) = receipt.steps.iter().find(|step| step.index == 0) else {
                return Some(CodeState::NotKnown {
                    run_id: Some(run_id),
                    reason: NotKnownReason::NoStepZero,
                });
            };
            match step.status {
                ReceiptStepStatus::Ok => Some(recorded(Evidence::FastForward)),
                ReceiptStepStatus::Running
                | ReceiptStepStatus::Failed
                | ReceiptStepStatus::Unknown => Some(CodeState::NotKnown {
                    run_id: Some(run_id),
                    reason: NotKnownReason::StepZero(step.status),
                }),
                ReceiptStepStatus::Pending
                | ReceiptStepStatus::NotStarted
                | ReceiptStepStatus::Skipped => None,
            }
        }
        // Preflight refuses these unless the target is checked out, so any
        // run that got past it recorded that commit.
        RunPlan::Rerun | RunPlan::FromStep(_) => receipt
            .mutation_started
            .then(|| recorded(Evidence::CheckedOutAtStart)),
    }
}

/// Something about one side that the commit count alone would hide.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Qualifier {
    DeployIncomplete,
    TreeDirty,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvComparison {
    /// Env `a` relative to env `b`.
    pub result: Comparison,
    /// Env name and what to say next to the count.
    pub notes: Vec<(String, Qualifier)>,
}

/// Compares the code two envs of one checkout are on. Only recorded or
/// observed commits are compared.
pub fn compare_envs(git: &Git, row: &RepoRow, a: &str, b: &str) -> EnvComparison {
    let mut notes = Vec::new();
    let unavailable = |reason: String| EnvComparison {
        result: Comparison::Unavailable(reason),
        notes: Vec::new(),
    };
    let mut shas = Vec::new();
    for name in [a, b] {
        let Some(cell) = row
            .envs
            .iter()
            .find(|cell| safe_component(&cell.env) == safe_component(name))
        else {
            return unavailable(format!("no {name} environment"));
        };
        match &cell.code {
            CodeState::Recorded { sha, complete, .. } => {
                if !complete {
                    notes.push((cell.env.clone(), Qualifier::DeployIncomplete));
                }
                shas.push(sha.clone());
            }
            CodeState::Observed { sha, dirty, .. } => {
                if *dirty == Some(true) {
                    notes.push((cell.env.clone(), Qualifier::TreeDirty));
                }
                shas.push(sha.clone());
            }
            _ => return unavailable(format!("no recorded code on {}", cell.env)),
        }
    }
    if row.path_missing {
        return unavailable("checkout not found".into());
    }
    EnvComparison {
        result: git.compare(Path::new(&row.repo_root), &shas[0], &shas[1]),
        notes,
    }
}

mod text;
pub use text::{age, code_text, comparison_text, sentence, short_id, short_sha, CodeText, Mark};

#[cfg(test)]
mod tests;