epoch_forge/bin_efo/src/commands/init.rs

83 lines
2.4 KiB
Rust

//! # `init` module
//!
//! Provides the implementation of the `init` sub-command for the
//! command-line interface. The sub-command creates an empty
//! repository, writes the default configuration (`.epoch`),
//! and sets up the first epoch (epoch 0).
//!
//! The main public API consists of:
//!
//! * `InitCmd` - a struct containing the command-line arguments.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use clap::Args;
use lib_efo::{
epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable},
error::EpochError,
};
use std::fs::read_dir;
use crate::{
error::AppError,
success::{SuccessMessages, display_success},
};
#[derive(Args, Debug)]
/// Arguments for the `init` subcommand.
///
/// The `--force` flag forces initialisation even when the target
/// directory already contains files.
pub struct InitCmd {
/// Force initialisation even if the directory isn't empty
#[arg(long)]
force: bool,
}
/// Initialise an empty repository.
///
/// Creates the default `EpochConfig`, verifies that the target directory
/// is empty, and writes the initial configuration and epoch data.
//TODO[5]: Upholster the logic behind force and empty detection
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let epoch_config = EpochConfig::default();
let root = epoch_config.save_folder();
if read_dir(root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
name: None,
show_label: None,
})?;
}
init_epoch(args)?;
epoch_config
.save_with_context(
"Creatig initial config",
&lib_efo::epoch::SaveMode::DoNotErase,
)
.map_err(|_| EpochError::AlreadyInitialized {
advice: Some(
"You must remove the .epoch configuration file manually or pick another folder"
.to_string(),
),
})?;
display_success(&SuccessMessages::FolderInitializedSuccessfully("."));
Ok(())
}
/// Helper that creates the initial epoch (epoch 0).
///
/// This function is not part of the public API; it is kept internal
/// to `init`. It creates an empty `EpochInfo`, crea
fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
let empty = EpochInfo::default();
_ = empty.create_subfolders();
empty.save_with_context(
"Creating empty epoch file 0",
&lib_efo::epoch::SaveMode::DoNotErase,
)?;
Ok(())
}