use crate::style as s;
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
static QUIET: AtomicBool = AtomicBool::new(false);
static VERBOSITY: AtomicU8 = AtomicU8::new(0);
pub fn set_quiet(q: bool) {
QUIET.store(q, Ordering::Relaxed);
}
pub fn set_verbosity(v: u8) {
VERBOSITY.store(v, Ordering::Relaxed);
}
pub fn is_quiet() -> bool {
QUIET.load(Ordering::Relaxed)
}
pub fn verbosity() -> u8 {
VERBOSITY.load(Ordering::Relaxed)
}
pub fn info<S: AsRef<str>>(msg: S) {
if is_quiet() {
return;
}
println!("{}", msg.as_ref());
}
pub fn success<S: AsRef<str>>(msg: S) {
if is_quiet() {
return;
}
let t = crate::theme::active();
if t.success_glyph.is_empty() {
println!("{}", msg.as_ref());
} else {
println!("{} {}", t.color_success.paint(&t.success_glyph), msg.as_ref());
}
}
pub fn warn<S: AsRef<str>>(msg: S) {
let t = crate::theme::active();
eprintln!("{} {}", t.color_warn.paint(&t.warn_label), msg.as_ref());
}
pub fn error<S: AsRef<str>>(msg: S) {
let t = crate::theme::active();
eprintln!("{} {}", t.color_error.paint(&t.error_label), msg.as_ref());
}
pub fn debug<S: AsRef<str>>(level: u8, msg: S) {
if verbosity() >= level {
let t = crate::theme::active();
eprintln!("{} {}", t.color_debug.paint(&t.debug_label), msg.as_ref());
}
}
pub struct Table {
headers: Vec<String>,
rows: Vec<Vec<String>>,
}
impl Table {
pub fn new(headers: &[&str]) -> Self {
Table {
headers: headers.iter().map(|h| h.to_string()).collect(),
rows: Vec::new(),
}
}
pub fn row(&mut self, cells: &[&str]) -> &mut Self {
self.rows.push(cells.iter().map(|c| c.to_string()).collect());
self
}
pub fn render(&self) -> String {
let cols = self.headers.len();
let mut widths = vec![0usize; cols];
for (i, h) in self.headers.iter().enumerate() {
widths[i] = h.chars().count();
}
for r in &self.rows {
for (i, c) in r.iter().enumerate() {
let cw = c.chars().count();
if i < cols && cw > widths[i] {
widths[i] = cw;
}
}
}
let mut out = String::new();
for (i, h) in self.headers.iter().enumerate() {
out.push_str(&pad_display(&s::bold(h), h, widths[i]));
if i + 1 < cols {
out.push_str(" ");
}
}
out.push('\n');
for (i, w) in widths.iter().enumerate() {
out.push_str(&"-".repeat(*w));
if i + 1 < cols {
out.push_str(" ");
}
}
out.push('\n');
for r in &self.rows {
for (i, c) in r.iter().enumerate() {
out.push_str(&pad_display(c, c, widths[i]));
if i + 1 < cols {
out.push_str(" ");
}
}
out.push('\n');
}
out
}
pub fn print(&self) {
if is_quiet() {
return;
}
print!("{}", self.render());
}
}
fn pad_display(styled: &str, plain: &str, target: usize) -> String {
let visible = plain.chars().count();
let pad = target.saturating_sub(visible);
format!("{}{}", styled, " ".repeat(pad))
}
pub struct Progress {
total: u64,
current: u64,
label: String,
active: bool,
width: usize,
}
impl Progress {
pub fn new(total: u64, label: &str) -> Self {
let active = !is_quiet() && s::is_stderr_tty();
let width = crate::theme::active().progress_width;
Progress {
total,
current: 0,
label: label.to_string(),
active,
width,
}
}
pub fn inc(&mut self, by: u64) {
self.current = (self.current + by).min(self.total);
self.draw();
}
pub fn set(&mut self, value: u64) {
self.current = value.min(self.total);
self.draw();
}
fn draw(&self) {
if !self.active {
return;
}
let t = crate::theme::active();
let frac = if self.total == 0 {
1.0
} else {
self.current as f64 / self.total as f64
};
let filled = (frac * self.width as f64).round() as usize;
let bar = format!(
"{}{}",
t.progress_fill.repeat(filled),
t.progress_empty.repeat(self.width - filled)
);
eprint!(
"\r{} [{}] {}/{}",
self.label,
t.color_accent.paint(&bar),
self.current,
self.total
);
let _ = std::io::stderr().flush();
}
pub fn finish(&self, msg: &str) {
if !self.active {
return;
}
let t = crate::theme::active();
eprint!("\r{}\r", " ".repeat(self.label.len() + self.width + 20));
if t.success_glyph.is_empty() {
eprintln!("{}", msg);
} else {
eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
}
}
}
pub struct Spinner {
frames: Vec<char>,
idx: usize,
label: String,
active: bool,
}
impl Spinner {
pub fn new(label: &str) -> Self {
Spinner {
frames: vec!['|', '/', '-', '\\'],
idx: 0,
label: label.to_string(),
active: !is_quiet() && s::is_stderr_tty(),
}
}
pub fn tick(&mut self) {
if !self.active {
return;
}
let f = self.frames[self.idx % self.frames.len()];
self.idx += 1;
eprint!("\r{} {}", crate::theme::active().color_accent.paint(f.to_string()), self.label);
let _ = std::io::stderr().flush();
}
pub fn finish(&self, msg: &str) {
if !self.active {
return;
}
eprint!("\r{}\r", " ".repeat(self.label.len() + 4));
let t = crate::theme::active();
if t.success_glyph.is_empty() {
eprintln!("{}", msg);
} else {
eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
}
}
}
pub struct Timer {
start: std::time::Instant,
}
impl Timer {
pub fn start() -> Self {
Timer {
start: std::time::Instant::now(),
}
}
pub fn elapsed_ms(&self) -> u128 {
self.start.elapsed().as_millis()
}
pub fn human(&self) -> String {
let ms = self.elapsed_ms();
if ms < 1000 {
format!("{}ms", ms)
} else if ms < 60_000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
let s = ms / 1000;
format!("{}m {}s", s / 60, s % 60)
}
}
}
pub fn kv(pairs: &[(&str, &str)]) {
if is_quiet() {
return;
}
let w = pairs.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
for (k, v) in pairs {
println!("{} {}", pad_display(&s::dim(k), k, w), v);
}
}
pub struct Tree {
pub label: String,
pub children: Vec<Tree>,
}
impl Tree {
pub fn new<S: Into<String>>(label: S) -> Self {
Tree {
label: label.into(),
children: Vec::new(),
}
}
pub fn child(mut self, node: Tree) -> Self {
self.children.push(node);
self
}
pub fn push(&mut self, node: Tree) -> &mut Self {
self.children.push(node);
self
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str(&self.label);
out.push('\n');
self.render_children(&mut out, "");
out
}
fn render_children(&self, out: &mut String, prefix: &str) {
let n = self.children.len();
for (i, child) in self.children.iter().enumerate() {
let last = i + 1 == n;
let (branch, cont) = if last {
("└── ", " ")
} else {
("├── ", "│ ")
};
out.push_str(prefix);
out.push_str(branch);
out.push_str(&child.label);
out.push('\n');
child.render_children(out, &format!("{}{}", prefix, cont));
}
}
pub fn print(&self) {
if is_quiet() {
return;
}
print!("{}", self.render());
}
}