add:add command + add existing
This commit is contained in:
53
src/services/registry_service.rs
Normal file
53
src/services/registry_service.rs
Normal 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(®istry)
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user