use std::io::IsTerminal;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rgb(pub u8, pub u8, pub u8);
pub mod palette {
use super::Rgb;
pub const PRIMARY: Rgb = Rgb(0x9E, 0xB3, 0xC2);
pub const SECONDARY: Rgb = Rgb(0x1C, 0x72, 0x93);
pub const DEEP: Rgb = Rgb(0x06, 0x5A, 0x82);
pub const NAVY: Rgb = Rgb(0x21, 0x29, 0x5C);
pub const ON_BADGE: Rgb = Rgb(0xF2, 0xF6, 0xF9);
pub const ACCENT: Rgb = Rgb(0x3D, 0xDC, 0x97);
pub const AMBER: Rgb = Rgb(0xE8, 0xA3, 0x3D);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorChoice {
#[default]
Auto,
Always,
Never,
}
impl ColorChoice {
pub fn parse(s: &str) -> Option<Self> {
match s {
"auto" => Some(ColorChoice::Auto),
"always" => Some(ColorChoice::Always),
"never" => Some(ColorChoice::Never),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Surroundings {
pub stdout_tty: bool,
pub stderr_tty: bool,
pub ci: bool,
pub no_color: bool,
pub dumb: bool,
pub unicode: bool,
}
impl Surroundings {
pub fn here() -> Self {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let stdout_tty = std::io::stdout().is_terminal();
let dumb = var("TERM").is_some_and(|t| t == "dumb");
Surroundings {
stdout_tty,
stderr_tty: std::io::stderr().is_terminal(),
ci: var("CI").is_some_and(|v| v != "false" && v != "0"),
no_color: var("NO_COLOR").is_some(),
dumb,
unicode: stdout_tty && !dumb && unicode_terminal(&var),
}
}
}
fn unicode_terminal(var: &dyn Fn(&str) -> Option<String>) -> bool {
if cfg!(windows) {
var("WT_SESSION").is_some() || var("TERM_PROGRAM").is_some() || var("ConEmuANSI").is_some()
} else {
["LC_ALL", "LC_CTYPE", "LANG"]
.iter()
.find_map(|name| var(name))
.is_some_and(|v| {
let v = v.to_ascii_lowercase();
v.contains("utf-8") || v.contains("utf8")
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
Human,
Json,
Protocol,
}
pub fn colour(choice: ColorChoice, channel: Channel, env: &Surroundings) -> bool {
if channel != Channel::Human {
return false;
}
match choice {
ColorChoice::Never => false,
ColorChoice::Always => true,
ColorChoice::Auto => env.stdout_tty && !env.ci && !env.no_color && !env.dumb,
}
}
pub fn motion(choice: ColorChoice, channel: Channel, env: &Surroundings) -> bool {
if channel != Channel::Human || !env.stderr_tty || env.dumb {
return false;
}
match choice {
ColorChoice::Never => false,
ColorChoice::Always => true,
ColorChoice::Auto => env.stdout_tty && !env.ci && !env.no_color,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Glyph {
Commit,
Lane,
JoinRight,
SplitRight,
Across,
Tee,
Cross,
Discarded,
Connected,
Waiting,
Added,
Removed,
Modified,
}
impl Glyph {
fn text(self, unicode: bool) -> &'static str {
match (self, unicode) {
(Glyph::Commit, true) => "●",
(Glyph::Commit, false) => "*",
(Glyph::Lane, true) => "│",
(Glyph::Lane, false) => "|",
(Glyph::JoinRight, true) => "╯",
(Glyph::JoinRight, false) => "/",
(Glyph::SplitRight, true) => "╮",
(Glyph::SplitRight, false) => "\\",
(Glyph::Across, true) => "─",
(Glyph::Across, false) => "-",
(Glyph::Tee, true) => "├",
(Glyph::Tee, false) => "|",
(Glyph::Cross, true) => "┼",
(Glyph::Cross, false) => "+",
(Glyph::Discarded, true) => "×",
(Glyph::Discarded, false) => "x",
(Glyph::Connected, true) => "●",
(Glyph::Connected, false) => "*",
(Glyph::Waiting, true) => "○",
(Glyph::Waiting, false) => "o",
(Glyph::Added, _) => "+",
(Glyph::Removed, _) => "-",
(Glyph::Modified, _) => "~",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Style {
pub colour: bool,
pub unicode: bool,
pub columns: Option<usize>,
}
impl Style {
pub const PLAIN: Style = Style {
colour: false,
unicode: false,
columns: None,
};
pub fn for_stdout(choice: ColorChoice, channel: Channel) -> Self {
let env = Surroundings::here();
let colour = colour(choice, channel, &env);
if colour {
let _ = anstyle_query::windows::enable_ansi_colors();
}
let columns = (channel == Channel::Human && env.stdout_tty)
.then(|| terminal_size::terminal_size().map(|(w, _)| usize::from(w.0)))
.flatten();
Style {
colour,
unicode: channel == Channel::Human && env.unicode,
columns,
}
}
pub fn glyph(&self, g: Glyph) -> &'static str {
g.text(self.unicode)
}
pub fn fg(&self, colour: Rgb, text: &str) -> String {
if !self.colour {
return text.to_owned();
}
let Rgb(r, g, b) = colour;
format!("\x1b[38;2;{r};{g};{b}m{text}\x1b[0m")
}
pub fn strong(&self, colour: Rgb, text: &str) -> String {
if !self.colour {
return text.to_owned();
}
let Rgb(r, g, b) = colour;
format!("\x1b[1;38;2;{r};{g};{b}m{text}\x1b[0m")
}
pub fn badge(&self, background: Rgb, text: &str) -> String {
if !self.colour {
return format!("[{text}]");
}
let Rgb(r, g, b) = background;
let Rgb(fr, fg, fb) = palette::ON_BADGE;
format!("\x1b[38;2;{fr};{fg};{fb};48;2;{r};{g};{b}m {text} \x1b[0m")
}
pub fn primary(&self, text: &str) -> String {
self.fg(palette::PRIMARY, text)
}
pub fn dim(&self, text: &str) -> String {
self.fg(palette::SECONDARY, text)
}
pub fn accent(&self, text: &str) -> String {
self.fg(palette::ACCENT, text)
}
pub fn warn(&self, text: &str) -> String {
self.fg(palette::AMBER, text)
}
}
static PREFERENCES: std::sync::OnceLock<(ColorChoice, Channel)> = std::sync::OnceLock::new();
pub fn set_preferences(choice: ColorChoice, channel: Channel) {
let _ = PREFERENCES.set((choice, channel));
}
pub fn preferences() -> (ColorChoice, Channel) {
PREFERENCES
.get()
.copied()
.unwrap_or((ColorChoice::Never, Channel::Protocol))
}
pub fn path(p: &std::path::Path) -> String {
let shown = p.display().to_string();
if cfg!(windows) {
shown.replace('/', "\\")
} else {
shown
}
}
#[derive(Debug)]
pub struct Spinner {
stop: Option<std::sync::mpsc::Sender<()>>,
thread: Option<std::thread::JoinHandle<()>>,
message: std::sync::Arc<std::sync::Mutex<String>>,
}
impl Spinner {
pub fn start(choice: ColorChoice, channel: Channel, message: &str) -> Spinner {
Spinner::begin(choice, channel, message, true)
}
pub fn quiet(message: &str) -> Spinner {
let (choice, channel) = preferences();
Spinner::begin(choice, channel, message, false)
}
fn begin(choice: ColorChoice, channel: Channel, message: &str, say_it: bool) -> Spinner {
let env = Surroundings::here();
let shared = std::sync::Arc::new(std::sync::Mutex::new(message.to_owned()));
let none = Spinner {
stop: None,
thread: None,
message: std::sync::Arc::clone(&shared),
};
if channel == Channel::Protocol {
return none;
}
if !motion(choice, channel, &env) {
if say_it {
eprintln!("memfork: {message}");
}
return none;
}
let frames: &[&str] = if env.unicode {
&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
} else {
&["|", "/", "-", "\\"]
};
let style = Style {
colour: colour(choice, channel, &env),
unicode: env.unicode,
columns: None,
};
let message = std::sync::Arc::clone(&shared);
let (tx, rx) = std::sync::mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
use std::io::Write as _;
let mut i = 0usize;
loop {
let frame = style.accent(frames[i % frames.len()]);
let text = message.lock().map(|m| m.clone()).unwrap_or_default();
let mut err = std::io::stderr().lock();
let _ = write!(err, "\r\x1b[2K{frame} {text}");
let _ = err.flush();
drop(err);
i += 1;
match rx.recv_timeout(std::time::Duration::from_millis(90)) {
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
_ => break,
}
}
let mut err = std::io::stderr().lock();
let _ = write!(err, "\r\x1b[2K");
let _ = err.flush();
});
Spinner {
stop: Some(tx),
thread: Some(thread),
message: shared,
}
}
pub fn update(&self, message: &str) {
if self.thread.is_some() {
if let Ok(mut current) = self.message.lock() {
*current = message.to_owned();
}
} else {
eprintln!("memfork: {message}");
}
}
}
impl Drop for Spinner {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn terminal() -> Surroundings {
Surroundings {
stdout_tty: true,
stderr_tty: true,
unicode: true,
..Surroundings::default()
}
}
#[test]
fn auto_colours_a_plain_terminal_and_nothing_else() {
let t = terminal();
assert!(colour(ColorChoice::Auto, Channel::Human, &t));
for env in [
Surroundings {
stdout_tty: false,
..t.clone()
},
Surroundings {
ci: true,
..t.clone()
},
Surroundings {
no_color: true,
..t.clone()
},
Surroundings {
dumb: true,
..t.clone()
},
] {
assert!(!colour(ColorChoice::Auto, Channel::Human, &env), "{env:?}");
}
}
#[test]
fn always_beats_the_environment_but_not_json_or_the_protocol() {
let hostile = Surroundings {
stdout_tty: false,
stderr_tty: false,
ci: true,
no_color: true,
dumb: false,
unicode: false,
};
assert!(colour(ColorChoice::Always, Channel::Human, &hostile));
assert!(!colour(ColorChoice::Always, Channel::Json, &terminal()));
assert!(!colour(ColorChoice::Always, Channel::Protocol, &terminal()));
assert!(!colour(ColorChoice::Never, Channel::Human, &terminal()));
}
#[test]
fn motion_needs_a_terminal_on_stderr_whatever_the_flag() {
let t = terminal();
assert!(motion(ColorChoice::Auto, Channel::Human, &t));
let piped = Surroundings {
stderr_tty: false,
..t.clone()
};
assert!(!motion(ColorChoice::Always, Channel::Human, &piped));
assert!(!motion(
ColorChoice::Auto,
Channel::Human,
&Surroundings {
ci: true,
..t.clone()
}
));
assert!(!motion(
ColorChoice::Auto,
Channel::Human,
&Surroundings {
no_color: true,
..t.clone()
}
));
assert!(!motion(ColorChoice::Always, Channel::Json, &t));
assert!(!motion(ColorChoice::Always, Channel::Protocol, &t));
}
#[test]
fn plain_output_carries_words_and_ascii_only() {
let s = Style::PLAIN;
assert_eq!(s.accent("forked"), "forked");
assert_eq!(s.badge(palette::DEEP, "main"), "[main]");
for g in [
Glyph::Commit,
Glyph::Lane,
Glyph::JoinRight,
Glyph::SplitRight,
Glyph::Across,
Glyph::Tee,
Glyph::Cross,
Glyph::Discarded,
Glyph::Connected,
Glyph::Waiting,
] {
assert!(s.glyph(g).is_ascii(), "{g:?}");
}
}
#[test]
fn coloured_output_is_24_bit_and_reset() {
let s = Style {
colour: true,
unicode: true,
columns: None,
};
let text = s.accent("ok");
assert!(text.starts_with("\x1b[38;2;61;220;151m"), "{text:?}");
assert!(text.ends_with("\x1b[0m"));
let badge = s.badge(palette::NAVY, "main");
assert!(badge.contains("48;2;33;41;92"), "{badge:?}");
}
#[test]
fn the_dark_blues_are_only_ever_backgrounds() {
let mut bad = Vec::new();
let mut stack = vec![std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src")];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).unwrap().flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
continue;
}
let text = std::fs::read_to_string(&path).unwrap_or_default();
for call in ["fg", "strong"] {
for name in ["DEEP", "NAVY"] {
let pattern = format!("{call}(palette::{name}");
if text.contains(&pattern) {
bad.push(format!("{}: {pattern}", path.display()));
}
}
}
}
}
assert!(bad.is_empty(), "dark blues used as text: {bad:?}");
}
}
#[cfg(test)]
mod path_tests {
#[test]
fn a_shown_path_uses_one_separator_on_windows_and_is_untouched_elsewhere() {
let mixed = std::path::Path::new(r"C:/Users/ada\AppData/Local");
let shown = super::path(mixed);
if cfg!(windows) {
assert_eq!(shown, r"C:\Users\ada\AppData\Local");
} else {
assert_eq!(shown, r"C:/Users/ada\AppData/Local");
}
assert_eq!(super::path(std::path::Path::new("plain")), "plain");
}
}