60 lines
2.0 KiB
Rust
60 lines
2.0 KiB
Rust
use std::str::FromStr;
|
|
|
|
use toml_edit::{DocumentMut, Item, Value};
|
|
|
|
use crate::{ConfigError, Profile};
|
|
|
|
/// A comment-preserving profile edit that is revalidated before use.
|
|
pub struct ProfileDocument {
|
|
document: DocumentMut,
|
|
}
|
|
|
|
impl ProfileDocument {
|
|
/// Parses both the editable TOML representation and semantic profile.
|
|
pub fn parse(input: &str) -> Result<Self, ConfigError> {
|
|
Profile::parse(input)?;
|
|
let document = DocumentMut::from_str(input)?;
|
|
Ok(Self { document })
|
|
}
|
|
|
|
/// Changes one application's display label without rebuilding its table.
|
|
pub fn set_application_label(
|
|
&mut self,
|
|
application_id: &str,
|
|
label: &str,
|
|
) -> Result<(), ConfigError> {
|
|
let applications = self
|
|
.document
|
|
.get_mut("applications")
|
|
.and_then(Item::as_array_of_tables_mut)
|
|
.ok_or_else(|| ConfigError::validation("applications", "missing application array"))?;
|
|
let Some(application) = applications.iter_mut().find(|table| {
|
|
table
|
|
.get("id")
|
|
.and_then(Item::as_str)
|
|
.is_some_and(|id| id == application_id)
|
|
}) else {
|
|
return Err(ConfigError::validation(
|
|
"applications",
|
|
format!("unknown application {application_id:?}"),
|
|
));
|
|
};
|
|
let existing = application
|
|
.get_mut("label")
|
|
.and_then(Item::as_value_mut)
|
|
.ok_or_else(|| ConfigError::validation("applications.label", "missing string label"))?;
|
|
let decor = existing.decor().clone();
|
|
let mut replacement = Value::from(label);
|
|
*replacement.decor_mut() = decor;
|
|
*existing = replacement;
|
|
Ok(())
|
|
}
|
|
|
|
/// Returns edited TOML only if the complete result remains valid.
|
|
pub fn finish(self) -> Result<String, ConfigError> {
|
|
let output = self.document.to_string();
|
|
Profile::parse(&output)?;
|
|
Ok(output)
|
|
}
|
|
}
|