ghee 0.6.1

That thin layer of data change management over the filesystem
Documentation
use std::path::PathBuf;

use anyhow::Result;
use ghee_lang::Key;
use thiserror::Error;

use crate::{set_table_info, table_info, GheeErr, TableInfo};

#[derive(Error, Debug)]
pub enum TableInitErr {
    #[error("Table is already initialized")]
    AlreadyInitialized,
}

/**
 * Initialize the directory `dir` as a table with primary key `key`.
 */
pub fn init(dir: &PathBuf, key: &Key, verbose: bool) -> Result<()> {
    if key.is_empty() {
        return Err(GheeErr::WontInitializeToEmptyKey.into());
    }

    let prior_info = table_info(&dir)?;

    if prior_info.is_none() {
        let info = TableInfo::new(key.clone(), dir.clone());
        set_table_info(&dir, &info)?;
        if verbose {
            print!("Initialized table {} with key:", dir.display());
            for k in key.iter() {
                print!(" {}", k);
            }
            println!();
        }
        Ok(())
    } else {
        Err(TableInitErr::AlreadyInitialized.into())
    }
}

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

    use crate::{table_info, test_support::TempDirAuto};

    use super::init;

    #[test]
    fn test_init() {
        let dir = TempDirAuto::new("ghee-test-init");
        init(&dir, &Key::from(vec!["user.ghee.test.init"]), false).unwrap();

        let info = table_info(dir).unwrap().unwrap();

        assert_eq!(info.key().len(), 1);

        assert_eq!(
            info.key()[0],
            parse_xattr(b"user.ghee.test.init").unwrap().1
        );
    }
}