use anyhow::{Context, Result};
use toml_edit::{DocumentMut, Item};
pub(crate) fn serialize_lockfile_with_inline_patches<T: serde::Serialize>(
lockfile: &T,
) -> Result<String> {
let toml_str = toml::to_string_pretty(lockfile).context("Failed to serialize to TOML")?;
let mut doc: DocumentMut = toml_str.parse().context("Failed to parse TOML document")?;
let resource_types =
["agents", "snippets", "commands", "scripts", "hooks", "mcp-servers", "skills"];
for resource_type in &resource_types {
if let Some(Item::ArrayOfTables(array)) = doc.get_mut(resource_type) {
for table in array.iter_mut() {
if let Some(Item::Table(patches_table)) = table.get_mut("applied_patches") {
let mut inline = toml_edit::InlineTable::new();
let mut keys: Vec<_> =
patches_table.iter().filter_map(|(k, v)| v.as_value().map(|_| k)).collect();
keys.sort();
for key in keys {
if let Some(val) = patches_table.get(key).and_then(|v| v.as_value()) {
inline.insert(key, val.clone());
}
}
table.insert("applied_patches", toml_edit::value(inline));
} else {
let inline = toml_edit::InlineTable::new();
table.insert("applied_patches", toml_edit::value(inline));
}
}
}
}
Ok(doc.to_string())
}