mj 0.4.3

My Journal - personal tool to capture ideas, work with journals, notes and tasks in your favourite text $EDITOR.
Documentation
use clap::ArgMatches;
use crate::core::*;
use std::fs::create_dir_all;
use std::path::Path;

#[derive(Debug)]
pub struct InitArgs {
  pub path: String,
}

impl InitArgs {
  fn to_vault(&self, config: &Config) -> std::io::Result<Vault> {
    let path = std::fs::canonicalize(self.path.to_owned())?.into_os_string().into_string().unwrap();
    Ok(Vault::new(config, path))
  }
}

pub fn run(vault: &Vault, args: &InitArgs) -> Result<()> {
  preflight_check(args)?;
  bootstrap(vault, &args)
}

pub fn match_args(matches: &ArgMatches) -> Option<InitArgs> {
  if let Some(matches) = matches.subcommand_matches("init") {
    let input = matches.value_of("PATH").unwrap();
    return Some(InitArgs {
      path: input.to_owned(),
    });
  }
  None
}

fn preflight_check(args: &InitArgs) -> Result<()> {
  let path = args.path.to_owned();
  if !Path::new(&path).exists() {
    create_dir_all(&path)?;
  }
  Ok(())
}

fn bootstrap(vault: &Vault, args: &InitArgs) -> Result<()> {
  args.to_vault(&vault.config)?.bootstrap()
}