add:add command + add existing

This commit is contained in:
kokopi-dev
2026-04-04 22:45:23 +09:00
parent 973356cda5
commit 69fa44b36a
19 changed files with 1088 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
use std::{fs, path::PathBuf};
use crate::{
config::{defaults::registry_file, types::{Registry, ScriptEntry}},
error::AppError,
};
pub struct RegistryService {
pub registry_path: PathBuf,
}
impl RegistryService {
pub fn new() -> Result<Self, AppError> {
Ok(Self {
registry_path: registry_file()?,
})
}
/// Creates an empty `registry.toml` if it does not already exist.
pub fn ensure_initialized(&self) -> Result<(), AppError> {
if !self.registry_path.exists() {
let empty = Registry::default();
let contents = toml::to_string_pretty(&empty)?;
fs::write(&self.registry_path, contents)?;
}
Ok(())
}
pub fn load(&self) -> Result<Registry, AppError> {
let contents = fs::read_to_string(&self.registry_path)?;
let registry = toml::from_str(&contents)?;
Ok(registry)
}
pub fn save(&self, registry: &Registry) -> Result<(), AppError> {
let contents = toml::to_string_pretty(registry)?;
fs::write(&self.registry_path, contents)?;
Ok(())
}
/// Appends a new entry and persists the registry.
pub fn add(&self, entry: ScriptEntry) -> Result<(), AppError> {
let mut registry = self.load()?;
registry.scripts.push(entry);
self.save(&registry)
}
/// Returns true if a script with the given name is already registered.
pub fn name_exists(&self, name: &str) -> Result<bool, AppError> {
let registry = self.load()?;
Ok(registry.scripts.iter().any(|s| s.name == name))
}
}