forge
Explore
Log in

Don't you dare go Hollow

kur

Clone
★ 0

0 watching0 forksRustAGPL-3.073.7 KiB6ae6238Tahinli21 days ago5 commits

migrate.rs127 lines, 4.4 KiBHistoryRawDownload
1//! Config key renames. Old configs keep working, and `kur run` rewrites them to the new names.
2
3use toml_edit::{DocumentMut, Item, Key, Table};
4
5/// Where a rename applies.
6// Nothing is renamed yet, so no entry constructs these variants.
7#[allow(dead_code)]
8#[derive(Clone, Copy)]
9pub enum Scope {
10 /// The root table.
11 Top,
12 /// Every table in the `[[app]]` array.
13 App,
14}
15
16/// `(scope, old name, new name)`. Add an entry here when a key is renamed, never remove one.
17/// Also add the new name to `KNOWN_TOP_KEYS` or `KNOWN_APP_KEYS` in `config.rs`.
18///
19/// Example, for an `[[app]]` key `health_wait` renamed to `health_timeout_secs`:
20/// ```text
21/// (Scope::App, "health_wait", "health_timeout_secs"),
22/// ```
23pub const RENAMES: &[(Scope, &str, &str)] = &[];
24
25/// What happened to the old key in one table.
26enum Change {
27 Renamed,
28 Dropped,
29}
30
31/// Renames keys in `doc` in place and returns one message per change.
32///
33/// A renamed key keeps its value, its position in the table, and its comments. If the new name
34/// is already set in the same table, the old key is removed instead.
35pub fn apply(doc: &mut DocumentMut, renames: &[(Scope, &str, &str)]) -> Vec<String> {
36 let mut messages = Vec::new();
37 for &(scope, old, new) in renames {
38 match scope {
39 Scope::Top => {
40 if let Some(change) = rename_key(doc.as_table_mut(), old, new) {
41 messages.push(describe(&change, old, new, None));
42 }
43 }
44 Scope::App => {
45 let Some(apps) = doc
46 .get_mut("app")
47 .and_then(|item| item.as_array_of_tables_mut())
48 else {
49 continue;
50 };
51 for (index, table) in apps.iter_mut().enumerate() {
52 let label = app_label(table, index);
53 if let Some(change) = rename_key(table, old, new) {
54 messages.push(describe(&change, old, new, Some(&label)));
55 }
56 }
57 }
58 }
59 }
60 messages
61}
62
63/// The `name` of an `[[app]]` table, or `#<1-based index>` if it has none.
64fn app_label(table: &Table, index: usize) -> String {
65 match table.get("name").and_then(Item::as_str) {
66 Some(name) => name.to_string(),
67 None => format!("#{}", index + 1),
68 }
69}
70
71/// Renames `old` to `new` in `table`, keeping the key's position and decor. Returns `None` if
72/// `old` is not set.
73fn rename_key(table: &mut Table, old: &str, new: &str) -> Option<Change> {
74 if !table.contains_key(old) {
75 return None;
76 }
77 if table.contains_key(new) {
78 table.remove(old);
79 return Some(Change::Dropped);
80 }
81 // toml_edit cannot change a key's name in place, so take every entry out in order and
82 // insert them back, with the renamed key where the old one was.
83 let names: Vec<String> = table.iter().map(|(key, _)| key.to_string()).collect();
84 let entries: Vec<(Key, Item)> = names
85 .iter()
86 .filter_map(|name| table.remove_entry(name))
87 .collect();
88 for (key, item) in entries {
89 if key.get() == old {
90 let renamed = Key::new(new).with_leaf_decor(key.leaf_decor().clone());
91 table.insert_formatted(&renamed, item);
92 } else {
93 table.insert_formatted(&key, item);
94 }
95 }
96 Some(Change::Renamed)
97}
98
99fn describe(change: &Change, old: &str, new: &str, app: Option<&str>) -> String {
100 let location = app
101 .map(|label| format!(" in [[app]] {label}"))
102 .unwrap_or_default();
103 match change {
104 Change::Renamed => format!("renamed {old:?} to {new:?}{location}"),
105 Change::Dropped => format!("dropped {old:?} (already set as {new:?}){location}"),
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn renames_app_key_keeping_comment_value_and_position() {
115 let text = "forge = \"https://x\"\n\n[[app]]\nname = \"im\"\n# how often\nold_key = 5\nrepo = \"a/b\"\n";
116 let mut doc: DocumentMut = text.parse().unwrap();
117 let renames = [(Scope::App, "old_key", "new_key")];
118 let messages = apply(&mut doc, &renames);
119 let out = doc.to_string();
120 assert!(out.contains("# how often\nnew_key = 5\nrepo"), "{out}");
121 assert!(!out.contains("old_key"), "{out}");
122 assert_eq!(
123 messages,
124 ["renamed \"old_key\" to \"new_key\" in [[app]] im"]
125 );
126 }
127}