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
//! Markdown rendering of a receipt for sharing.
//!
//! By default only structured facts are included: identifiers, commands and
//! commit subjects from the repository, statuses, exit codes and counts. The
//! deployer appears by name only; the email address needs `details`.
//! Text that came from the server or from errors (step output, log messages,
//! reasons, warnings) can contain secrets and appears only with `details`.

use std::fmt::Write;

use super::{format_duration, format_utc, strip_color, timing_suffix, Receipt};
use crate::logs::{escape, escape_field};
use crate::records::{ErrorGroup, ReceiptRecord, Smoke, StepKind};

mod words;
use words::{flag_text, headline, step_label};

pub fn markdown(receipt: &Receipt, details: bool) -> String {
    render(
        &ReceiptRecord::from_receipt(std::path::Path::new(""), receipt),
        details,
    )
}

pub fn render(receipt: &ReceiptRecord, details: bool) -> String {
    let mut out = String::new();
    let target = &receipt.target;
    let badge = receipt.badge();
    let _ = writeln!(
        out,
        "# Shipslip receipt: {} / {}\n",
        inline(receipt.project.raw()),
        inline(target.env.raw())
    );
    if details {
        out.push_str(
            "> Includes server output and error text. Review it for secrets before sharing.\n\n",
        );
    }
    let outcome = match (receipt.summary.as_ref(), details) {
        (Some(summary), true) if !badge.outcome.unfinished => inline(summary.raw()),
        _ => inline(&headline(badge.outcome)),
    };
    out.push_str("| | |\n|---|---|\n");
    row(&mut out, "Run", &code(receipt.run_id.raw()));
    row(&mut out, "Outcome", &outcome);
    row(&mut out, "Plan", &inline(&receipt.plan_text()));
    row(
        &mut out,
        "Server",
        &format!(
            "{} {}{}",
            code(target.ssh_alias.raw()),
            code(target.path.raw()),
            if target.production {
                " (production)"
            } else {
                ""
            }
        ),
    );
    row(&mut out, "Branch", &code(target.branch.raw()));
    row(&mut out, "Started", &format_utc(receipt.started_at_ms));
    row(
        &mut out,
        "Finished",
        &receipt
            .finished_at_ms
            .map(format_utc)
            .unwrap_or_else(|| "not finished".into()),
    );
    if let Some(finished) = receipt.finished_at_ms {
        row(
            &mut out,
            "Duration",
            &format_duration(finished.saturating_sub(receipt.started_at_ms)),
        );
    }
    row(
        &mut out,
        "Started by",
        &if details {
            receipt.started_by.as_ref()
        } else {
            receipt.started_by_name.as_ref()
        }
        .map_or_else(|| "not recorded".into(), |who| inline(who.raw())),
    );
    if receipt.kind == super::ReceiptKind::Up {
        row(
            &mut out,
            "Server HEAD",
            &code(short(receipt.from_sha.raw())),
        );
    } else {
        row(
            &mut out,
            "From → target",
            &format!(
                "{} → {}",
                code(short(receipt.from_sha.raw())),
                code(short(receipt.target_sha.raw()))
            ),
        );
    }
    if receipt.ended_in_failure() {
        row(&mut out, "Server HEAD at end", &server_head(receipt));
    }

    if !badge.flags.is_empty() {
        out.push_str("\n## Flags\n\n");
        for flag in &badge.flags {
            let _ = writeln!(out, "- {}", inline(&flag_text(*flag)));
        }
    }

    if !receipt.commits.is_empty() {
        out.push_str("\n## Commits\n\n");
        for commit in &receipt.commits {
            let _ = writeln!(out, "- {}", inline(commit.raw()));
        }
        if receipt.more_commits > 0 {
            let _ = writeln!(out, "- and {} more commits", receipt.more_commits);
        }
    }

    out.push_str("\n## Steps\n\n| Step | Command | Status | Exit |\n|---|---|---|---|\n");
    for step in &receipt.steps {
        let label = match step.kind {
            StepKind::MaintenanceDown => "Maintenance on".to_string(),
            StepKind::Step { index } => index.to_string(),
            StepKind::MaintenanceUp => "Maintenance off".to_string(),
        };
        let _ = writeln!(
            out,
            "| {label} | {} | {}{} | {} |",
            code(step.command.raw()),
            step_label(step.status),
            timing_suffix(step.times(), time_of_day),
            exit(step.exit_code)
        );
    }

    render_connection_gaps(&mut out, receipt, details);
    if let Some(watch) = receipt.watch.as_ref().filter(|_| !badge.outcome.unfinished) {
        out.push_str("\n## Log watch\n\n");
        if watch.status == crate::WatchStatus::NotRun {
            let _ = writeln!(
                out,
                "Status: {}.",
                watch.status.description(receipt.checks_skip_reason)
            );
        } else {
            let _ = writeln!(
                out,
                "Status: {}, {}, {} lines read from {}.",
                watch.status.description(receipt.checks_skip_reason),
                format_duration(u128::from(watch.duration_ms)),
                watch.observed_lines,
                code(watch.log_path.as_ref().unwrap_or(&target.log_path).raw())
            );
        }
        if !watch.new_errors.is_empty() {
            out.push_str(if details {
                "\n| New error | Message | File | Count |\n|---|---|---|---|\n"
            } else {
                "\n| New error | File | Count |\n|---|---|---|\n"
            });
            for group in &watch.new_errors {
                let message = match (details, group_message(group)) {
                    (false, _) => String::new(),
                    (true, "") => "  |".into(),
                    (true, text) => format!(" {} |", code(text)),
                };
                let _ = writeln!(
                    out,
                    "| {} |{message} {} | {} |",
                    code(group.exception.raw()),
                    group
                        .file
                        .as_ref()
                        .map(|file| code(file.raw()))
                        .unwrap_or_default(),
                    group.count
                );
            }
            if watch.overflow_groups > 0 {
                let _ = writeln!(out, "\nAnd {} more groups.", watch.overflow_groups);
            }
            if details {
                for group in &watch.new_errors {
                    for variant in &group.variants {
                        let _ = writeln!(
                            out,
                            "\n{} ×{}{}\n{}",
                            code(group.exception.raw()),
                            variant.count,
                            variant
                                .display_file_line
                                .as_ref()
                                .map(|line| format!(" at {}", code(line.raw())))
                                .unwrap_or_default(),
                            fence(variant.message.raw())
                        );
                    }
                }
            }
        }
        if details && !watch.warnings.is_empty() {
            out.push('\n');
            for warning in &watch.warnings {
                let _ = writeln!(out, "- {}", inline(warning.raw()));
            }
        }
    }

    if let Some(smoke) = receipt.smoke.as_ref().filter(|_| !badge.outcome.unfinished) {
        out.push_str("\n## Smoke check\n\n");
        let text = match smoke {
            Smoke::NotConfigured => "Not configured.".into(),
            Smoke::Skipped => receipt.checks_skip_reason.map_or_else(
                || "Skipped.".into(),
                |reason| format!("Skipped: {}.", reason.description()),
            ),
            Smoke::Passed { status, latency_ms } => {
                format!("Passed: HTTP {status} in {latency_ms} ms.")
            }
            Smoke::Failed { status, reason } => match (status, details) {
                (Some(status), true) if reason.raw() != format!("HTTP {status}") => {
                    format!("Failed: HTTP {status}: {}", inline(reason.raw()))
                }
                (Some(status), _) => format!("Failed: HTTP {status}."),
                (None, true) => format!("Failed: {}", inline(reason.raw())),
                (None, false) => "Failed.".into(),
            },
        };
        let _ = writeln!(out, "{text}");
    }

    if details {
        let notes = &receipt.notes;
        if !notes.is_empty() {
            out.push_str("\n## Notes\n\n");
            for note in notes {
                let _ = writeln!(out, "- {}", inline(note.raw()));
            }
        }
        let with_output: Vec<_> = receipt
            .steps
            .iter()
            .filter(|step| !step.output.is_empty())
            .collect();
        if !with_output.is_empty() {
            out.push_str("\n## Output\n");
            for step in with_output {
                let _ = writeln!(
                    out,
                    "\n{} (last {} lines):\n{}",
                    step_name(step.kind),
                    step.output.len(),
                    fence(&strip_color(
                        &step
                            .output
                            .iter()
                            .map(|line| line.raw())
                            .collect::<Vec<_>>()
                            .join("\n")
                    ))
                );
            }
        }
    }
    out
}

/// The first line of a group's most frequent message.
fn group_message(group: &ErrorGroup) -> &str {
    // Reversed so the earliest of equally frequent variants wins.
    let top = group
        .variants
        .iter()
        .rev()
        .max_by_key(|variant| variant.count);
    top.map(|variant| variant.message.raw())
        .or_else(|| {
            group
                .normalized_message
                .as_ref()
                .map(|message| message.raw())
        })
        .unwrap_or("")
        .lines()
        .next()
        .unwrap_or("")
}

fn row(out: &mut String, label: &str, value: &str) {
    let _ = writeln!(out, "| {label} | {value} |");
}

fn step_name(kind: StepKind) -> String {
    match kind {
        StepKind::Step { index } => format!("Step {index}"),
        StepKind::MaintenanceDown => "Maintenance on".into(),
        StepKind::MaintenanceUp => "Maintenance off".into(),
    }
}

fn render_connection_gaps(out: &mut String, receipt: &ReceiptRecord, details: bool) {
    let mut heading = false;
    for step in &receipt.steps {
        let label = step_name(step.kind);
        for gap in &step.connection_gaps {
            if !heading {
                out.push_str("\n## Connection gaps\n\n");
                heading = true;
            }
            let _ = writeln!(
                out,
                "- {label}: 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())
            );
            if details {
                let _ = writeln!(out, "  Detail: {}", inline(gap.detail.raw()));
            }
        }
    }
}

fn time_of_day(millis: u128) -> String {
    format_utc(millis)[11..].to_string()
}

fn server_head(receipt: &ReceiptRecord) -> String {
    match (&receipt.server_head_at_end, receipt.tree_dirty) {
        (Some(head), Some(true)) => format!("{} with uncommitted changes", code(short(head.raw()))),
        (Some(head), _) => code(short(head.raw())),
        (None, _) => "not recorded".into(),
    }
}

fn exit(code: Option<i32>) -> String {
    code.map(|code| code.to_string()).unwrap_or_default()
}

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

/// Text inside a table cell or list item: one line, no Markdown syntax.
pub fn inline(text: &str) -> String {
    let mut out = String::new();
    for c in escape_field(text).chars() {
        if matches!(
            c,
            '\\' | '`'
                | '*'
                | '_'
                | '['
                | ']'
                | '<'
                | '>'
                | '#'
                | '|'
                | '~'
                | '!'
                | '('
                | ')'
                | '&'
        ) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// Inline code that no backtick in `text` can close early.
pub fn code(text: &str) -> String {
    let text = escape_field(text).replace('|', "\\|");
    let ticks = "`".repeat(longest_run(&text, '`') + 1);
    let pad = if text.starts_with('`') || text.ends_with('`') {
        " "
    } else {
        ""
    };
    format!("{ticks}{pad}{text}{pad}{ticks}")
}

/// A fenced block longer than any backtick run inside it.
pub fn fence(text: &str) -> String {
    let text = escape(text);
    let ticks = "`".repeat((longest_run(&text, '`') + 1).max(3));
    format!("{ticks}text\n{text}\n{ticks}")
}

fn longest_run(text: &str, target: char) -> usize {
    let mut longest = 0;
    let mut current = 0;
    for c in text.chars() {
        if c == target {
            current += 1;
            longest = longest.max(current);
        } else {
            current = 0;
        }
    }
    longest
}