ghee 0.6.1

That thin layer of data change management over the filesystem
Documentation
use anyhow::Result;
use btrfsutil::subvolume::Subvolume;
use ghee_lang::Key;
use thiserror::Error;

use std::fs::{create_dir, create_dir_all};

use std::path::PathBuf;

use crate::GheeErr;

use super::init;

#[derive(Error, Debug)]
pub enum CreateErr {
    #[error("Directory {0} already exists")]
    DirAlreadyExists(PathBuf),

    #[error("IO error creating directory ")]
    IoError { path: PathBuf, err: std::io::Error },
}

/** Like `init`, but creates the directory first, or errors if one exists already */
pub fn create(dir: &PathBuf, key: &Key, verbose: bool) -> Result<()> {
    if dir.exists() {
        return Err(CreateErr::DirAlreadyExists(dir.clone()).into());
    }

    if key.is_empty() {
        return Err(GheeErr::WontInitializeToEmptyKey.into());
    }

    if let Some(parent) = dir.parent() {
        create_dir_all(parent).map_err(|err| CreateErr::IoError {
            path: dir.clone(),
            err,
        })?;
    }

    // Attempt to create a BTRFS subvolume for the table
    if Subvolume::create(dir.as_path(), None).is_ok() {
        // if verbose {
        //     println!("+Created as BTRFS subvolume");
        // }
    } else {
        create_dir(dir).map_err(|err| CreateErr::IoError {
            path: dir.clone(),
            err,
        })?;
    }

    init(dir, key, verbose)
}

#[cfg(test)]
mod test {
    use ghee_lang::Key;

    use crate::test_support::TempDirAuto;

    use super::create;

    #[test]
    pub fn test_create() {
        let key = Key::from_string("test1");

        let dir = TempDirAuto::new("ghee-test-create");

        let mut nonexistent = dir.clone();
        nonexistent.push("nonexistent");

        assert!(create(&nonexistent, &key, false).is_ok());

        let existent = TempDirAuto::new("ghee-test-create:existent");

        assert!(create(&existent, &key, false).is_err());
    }
}