navid/veins / eb4f3d934fd0144c58b4695b6e7abf7fb638b384d96c5e06a1d58231e91071f6 / veinsrs/src/cli/output.rs

output.rs

← veinsrs/src/cli · 2530 bytes · raw · download

use crate::core;

pub fn enabled() -> bool {
    core::colors_enabled()
}

fn style(text: &str, code: &str) -> String {
    if enabled() {
        format!("\x1b[{code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

pub fn print_styled(code: &str, text: &str) {
    if enabled() {
        print!("\x1b[{code}m{text}\x1b[0m");
    } else {
        print!("{text}");
    }
}

pub fn error_prefix() {
    if enabled() {
        print!("\x1b[1m\x1b[31merror\x1b[0m: ");
    } else {
        print!("error: ");
    }
}

pub fn warning_prefix() {
    if enabled() {
        print!("\x1b[1m\x1b[33mwarning\x1b[0m: ");
    } else {
        print!("warning: ");
    }
}

pub fn info_prefix() {
    print!("{}: ", style("info", "36"));
}

pub fn red(text: &str) -> String {
    style(text, "31")
}

pub fn green(text: &str) -> String {
    style(text, "32")
}

pub fn cyan(text: &str) -> String {
    style(text, "36")
}

pub fn dim(text: &str) -> String {
    style(text, "2")
}

pub fn bold_cyan(text: &str) -> String {
    if enabled() {
        format!("\x1b[1m\x1b[96m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

pub fn print_cell(text: &str, width: usize) {
    print!("{text}");
    for _ in text.chars().count()..width {
        print!(" ");
    }
}

pub fn open_repo() -> Option<std::path::PathBuf> {
    crate::store::layout::discover(std::path::Path::new(".")).ok()
}

pub fn status_path(path: &[u8], cwd_rel: &str) -> String {
    let path = String::from_utf8_lossy(path);
    if cwd_rel.is_empty() {
        return path.into_owned();
    }
    let current: Vec<&str> = cwd_rel
        .split('/')
        .filter(|value| !value.is_empty())
        .collect();
    let target: Vec<&str> = path.split('/').collect();
    let mut common = 0;
    while common < current.len() && common < target.len() && current[common] == target[common] {
        common += 1;
    }
    let mut output = String::new();
    for _ in common..current.len() {
        output.push_str("../");
    }
    output.push_str(&target[common..].join("/"));
    output
}

pub fn join_args(parts: &[String]) -> String {
    parts.join(" ")
}

pub fn message_is_blank(parts: &[String]) -> bool {
    parts
        .iter()
        .flat_map(|part| part.bytes())
        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
}

pub fn pager_output(root: &std::path::Path, text: &str, pager: bool) {
    if pager && core::stdout_is_terminal() {
        core::run_pager(root, text);
    } else {
        print!("{text}");
    }
}