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
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, describe_plan, describe_watch, format_duration, strip_color, Found, Listed, Receipt,
    ReceiptError, ReceiptStatus, ReceiptStepStatus,
};
use shipslip::{DeployOutcome, SmokeResult, WatchStatus};

use super::invalid_input;

/// Receipts listed unless `--all` is given.
const LIST_LIMIT: usize = 20;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Args {
    List { env: Option<String>, all: bool },
    Show { id: String, md: bool, details: 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) = (false, false);
            for arg in &args[1..] {
                match arg.as_str() {
                    "--md" => md = 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 details && !md {
                return Err(invalid_input("--with-details only applies with --md").into());
            }
            return Ok(Self::Show { id, md, details });
        }
        let mut env = None;
        let mut all = false;
        for arg in args {
            match arg.as_str() {
                "--all" => all = 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 })
    }
}

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 } => {
            let listing =
                receipt::list(root, project, env.as_deref(), (!all).then_some(LIST_LIMIT))?;
            print!("{}", render_list(project, env.as_deref(), &listing));
        }
        Args::Show { id, md, details } => {
            let path = match receipt::find(root, project, &id)? {
                Found::One(path) => path,
                Found::Missing => {
                    return Err(invalid_input(format!(
                        "no receipt of {} matches `{}`; run `slip receipts` to list them",
                        escape_field(project),
                        escape_field(&id)
                    ))
                    .into())
                }
                Found::Ambiguous(ids) => {
                    return Err(invalid_input(format!(
                        "`{}` matches several receipts ({}); type more of the ID",
                        escape_field(&id),
                        ids.join(", ")
                    ))
                    .into())
                }
            };
            let receipt = receipt::read(&path).map_err(|error| match error {
                ReceiptError::Version(version) => invalid_input(format!(
                    "this receipt was written by a newer Shipslip (receipt schema v{version}); upgrade slip to read it"
                ))
                .into(),
                error => Box::<dyn Error>::from(error),
            })?;
            if md {
                print!("{}", receipt::markdown(&receipt, details));
            } else {
                print!("{}", render_show(&receipt));
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn render_list(project: &str, env: Option<&str>, listing: &receipt::Listing) -> 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 {
            Listed::Receipt { id, receipt, .. } => {
                let badge = receipt.badge();
                let mut outcome = badge.headline();
                for flag in &badge.flags {
                    outcome.push_str("  ");
                    outcome.push_str(&flag.text());
                }
                [
                    id.clone(),
                    local_time(receipt.started_at_ms, false),
                    escape_field(&receipt.target.env),
                    format!(
                        "{} → {}",
                        short(&receipt.from_sha),
                        short(&receipt.target_sha)
                    ),
                    escape_field(&outcome),
                ]
            }
            Listed::Newer {
                id,
                env,
                started_at_ms,
                version,
                ..
            } => [
                id.clone(),
                started_at_ms
                    .map(|ms| local_time(ms, false))
                    .unwrap_or_default(),
                escape_field(env),
                String::new(),
                format!("needs a newer slip (receipt schema v{version})"),
            ],
            Listed::Unreadable {
                id,
                env,
                started_at_ms,
                reason,
                ..
            } => [
                escape_field(id),
                started_at_ms
                    .map(|ms| local_time(ms, false))
                    .unwrap_or_default(),
                escape_field(env),
                String::new(),
                format!("unreadable: {}", escape_field(reason)),
            ],
        });
    }
    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: &Receipt) -> 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));
    let outcome = match &receipt.outcome {
        Some(outcome) if !badge.unfinished => outcome.summary(),
        _ => badge.headline(),
    };
    field(&mut out, "Outcome:", &escape_field(&outcome));
    if !badge.flags.is_empty() {
        let flags: Vec<String> = badge.flags.iter().map(|flag| flag.text()).collect();
        field(&mut out, "Flags:", &flags.join(", "));
    }
    field(
        &mut out,
        "Project:",
        &format!(
            "{} (checkout {})",
            escape_field(&receipt.project),
            escape_field(&receipt.repo_root)
        ),
    );
    field(
        &mut out,
        "Environment:",
        &format!(
            "{}{} via {}:{}, branch {}",
            escape_field(&target.env),
            if target.production {
                " (production)"
            } else {
                ""
            },
            escape_field(&target.ssh_alias),
            escape_field(&target.path),
            escape_field(&target.branch)
        ),
    );
    field(&mut out, "Plan:", &describe_plan(receipt.run_plan));
    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:",
        &escape_field(
            &receipt
                .started_by()
                .unwrap_or_else(|| "not recorded".into()),
        ),
    );
    field(
        &mut out,
        "From → target:",
        &format!(
            "{} → {}",
            short(&receipt.from_sha),
            short(&receipt.target_sha)
        ),
    );
    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)),
                (Some(head), _) => short(head),
                (None, _) => "not recorded".into(),
            },
        );
    }

    if !receipt.commits.is_empty() {
        out.push_str("\nCommits:\n");
        for commit in &receipt.commits {
            let _ = writeln!(out, "  {}", escape_field(commit));
        }
    }

    out.push_str("\nSteps:\n");
    if let Some(status) = &receipt.maintenance_down_status {
        step_line(
            &mut out,
            "on",
            "Maintenance on: php artisan down",
            status.clone().into(),
            receipt.maintenance_down_exit_code,
        );
    }
    for step in &receipt.steps {
        step_line(
            &mut out,
            &step.index.to_string(),
            &step.command,
            step.status,
            step.exit_code,
        );
        for line in &step.output {
            let _ = writeln!(out, "        {}", escape(&strip_color(line)));
        }
    }
    if let Some(status) = &receipt.maintenance_up_status {
        step_line(
            &mut out,
            "off",
            "Maintenance off: php artisan up",
            status.clone().into(),
            receipt.maintenance_up_exit_code,
        );
    }

    if let Some(watch) = &receipt.watch {
        let _ = writeln!(
            out,
            "\nLog watch: {}, {}, {} lines read from {}",
            describe_watch(watch.status),
            format_duration(u128::from(watch.duration_ms)),
            watch.observed_lines,
            escape_field(watch.log_path.as_deref().unwrap_or(target.log_path()))
        );
        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,
                escape_field(&group.exception),
                group
                    .file
                    .as_deref()
                    .map(|file| format!("  {}", escape_field(file)))
                    .unwrap_or_default()
            );
            for variant in &group.variants {
                let _ = writeln!(
                    out,
                    "    ×{}{} {}",
                    variant.count,
                    variant
                        .display_file_line
                        .as_deref()
                        .map(|line| format!(" {}", escape_field(line)))
                        .unwrap_or_default(),
                    escape_field(&variant.message)
                );
            }
        }
        if watch.overflow_groups > 0 {
            let _ = writeln!(out, "  And {} more groups", watch.overflow_groups);
        }
        for warning in &watch.warnings {
            let _ = writeln!(out, "  Warning: {}", escape_field(warning));
        }
    }

    if let Some(smoke) = &receipt.smoke {
        let text = match smoke {
            SmokeResult::NotConfigured => "not configured".into(),
            SmokeResult::Skipped => "skipped".into(),
            SmokeResult::Passed { status, latency_ms } => {
                format!("passed, HTTP {status} in {latency_ms} ms")
            }
            SmokeResult::Failed {
                status: Some(status),
                reason,
            } if *reason == format!("HTTP {status}") => format!("failed, HTTP {status}"),
            SmokeResult::Failed {
                status: Some(status),
                reason,
            } => format!("failed, HTTP {status}: {}", escape_field(reason)),
            SmokeResult::Failed {
                status: None,
                reason,
            } => format!("failed: {}", escape_field(reason)),
        };
        let _ = writeln!(out, "\nSmoke check: {text}");
    }

    let notes: Vec<&String> = receipt
        .last_message
        .iter()
        .chain(&receipt.warnings)
        .collect();
    if !notes.is_empty() {
        out.push_str("\nNotes:\n");
        for note in notes {
            let _ = writeln!(out, "  {}", escape_field(note));
        }
    }

    let next = receipt.next_steps();
    if !next.is_empty() {
        out.push_str("\nAt the time of this run:\n");
        for line in next {
            let _ = writeln!(out, "  {line}");
        }
    }
    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(10)).ok()?;
    let (id, receipt) = listing.rows.iter().find_map(|row| match row {
        Listed::Receipt { id, receipt, .. } if receipt.mutation_started => Some((id, receipt)),
        _ => None,
    })?;
    let needs_attention = receipt.status == ReceiptStatus::InProgress
        || receipt.ended_in_failure()
        || receipt.app_left_down;
    if !needs_attention {
        return None;
    }
    let env = escape_field(env);
    let mut lines = vec![format!(
        "The last run here ({id}) did not succeed: {}. See `slip receipts show {id}`.",
        receipt.badge().headline()
    )];
    if let Some(DeployOutcome::FailedAtStep { step, .. }) = &receipt.outcome {
        if *step > 0 {
            lines.extend(receipt::failed_step_options(&env, *step));
        }
    }
    if receipt.app_left_down {
        lines.push(format!(
            "The app may still be in maintenance mode; `slip up {env}` turns it off."
        ));
    }
    Some(lines.join("\n"))
}

fn step_line(
    out: &mut String,
    index: &str,
    command: &str,
    status: ReceiptStepStatus,
    exit_code: Option<i32>,
) {
    let _ = writeln!(
        out,
        "  {:<12}{:>4}  {}{}",
        status.label(),
        index,
        escape_field(command),
        exit_code
            .map(|code| format!(" (exit {code})"))
            .unwrap_or_default()
    );
}

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)
}

/// 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;