use std::io;
use owo_colors::{OwoColorize, Style};
use super::{BECAUSE, palette};
pub(super) const GUTTER: &str = " ";
pub(super) const MAX_PATH_COLUMN: usize = 40;
pub(super) struct Line {
pub(super) label: &'static str,
pub(super) label_style: Style,
pub(super) size: Option<String>,
pub(super) tag: Option<&'static str>,
pub(super) tag_style: Style,
pub(super) path: String,
pub(super) detail: Option<String>,
}
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct Widths {
pub(super) label: usize,
pub(super) size: usize,
pub(super) tag: usize,
pub(super) path: usize,
}
impl Widths {
pub(super) fn measure(lines: &[Line]) -> Self {
let mut widths = Self::default();
for line in lines {
widths.label = widths.label.max(width_of(line.label));
if let Some(size) = &line.size {
widths.size = widths.size.max(width_of(size));
}
if let Some(tag) = line.tag {
widths.tag = widths.tag.max(width_of(tag));
}
if line.detail.is_some() {
widths.path = widths.path.max(width_of(&line.path));
}
}
widths.path = widths.path.min(MAX_PATH_COLUMN);
widths
}
}
pub(super) fn width_of(text: &str) -> usize {
text.chars().count()
}
pub(super) fn write_fill(out: &mut impl io::Write, spaces: usize) -> io::Result<()> {
write!(out, "{:spaces$}", "")
}
pub(super) fn write_column(out: &mut impl io::Write, text: &str, style: Style, width: usize) -> io::Result<()> {
write!(out, "{}", style.style(text))?;
write_fill(out, width.saturating_sub(width_of(text)))
}
pub(super) fn write_column_right(out: &mut impl io::Write, text: &str, style: Style, width: usize) -> io::Result<()> {
write_fill(out, width.saturating_sub(width_of(text)))?;
write!(out, "{}", style.style(text))
}
pub(super) fn write_line(line: &Line, widths: Widths, out: &mut impl io::Write) -> io::Result<()> {
write!(out, "{GUTTER}")?;
write_column(out, line.label, line.label_style, widths.label)?;
if widths.size > 0 {
write!(out, "{GUTTER}")?;
write_column_right(
out,
line.size.as_deref().unwrap_or_default(),
palette::quiet(),
widths.size,
)?;
}
if widths.tag > 0 {
write!(out, "{GUTTER}")?;
write_column(out, line.tag.unwrap_or_default(), line.tag_style, widths.tag)?;
}
write!(out, "{GUTTER}{}", line.path)?;
match &line.detail {
None => writeln!(out),
Some(detail) => {
write_fill(out, widths.path.saturating_sub(width_of(&line.path)))?;
writeln!(
out,
"{GUTTER}{}",
format_args!("{BECAUSE}{detail}").style(palette::quiet())
)
}
}
}
pub(super) fn write_block(lines: &[Line], out: &mut impl io::Write) -> io::Result<()> {
let widths = Widths::measure(lines);
for line in lines {
write_line(line, widths, out)?;
}
Ok(())
}