style: 💄 improve code formatting

This commit is contained in:
Lucas Colombo 2024-03-31 01:32:13 -03:00
parent 30f87f9626
commit 7d79868eb4
Signed by: lucas
GPG Key ID: EF34786CFEFFAE35
10 changed files with 124 additions and 56 deletions

View File

@ -1,6 +1,4 @@
use log::Level; use {log::Level, lool::logger::ConsoleLogger};
use lool::logger::ConsoleLogger;
fn main() { fn main() {
ConsoleLogger::default_setup(Level::Trace, "test").unwrap(); ConsoleLogger::default_setup(Level::Trace, "test").unwrap();
@ -9,4 +7,4 @@ fn main() {
log::error!("log line"); log::error!("log line");
log::debug!("log line"); log::debug!("log line");
log::trace!("log line"); log::trace!("log line");
} }

View File

@ -1,5 +1,7 @@
use eyre::{set_hook, DefaultHandler, Result}; use {
use lool::cli::stylize::{stylize, Stylize}; eyre::{set_hook, DefaultHandler, Result},
lool::cli::stylize::{stylize, Stylize},
};
fn setup_eyre() { fn setup_eyre() {
let _ = set_hook(Box::new(DefaultHandler::default_with)); let _ = set_hook(Box::new(DefaultHandler::default_with));
@ -12,7 +14,10 @@ fn main() -> Result<()> {
let alt_red_bold = stylize(stylize("alt [red+bold]", "red"), "+bold"); let alt_red_bold = stylize(stylize("alt [red+bold]", "red"), "+bold");
let red_bold_italic = stylize("[red+bold|italic]", "red+bold|italic"); let red_bold_italic = stylize("[red+bold|italic]", "red+bold|italic");
let alt_red_bold_italic = stylize(stylize(stylize("alt [red+bold|italic]", "red"), "+bold"), "+italic"); let alt_red_bold_italic = stylize(
stylize(stylize("alt [red+bold|italic]", "red"), "+bold"),
"+italic",
);
let red_on_blue = stylize("[white on blue]", "white on blue"); let red_on_blue = stylize("[white on blue]", "white on blue");
let rgb = stylize("[#3a95ef]", "#3a95ef"); let rgb = stylize("[#3a95ef]", "#3a95ef");
@ -31,13 +36,16 @@ fn main() -> Result<()> {
println!("pre {} post", "[green]".stl("green").stl("+bold")); println!("pre {} post", "[green]".stl("green").stl("+bold"));
println!("pre {} post", "[green+bold]".stl("green+bold")); println!("pre {} post", "[green+bold]".stl("green+bold"));
println!("pre {} post", "[.blue()]".blue()); println!("pre {} post", "[.blue()]".blue());
println!("pre {} post", "[.blue().bold()]".blue().bold()); println!("pre {} post", "[.blue().bold()]".blue().bold());
println!("pre {} post", "[.blue().on_red().bold()]".blue().on_red().bold()); println!(
"pre {} post",
"[.blue().on_red().bold()]".blue().on_red().bold()
);
println!("pre {} post", "[.dim()]".dim()); println!("pre {} post", "[.dim()]".dim());
println!("pre {} post", "[.blue().dim()]".blue().dim()); println!("pre {} post", "[.blue().dim()]".blue().dim());
Ok(()) Ok(())
} }

View File

@ -4,4 +4,4 @@ mod stylizer;
pub use stylizer::{stylize, Stylize}; pub use stylizer::{stylize, Stylize};
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;

View File

@ -1,6 +1,4 @@
use bitflags::bitflags; use {bitflags::bitflags, eyre::Context, std::borrow::Cow};
use eyre::Context;
use std::borrow::Cow;
/// The 8 standard colors. /// The 8 standard colors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]

View File

@ -1,10 +1,14 @@
use super::style::{Color, StyleAttributes as StyleBitflags}; use {
use eyre::Result; super::style::{Color, StyleAttributes as StyleBitflags},
eyre::Result,
};
pub mod instructions { pub mod instructions {
use super::{Result, StyleBitflags, Color}; use {
use bitflags::parser::{from_str, ParseError}; super::{Color, Result, StyleBitflags},
bitflags::parser::{from_str, ParseError},
};
pub struct StyledString { pub struct StyledString {
pub fg: Option<Color>, pub fg: Option<Color>,
pub bg: Option<Color>, pub bg: Option<Color>,
@ -27,8 +31,9 @@ pub mod instructions {
if instructions.starts_with("+") { if instructions.starts_with("+") {
// only attributes // only attributes
styled_string.attrs = attributes_from_str(instructions.trim_start_matches('+')).map_err(|e| eyre::eyre!(e))?; styled_string.attrs = attributes_from_str(instructions.trim_start_matches('+'))
return Ok(styled_string); .map_err(|e| eyre::eyre!(e))?;
return Ok(styled_string);
} }
// try to separate the colors from the attributes // try to separate the colors from the attributes
@ -71,20 +76,23 @@ pub mod instructions {
} }
2 => { 2 => {
// Both fg and bg colors are provided // Both fg and bg colors are provided
Ok((Some(Color::from_str(colors[0])?), Some(Color::from_str(colors[1])?))) Ok((
Some(Color::from_str(colors[0])?),
Some(Color::from_str(colors[1])?),
))
} }
_ => Err(eyre::eyre!("Invalid color instruction: {}", instruction)), _ => Err(eyre::eyre!("Invalid color instruction: {}", instruction)),
} }
} }
fn attributes_from_str (s: &str) -> Result<StyleBitflags, ParseError> { fn attributes_from_str(s: &str) -> Result<StyleBitflags, ParseError> {
from_str(s.to_uppercase().as_str()) from_str(s.to_uppercase().as_str())
} }
} }
/// 🧉 » Stylize Trait /// 🧉 » Stylize Trait
/// -- /// --
/// ///
/// `Trait` that extends `String` and `str` with the ability to stylize them /// `Trait` that extends `String` and `str` with the ability to stylize them
/// with ANSI color and attrs, using methods that return a new string with the given style. /// with ANSI color and attrs, using methods that return a new string with the given style.
pub trait Stylize { pub trait Stylize {
@ -149,9 +157,9 @@ impl Stylize for String {
/// 🧉 » stylize fn /// 🧉 » stylize fn
/// -- /// --
/// ///
/// Stylizes a string with optional ANSI color and attributes. /// Stylizes a string with optional ANSI color and attributes.
/// ///
pub fn stylize<S: AsRef<str>>(s: S, instructions: &str) -> String { pub fn stylize<S: AsRef<str>>(s: S, instructions: &str) -> String {
let styled_string = instructions::parse(instructions); let styled_string = instructions::parse(instructions);

View File

@ -1 +1 @@
mod stylizo; mod stylizo;

View File

@ -2,10 +2,11 @@
mod parse_instruction { mod parse_instruction {
use { use {
crate::cli::stylize::{ crate::cli::stylize::{
stylizer::instructions::{parse, parse_color_instruction}, style::{Color, StyleAttributes} style::{Color, StyleAttributes},
}, eyre::{set_hook, DefaultHandler} stylizer::instructions::{parse, parse_color_instruction},
},
eyre::{set_hook, DefaultHandler},
}; };
fn setup_eyre() { fn setup_eyre() {
let _ = set_hook(Box::new(DefaultHandler::default_with)); let _ = set_hook(Box::new(DefaultHandler::default_with));
@ -16,11 +17,29 @@ mod parse_instruction {
setup_eyre(); setup_eyre();
assert_eq!(parse_color_instruction("red")?, (Some(Color::Red), None)); assert_eq!(parse_color_instruction("red")?, (Some(Color::Red), None));
assert_eq!(parse_color_instruction("#FF0000")?, (Some(Color::TrueColor { r: 255, g: 0, b: 0 }), None)); assert_eq!(
assert_eq!(parse_color_instruction("on blue")?, (None, Some(Color::Blue))); parse_color_instruction("#FF0000")?,
assert_eq!(parse_color_instruction("on #0000FF")?, (None, Some(Color::TrueColor { r: 0, g: 0, b: 255 }))); (Some(Color::TrueColor { r: 255, g: 0, b: 0 }), None)
assert_eq!(parse_color_instruction("red on blue")?, (Some(Color::Red), Some(Color::Blue))); );
assert_eq!(parse_color_instruction("#FF0000 on #0000FF")?, (Some(Color::TrueColor { r: 255, g: 0, b: 0 }), Some(Color::TrueColor { r: 0, g: 0, b: 255 }))); assert_eq!(
parse_color_instruction("on blue")?,
(None, Some(Color::Blue))
);
assert_eq!(
parse_color_instruction("on #0000FF")?,
(None, Some(Color::TrueColor { r: 0, g: 0, b: 255 }))
);
assert_eq!(
parse_color_instruction("red on blue")?,
(Some(Color::Red), Some(Color::Blue))
);
assert_eq!(
parse_color_instruction("#FF0000 on #0000FF")?,
(
Some(Color::TrueColor { r: 255, g: 0, b: 0 }),
Some(Color::TrueColor { r: 0, g: 0, b: 255 })
)
);
assert!(parse_color_instruction("red on blue on green").is_err()); assert!(parse_color_instruction("red on blue on green").is_err());
assert!(parse_color_instruction("red on").is_err()); assert!(parse_color_instruction("red on").is_err());
assert!(parse_color_instruction("on").is_err()); assert!(parse_color_instruction("on").is_err());
@ -34,7 +53,6 @@ mod parse_instruction {
#[test] #[test]
fn test_parse_instructions() -> eyre::Result<()> { fn test_parse_instructions() -> eyre::Result<()> {
setup_eyre(); setup_eyre();
let styled_string = parse("red on blue")?; let styled_string = parse("red on blue")?;
@ -54,8 +72,14 @@ mod parse_instruction {
// ##RRGGBB // ##RRGGBB
let styled_string = parse("#FF0000 on #0000FF")?; let styled_string = parse("#FF0000 on #0000FF")?;
assert_eq!(styled_string.fg, Some(Color::TrueColor { r: 255, g: 0, b: 0 })); assert_eq!(
assert_eq!(styled_string.bg, Some(Color::TrueColor { r: 0, g: 0, b: 255 })); styled_string.fg,
Some(Color::TrueColor { r: 255, g: 0, b: 0 })
);
assert_eq!(
styled_string.bg,
Some(Color::TrueColor { r: 0, g: 0, b: 255 })
);
assert_eq!(styled_string.attrs, StyleAttributes::empty()); assert_eq!(styled_string.attrs, StyleAttributes::empty());
let styled_string = parse("red on blue+bold")?; let styled_string = parse("red on blue+bold")?;
@ -65,19 +89,34 @@ mod parse_instruction {
// ##RRGGBB // ##RRGGBB
let styled_string = parse("#FF0000 on #0000FF+bold")?; let styled_string = parse("#FF0000 on #0000FF+bold")?;
assert_eq!(styled_string.fg, Some(Color::TrueColor { r: 255, g: 0, b: 0 })); assert_eq!(
assert_eq!(styled_string.bg, Some(Color::TrueColor { r: 0, g: 0, b: 255 })); styled_string.fg,
Some(Color::TrueColor { r: 255, g: 0, b: 0 })
);
assert_eq!(
styled_string.bg,
Some(Color::TrueColor { r: 0, g: 0, b: 255 })
);
assert_eq!(styled_string.attrs, StyleAttributes::BOLD); assert_eq!(styled_string.attrs, StyleAttributes::BOLD);
let styled_string = parse("red on blue+bold|underline")?; let styled_string = parse("red on blue+bold|underline")?;
assert_eq!(styled_string.fg, Some(Color::Red)); assert_eq!(styled_string.fg, Some(Color::Red));
assert_eq!(styled_string.bg, Some(Color::Blue)); assert_eq!(styled_string.bg, Some(Color::Blue));
assert_eq!(styled_string.attrs, StyleAttributes::BOLD | StyleAttributes::UNDERLINE); assert_eq!(
styled_string.attrs,
StyleAttributes::BOLD | StyleAttributes::UNDERLINE
);
let styled_string = parse("red on #0000FF+bold|underline|italic")?; let styled_string = parse("red on #0000FF+bold|underline|italic")?;
assert_eq!(styled_string.fg, Some(Color::Red)); assert_eq!(styled_string.fg, Some(Color::Red));
assert_eq!(styled_string.bg, Some(Color::TrueColor { r: 0, g: 0, b: 255 })); assert_eq!(
assert_eq!(styled_string.attrs, StyleAttributes::BOLD | StyleAttributes::UNDERLINE | StyleAttributes::ITALIC); styled_string.bg,
Some(Color::TrueColor { r: 0, g: 0, b: 255 })
);
assert_eq!(
styled_string.attrs,
StyleAttributes::BOLD | StyleAttributes::UNDERLINE | StyleAttributes::ITALIC
);
let styled_string = parse("+bold")?; let styled_string = parse("+bold")?;
assert_eq!(styled_string.fg, None); assert_eq!(styled_string.fg, None);
@ -100,4 +139,4 @@ mod parse_instruction {
Ok(()) Ok(())
} }
} }

View File

@ -1,2 +1,2 @@
pub mod cli; pub mod cli;
pub mod logger; pub mod logger;

View File

@ -33,7 +33,15 @@ pub fn utc_current_time() -> String {
let minutes = (secs / 60) % 60; let minutes = (secs / 60) % 60;
let seconds = secs % 60; let seconds = secs % 60;
format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", years, month + 1, day, hours, minutes, seconds) format!(
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
years,
month + 1,
day,
hours,
minutes,
seconds
)
} }
Err(_) => "0".to_string(), Err(_) => "0".to_string(),
} }
@ -57,4 +65,3 @@ fn days_to_date(days: u64, leap: bool) -> (u64, u64) {
(month, days_left + 1) // Adding 1 to day to make it 1-based (month, days_left + 1) // Adding 1 to day to make it 1-based
} }

View File

@ -1,7 +1,9 @@
pub mod datetime; pub mod datetime;
use eyre::{eyre, Result}; use {
use log::{Level, Metadata, Record}; eyre::{eyre, Result},
log::{Level, Metadata, Record},
};
const RESET: &str = "\x1b[0m"; const RESET: &str = "\x1b[0m";
@ -17,8 +19,8 @@ impl StyledRecord {
fn from(record: &Record, get_time: fn() -> String) -> Self { fn from(record: &Record, get_time: fn() -> String) -> Self {
let ansi_style_level = match record.level() { let ansi_style_level = match record.level() {
Level::Error => "\x1b[31m", // red Level::Error => "\x1b[31m", // red
Level::Warn => "\x1b[33m", // yellow Level::Warn => "\x1b[33m", // yellow
Level::Info => "\x1b[32m", // green Level::Info => "\x1b[32m", // green
Level::Debug => "\x1b[95m", // magenta Level::Debug => "\x1b[95m", // magenta
Level::Trace => "\x1b[34m", // blue Level::Trace => "\x1b[34m", // blue
}; };
@ -34,28 +36,36 @@ impl StyledRecord {
Self { Self {
level: format!("{}{:<5}{}", ansi_style_level, record.level(), RESET), level: format!("{}{:<5}{}", ansi_style_level, record.level(), RESET),
message: format!("{}", record.args()), message: format!("{}", record.args()),
file: format!("{}{}{}", file_ansi_color, record.file().unwrap_or("unknown"), RESET), file: format!(
"{}{}{}",
file_ansi_color,
record.file().unwrap_or("unknown"),
RESET
),
line: format!("{}{}{}", line_ansi_color, record.line().unwrap_or(0), RESET), line: format!("{}{}{}", line_ansi_color, record.line().unwrap_or(0), RESET),
time, time,
} }
} }
} }
pub struct ConsoleLogger<'a>{ pub struct ConsoleLogger<'a> {
context: &'a str, context: &'a str,
time_fn: fn() -> String, time_fn: fn() -> String,
} }
impl<'a> ConsoleLogger<'a> { impl<'a> ConsoleLogger<'a> {
pub fn default_setup(max_level: Level, context: &'static str) -> Result<()> { pub fn default_setup(max_level: Level, context: &'static str) -> Result<()> {
let logger = Box::new(ConsoleLogger { context, time_fn: datetime::utc_current_time}); let logger = Box::new(ConsoleLogger {
context,
time_fn: datetime::utc_current_time,
});
log::set_logger(Box::leak(logger) as &'static ConsoleLogger) log::set_logger(Box::leak(logger) as &'static ConsoleLogger)
.map(|()| log::set_max_level(max_level.to_level_filter())) .map(|()| log::set_max_level(max_level.to_level_filter()))
.map_err(|err| eyre!("failed to set logger: {}", err)) .map_err(|err| eyre!("failed to set logger: {}", err))
} }
pub fn setup(max_level: Level, context: &'static str, time_fn: fn() -> String) -> Result<()> { pub fn setup(max_level: Level, context: &'static str, time_fn: fn() -> String) -> Result<()> {
let logger = Box::new(ConsoleLogger { context, time_fn}); let logger = Box::new(ConsoleLogger { context, time_fn });
log::set_logger(Box::leak(logger) as &'static ConsoleLogger) log::set_logger(Box::leak(logger) as &'static ConsoleLogger)
.map(|()| log::set_max_level(max_level.to_level_filter())) .map(|()| log::set_max_level(max_level.to_level_filter()))
.map_err(|err| eyre!("failed to set logger: {}", err)) .map_err(|err| eyre!("failed to set logger: {}", err))