From 617acba799dc77e71a46c98b998d106b1344f714 Mon Sep 17 00:00:00 2001 From: Nathan McCarty Date: Thu, 16 Mar 2023 14:16:06 -0400 Subject: [PATCH] feat: Add site_path method to GlobalArgs --- src/bin/cli/mod.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/bin/cli/mod.rs b/src/bin/cli/mod.rs index b8fb238..473d0f0 100644 --- a/src/bin/cli/mod.rs +++ b/src/bin/cli/mod.rs @@ -1,11 +1,36 @@ use clap::{Args, Parser, Subcommand}; use color_eyre::eyre::Result; -use std::path::PathBuf; +use snafu::{ensure, ResultExt, Snafu}; +use std::{env::current_dir, path::PathBuf}; mod init; pub use init::InitArgs; +/// Error encountered while parsing CLI +#[derive(Debug, Snafu)] +pub enum CliError { + /// Site path is not a directory + #[snafu(display("Path exists, but is not a directory: {:?}", path))] + NotADirectory { + /// The nonexistant path + path: PathBuf, + }, + /// Failed checking to see if a path exists + #[snafu(display("Failed checking for existance of path: {:?}", path))] + ExistanceCheck { + /// The nonexistant path + path: PathBuf, + /// The underlying error + source: std::io::Error, + }, + /// Failed getting the current directory + CurrentDirectory { + /// The underlying error + source: std::io::Error, + }, +} + /// Djot based static site generator #[derive(Parser, Debug)] #[command(author, version, about, long_about=None)] @@ -27,6 +52,30 @@ pub struct GlobalArgs { pub site_path: Option, } +impl GlobalArgs { + /// Get the site path folder + /// + /// Defaults to the current working directory + pub fn site_path(&self) -> Result { + if let Some(site_path) = self.site_path.as_ref() { + // If the path exists, make sure it is a directory + if site_path + .try_exists() + .context(ExistanceCheckSnafu { path: site_path })? + { + ensure!(site_path.is_dir(), NotADirectorySnafu { path: site_path }); + Ok(site_path.clone()) + } else { + // It doesn't exist yet, so go ahead and return + Ok(site_path.clone()) + } + } else { + let current_dir = current_dir().context(CurrentDirectorySnafu)?; + Ok(current_dir) + } + } +} + /// Command to run #[derive(Subcommand, Debug)] pub enum Command {