use std::path::Path;
use super::super::registry::{PluginRegistry, ToolPin};
use super::build::*;
use super::source::*;
use super::types::*;
pub async fn plan_install(
source: &PluginSource,
plugins_root: &Path,
) -> Result<InstallPlan, InstallError> {
let staging_dir = staging_dir_for(plugins_root);
std::fs::create_dir_all(&staging_dir).map_err(InstallError::Io)?;
match materialize(source, &staging_dir).await {
Ok(()) => {}
Err(e) => {
let _ = std::fs::remove_dir_all(&staging_dir);
return Err(e);
}
}
match build_plan(staging_dir, plugins_root) {
Ok(plan) => Ok(plan),
Err(e) => Err(e),
}
}
pub fn commit_install(
plan: &InstallPlan,
registry: &mut PluginRegistry,
) -> Result<InstalledPlugin, InstallError> {
if plan.plugin_root.exists() {
std::fs::remove_dir_all(&plan.plugin_root).map_err(InstallError::Io)?;
}
if let Some(parent) = plan.plugin_root.parent() {
std::fs::create_dir_all(parent).map_err(InstallError::Io)?;
}
std::fs::rename(&plan.staging.dir, &plan.plugin_root).map_err(InstallError::Io)?;
registry.insert(plan.pin.clone());
let registry_path = PluginRegistry::path_in(&plan.plugins_root);
registry
.save(®istry_path)
.map_err(InstallError::Registry)?;
let identity_keys = plan
.pin
.tools
.iter()
.flat_map(|t| match t {
ToolPin::Wasm { identity, .. } | ToolPin::Script { identity, .. } => {
vec![identity.clone()]
}
ToolPin::Mcp { label, .. } => vec![format!("plugin.{}.{label}", plan.pin.name)],
})
.collect();
Ok(InstalledPlugin {
pin: plan.pin.clone(),
plugin_dir: plan.plugin_root.clone(),
identity_keys,
})
}
pub fn remove_plugin(
plugins_root: &Path,
registry: &mut PluginRegistry,
name: &str,
) -> Result<RemovalReport, InstallError> {
let pin = registry
.remove(name)
.ok_or_else(|| InstallError::NotInstalled {
name: name.to_string(),
})?;
let registry_path = PluginRegistry::path_in(plugins_root);
registry
.save(®istry_path)
.map_err(InstallError::Registry)?;
let plugin_dir = plugins_root.join(name);
let dir_removed = if plugin_dir.exists() {
std::fs::remove_dir_all(&plugin_dir).map_err(InstallError::Io)?;
true
} else {
false
};
let mut identity_keys = Vec::new();
for tool in &pin.tools {
match tool {
ToolPin::Wasm { identity, .. } | ToolPin::Script { identity, .. } => {
identity_keys.push(identity.clone());
}
ToolPin::Mcp { label, .. } => {
identity_keys.push(format!("plugin.{name}.{label}"));
}
}
}
Ok(RemovalReport {
name: name.to_string(),
identity_keys,
ledger_prefix: format!("plugin.{name}."),
dir_removed,
registry_removed: true,
})
}