use std::fmt;
use crate::block::Block;
use crate::output::{self, Val};
use crate::style::palette::{AMBER, BLUSH, LINE, MUTED, RED, ROSE, SAGE, SOFT, TEXT};
use crate::style::{Rgb, bold, paint};
use crate::term::content_width;
use crate::text;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tone {
Success,
Info,
Warn,
Error,
Hint,
}
impl Tone {
pub fn line(self, msg: &str) -> String {
let (glyph, color, text_color): (&str, Rgb, Rgb) = match self {
Tone::Success => ("●", ROSE, TEXT),
Tone::Info => ("›", BLUSH, TEXT),
Tone::Warn => ("▲", AMBER, TEXT),
Tone::Error => ("✕", RED, TEXT),
Tone::Hint => ("→", MUTED, SOFT),
};
format!(" {} {}", paint(color, glyph), paint(text_color, msg))
}
pub fn print(self, msg: &str) {
if output::json() {
return output::emit("message", &[("level", Val::Str(self.name())), ("text", Val::Str(msg))]);
}
if output::quiet() && !matches!(self, Tone::Warn | Tone::Error) {
return;
}
match self {
Tone::Error => eprintln!("{}", self.line(msg)),
_ => output::line(&self.line(msg)),
}
}
}
impl Tone {
fn name(self) -> &'static str {
match self {
Tone::Success => "success",
Tone::Info => "info",
Tone::Warn => "warn",
Tone::Error => "error",
Tone::Hint => "hint",
}
}
}
pub fn success(msg: &str) {
Tone::Success.print(msg);
}
pub fn info(msg: &str) {
Tone::Info.print(msg);
}
pub fn warn(msg: &str) {
Tone::Warn.print(msg);
}
pub fn error(msg: &str) {
Tone::Error.print(msg);
}
pub fn hint(msg: &str) {
Tone::Hint.print(msg);
}
pub fn counter(n: usize, total: usize, msg: &str) {
if output::json() {
let fields = [
("n", Val::Num(n as f64)),
("total", Val::Num(total as f64)),
("text", Val::Str(msg)),
];
return output::emit("counter", &fields);
}
if output::quiet() {
return;
}
let w = total.to_string().len();
output::line(&format!(
" {} {}",
paint(MUTED, &format!("{n:>w$}/{total}")),
paint(TEXT, msg)
));
}
pub fn title(text: &str, subtitle: Option<&str>) {
if output::json() {
let sub = subtitle.unwrap_or_default();
return output::emit("title", &[("text", Val::Str(text)), ("subtitle", Val::Str(sub))]);
}
if output::quiet() {
return;
}
let sub = subtitle.map(|s| format!(" {}", paint(SOFT, s))).unwrap_or_default();
output::line(&format!("\n {}{sub}\n", bold(&paint(ROSE, text))));
}
pub fn rule(label: &str) -> String {
let w = content_width().saturating_sub(2);
if label.is_empty() {
return format!(" {}", paint(LINE, &"─".repeat(w)));
}
let rest = w.saturating_sub(text::width(label) + 4);
format!(
" {} {} {}",
paint(LINE, "──"),
paint(SOFT, label),
paint(LINE, &"─".repeat(rest))
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Callout {
Note,
Tip,
Warning,
Danger,
}
impl Callout {
fn color(self) -> Rgb {
match self {
Callout::Note => ROSE,
Callout::Tip => SAGE,
Callout::Warning => AMBER,
Callout::Danger => RED,
}
}
}
pub fn callout(kind: Callout, title: &str, body: &str) -> Block {
let bar = paint(kind.color(), "▎");
let mut out = Block::new();
out.push(format!(" {bar} {}", bold(&paint(kind.color(), title))));
for line in text::wrap(body, content_width().saturating_sub(6)) {
out.push(format!(" {bar} {}", paint(SOFT, &line)));
}
out
}
#[derive(Clone, Debug, Default)]
pub struct Report {
title: String,
causes: Vec<String>,
code: Option<crate::layout::Code>,
hint: Option<String>,
}
impl Report {
pub fn new(title: impl Into<String>) -> Self {
Report {
title: title.into(),
..Self::default()
}
}
pub fn from_error(title: impl Into<String>, err: &dyn std::error::Error) -> Self {
let mut report = Report::new(title).cause(err.to_string());
let mut source = err.source();
while let Some(e) = source {
report = report.cause(e.to_string());
source = e.source();
}
report
}
pub fn cause(mut self, cause: impl Into<String>) -> Self {
self.causes.push(cause.into());
self
}
pub fn code(mut self, code: crate::layout::Code) -> Self {
self.code = Some(code);
self
}
pub fn hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
pub fn lines(&self) -> Block {
let mut out = Block::new();
out.push(format!(" {} {}", paint(RED, "✕"), bold(&paint(TEXT, &self.title))));
for (depth, cause) in self.causes.iter().enumerate() {
let indent = " ".repeat(5 + depth * 3);
out.push(format!("{indent}{} {}", paint(LINE, "╰─"), paint(SOFT, cause)));
}
if let Some(code) = &self.code {
for line in code.lines() {
out.push(format!(" {line}"));
}
}
if let Some(h) = &self.hint {
out.push(Tone::Hint.line(h));
}
out
}
pub fn eprint(&self) {
if output::json() {
let hint = self.hint.as_deref().unwrap_or_default();
let code: Vec<String> = self
.code
.iter()
.flat_map(|c| c.lines().plain().lines().map(String::from).collect::<Vec<_>>())
.collect();
let fields = [
("title", Val::Str(&self.title)),
("causes", Val::List(&self.causes)),
("code", Val::List(&code)),
("hint", Val::Str(hint)),
];
return output::emit("error", &fields);
}
self.lines().eprint();
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.lines().fmt(f)
}
}