68 lines
2.0 KiB
Rust
68 lines
2.0 KiB
Rust
use std::fs::{create_dir, read_dir};
|
|
use std::io::Write;
|
|
use std::{fs::File, path::Path};
|
|
|
|
use clap::Args;
|
|
use lib_efo::epoch_struct::{ConfigWritable, EpochId, EpochInfo};
|
|
use lib_efo::{epoch_struct::EpochConfig, error::EpochError};
|
|
|
|
use crate::error::AppError;
|
|
|
|
#[derive(Args, Debug)]
|
|
pub struct InitCmd {
|
|
/// Force initialisation even if the directory isn't empty
|
|
#[arg(long)]
|
|
force: bool,
|
|
}
|
|
|
|
/// Init an empty repository
|
|
pub fn init(args: &InitCmd) -> Result<(), AppError> {
|
|
let root = Path::new(".");
|
|
if read_dir(root)?.count() != 0 {
|
|
Err(EpochError::FolderNotEmpty {
|
|
name: None,
|
|
show_label: None,
|
|
})?;
|
|
}
|
|
init_epoch(args)?;
|
|
let s = EpochConfig::empty().as_json("Creating config".into())?;
|
|
let path = root.join(".epoch");
|
|
// TODO: Just have a flag in save instad of this
|
|
if let Ok(mut f) = File::create_new(path) {
|
|
write!(f, "{}", s)?;
|
|
Ok(())
|
|
} else {
|
|
Err(EpochError::AlreadyInitialized {
|
|
advice: Some(
|
|
"You must remove the .epoch configuration file manually or pick another folder"
|
|
.to_string(),
|
|
),
|
|
})?
|
|
}
|
|
}
|
|
|
|
/// Tries to init the epoch 0
|
|
fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
|
|
let path = Path::new(".").join("0");
|
|
create_dir(&path).map_err(|_| EpochError::FolderNotEmpty {
|
|
name: Some(path.to_string_lossy().to_string()),
|
|
show_label: Some((0, 0)),
|
|
})?;
|
|
|
|
let json = EpochInfo::empty().as_json("Creating empty epoch file".into())?;
|
|
// TODO: Add a flag for creation only instead
|
|
if let Ok(mut f) = File::create_new("0/.epochfile") {
|
|
write!(f, "{}", json)?;
|
|
Ok(())
|
|
} else {
|
|
Err(EpochError::EpochInfoWrite {
|
|
id: EpochId::new(0),
|
|
path,
|
|
help: Some(
|
|
"The .epochinfo was already present in the folder this is likely an error and shouldn't have happen".to_owned(),
|
|
),
|
|
src: None,
|
|
})?
|
|
}
|
|
}
|