From f5680d46900f9f0a93506d1a15edd29ff94d5708 Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Sun, 31 Dec 2023 11:39:11 +0000 Subject: [PATCH] Initial command-line parser. Allows '-c some_directory' to specify a non-default config dir. --- Cargo.toml | 1 + src/config.rs | 6 ++++++ src/main.rs | 26 +++++++++++++++++++++++--- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 44f2525..c425f21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] chrono = { version = "0.4.31", features = ["serde"] } +clap = { version = "4.4.12", features = ["derive"] } crossterm = "0.27.0" html2text = { version = "0.9.2", features = ["css"] } itertools = "0.12.0" diff --git a/src/config.rs b/src/config.rs index 549ae0d..70e1ab4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,6 +33,12 @@ impl ConfigLocation { }) } + pub fn from_pathbuf(dir: PathBuf) -> Self { + ConfigLocation { + dir: dir, + } + } + pub fn get_path(&self, leaf: &str) -> PathBuf { self.dir.join(leaf) } diff --git a/src/main.rs b/src/main.rs index 4a2cfd8..f4d891c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,20 @@ +use clap::Parser; use std::fmt::Display; use std::process::ExitCode; use mastodonochrome::config::{ConfigLocation, ConfigError}; use mastodonochrome::tui::{Tui, TuiError}; +#[derive(Parser, Debug)] +struct Args { + /// Directory containing configuration files. + #[arg(short, long)] + config: Option, +} + #[derive(Debug)] pub struct TopLevelError { + prefix: String, message: String, } @@ -13,15 +22,18 @@ impl Display for TopLevelError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - write!(f, "mastodonochrome: error: {}", self.message) + write!(f, "mastodonochrome: {}{}", self.prefix, self.message) } } -trait TopLevelErrorCandidate: Display {} +trait TopLevelErrorCandidate: Display { + fn get_prefix() -> String { "error: ".to_owned() } +} impl From for TopLevelError { fn from(err: E) -> Self { TopLevelError { + prefix: E::get_prefix(), message: err.to_string(), } } @@ -29,9 +41,17 @@ impl From for TopLevelError { impl TopLevelErrorCandidate for ConfigError {} impl TopLevelErrorCandidate for TuiError {} +impl TopLevelErrorCandidate for clap::error::Error { + // clap prints its own "error: " + fn get_prefix() -> String { "".to_owned() } +} fn main_inner() -> Result<(), TopLevelError> { - let cfgloc = ConfigLocation::default()?; + let cli = Args::try_parse()?; + let cfgloc = match cli.config { + None => ConfigLocation::default()?, + Some(dir) => ConfigLocation::from_pathbuf(dir), + }; Tui::run(&cfgloc)?; Ok(()) } -- 2.30.2