chiark / gitweb /
Initial command-line parser.
authorSimon Tatham <anakin@pobox.com>
Sun, 31 Dec 2023 11:39:11 +0000 (11:39 +0000)
committerSimon Tatham <anakin@pobox.com>
Sun, 31 Dec 2023 13:05:07 +0000 (13:05 +0000)
Allows '-c some_directory' to specify a non-default config dir.

Cargo.toml
src/config.rs
src/main.rs

index 44f2525ea02211f1629bf9b4fcfd82b79ed698b7..c425f21135cbb41488de9a86cdff126d26fc131c 100644 (file)
@@ -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"
index 549ae0d2cacc03e4956940682a687406981c6196..70e1ab44ae7cfb85e4411d54c5ee3fd62dac511d 100644 (file)
@@ -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)
     }
index 4a2cfd8806702bbfcf24173763e8bccbf975c40a..f4d891c6d1330c1a8d3b37321a05c92e5695489c 100644 (file)
@@ -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<std::path::PathBuf>,
+}
+
 #[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<E: TopLevelErrorCandidate> From<E> for TopLevelError {
     fn from(err: E) -> Self {
         TopLevelError {
+            prefix: E::get_prefix(),
             message: err.to_string(),
         }
     }
@@ -29,9 +41,17 @@ impl<E: TopLevelErrorCandidate> From<E> 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(())
 }