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
}
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];
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));
}
}
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());
}
}
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))
}
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);
zone.split(' ').nth(2).map(str::to_string)
}
fn time_of_day(millis: u128) -> String {
let shown = local_time(millis, true);
match shown.split_once(' ') {
Some((_, time)) => time.to_string(),
None => shown,
}
}
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() };
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 {
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;