shipslip 0.14.0

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
use std::error::Error;
use std::fmt::Write;
use std::path::Path;
use std::process::ExitCode;

use shipslip::config::LoadedConfig;
use shipslip::logs::{escape, escape_field};
use shipslip::receipt::{
    self, format_duration, strip_color, timing_suffix, Listed, Receipt, ReceiptKind, ReceiptStatus,
};
use shipslip::records::{
    self, failed_step_options, NextStep, Part, ReceiptList, ReceiptListRow, ReceiptQueryError,
    ReceiptRecord, StepKind, StepRow, DEFAULT_RECEIPTS_LIMIT,
};
use shipslip::{DeployOutcome, WatchStatus};

use super::invalid_input;

#[path = "receipt_words.rs"]
mod words;
pub(super) use words::{flag_text, headline};
use words::{smoke_text, step_label};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Args {
    List {
        env: Option<String>,
        all: bool,
        json: bool,
    },
    Show {
        id: String,
        md: bool,
        details: bool,
        json: bool,
    },
}

impl Args {
    pub(super) fn parse(args: &[String]) -> Result<Self, Box<dyn Error>> {
        if args.first().map(String::as_str) == Some("show") {
            let mut id = None;
            let (mut md, mut details, mut json) = (false, false, false);
            for arg in &args[1..] {
                match arg.as_str() {
                    "--md" => md = true,
                    "--json" => json = true,
                    "--with-details" => details = true,
                    flag if flag.starts_with('-') => {
                        return Err(
                            invalid_input(format!("unknown receipts show option {flag}")).into(),
                        )
                    }
                    _ if id.is_some() => {
                        return Err(invalid_input("receipts show accepts one receipt ID").into())
                    }
                    value => id = Some(value.to_string()),
                }
            }
            let id = id.ok_or_else(|| invalid_input("receipts show requires a receipt ID"))?;
            if json && (md || details) {
                return Err(
                    invalid_input("--json cannot be combined with --md or --with-details").into(),
                );
            }
            if details && !md {
                return Err(invalid_input("--with-details only applies with --md").into());
            }
            return Ok(Self::Show {
                id,
                md,
                details,
                json,
            });
        }
        let mut env = None;
        let mut all = false;
        let mut json = false;
        for arg in args {
            match arg.as_str() {
                "--all" => all = true,
                "--json" => json = true,
                flag if flag.starts_with('-') => {
                    return Err(invalid_input(format!("unknown receipts option {flag}")).into())
                }
                _ if env.is_some() => {
                    return Err(
                        invalid_input("receipts accepts at most one environment name").into(),
                    )
                }
                value => env = Some(value.to_string()),
            }
        }
        Ok(Self::List { env, all, json })
    }
}

pub(super) fn run(
    config: &LoadedConfig,
    root: &Path,
    args: Args,
) -> Result<ExitCode, Box<dyn Error>> {
    let project = config.project_name();
    match args {
        Args::List { env, all, json } => {
            let listing = match records::receipts(
                root,
                project,
                env.as_deref(),
                (!all).then_some(DEFAULT_RECEIPTS_LIMIT),
                None,
            ) {
                Ok(listing) => listing,
                Err(error) => {
                    let text_error = show_error(project, "", &error);
                    if json {
                        println!(
                            "{}",
                            serde_json::to_string(&records::versioned_error(error))?
                        );
                        return Ok(super::error_exit_code(text_error.as_ref()));
                    }
                    return Err(text_error);
                }
            };
            if json {
                println!("{}", serde_json::to_string(&records::versioned(listing))?);
            } else {
                print!("{}", render_list(project, env.as_deref(), &listing));
            }
        }
        Args::Show {
            id,
            md,
            details,
            json,
        } => {
            let record = match records::receipt(root, project, &id) {
                Ok(record) => record,
                Err(error) => {
                    let text_error = show_error(project, &id, &error);
                    if json {
                        println!(
                            "{}",
                            serde_json::to_string(&records::versioned_error(error))?
                        );
                        return Ok(super::error_exit_code(text_error.as_ref()));
                    }
                    return Err(text_error);
                }
            };
            if json {
                println!("{}", serde_json::to_string(&records::versioned(record))?);
            } else if md {
                print!("{}", records::markdown(&record, details));
            } else {
                print!("{}", render_show(&record));
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn show_error(project: &str, id: &str, error: &ReceiptQueryError) -> Box<dyn Error> {
    match error {
        ReceiptQueryError::Missing => invalid_input(format!(
            "no receipt of {} matches `{}`; run `slip receipts` to list them",
            escape_field(project), escape_field(id)
        )).into(),
        ReceiptQueryError::Ambiguous { ids } => invalid_input(format!(
            "`{}` matches several receipts ({}); type more of the ID",
            escape_field(id), ids.join(", ")
        )).into(),
        ReceiptQueryError::NewerVersion { version } => invalid_input(format!(
            "this receipt was written by a newer Shipslip (receipt schema v{version}); upgrade slip to read it"
        )).into(),
        ReceiptQueryError::Unreadable { message } => std::io::Error::other(message.raw()).into(),
    }
}

fn render_list(project: &str, env: Option<&str>, listing: &ReceiptList) -> String {
    let mut out = String::new();
    let scope = match env {
        Some(env) => format!("{} in {}", escape_field(project), escape_field(env)),
        None => escape_field(project),
    };
    if listing.rows.is_empty() {
        let _ = writeln!(out, "No receipts for {scope} yet.");
        return out;
    }
    let mut rows = vec![[
        "ID".to_string(),
        match local_zone() {
            Some(zone) => format!("STARTED ({zone})"),
            None => "STARTED (UTC)".into(),
        },
        "ENV".into(),
        "FROM → TARGET".into(),
        "OUTCOME".into(),
    ]];
    for listed in &listing.rows {
        rows.push(match listed {
            ReceiptListRow::Receipt { id, receipt, .. } => {
                let mut outcome = headline(receipt.outcome);
                for flag in &receipt.flags {
                    outcome.push_str("  ");
                    outcome.push_str(&flag_text(*flag));
                }
                [
                    id.field(),
                    local_time(receipt.started_at_ms, false),
                    receipt.env.field(),
                    match receipt.kind {
                        ReceiptKind::Up => {
                            format!("brought up at {}", short(receipt.target_sha.raw()))
                        }
                        ReceiptKind::Deploy => format!(
                            "{} → {}",
                            short(receipt.from_sha.raw()),
                            short(receipt.target_sha.raw())
                        ),
                    },
                    escape_field(&outcome),
                ]
            }
            ReceiptListRow::Newer {
                id,
                env,
                started_at_ms,
                version,
                ..
            } => [
                id.field(),
                started_at_ms
                    .map(|ms| local_time(ms, false))
                    .unwrap_or_default(),
                env.field(),
                String::new(),
                format!("needs a newer slip (receipt schema v{version})"),
            ],
            ReceiptListRow::Unreadable {
                id,
                env,
                started_at_ms,
                reason,
                ..
            } => [
                id.field(),
                started_at_ms
                    .map(|ms| local_time(ms, false))
                    .unwrap_or_default(),
                env.field(),
                String::new(),
                format!("unreadable: {}", reason.field()),
            ],
        });
    }
    let widths: Vec<usize> = (0..4)
        .map(|column| {
            rows.iter()
                .map(|row| row[column].chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect();
    let _ = writeln!(out, "Receipts for {scope}, newest first\n");
    for row in &rows {
        let mut line = String::new();
        for (column, width) in widths.iter().enumerate() {
            let _ = write!(line, "{:<width$}  ", row[column]);
        }
        line.push_str(&row[4]);
        let _ = writeln!(out, "{}", line.trim_end());
    }
    if listing.older > 0 {
        let _ = writeln!(
            out,
            "\n{} older receipt{}; use --all to list them.",
            listing.older,
            if listing.older == 1 { "" } else { "s" }
        );
    }
    let _ = writeln!(out, "\nShow one: slip receipts show ID [--md]");
    out
}

fn render_show(receipt: &ReceiptRecord) -> String {
    let mut out = String::new();
    let target = &receipt.target;
    let badge = receipt.badge();
    let field = |out: &mut String, label: &str, value: &str| {
        let _ = writeln!(out, "{label:<20}{value}");
    };
    let _ = writeln!(out, "Receipt {}\n", escape_field(receipt.run_id.raw()));
    let outcome = match receipt.summary.as_ref() {
        Some(summary) if !badge.outcome.unfinished => summary.field(),
        _ => escape_field(&headline(badge.outcome)),
    };
    field(&mut out, "Outcome:", &outcome);
    if !badge.flags.is_empty() {
        let flags: Vec<String> = badge.flags.iter().map(|flag| flag_text(*flag)).collect();
        field(&mut out, "Flags:", &flags.join(", "));
    }
    field(
        &mut out,
        "Project:",
        &format!(
            "{} (checkout {})",
            escape_field(receipt.project.raw()),
            escape_field(receipt.repo_root.raw())
        ),
    );
    field(
        &mut out,
        "Environment:",
        &format!(
            "{}{} via {}:{}, branch {}",
            escape_field(target.env.raw()),
            if target.production {
                " (production)"
            } else {
                ""
            },
            escape_field(target.ssh_alias.raw()),
            escape_field(target.path.raw()),
            escape_field(target.branch.raw())
        ),
    );
    field(&mut out, "Plan:", &receipt.plan_text());
    field(
        &mut out,
        "Started:",
        &local_time(receipt.started_at_ms, true),
    );
    field(
        &mut out,
        "Finished:",
        &match receipt.finished_at_ms {
            Some(finished) => format!(
                "{} ({})",
                local_time(finished, true),
                format_duration(finished.saturating_sub(receipt.started_at_ms))
            ),
            None => "not finished".into(),
        },
    );
    field(
        &mut out,
        "Started by:",
        &receipt
            .started_by
            .as_ref()
            .map_or_else(|| "not recorded".into(), |who| who.field()),
    );
    if receipt.kind == ReceiptKind::Up {
        field(&mut out, "Server HEAD:", &short(receipt.from_sha.raw()));
    } else {
        field(
            &mut out,
            "From → target:",
            &format!(
                "{} → {}",
                short(receipt.from_sha.raw()),
                short(receipt.target_sha.raw())
            ),
        );
    }
    if receipt.ended_in_failure() {
        field(
            &mut out,
            "Server HEAD at end:",
            &match (&receipt.server_head_at_end, receipt.tree_dirty) {
                (Some(head), Some(true)) => {
                    format!("{} with uncommitted changes", short(head.raw()))
                }
                (Some(head), _) => short(head.raw()),
                (None, _) => "not recorded".into(),
            },
        );
    }

    if !receipt.commits.is_empty() {
        out.push_str("\nCommits:\n");
        for commit in &receipt.commits {
            let _ = writeln!(out, "  {}", commit.field());
        }
        if receipt.more_commits > 0 {
            let _ = writeln!(out, "  and {} more commits", receipt.more_commits);
        }
    }

    out.push_str("\nSteps:\n");
    for step in &receipt.steps {
        step_line(&mut out, step);
        for line in &step.output {
            let _ = writeln!(out, "        {}", escape(&strip_color(line.raw())));
        }
    }

    if let Some(watch) = receipt.watch.as_ref().filter(|_| !badge.outcome.unfinished) {
        let _ = writeln!(
            out,
            "\nLog watch: {}, {}, {} lines read from {}",
            watch.status.description(receipt.checks_skip_reason),
            format_duration(u128::from(watch.duration_ms)),
            watch.observed_lines,
            escape_field(watch.log_path.as_ref().unwrap_or(&target.log_path).raw())
        );
        if watch.status != WatchStatus::NotRun {
            let _ = writeln!(
                out,
                "  Compared against {} recent log signatures and {} from earlier deploys",
                watch.baseline_signatures, watch.history_signatures
            );
        }
        for group in &watch.new_errors {
            let _ = writeln!(
                out,
                "  New: ×{} {}{}",
                group.count,
                group.exception.field(),
                group
                    .file
                    .as_ref()
                    .map(|file| format!("  {}", file.field()))
                    .unwrap_or_default()
            );
            for variant in &group.variants {
                let _ = writeln!(
                    out,
                    "    ×{}{} {}",
                    variant.count,
                    variant
                        .display_file_line
                        .as_ref()
                        .map(|line| format!(" {}", line.field()))
                        .unwrap_or_default(),
                    variant.message.field()
                );
            }
        }
        if watch.overflow_groups > 0 {
            let _ = writeln!(out, "  And {} more groups", watch.overflow_groups);
        }
        for warning in &watch.warnings {
            let _ = writeln!(out, "  Warning: {}", warning.field());
        }
    }

    if let Some(smoke) = receipt.smoke.as_ref().filter(|_| !badge.outcome.unfinished) {
        let text = smoke_text(smoke);
        let _ = writeln!(out, "\nSmoke check: {text}");
    }

    let notes = &receipt.notes;
    if !notes.is_empty() {
        out.push_str("\nNotes:\n");
        for note in notes {
            let _ = writeln!(out, "  {}", note.field());
        }
    }

    let next = &receipt.next_steps;
    if !next.steps.is_empty() {
        out.push_str("\nAt the time of this run:\n");
        for step in &next.steps {
            let _ = writeln!(out, "  {}", next_step_text(step));
        }
    }
    out
}

/// Explains an "already up to date" block when the deployed commit's last run
/// did not succeed, so a retry does not hide a broken or down app.
pub(super) fn up_to_date_hint(root: &Path, project: &str, env: &str) -> Option<String> {
    let listing = receipt::list(root, project, Some(env), Some(receipt::WALK_LIMIT)).ok()?;
    let runs: Vec<_> = listing
        .rows
        .iter()
        .filter_map(|row| match row {
            Listed::Receipt { id, receipt, .. } if receipt.mutation_started => Some((id, receipt)),
            _ => None,
        })
        .collect();
    let same_target = |a: &Receipt, b: &Receipt| {
        a.target.ssh_alias == b.target.ssh_alias && a.target.path == b.target.path
    };
    let needs_attention = |receipt: &Receipt| {
        receipt.status == ReceiptStatus::InProgress
            || receipt.ended_in_failure()
            || receipt.app_left_down
    };
    let latest_up = runs
        .first()
        .copied()
        .filter(|(_, receipt)| receipt.kind == ReceiptKind::Up && needs_attention(receipt));
    let deploy_index = runs
        .iter()
        .position(|(_, receipt)| receipt.kind == ReceiptKind::Deploy);
    let relevant_up = deploy_index.and_then(|index| {
        runs[..index]
            .iter()
            .copied()
            .find(|(_, up)| same_target(runs[index].1, up))
    });
    let mut lines = Vec::new();
    if let Some(index) = deploy_index {
        let (id, deploy) = runs[index];
        // An Up changes maintenance state, not the result of the deploy. Only
        // newer runs on the same server checkout can update that state.
        let app_left_down = relevant_up.map_or(deploy.app_left_down, |(_, up)| {
            up.status != ReceiptStatus::Final
                || up.outcome != Some(DeployOutcome::Succeeded)
                || up.app_left_down
        });
        if deploy.status == ReceiptStatus::InProgress || deploy.ended_in_failure() || app_left_down
        {
            lines.push(format!(
                "The last run here ({id}) did not succeed: {}. See `slip receipts show {id}`.",
                headline(deploy.badge().outcome)
            ));
            if let Some(DeployOutcome::FailedAtStep { step, .. }) = &deploy.outcome {
                if *step > 0 {
                    lines.extend(failed_step_options(env, *step).iter().map(next_step_text));
                }
            }
            // A failed/unfinished Up has more specific recovery instructions,
            // including attach or checking an unknown result before retrying.
            if app_left_down && !relevant_up.is_some_and(|(_, up)| needs_attention(up)) {
                lines.push(format!(
                    "The app may still be in maintenance mode; `slip up {}` turns it off.",
                    escape_field(env)
                ));
            }
        }
    }
    let up_recovery = [
        relevant_up.filter(|(_, up)| needs_attention(up)),
        latest_up.filter(|(id, _)| !relevant_up.is_some_and(|(relevant_id, _)| relevant_id == *id)),
    ];
    for (id, up) in up_recovery.into_iter().flatten() {
        lines.push(format!(
            "The last `slip up` here ({id}) did not succeed: {}. See `slip receipts show {id}`.",
            headline(up.badge().outcome)
        ));
        lines.extend(up.next_steps().steps.iter().map(next_step_text));
    }
    (!lines.is_empty()).then(|| lines.join("\n"))
}

fn step_line(out: &mut String, step: &StepRow) {
    let (index, command) = match step.kind {
        StepKind::MaintenanceDown => (
            "on".to_string(),
            format!("Maintenance on: {}", step.command.field()),
        ),
        StepKind::Step { index } => (index.to_string(), step.command.field()),
        StepKind::MaintenanceUp => (
            "off".to_string(),
            format!("Maintenance off: {}", step.command.field()),
        ),
    };
    let _ = writeln!(
        out,
        "  {:<12}{:>4}  {}{}{}",
        step_label(step.status),
        index,
        command,
        step.exit_code
            .map(|code| format!(" (exit {code})"))
            .unwrap_or_default(),
        timing_suffix(step.times(), time_of_day)
    );
    for gap in &step.connection_gaps {
        let _ = writeln!(
            out,
            "        Connection lost {}; {}",
            time_of_day(gap.lost_at_ms),
            gap.reattached_at_ms
                .map(|at| format!("re-attached {}", time_of_day(at)))
                .unwrap_or_else(|| "not re-attached".into())
        );
        let _ = writeln!(out, "        Detail: {}", gap.detail.field());
    }
}

/// A next step on one line, its commands in backticks, every part escaped.
pub(super) fn next_step_text(step: &NextStep) -> String {
    step.0
        .iter()
        .map(|part| match part {
            Part::Text(text) => text.field(),
            Part::Command(args) => {
                let args: Vec<String> = args.iter().map(|arg| arg.field()).collect();
                format!("`{}`", args.join(" "))
            }
        })
        .collect()
}

fn short(sha: &str) -> String {
    escape_field(sha.get(..12).unwrap_or(sha))
}

/// The local time zone's abbreviation, e.g. `IST`; `None` where times fall
/// back to UTC.
fn local_zone() -> Option<String> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis())
        .unwrap_or_default();
    let zone = local_time(now, true);
    // `2026-10-08 16:30:00 IST`: the zone is the third field.
    zone.split(' ').nth(2).map(str::to_string)
}

/// `19:32:11 IST`.
fn time_of_day(millis: u128) -> String {
    let shown = local_time(millis, true);
    match shown.split_once(' ') {
        Some((_, time)) => time.to_string(),
        None => shown,
    }
}

/// Local time, `2026-10-07 19:32` or with seconds and zone.
fn local_time(millis: u128, seconds: bool) -> String {
    #[cfg(unix)]
    {
        let secs = (millis / 1000) as libc::time_t;
        let mut tm: libc::tm = unsafe { std::mem::zeroed() };
        // SAFETY: `secs` and `tm` are valid for the duration of the call.
        if !unsafe { libc::localtime_r(&secs, &mut tm) }.is_null() {
            let date = format!(
                "{:04}-{:02}-{:02} {:02}:{:02}",
                tm.tm_year + 1900,
                tm.tm_mon + 1,
                tm.tm_mday,
                tm.tm_hour,
                tm.tm_min
            );
            if !seconds {
                return date;
            }
            let zone = if tm.tm_zone.is_null() {
                String::new()
            } else {
                // SAFETY: localtime_r sets tm_zone to a static NUL-terminated string.
                unsafe { std::ffi::CStr::from_ptr(tm.tm_zone) }
                    .to_string_lossy()
                    .into_owned()
            };
            return format!("{date}:{:02} {zone}", tm.tm_sec)
                .trim_end()
                .to_string();
        }
    }
    let utc = receipt::format_utc(millis);
    if seconds {
        utc
    } else {
        utc[..16].to_string()
    }
}

#[cfg(test)]
#[path = "receipts_tests.rs"]
mod tests;