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
}
fn group_message(group: &ErrorGroup) -> &str {
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)
}
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
}
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}")
}
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
}