feat: Add site_path method to GlobalArgs

This commit is contained in:
Nathan McCarty 2023-03-16 14:16:06 -04:00
parent 715b578bb9
commit 617acba799
Signed by: thatonelutenist
GPG Key ID: D70DA3DD4D1E9F96
1 changed files with 50 additions and 1 deletions

View File

@ -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<PathBuf>,
}
impl GlobalArgs {
/// Get the site path folder
///
/// Defaults to the current working directory
pub fn site_path(&self) -> Result<PathBuf, CliError> {
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 {