use std::time::{Duration, SystemTime};
use indicatif::{ProgressBar, ProgressStyle};
pub fn braille_spinner(template: &str) -> ProgressBar {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::with_template(template)
.unwrap_or_else(|_| ProgressStyle::default_spinner())
.tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
);
pb.enable_steady_tick(Duration::from_millis(100));
pb
}
pub fn terminal_cols(fd: i32) -> Option<u16> {
#[cfg(unix)]
{
let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
if unsafe { libc::ioctl(fd, libc::TIOCGWINSZ, &mut ws) } == 0 && ws.ws_col > 0 {
return Some(ws.ws_col);
}
}
#[cfg(not(unix))]
let _ = fd;
None
}
pub const GREEN: &str = "\x1b[32m";
pub const YELLOW: &str = "\x1b[33m";
pub const RED: &str = "\x1b[31m";
pub fn stdout_color() -> bool {
console::Term::stdout().features().colors_supported()
}
pub fn paint(text: &str, code: &str, color: bool) -> String {
if color {
format!("{code}{text}\x1b[0m")
} else {
text.to_string()
}
}
pub fn columns(rows: &[Vec<String>], gap: usize) -> String {
let width = |column: usize| {
rows.iter()
.filter(|row| column + 1 < row.len())
.map(|row| row[column].chars().count())
.max()
.unwrap_or(0)
};
let mut out = String::new();
for row in rows {
for (column, cell) in row.iter().enumerate() {
if column + 1 < row.len() {
out.push_str(&format!("{cell:<w$}{:gap$}", "", w = width(column)));
} else {
out.push_str(cell);
}
}
out.push('\n');
}
out
}
pub fn short_id(digest: &str) -> String {
let hex = digest.strip_prefix("sha256:").unwrap_or(digest);
hex.chars().take(12).collect()
}
pub fn human_size(bytes: u64) -> String {
const GB: u64 = 1_000_000_000;
const MB: u64 = 1_000_000;
const KB: u64 = 1_000;
if bytes >= GB {
format!("{:.1} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{:.1} MB", bytes as f64 / MB as f64)
} else if bytes >= KB {
format!("{:.1} kB", bytes as f64 / KB as f64)
} else {
format!("{bytes} B")
}
}
pub fn human_count(n: u64) -> String {
const B: u64 = 1_000_000_000;
const M: u64 = 1_000_000;
const K: u64 = 1_000;
if n >= B {
format!("{:.1}B", n as f64 / B as f64)
} else if n >= M {
format!("{:.1}M", n as f64 / M as f64)
} else if n >= K {
format!("{:.1}K", n as f64 / K as f64)
} else {
n.to_string()
}
}
fn relative_time_secs(secs: u64) -> String {
match secs {
s if s < 60 => "just now".into(),
s if s < 3600 => format!("{} minutes ago", s / 60),
s if s < 86400 => format!("{} hours ago", s / 3600),
s if s < 86400 * 2 => "yesterday".into(),
s if s < 86400 * 7 => format!("{} days ago", s / 86400),
s if s < 86400 * 14 => "1 week ago".into(),
s if s < 86400 * 30 => format!("{} weeks ago", s / (86400 * 7)),
s if s < 86400 * 60 => "1 month ago".into(),
s if s < 86400 * 365 => format!("{} months ago", s / (86400 * 30)),
s if s < 86400 * 730 => "1 year ago".into(),
s => format!("{} years ago", s / (86400 * 365)),
}
}
pub fn relative_time(t: Option<SystemTime>) -> String {
let secs = match t {
Some(t) => SystemTime::now()
.duration_since(t)
.unwrap_or_default()
.as_secs(),
None => return "unknown".into(),
};
relative_time_secs(secs)
}
pub fn relative_time_rfc3339(s: &str) -> String {
let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(s) else {
return "unknown".into();
};
let secs = (chrono::Utc::now() - parsed.with_timezone(&chrono::Utc))
.num_seconds()
.max(0) as u64;
relative_time_secs(secs)
}
fn until_secs(secs: u64) -> String {
match secs {
s if s < 60 => "just now".into(),
s if s < 3600 => format!("{} minutes from now", s / 60),
s if s < 86400 => format!("{} hours from now", s / 3600),
s => format!("{} days from now", s / 86400),
}
}
pub fn until_rfc3339(s: &str) -> String {
let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(s) else {
return "unknown".into();
};
let secs = (parsed.with_timezone(&chrono::Utc) - chrono::Utc::now())
.num_seconds()
.max(0) as u64;
until_secs(secs)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn columns_pad_all_but_the_last_cell() {
let rows = [["NAME", "SIZE", "FIT"], ["a", "10", "\x1b[32m5%\x1b[0m"]]
.map(|r| r.map(String::from).to_vec());
assert_eq!(
columns(&rows, 4),
"NAME SIZE FIT\na 10 \x1b[32m5%\x1b[0m\n"
);
assert_eq!(columns(&[], 4), "");
let rows = [vec!["a", "yes", "100%"], vec!["b", "Soon", "64%", "1.2"]]
.map(|r| r.into_iter().map(String::from).collect::<Vec<_>>());
assert_eq!(columns(&rows, 2), "a yes 100%\nb Soon 64% 1.2\n");
}
#[test]
fn short_id_truncates_to_12_hex_chars() {
assert_eq!(
short_id("sha256:0123456789abcdef0123456789abcdef"),
"0123456789ab"
);
assert_eq!(short_id("0123456789abcdef"), "0123456789ab");
}
#[test]
fn human_size_picks_the_right_unit() {
assert_eq!(human_size(512), "512 B");
assert_eq!(human_size(1_500), "1.5 kB");
assert_eq!(human_size(1_500_000), "1.5 MB");
assert_eq!(human_size(1_500_000_000), "1.5 GB");
}
#[test]
fn human_count_picks_the_right_unit() {
assert_eq!(human_count(512), "512");
assert_eq!(human_count(999), "999");
assert_eq!(human_count(1_000), "1.0K");
assert_eq!(human_count(1_500), "1.5K");
assert_eq!(human_count(7_200_000_000), "7.2B");
assert_eq!(human_count(600_000_000), "600.0M");
assert_eq!(human_count(999_999_999), "1000.0M");
}
#[test]
fn relative_time_rfc3339_handles_recent_and_invalid_timestamps() {
let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
assert_eq!(relative_time_rfc3339(&now), "just now");
assert_eq!(relative_time_rfc3339("not a timestamp"), "unknown");
}
#[test]
fn until_secs_formats_the_unit_ladder() {
assert_eq!(until_secs(0), "just now");
assert_eq!(until_secs(59), "just now");
assert_eq!(until_secs(60), "1 minutes from now");
assert_eq!(until_secs(300), "5 minutes from now");
assert_eq!(until_secs(3_600), "1 hours from now");
assert_eq!(until_secs(7_200), "2 hours from now");
assert_eq!(until_secs(86_400), "1 days from now");
}
#[test]
fn until_rfc3339_clamps_a_past_timestamp_and_rejects_garbage() {
let a_minute_ago = (chrono::Utc::now() - chrono::Duration::minutes(1))
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
assert_eq!(until_rfc3339(&a_minute_ago), "just now");
assert_eq!(until_rfc3339("not a timestamp"), "unknown");
}
#[test]
fn human_size_ported_ollama_humanbytes_boundaries() {
assert_eq!(human_size(0), "0 B");
assert_eq!(human_size(1), "1 B");
assert_eq!(human_size(999), "999 B");
assert_eq!(human_size(1_000), "1.0 kB");
assert_eq!(human_size(1_234), "1.2 kB");
assert_eq!(human_size(999_999), "1000.0 kB");
assert_eq!(human_size(1_000_000), "1.0 MB");
assert_eq!(human_size(1_234_567), "1.2 MB");
assert_eq!(human_size(1_000_000_000), "1.0 GB");
assert_eq!(human_size(1_234_567_890), "1.2 GB");
assert_eq!(human_size(1_000_000_000_000), "1000.0 GB");
assert_eq!(human_size(1_500_000_000_000), "1500.0 GB");
}
#[test]
fn relative_time_secs_ported_ollama_humantime_unit_ladder() {
const DAY: u64 = 86_400;
assert_eq!(relative_time_secs(0), "just now");
assert_eq!(relative_time_secs(59), "just now");
assert_eq!(relative_time_secs(60), "1 minutes ago");
assert_eq!(relative_time_secs(120), "2 minutes ago");
assert_eq!(relative_time_secs(3_600), "1 hours ago");
assert_eq!(relative_time_secs(7_200), "2 hours ago");
assert_eq!(relative_time_secs(DAY), "yesterday");
assert_eq!(relative_time_secs(2 * DAY - 1), "yesterday");
assert_eq!(relative_time_secs(2 * DAY), "2 days ago");
assert_eq!(relative_time_secs(6 * DAY), "6 days ago");
assert_eq!(relative_time_secs(7 * DAY), "1 week ago");
assert_eq!(relative_time_secs(14 * DAY), "2 weeks ago");
assert_eq!(relative_time_secs(30 * DAY), "1 month ago");
assert_eq!(relative_time_secs(60 * DAY), "2 months ago");
assert_eq!(relative_time_secs(365 * DAY), "1 year ago");
assert_eq!(relative_time_secs(730 * DAY), "2 years ago");
assert_eq!(relative_time_secs(200 * 365 * DAY), "200 years ago");
}
#[test]
fn relative_time_ported_ollama_humantime_edge_cases() {
assert_eq!(relative_time(None), "unknown");
let future = SystemTime::now() + std::time::Duration::from_secs(2 * 86_400);
assert_eq!(relative_time(Some(future)), "just now");
let past = SystemTime::now() - std::time::Duration::from_secs(2 * 86_400);
assert_eq!(relative_time(Some(past)), "2 days ago");
}
}