//! Config key renames. Old configs keep working, and `kur run` rewrites them to the new names. use toml_edit::{DocumentMut, Item, Key, Table}; /// Where a rename applies. // Nothing is renamed yet, so no entry constructs these variants. #[allow(dead_code)] #[derive(Clone, Copy)] pub enum Scope { /// The root table. Top, /// Every table in the `[[app]]` array. App, } /// `(scope, old name, new name)`. Add an entry here when a key is renamed, never remove one. /// Also add the new name to `KNOWN_TOP_KEYS` or `KNOWN_APP_KEYS` in `config.rs`. /// /// Example, for an `[[app]]` key `health_wait` renamed to `health_timeout_secs`: /// ```text /// (Scope::App, "health_wait", "health_timeout_secs"), /// ``` pub const RENAMES: &[(Scope, &str, &str)] = &[]; /// What happened to the old key in one table. enum Change { Renamed, Dropped, } /// Renames keys in `doc` in place and returns one message per change. /// /// A renamed key keeps its value, its position in the table, and its comments. If the new name /// is already set in the same table, the old key is removed instead. pub fn apply(doc: &mut DocumentMut, renames: &[(Scope, &str, &str)]) -> Vec { let mut messages = Vec::new(); for &(scope, old, new) in renames { match scope { Scope::Top => { if let Some(change) = rename_key(doc.as_table_mut(), old, new) { messages.push(describe(&change, old, new, None)); } } Scope::App => { let Some(apps) = doc .get_mut("app") .and_then(|item| item.as_array_of_tables_mut()) else { continue; }; for (index, table) in apps.iter_mut().enumerate() { let label = app_label(table, index); if let Some(change) = rename_key(table, old, new) { messages.push(describe(&change, old, new, Some(&label))); } } } } } messages } /// The `name` of an `[[app]]` table, or `#<1-based index>` if it has none. fn app_label(table: &Table, index: usize) -> String { match table.get("name").and_then(Item::as_str) { Some(name) => name.to_string(), None => format!("#{}", index + 1), } } /// Renames `old` to `new` in `table`, keeping the key's position and decor. Returns `None` if /// `old` is not set. fn rename_key(table: &mut Table, old: &str, new: &str) -> Option { if !table.contains_key(old) { return None; } if table.contains_key(new) { table.remove(old); return Some(Change::Dropped); } // toml_edit cannot change a key's name in place, so take every entry out in order and // insert them back, with the renamed key where the old one was. let names: Vec = table.iter().map(|(key, _)| key.to_string()).collect(); let entries: Vec<(Key, Item)> = names .iter() .filter_map(|name| table.remove_entry(name)) .collect(); for (key, item) in entries { if key.get() == old { let renamed = Key::new(new).with_leaf_decor(key.leaf_decor().clone()); table.insert_formatted(&renamed, item); } else { table.insert_formatted(&key, item); } } Some(Change::Renamed) } fn describe(change: &Change, old: &str, new: &str, app: Option<&str>) -> String { let location = app .map(|label| format!(" in [[app]] {label}")) .unwrap_or_default(); match change { Change::Renamed => format!("renamed {old:?} to {new:?}{location}"), Change::Dropped => format!("dropped {old:?} (already set as {new:?}){location}"), } } #[cfg(test)] mod tests { use super::*; #[test] fn renames_app_key_keeping_comment_value_and_position() { let text = "forge = \"https://x\"\n\n[[app]]\nname = \"im\"\n# how often\nold_key = 5\nrepo = \"a/b\"\n"; let mut doc: DocumentMut = text.parse().unwrap(); let renames = [(Scope::App, "old_key", "new_key")]; let messages = apply(&mut doc, &renames); let out = doc.to_string(); assert!(out.contains("# how often\nnew_key = 5\nrepo"), "{out}"); assert!(!out.contains("old_key"), "{out}"); assert_eq!( messages, ["renamed \"old_key\" to \"new_key\" in [[app]] im"] ); } }