Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(console): Support config file #320

Merged
merged 20 commits into from
Apr 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions tokio-console/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ h2 = "0.3"
regex = "1.5"
once_cell = "1.8"
humantime = "2.1.0"
serde = { version = "1", features = ["derive"] }
toml = "0.5"
dirs = "4"
187 changes: 176 additions & 11 deletions tokio-console/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use crate::view::Palette;
use clap::{ArgGroup, Parser as Clap, ValueHint};
use color_eyre::eyre::WrapErr;
use serde::Deserialize;
use std::fs;
use std::ops::Not;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use std::time::Duration;
Expand Down Expand Up @@ -71,15 +76,15 @@ struct RetainFor(Option<Duration>);
pub struct ViewOptions {
/// Disable ANSI colors entirely.
#[clap(name = "no-colors", long = "no-colors")]
no_colors: bool,
no_colors: Option<bool>,

/// Overrides the terminal's default language.
#[clap(long = "lang", env = "LANG", default_value = "en_us.UTF-8")]
lang: String,
#[clap(long = "lang", env = "LANG")]
lang: Option<String>,

/// Explicitly use only ASCII characters.
#[clap(long = "ascii-only")]
ascii_only: bool,
ascii_only: Option<bool>,

/// Overrides the value of the `COLORTERM` environment variable.
///
Expand Down Expand Up @@ -107,20 +112,62 @@ pub struct ViewOptions {
}

/// Toggles on and off color coding for individual UI elements.
#[derive(Clap, Debug, Copy, Clone)]
#[derive(Clap, Debug, Copy, Clone, Deserialize)]
pub struct ColorToggles {
/// Disable color-coding for duration units.
#[clap(long = "no-duration-colors", parse(from_flag = std::ops::Not::not), group = "colors")]
pub(crate) color_durations: bool,
#[clap(long = "no-duration-colors", group = "colors")]
#[serde(rename = "durations")]
color_durations: Option<bool>,

/// Disable color-coding for terminated tasks.
#[clap(long = "no-terminated-colors", parse(from_flag = std::ops::Not::not), group = "colors")]
pub(crate) color_terminated: bool,
#[clap(long = "no-terminated-colors", group = "colors")]
#[serde(rename = "terminated")]
color_terminated: Option<bool>,
}

/// A sturct used to parse the toml config file
#[derive(Debug, Clone, Deserialize)]
struct ConfigFile {
charset: Option<CharsetConfig>,
colors: Option<ColorsConfig>,
}

#[derive(Debug, Clone, Deserialize)]
struct CharsetConfig {
lang: Option<String>,
ascii_only: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
struct ColorsConfig {
enabled: Option<bool>,
truecolor: Option<bool>,
palette: Option<Palette>,
enable: Option<ColorToggles>,
}

// === impl Config ===

impl Config {
/// Parse from config files and command line options.
pub fn parse() -> color_eyre::Result<Self> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one last naming nit, take it or leave it: I'm not the biggest fan of calling this parse, as it conflicts with the Clap::parse implementation, which is a bit confusing. but, I can't immediately think of a better name for it, so 🤷‍♀️

let home = ViewOptions::from_config(ConfigPath::Home)?;
let current = ViewOptions::from_config(ConfigPath::Current)?;
let base = match (home, current) {
(None, None) => None,
(Some(home), None) => Some(home),
(None, Some(current)) => Some(current),
(Some(home), Some(current)) => Some(home.merge_with(current)),
};
let mut config = <Self as Clap>::parse();
let view_options = match base {
None => config.view_options,
Some(base) => base.merge_with(config.view_options),
};
config.view_options = view_options;
Ok(config)
}

pub fn trace_init(&mut self) -> color_eyre::Result<()> {
let filter = std::mem::take(&mut self.env_filter);
use tracing_subscriber::prelude::*;
Expand Down Expand Up @@ -167,7 +214,10 @@ impl Config {

impl ViewOptions {
pub fn is_utf8(&self) -> bool {
self.lang.ends_with("UTF-8") && !self.ascii_only
if !self.ascii_only.unwrap_or(true) {
return false;
}
self.lang.as_deref().unwrap_or_default().ends_with("UTF-8")
}

/// Determines the color palette to use.
Expand All @@ -179,7 +229,7 @@ impl ViewOptions {
/// - Checking the `terminfo` database via `tput`
pub(crate) fn determine_palette(&self) -> Palette {
// Did the user explicitly disable colors?
if self.no_colors {
if self.no_colors.unwrap_or(true) {
tracing::debug!("colors explicitly disabled by `--no-colors`");
return Palette::NoColors;
}
Expand Down Expand Up @@ -219,6 +269,31 @@ impl ViewOptions {
pub(crate) fn toggles(&self) -> ColorToggles {
self.toggles
}

fn from_config(path: ConfigPath) -> color_eyre::Result<Option<Self>> {
let options = ConfigFile::from_config(path)?.map(|config| config.into_view_options());
Ok(options)
}

fn merge_with(self, command_line: ViewOptions) -> Self {
Self {
no_colors: command_line.no_colors.or(self.no_colors),
lang: command_line.lang.or(self.lang),
ascii_only: command_line.ascii_only.or(self.ascii_only),
truecolor: command_line.truecolor.or(self.truecolor),
palette: command_line.palette.or(self.palette),
toggles: ColorToggles {
color_durations: command_line
.toggles
.color_durations
.or(self.toggles.color_durations),
color_terminated: command_line
.toggles
.color_terminated
.or(self.toggles.color_terminated),
},
}
}
}

fn parse_true_color(s: &str) -> bool {
Expand All @@ -238,3 +313,93 @@ impl FromStr for RetainFor {
}
}
}

// === impl ColorToggles ===

impl ColorToggles {
/// Return true when disabling color-coding for duration units.
pub fn color_durations(&self) -> bool {
self.color_durations.map(Not::not).unwrap_or(true)
}

/// Return true when disabling color-coding for terminated tasks.
pub fn color_terminated(&self) -> bool {
self.color_durations.map(Not::not).unwrap_or(true)
}
}

// === impl ColorToggles ===

impl ConfigFile {
fn from_config(path: ConfigPath) -> color_eyre::Result<Option<Self>> {
let config = path
.into_path()
.and_then(|path| fs::read_to_string(path).ok())
.map(|raw| toml::from_str::<ConfigFile>(&raw))
.transpose()
.wrap_err_with(|| {
format!(
"failed to parse {}",
path.into_path().unwrap_or_default().display()
)
})?;
Ok(config)
}

fn into_view_options(self) -> ViewOptions {
ViewOptions {
no_colors: self.no_colors(),
lang: self.charset.as_ref().and_then(|config| config.lang.clone()),
ascii_only: self.charset.as_ref().and_then(|config| config.ascii_only),
truecolor: self.colors.as_ref().and_then(|config| config.truecolor),
palette: self.colors.as_ref().and_then(|config| config.palette),
toggles: ColorToggles {
color_durations: self.color_durations(),
color_terminated: self.color_terminated(),
},
}
}

fn no_colors(&self) -> Option<bool> {
self.colors
.as_ref()
.and_then(|config| config.enabled.map(Not::not))
}

fn color_durations(&self) -> Option<bool> {
self.colors
.as_ref()
.and_then(|config| config.enable.map(|toggles| toggles.color_durations()))
}

fn color_terminated(&self) -> Option<bool> {
self.colors
.as_ref()
.and_then(|config| config.enable.map(|toggles| toggles.color_terminated()))
}
}

#[derive(Debug, Clone, Copy)]
enum ConfigPath {
Home,
Current,
}

impl ConfigPath {
fn into_path(self) -> Option<PathBuf> {
match self {
Self::Home => {
let mut path = dirs::config_dir();
if let Some(path) = path.as_mut() {
path.push("tokio-console/console.toml");
}
path
}
Self::Current => {
let mut path = PathBuf::new();
path.push("./console.toml");
Some(path)
}
}
}
}
3 changes: 1 addition & 2 deletions tokio-console/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use color_eyre::{eyre::eyre, Help, SectionExt};
use console_api::tasks::TaskDetails;
use state::State;

use clap::Parser as Clap;
use futures::stream::StreamExt;
use tokio::sync::{mpsc, watch};
use tui::{
Expand All @@ -26,7 +25,7 @@ mod warnings;

#[tokio::main]
async fn main() -> color_eyre::Result<()> {
let mut args = config::Config::parse();
let mut args = config::Config::parse()?;
let retain_for = args.retain_for();
args.trace_init()?;
tracing::debug!(?args.target_addr, ?args.view_options);
Expand Down
Loading