From c9a8ef7db4d0f6f980f9a9a974fc49375b4d5cc0 Mon Sep 17 00:00:00 2001 From: Nadja Reitzenstein Date: Fri, 24 Jun 2022 15:14:38 +0200 Subject: [PATCH] Return a better error when --load is given a directory Closes: #55 --- bffhd/users/mod.rs | 35 +++++++++++++++++++++++++++++++++-- bin/bffhd/main.rs | 14 +++++--------- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/bffhd/users/mod.rs b/bffhd/users/mod.rs index 98d4b54..8471dbf 100644 --- a/bffhd/users/mod.rs +++ b/bffhd/users/mod.rs @@ -4,9 +4,11 @@ use rkyv::{Archive, Deserialize, Infallible, Serialize}; use std::collections::HashMap; use std::fmt::{Display, Formatter, Write}; -use miette::{Context, IntoDiagnostic}; +use clap::ArgMatches; +use miette::{Context, Diagnostic, IntoDiagnostic, SourceOffset, SourceSpan}; use std::path::Path; use std::sync::Arc; +use thiserror::Error; pub mod db; @@ -100,7 +102,36 @@ impl Users { self.userdb.delete(uid) } - pub fn load_file>(&self, path: P) -> miette::Result<()> { + pub fn load_file(&self, path_str: &str) -> miette::Result<()> { + let path: &Path = Path::new(path_str); + if path.is_dir() { + #[derive(Debug, Error, Diagnostic)] + #[error("load takes a file, not a directory")] + #[diagnostic( + code(load::file), + url("https://gitlab.com/fabinfra/fabaccess/bffh/-/issues/55") + )] + struct LoadIsDirError { + #[source_code] + src: String, + + #[label("path provided")] + dir_path: SourceSpan, + + #[help] + help: String, + } + + Err(LoadIsDirError { + src: format!("--load {}", path_str), + dir_path: (7, path_str.as_bytes().len()).into(), + help: format!( + "Provide a path to a file instead, e.g. {}/users.toml", + path_str + ), + })?; + return Ok(()); + } let f = std::fs::read(path).into_diagnostic()?; let map: HashMap = toml::from_slice(&f).into_diagnostic()?; diff --git a/bin/bffhd/main.rs b/bin/bffhd/main.rs index 27b9146..30ee060 100644 --- a/bin/bffhd/main.rs +++ b/bin/bffhd/main.rs @@ -122,15 +122,11 @@ fn main() -> miette::Result<()> { unimplemented!() } else if matches.is_present("load") { let bffh = Diflouroborane::new(config)?; - if let Err(error) = bffh.users.load_file(matches.value_of("load").unwrap()) { - tracing::error!( - "failed to load users from {}: {}", - matches.value_of("load").unwrap(), - error, - ); - } else { - tracing::info!("loaded users from {}", matches.value_of("load").unwrap()); - } + + bffh.users.load_file(matches.value_of("load").unwrap())?; + + tracing::info!("loaded users from {}", matches.value_of("load").unwrap()); + return Ok(()); } else { let keylog = matches.value_of("keylog");