use std::path::{Path, PathBuf};
use crate::error::ForgeError;
pub(crate) fn resolve_local_skill_sources(
input: &str,
declaring_file: &Path,
) -> Result<String, ForgeError> {
let mut value: toml::Value = toml::from_str(input)
.map_err(|error| ForgeError::Parse(format!("invalid TOML: {error}")))?;
let Some(components) = value
.get_mut("components")
.and_then(toml::Value::as_array_mut)
else {
return Ok(input.to_string());
};
let declared_base = declaring_file.parent().unwrap_or_else(|| Path::new("."));
let base = declared_base
.canonicalize()
.map_err(|source| ForgeError::Io {
path: declared_base.to_path_buf(),
source,
})?;
for component in components {
let Some(table) = component.as_table_mut() else {
continue;
};
if table.get("kind").and_then(toml::Value::as_str) != Some("skill") {
continue;
}
let Some(source) = table.get_mut("source") else {
continue;
};
let Some(path) = source.as_str().map(PathBuf::from) else {
continue;
};
if path.is_relative() {
*source = toml::Value::String(base.join(path).display().to_string());
}
}
toml::to_string(&value).map_err(|error| {
ForgeError::Config(format!("failed to normalize the local skill path: {error}"))
})
}