Adds some more epoch plumbing
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-11-27 01:33:25 +01:00
parent 3db8139b5f
commit 80026b502b
5 changed files with 137 additions and 86 deletions

View File

@ -27,11 +27,12 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> {
}
fn handle_diff() -> Result<(), AppError> {
// Blocker: There is actually no way to diff the world yet
todo!()
}
fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> {
// NOTE: `world.epoch_manager` already owns the schedule.
// Just needs for the epoch to implement lvels of displays trait: DisplayLevels
println!("Epoch log (most recent first):");
// println!(
// "#{} {} [{}] {}",
@ -41,21 +42,22 @@ fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> {
}
fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let target = match args.target {
cli_epoch::EpochIdentifier::Tag(ref s) => main_epoch
.tags
.get(s)
.copied()
.ok_or(EpochError::AmbiguousTag(s.to_string())),
cli_epoch::EpochIdentifier::Id(epoch_id) => main_epoch
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(epoch_id, ".".into())),
}?;
let target = main_epoch.get(&args.target)?;
// TODO: Check if the epoch is valid
// let b = main_epoch
// .list_existing_epochs
// .get(&target.to_string())
// .unwrap();
main_epoch
.try_load(&target)
.map_err(|_e| EpochError::EpochFolderMissing(target, ".".into()))?;
main_epoch.epoch_id = target;
println!("Switched to epoch {:?}", target);
main_epoch.save("Saving modified config".into())?;
main_epoch.save(
"Saving modified config".into(),
lib_efo::epoch_struct::SaveMode::Erase,
)?;
Ok(())
}

View File

@ -1,10 +1,5 @@
use clap::{Args, Subcommand, error::ErrorKind};
use serde::Deserialize;
use serde::Serialize;
use std::str::FromStr;
use lib_efo::epoch_struct::EpochId;
use clap::{Args, Subcommand};
use lib_efo::epoch_struct::EpochIdentifier;
/// The outer clap entry that the binary will dispatch to
#[derive(Subcommand, Debug)]
@ -65,43 +60,3 @@ pub struct Diff {
/// The end point to compute the differences, the current epoch by default
pub end: Option<EpochIdentifier>,
}
/// A flexible identifier for *any* epoch – the world may be
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
///
/// The enum is `untagged` so that serialising/deserialising does
/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
/// Instead the JSON representation is exactly the inner value:
/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON
pub enum EpochIdentifier {
/// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
Tag(String),
/// The raw numeric identifier of the epoch.
Id(EpochId),
}
impl FromStr for EpochIdentifier {
type Err = clap::Error; // any `std::error::Error` works
/// Try to parse either a decimal number (-> `Id`) or any non‑empty
/// string (-> `Tag`).
///
/// Errors are converted to a Clap error so that the CLI shows a
/// nice message.
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(num) = s.parse::<u64>() {
Ok(EpochIdentifier::Id(EpochId::new(num)))
} else if !s.is_empty() {
Ok(EpochIdentifier::Tag(s.to_owned()))
} else {
Err(clap::Error::raw(
ErrorKind::InvalidValue,
format!("{} is not a valid epoch id or tag", s),
))
}
}
}

View File

@ -1,6 +1,5 @@
use std::fs::{create_dir, read_dir};
use std::io::Write;
use std::{fs::File, path::Path};
use std::path::Path;
use clap::Args;
use lib_efo::epoch_struct::{ConfigWritable, EpochId, EpochInfo};
@ -18,6 +17,7 @@ pub struct InitCmd {
/// Init an empty repository
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let root = Path::new(".");
//TODO: This can be really deceiving when only .epoch is present
if read_dir(root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
name: None,
@ -25,20 +25,18 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
})?;
}
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 {
EpochConfig::empty()
.save(
"Creatig initial config".into(),
lib_efo::epoch_struct::SaveMode::DoNotErase,
)
.map_err(|_| EpochError::AlreadyInitialized {
advice: Some(
"You must remove the .epoch configuration file manually or pick another folder"
.to_string(),
),
})?
}
})?;
Ok(())
}
/// Tries to init the epoch 0
@ -49,19 +47,17 @@ fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
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 {
// let json = EpochInfo::empty().as_json("Creating empty epoch file".into())?;
EpochInfo::empty().save(
"Creating empty epoch file".into(),
lib_efo::epoch_struct::SaveMode::DoNotErase,
).map_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,
})?
}
})?;
Ok(())
}

View File

@ -74,7 +74,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
}
TopLevelCmd::Epoch(cmd) => {
commands::epoch::handle_cmd(cmd)?;
println!("Epoch nicely executed")
// println!("")
}
}
Ok(())

View File

@ -19,8 +19,10 @@
//! files, just like a git repository tracks its commits and
//! `HEAD` pointer.
use clap::error::ErrorKind;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::str::FromStr;
use std::{
collections::HashMap,
fmt,
@ -49,6 +51,7 @@ pub struct EpochConfig {
// /// Absolute path to `epoch/<epoch_id>/`.
// pub path: PathBuf,
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
// TODO: Only serialize epoch valid folders and map EpochId instead of Strings ?
#[serde(skip)]
pub list_existing_epochs: HashMap<String, Option<EpochInfo>>,
}
@ -67,6 +70,7 @@ impl EpochConfig {
pub fn new_from_path(_path: Option<&Path>) -> Result<Self, EpochError> {
let path = Path::new(".").join(".epoch");
if path.is_file() {
// TODO: write a trait for this
let config: EpochConfig =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
source: e,
@ -92,6 +96,47 @@ impl EpochConfig {
}
Ok(self)
}
/// Try to load into memory the given epoch id
pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
// TODO: Cleanse this abomination
let _ep = self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.copied()?;
let path = Path::new(&epoch_id.to_string()).join(".epochinfo");
let maybe_epoch: EpochInfo =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
let value = self
.list_existing_epochs
.get_mut(&epoch_id.to_string())
.unwrap();
*value = Some(maybe_epoch);
Ok(())
}
/// Get an identifier or returns None
pub fn get(&self, id: &EpochIdentifier) -> Result<EpochId, EpochError> {
match id {
EpochIdentifier::Tag(s) => self
.tags
.get(s)
.copied()
.ok_or(EpochError::AmbiguousTag(s.to_string())),
EpochIdentifier::Id(epoch_id) => self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.copied(),
}
}
}
/// Trait representing a serialisable / writable config
@ -109,9 +154,17 @@ pub trait ConfigWritable: Serialize {
}
/// Save the config into it's nominal path
fn save(&self, action: String) -> Result<(), EpochError> {
let mut f = File::create(self.save_path())
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
fn save(
&self,
action: String,
do_not_erase: SaveMode,
// advice: Option<String>,
) -> Result<(), EpochError> {
let mut f = match do_not_erase {
SaveMode::Erase => File::create(self.save_path()),
SaveMode::DoNotErase => File::create_new(self.save_path()),
}
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
write!(f, "{}", self.as_json(action)?).map_err(EpochError::ConfigWrite)?;
Ok(())
}
@ -148,6 +201,11 @@ pub struct EpochInfo {
pub summary: Option<String>,
}
pub enum SaveMode {
DoNotErase,
Erase,
}
impl EpochInfo {
pub fn empty() -> Self {
Self {
@ -199,3 +257,43 @@ impl ConfigWritable for EpochInfo {
format!("{}/.epochinfo", self.epoch_id)
}
}
/// A flexible identifier for *any* epoch – the world may be
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
///
/// The enum is `untagged` so that serialising/deserialising does
/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
/// Instead the JSON representation is exactly the inner value:
/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON
pub enum EpochIdentifier {
/// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
Tag(String),
/// The raw numeric identifier of the epoch.
Id(EpochId),
}
impl FromStr for EpochIdentifier {
type Err = clap::Error; // any `std::error::Error` works
/// Try to parse either a decimal number (-> `Id`) or any non‑empty
/// string (-> `Tag`).
///
/// Errors are converted to a Clap error so that the CLI shows a
/// nice message.
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(num) = s.parse::<u64>() {
Ok(EpochIdentifier::Id(EpochId::new(num)))
} else if !s.is_empty() {
Ok(EpochIdentifier::Tag(s.to_owned()))
} else {
Err(clap::Error::raw(
ErrorKind::InvalidValue,
format!("{} is not a valid epoch id or tag", s),
))
}
}
}