From cffea6d80605dde52f248a9828aa7b75b6594170 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 15:30:14 +0100 Subject: [PATCH 01/15] added xml, properties and ini --- Cargo.lock | 125 +++++++++++++++++-- Cargo.toml | 5 +- README.md | 9 +- config.toml | 37 ++++++ src/format/hierarchical.rs | 241 ++++++++++++++++++++++++++++++++++++- src/format/ini.rs | 125 +++++++++++++++++++ src/format/mod.rs | 17 +++ src/format/properties.rs | 129 ++++++++++++++++++++ src/resolver.rs | 6 + 9 files changed, 677 insertions(+), 17 deletions(-) create mode 100644 config.toml create mode 100644 src/format/ini.rs create mode 100644 src/format/properties.rs diff --git a/Cargo.lock b/Cargo.lock index 182d2e3..411fc4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -247,6 +247,26 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -292,6 +312,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -414,6 +440,15 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "dlv-list" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" +dependencies = [ + "const-random", +] + [[package]] name = "document-features" version = "0.2.12" @@ -429,6 +464,15 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "env_filter" version = "1.0.0" @@ -580,6 +624,12 @@ dependencies = [ "wasip3", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -679,6 +729,17 @@ version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +[[package]] +name = "java-properties" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37bf6f484471c451f2b51eabd9e66b3fa7274550c5ec4b6c3d6070840945117f" +dependencies = [ + "encoding_rs", + "lazy_static", + "regex", +] + [[package]] name = "jiff" version = "0.2.23" @@ -860,8 +921,11 @@ dependencies = [ "crossterm", "dirs", "env_logger", + "java-properties", "log", + "quick-xml", "ratatui", + "rust-ini", "serde", "serde_json", "serde_yaml", @@ -956,6 +1020,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ordered-multimap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79" +dependencies = [ + "dlv-list", + "hashbrown 0.14.5", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -1114,6 +1188,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-xml" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "958f21e8e7ceb5a1aa7fa87fab28e7c75976e0bfe7e23ff069e0a260f894067d" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quote" version = "1.0.45" @@ -1284,6 +1368,16 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "rust-ini" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" +dependencies = [ + "cfg-if", + "ordered-multimap", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -1642,10 +1736,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] -name = "toml" -version = "1.0.6+spec-1.1.0" +name = "tiny-keccak" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "399b1124a3c9e16766831c6bba21e50192572cdd98706ea114f9502509686ffc" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "toml" +version = "1.0.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd28d57d8a6f6e458bc0b8784f8fdcc4b99a437936056fa122cb234f18656a96" dependencies = [ "indexmap", "serde_core", @@ -1658,27 +1761,27 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.0.0+spec-1.1.0" +version = "1.0.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e" +checksum = "9b320e741db58cac564e26c607d3cc1fdc4a88fd36c879568c07856ed83ff3e9" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" -version = "1.0.9+spec-1.1.0" +version = "1.0.10+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4" +checksum = "7df25b4befd31c4816df190124375d5a20c6b6921e2cad937316de3fccd63420" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.0.6+spec-1.1.0" +version = "1.0.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" +checksum = "f17aaa1c6e3dc22b1da4b6bba97d066e354c7945cac2f7852d4e4e7ca7a6b56d" [[package]] name = "tui-input" @@ -1990,9 +2093,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.7.15" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +checksum = "a90e88e4667264a994d34e6d1ab2d26d398dcdca8b7f52bec8668957517fc7d8" [[package]] name = "wit-bindgen" diff --git a/Cargo.toml b/Cargo.toml index 1b0627f..d4d6229 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,12 +7,15 @@ anyhow = "1.0.102" crossterm = "0.29.0" dirs = "6.0.0" env_logger = "0.11.9" +java-properties = "2.0.0" log = "0.4.29" +quick-xml = { version = "0.39.2", features = ["serde", "serialize"] } ratatui = "0.30.0" +rust-ini = "0.21.3" serde_json = "1.0.149" serde_yaml = "0.9.34" thiserror = "2.0.18" -toml = "1.0.6" +toml = "1.0.7" tui-input = "0.15.0" [dependencies.clap] diff --git a/README.md b/README.md index 78a01d9..9979a7b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ # mould -mould is a modern Terminal User Interface (TUI) tool designed for interactively generating and editing configuration files from templates. Whether you are setting up a `.env` file from an example, creating a `docker-compose.override.yml`, or editing nested `JSON`, `YAML`, or `TOML` configurations, mould provides a fast, Vim-inspired workflow to get your environment ready. +mould is a modern Terminal User Interface (TUI) tool designed for interactively generating and editing configuration files from templates. Whether you are setting up a `.env` file from an example, creating a `docker-compose.override.yml`, or editing nested `JSON`, `YAML`, `TOML`, `XML`, `INI`, or `Properties` configurations, mould provides a fast, Vim-inspired workflow to get your environment ready. ## Features -- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly. -- **Tree View Navigation**: Edit nested data structures (JSON, YAML, TOML) in a beautiful, depth-colored tree view. -- **Smart Template Comparison**: Automatically discovers `.env.example` vs `.env` relationships and highlights missing or modified keys. +- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, `TOML`, `XML`, `INI`, and `Properties` seamlessly. +- **Tree View Navigation**: Edit nested data structures in a beautiful, depth-colored tree view. +- **Smart Template Discovery**: Rule-based resolver automatically discovers relationships (e.g., `.env.example` vs `.env`, `config.template.properties` vs `config.properties`) and highlights differences. +- **Strict Type Preservation**: Intelligently preserves data types (integers, booleans, strings) during edit-save cycles, ensuring your configuration stays valid. - **Add Missing Keys**: Instantly pull missing keys and their default values from your template into your active configuration with a single keystroke. - **Neovim Integration**: Comes with a built-in Neovim plugin for seamless in-editor configuration management. - **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`. diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..3a47008 --- /dev/null +++ b/config.toml @@ -0,0 +1,37 @@ +[keybinds] +append_item = "o" +delete_item = "dd" +down = "j" +edit = "i" +edit_append = "A" +edit_substitute = "S" +jump_bottom = "G" +jump_top = "gg" +next_match = "n" +normal_mode = "Esc" +prepend_item = "O" +previous_match = "N" +quit = ":q" +save = ":w" +search = "/" +undo = "u" +up = "k" + +[theme] +bg_active = "#a6e3a1" +bg_highlight = "#89b4fa" +bg_normal = "#1e1e2e" +bg_search = "#cba6f7" +border_active = "#a6e3a1" +border_normal = "#45475a" +fg_accent = "#b4befe" +fg_dimmed = "#6c7086" +fg_highlight = "#1e1e2e" +fg_modified = "#fab387" +fg_normal = "#cdd6f4" +fg_warning = "#f38ba8" +transparent = true +tree_depth_1 = "#b4befe" +tree_depth_2 = "#cba6f7" +tree_depth_3 = "#89b4fa" +tree_depth_4 = "#fab387" diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index 6970f91..3efd862 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -22,6 +22,8 @@ impl HierarchicalHandler { .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, FormatType::Toml => toml::from_str(&content) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, + FormatType::Xml => xml_to_json(&content) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, _ => unreachable!(), }; Ok(value) @@ -47,12 +49,124 @@ impl HierarchicalHandler { )); } } + FormatType::Xml => json_to_xml(value), _ => unreachable!(), }; fs::write(path, content) } } +fn xml_to_json(content: &str) -> io::Result { + use quick_xml::reader::Reader; + use quick_xml::events::Event; + + let mut reader = Reader::from_str(content); + reader.config_mut().trim_text(true); + let mut buf = Vec::new(); + + fn parse_recursive(reader: &mut Reader<&[u8]>) -> io::Result { + let mut map = Map::new(); + let mut text = String::new(); + let mut buf = Vec::new(); + + loop { + match reader.read_event_into(&mut buf) { + Ok(Event::Start(e)) => { + let name = String::from_utf8_lossy(e.name().as_ref()).to_string(); + let val = parse_recursive(reader)?; + + if let Some(existing) = map.get_mut(&name) { + if let Some(arr) = existing.as_array_mut() { + arr.push(val); + } else { + let old = existing.take(); + *existing = Value::Array(vec![old, val]); + } + } else { + map.insert(name, val); + } + } + Ok(Event::End(_)) => break, + Ok(Event::Text(e)) => { + text.push_str(&String::from_utf8_lossy(e.as_ref())); + } + Ok(Event::Eof) => break, + _ => {} + } + buf.clear(); + } + + if map.is_empty() { + if text.is_empty() { + Ok(Value::Null) + } else { + Ok(Value::String(text)) + } + } else { + if !text.is_empty() { + map.insert("$text".to_string(), Value::String(text)); + } + Ok(Value::Object(map)) + } + } + + // Move to the first start tag + loop { + match reader.read_event_into(&mut buf) { + Ok(Event::Start(e)) => { + let name = String::from_utf8_lossy(e.name().as_ref()).to_string(); + let val = parse_recursive(&mut reader)?; + let mut root = Map::new(); + root.insert(name, val); + return Ok(Value::Object(root)); + } + Ok(Event::Eof) => break, + _ => {} + } + buf.clear(); + } + + Ok(Value::Object(Map::new())) +} + +fn json_to_xml(value: &Value) -> String { + match value { + Value::Object(map) => { + let mut s = String::new(); + for (k, v) in map { + if k == "$text" { + s.push_str(&v.as_str().unwrap_or("")); + } else if let Some(arr) = v.as_array() { + for item in arr { + s.push_str(&format!("<{}>", k)); + s.push_str(&json_to_xml(item)); + s.push_str(&format!("", k)); + } + } else { + s.push_str(&format!("<{}>", k)); + s.push_str(&json_to_xml(v)); + s.push_str(&format!("", k)); + } + } + s + } + Value::Array(arr) => { + let mut s = String::new(); + for v in arr { + s.push_str(&json_to_xml(v)); + } + s + } + Value::String(v) => v.clone(), + Value::Number(v) => v.to_string(), + Value::Bool(v) => v.to_string(), + Value::Null => "".to_string(), + } +} + +// remove unused get_xml_root_name +// fn get_xml_root_name(content: &str) -> Option { ... } + fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec) { let path = if prefix.is_empty() { key_name.to_string() @@ -322,7 +436,7 @@ mod tests { use super::*; #[test] - fn test_flatten_unflatten() { + fn test_json_flatten_unflatten() { let mut vars = Vec::new(); let json = serde_json::json!({ "services": { @@ -350,4 +464,129 @@ mod tests { assert!(unflattened_json.contains("\"8080:80\"")); assert!(unflattened_json.contains("true")); } + + #[test] + fn test_type_preservation() { + let mut vars = Vec::new(); + // A JSON with various tricky types + let json = serde_json::json!({ + "port_num": 8080, + "port_str": "8080", + "is_enabled": true, + "is_enabled_str": "true", + "float_num": 3.14, + "float_str": "3.14" + }); + + flatten(&json, "", 0, "", &mut vars); + + let mut root = Value::Object(Map::new()); + for var in vars { + if !var.is_group { + insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); + } + } + + // Validate that types are exactly preserved after re-assembling + let unflattened = root.as_object().unwrap(); + + assert!(unflattened["port_num"].is_number(), "port_num should be a number"); + assert_eq!(unflattened["port_num"].as_i64(), Some(8080)); + + assert!(unflattened["port_str"].is_string(), "port_str should be a string"); + assert_eq!(unflattened["port_str"].as_str(), Some("8080")); + + assert!(unflattened["is_enabled"].is_boolean(), "is_enabled should be a boolean"); + assert_eq!(unflattened["is_enabled"].as_bool(), Some(true)); + + assert!(unflattened["is_enabled_str"].is_string(), "is_enabled_str should be a string"); + assert_eq!(unflattened["is_enabled_str"].as_str(), Some("true")); + + assert!(unflattened["float_num"].is_number(), "float_num should be a number"); + assert_eq!(unflattened["float_num"].as_f64(), Some(3.14)); + + assert!(unflattened["float_str"].is_string(), "float_str should be a string"); + assert_eq!(unflattened["float_str"].as_str(), Some("3.14")); + } + + #[test] + fn test_yaml_flatten_unflatten() { + let yaml_str = " +server: + port: 8080 + port_str: \"8080\" + enabled: true +"; + let yaml_val: Value = serde_yaml::from_str(yaml_str).unwrap(); + let mut vars = Vec::new(); + flatten(&yaml_val, "", 0, "", &mut vars); + + let mut root = Value::Object(Map::new()); + for var in vars { + if !var.is_group { + insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); + } + } + + let unflattened_yaml = serde_yaml::to_string(&root).unwrap(); + assert!(unflattened_yaml.contains("port: 8080")); + // Serde YAML might output '8080' or "8080" + assert!(unflattened_yaml.contains("port_str: '8080'") || unflattened_yaml.contains("port_str: \"8080\"")); + assert!(unflattened_yaml.contains("enabled: true")); + } + + #[test] + fn test_toml_flatten_unflatten() { + let toml_str = " +[server] +port = 8080 +port_str = \"8080\" +enabled = true +"; + // parse to toml Value, then convert to serde_json Value to reuse the same flatten path + let toml_val: toml::Value = toml::from_str(toml_str).unwrap(); + let json_val: Value = serde_json::to_value(toml_val).unwrap(); + + let mut vars = Vec::new(); + flatten(&json_val, "", 0, "", &mut vars); + + let mut root = Value::Object(Map::new()); + for var in vars { + if !var.is_group { + insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); + } + } + + // Convert back to TOML + let toml_root: toml::Value = serde_json::from_value(root).unwrap(); + let unflattened_toml = toml::to_string(&toml_root).unwrap(); + + assert!(unflattened_toml.contains("port = 8080")); + assert!(unflattened_toml.contains("port_str = \"8080\"")); + assert!(unflattened_toml.contains("enabled = true")); + } + + #[test] + fn test_xml_flatten_unflatten() { + let xml_str = "8080true"; + + let json_val = xml_to_json(xml_str).unwrap(); + + let mut vars = Vec::new(); + flatten(&json_val, "", 0, "", &mut vars); + + let mut root = Value::Object(Map::new()); + for var in vars { + if !var.is_group { + insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); + } + } + + println!("Reconstructed root: {:?}", root); + let unflattened_xml = json_to_xml(&root); + + assert!(unflattened_xml.contains("8080")); + assert!(unflattened_xml.contains("true")); + assert!(unflattened_xml.contains("") && unflattened_xml.contains("")); + } } diff --git a/src/format/ini.rs b/src/format/ini.rs new file mode 100644 index 0000000..898beee --- /dev/null +++ b/src/format/ini.rs @@ -0,0 +1,125 @@ +use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; +use ini::Ini; +use std::io; +use std::path::Path; + +pub struct IniHandler; + +impl FormatHandler for IniHandler { + fn parse(&self, path: &Path) -> io::Result> { + let conf = Ini::load_from_file(path) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let mut vars = Vec::new(); + + for (section, prop) in &conf { + let section_name = section.unwrap_or_default(); + + if !section_name.is_empty() { + vars.push(ConfigItem { + key: section_name.to_string(), + path: section_name.to_string(), + value: None, + template_value: None, + default_value: None, + depth: 0, + is_group: true, + status: ItemStatus::Present, + value_type: ValueType::Null, + }); + } + + for (key, value) in prop { + let path = if section_name.is_empty() { + key.to_string() + } else { + format!("{}.{}", section_name, key) + }; + + vars.push(ConfigItem { + key: key.to_string(), + path, + value: Some(value.to_string()), + template_value: Some(value.to_string()), + default_value: Some(value.to_string()), + depth: if section_name.is_empty() { 0 } else { 1 }, + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + }); + } + } + + Ok(vars) + } + + fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { + if !path.exists() { + return Ok(()); + } + + let existing_vars = self.parse(path).unwrap_or_default(); + + for var in vars.iter_mut() { + if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) { + if var.value != existing.value { + var.value = existing.value.clone(); + var.status = ItemStatus::Modified; + } + } else { + var.status = ItemStatus::MissingFromActive; + } + } + + // Add items from active that are not in template + for existing in existing_vars { + if !vars.iter().any(|v| v.path == existing.path) { + let mut new_item = existing.clone(); + new_item.status = ItemStatus::MissingFromTemplate; + new_item.template_value = None; + new_item.default_value = None; + vars.push(new_item); + } + } + + Ok(()) + } + + fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + let mut conf = Ini::new(); + for var in vars { + if !var.is_group { + let val = var.value.as_deref() + .or(var.template_value.as_deref()) + .unwrap_or(""); + + if let Some((section, key)) = var.path.split_once('.') { + conf.with_section(Some(section)).set(key, val); + } else { + conf.with_section(None::).set(&var.path, val); + } + } + } + conf.write_to_file(path) + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::NamedTempFile; + use std::io::Write; + + #[test] + fn test_parse_ini() { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "[server]\nport=8080\n[database]\nhost=localhost").unwrap(); + + let handler = IniHandler; + let vars = handler.parse(file.path()).unwrap(); + + assert!(vars.iter().any(|v| v.path == "server" && v.is_group)); + assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080"))); + assert!(vars.iter().any(|v| v.path == "database.host" && v.value.as_deref() == Some("localhost"))); + } +} diff --git a/src/format/mod.rs b/src/format/mod.rs index 30afb02..9a83531 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -3,6 +3,8 @@ use std::path::Path; pub mod env; pub mod hierarchical; +pub mod ini; +pub mod properties; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ItemStatus { @@ -39,6 +41,9 @@ pub enum FormatType { Json, Yaml, Toml, + Xml, + Ini, + Properties, } pub trait FormatHandler { @@ -54,6 +59,9 @@ pub fn detect_format(path: &Path, override_format: Option) -> FormatType "json" => return FormatType::Json, "yaml" | "yml" => return FormatType::Yaml, "toml" => return FormatType::Toml, + "xml" => return FormatType::Xml, + "ini" => return FormatType::Ini, + "properties" => return FormatType::Properties, _ => {} } } @@ -65,6 +73,12 @@ pub fn detect_format(path: &Path, override_format: Option) -> FormatType FormatType::Yaml } else if file_name.ends_with(".toml") { FormatType::Toml + } else if file_name.ends_with(".xml") { + FormatType::Xml + } else if file_name.ends_with(".ini") { + FormatType::Ini + } else if file_name.ends_with(".properties") { + FormatType::Properties } else { FormatType::Env } @@ -76,5 +90,8 @@ pub fn get_handler(format: FormatType) -> Box { FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)), FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)), FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)), + FormatType::Xml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Xml)), + FormatType::Ini => Box::new(ini::IniHandler), + FormatType::Properties => Box::new(properties::PropertiesHandler), } } diff --git a/src/format/properties.rs b/src/format/properties.rs new file mode 100644 index 0000000..efe567f --- /dev/null +++ b/src/format/properties.rs @@ -0,0 +1,129 @@ +use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; +use java_properties::{read, write}; +use std::collections::HashMap; +use std::fs::File; +use std::io::{self, BufReader}; +use std::path::Path; + +pub struct PropertiesHandler; + +impl FormatHandler for PropertiesHandler { + fn parse(&self, path: &Path) -> io::Result> { + let file = File::open(path)?; + let reader = BufReader::new(file); + let props = read(reader) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + + let mut vars = Vec::new(); + let mut groups = std::collections::HashSet::new(); + + for (path, value) in &props { + // Add groups based on dot notation + let parts: Vec<&str> = path.split('.').collect(); + let mut current_path = String::new(); + + for i in 0..parts.len() - 1 { + if !current_path.is_empty() { + current_path.push('.'); + } + current_path.push_str(parts[i]); + + if groups.insert(current_path.clone()) { + vars.push(ConfigItem { + key: parts[i].to_string(), + path: current_path.clone(), + value: None, + template_value: None, + default_value: None, + depth: i, + is_group: true, + status: ItemStatus::Present, + value_type: ValueType::Null, + }); + } + } + + vars.push(ConfigItem { + key: parts.last().unwrap().to_string(), + path: path.clone(), + value: Some(value.clone()), + template_value: Some(value.clone()), + default_value: Some(value.clone()), + depth: parts.len() - 1, + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + }); + } + + // Sort by path to keep it organized + vars.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(vars) + } + + fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { + if !path.exists() { + return Ok(()); + } + + let existing_vars = self.parse(path).unwrap_or_default(); + + for var in vars.iter_mut() { + if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) { + if var.value != existing.value { + var.value = existing.value.clone(); + var.status = ItemStatus::Modified; + } + } else { + var.status = ItemStatus::MissingFromActive; + } + } + + // Add items from active that are not in template + for existing in existing_vars { + if !vars.iter().any(|v| v.path == existing.path) { + let mut new_item = existing.clone(); + new_item.status = ItemStatus::MissingFromTemplate; + new_item.template_value = None; + new_item.default_value = None; + vars.push(new_item); + } + } + + Ok(vars.sort_by(|a, b| a.path.cmp(&b.path))) + } + + fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + let mut props = HashMap::new(); + for var in vars { + if !var.is_group { + let val = var.value.as_deref() + .or(var.template_value.as_deref()) + .unwrap_or(""); + props.insert(var.path.clone(), val.to_string()); + } + } + + let file = File::create(path)?; + write(file, &props).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::NamedTempFile; + use std::io::Write; + + #[test] + fn test_parse_properties() { + let mut file = NamedTempFile::new().unwrap(); + writeln!(file, "server.port=8080\ndatabase.host=localhost").unwrap(); + + let handler = PropertiesHandler; + let vars = handler.parse(file.path()).unwrap(); + + assert!(vars.iter().any(|v| v.path == "server" && v.is_group)); + assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080"))); + } +} diff --git a/src/resolver.rs b/src/resolver.rs index eb5b438..906819e 100644 --- a/src/resolver.rs +++ b/src/resolver.rs @@ -24,6 +24,12 @@ pub const RULES: &[Rule] = &[ Rule { template_suffix: ".template.yaml", active_suffix: ".yaml", is_exact_match: false }, Rule { template_suffix: ".example.toml", active_suffix: ".toml", is_exact_match: false }, Rule { template_suffix: ".template.toml", active_suffix: ".toml", is_exact_match: false }, + Rule { template_suffix: ".example.xml", active_suffix: ".xml", is_exact_match: false }, + Rule { template_suffix: ".template.xml", active_suffix: ".xml", is_exact_match: false }, + Rule { template_suffix: ".example.ini", active_suffix: ".ini", is_exact_match: false }, + Rule { template_suffix: ".template.ini", active_suffix: ".ini", is_exact_match: false }, + Rule { template_suffix: ".example.properties", active_suffix: ".properties", is_exact_match: false }, + Rule { template_suffix: ".template.properties", active_suffix: ".properties", is_exact_match: false }, ]; pub const DEFAULT_CANDIDATES: &[&str] = &[ From a58906a2a48ded42e33d7a4074df12d068b073f4 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 15:34:00 +0100 Subject: [PATCH 02/15] version bump to 0.5.0 --- Cargo.toml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d4d6229..2dda6f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,9 @@ +[package] +authors = ["Nils Pukropp "] +edition = "2024" +name = "mould" +version = "0.5.0" + [[bin]] name = "mould" path = "src/main.rs" @@ -28,9 +34,3 @@ version = "1.0.228" [dev-dependencies] tempfile = "3.27.0" - -[package] -authors = ["Nils Pukropp "] -edition = "2024" -name = "mould" -version = "0.4.3" From b8c49d4c136c549549efa7a9febdcf87b2951c0e Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 16:44:59 +0100 Subject: [PATCH 03/15] unified merge --- Cargo.lock | 2 +- src/format/env.rs | 76 ++++++++++---------------------------- src/format/hierarchical.rs | 37 ------------------- src/format/ini.rs | 32 ---------------- src/format/mod.rs | 37 ++++++++++++++++++- src/format/properties.rs | 32 ---------------- 6 files changed, 55 insertions(+), 161 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 411fc4b..668debc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -914,7 +914,7 @@ dependencies = [ [[package]] name = "mould" -version = "0.4.3" +version = "0.5.0" dependencies = [ "anyhow", "clap", diff --git a/src/format/env.rs b/src/format/env.rs index 5277283..924c3e7 100644 --- a/src/format/env.rs +++ b/src/format/env.rs @@ -35,53 +35,6 @@ impl FormatHandler for EnvHandler { Ok(vars) } - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { - if !path.exists() { - return Ok(()); - } - - let content = fs::read_to_string(path)?; - for line in content.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - - if let Some((key, val)) = line.split_once('=') { - let key = key.trim(); - let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string(); - - if let Some(var) = vars.iter_mut().find(|v| v.key == key) { - if var.value.as_deref() != Some(&parsed_val) { - var.value = Some(parsed_val); - var.status = ItemStatus::Modified; - } - } else { - vars.push(ConfigItem { - key: key.to_string(), - path: key.to_string(), - value: Some(parsed_val), - template_value: None, - default_value: None, - depth: 0, - is_group: false, - status: ItemStatus::MissingFromTemplate, - value_type: ValueType::String, - }); - } - } - } - - // Mark missing from active - for var in vars.iter_mut() { - if var.status == ItemStatus::Present && var.value.is_none() { - var.status = ItemStatus::MissingFromActive; - } - } - - Ok(()) - } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { let mut file = fs::File::create(path)?; for var in vars { @@ -126,27 +79,36 @@ mod tests { #[test] fn test_merge_env() { - let mut example_file = NamedTempFile::new().unwrap(); - writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap(); let handler = EnvHandler; - let mut vars = handler.parse(example_file.path()).unwrap(); let mut env_file = NamedTempFile::new().unwrap(); writeln!(env_file, "KEY1=custom1\nKEY3=custom3").unwrap(); + let mut vars = handler.parse(env_file.path()).unwrap(); // Active vars - handler.merge(env_file.path(), &mut vars).unwrap(); + let mut example_file = NamedTempFile::new().unwrap(); + writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap(); + handler.merge(example_file.path(), &mut vars).unwrap(); // Merge template into active + + // Should preserve order of active, then append template assert_eq!(vars.len(), 3); + + // Active key that exists in template assert_eq!(vars[0].key, "KEY1"); - assert_eq!(vars[0].value.as_deref(), Some("custom1")); + assert_eq!(vars[0].value.as_deref(), Some("custom1")); // Keeps active value + assert_eq!(vars[0].template_value.as_deref(), Some("default1")); // Gets template default assert_eq!(vars[0].status, ItemStatus::Modified); - assert_eq!(vars[1].key, "KEY2"); - assert_eq!(vars[1].value.as_deref(), Some("default2")); + // Active key that DOES NOT exist in template + assert_eq!(vars[1].key, "KEY3"); + assert_eq!(vars[1].value.as_deref(), Some("custom3")); + assert_eq!(vars[1].status, ItemStatus::Present); - assert_eq!(vars[2].key, "KEY3"); - assert_eq!(vars[2].value.as_deref(), Some("custom3")); - assert_eq!(vars[2].status, ItemStatus::MissingFromTemplate); + // Template key that DOES NOT exist in active + assert_eq!(vars[2].key, "KEY2"); + assert_eq!(vars[2].value.as_deref(), None); // Missing from active + assert_eq!(vars[2].template_value.as_deref(), Some("default2")); + assert_eq!(vars[2].status, ItemStatus::MissingFromActive); } #[test] diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index 3efd862..a50ebc8 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -283,43 +283,6 @@ impl FormatHandler for HierarchicalHandler { Ok(vars) } - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { - if !path.exists() { - return Ok(()); - } - let existing_value = self.read_value(path)?; - let mut existing_vars = Vec::new(); - flatten(&existing_value, "", 0, "", &mut existing_vars); - - for var in vars.iter_mut() { - if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) { - if var.value != existing.value { - var.value = existing.value.clone(); - var.status = ItemStatus::Modified; - } - } else { - var.status = ItemStatus::MissingFromActive; - } - } - - // Find keys in active that are not in template - let mut to_add = Vec::new(); - for existing in existing_vars { - if !vars.iter().any(|v| v.path == existing.path) { - let mut new_item = existing.clone(); - new_item.status = ItemStatus::MissingFromTemplate; - new_item.template_value = None; - new_item.default_value = None; - to_add.push(new_item); - } - } - - // Basic insertion logic for extra keys (could be improved to insert at correct depth/position) - vars.extend(to_add); - - Ok(()) - } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { let mut root = Value::Object(Map::new()); for var in vars { diff --git a/src/format/ini.rs b/src/format/ini.rs index 898beee..dbda8d7 100644 --- a/src/format/ini.rs +++ b/src/format/ini.rs @@ -52,38 +52,6 @@ impl FormatHandler for IniHandler { Ok(vars) } - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { - if !path.exists() { - return Ok(()); - } - - let existing_vars = self.parse(path).unwrap_or_default(); - - for var in vars.iter_mut() { - if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) { - if var.value != existing.value { - var.value = existing.value.clone(); - var.status = ItemStatus::Modified; - } - } else { - var.status = ItemStatus::MissingFromActive; - } - } - - // Add items from active that are not in template - for existing in existing_vars { - if !vars.iter().any(|v| v.path == existing.path) { - let mut new_item = existing.clone(); - new_item.status = ItemStatus::MissingFromTemplate; - new_item.template_value = None; - new_item.default_value = None; - vars.push(new_item); - } - } - - Ok(()) - } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { let mut conf = Ini::new(); for var in vars { diff --git a/src/format/mod.rs b/src/format/mod.rs index 9a83531..a86d35e 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -10,7 +10,6 @@ pub mod properties; pub enum ItemStatus { Present, MissingFromActive, - MissingFromTemplate, Modified, } @@ -48,7 +47,41 @@ pub enum FormatType { pub trait FormatHandler { fn parse(&self, path: &Path) -> io::Result>; - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()>; + fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { + if !path.exists() { + return Ok(()); + } + + let template_vars = self.parse(path).unwrap_or_default(); + + for var in vars.iter_mut() { + if let Some(template_var) = template_vars.iter().find(|v| v.path == var.path) { + var.template_value = template_var.value.clone(); + var.default_value = template_var.value.clone(); + + if var.value != template_var.value { + var.status = ItemStatus::Modified; + } else { + var.status = ItemStatus::Present; + } + } else { + // Exists in active, but not in template + var.status = ItemStatus::Present; + } + } + + // Add items from template that are missing in active + for template_var in template_vars { + if !vars.iter().any(|v| v.path == template_var.path) { + let mut new_item = template_var.clone(); + new_item.status = ItemStatus::MissingFromActive; + new_item.value = None; + vars.push(new_item); + } + } + + Ok(()) + } fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>; } diff --git a/src/format/properties.rs b/src/format/properties.rs index efe567f..31f7179 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -61,38 +61,6 @@ impl FormatHandler for PropertiesHandler { Ok(vars) } - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { - if !path.exists() { - return Ok(()); - } - - let existing_vars = self.parse(path).unwrap_or_default(); - - for var in vars.iter_mut() { - if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) { - if var.value != existing.value { - var.value = existing.value.clone(); - var.status = ItemStatus::Modified; - } - } else { - var.status = ItemStatus::MissingFromActive; - } - } - - // Add items from active that are not in template - for existing in existing_vars { - if !vars.iter().any(|v| v.path == existing.path) { - let mut new_item = existing.clone(); - new_item.status = ItemStatus::MissingFromTemplate; - new_item.template_value = None; - new_item.default_value = None; - vars.push(new_item); - } - } - - Ok(vars.sort_by(|a, b| a.path.cmp(&b.path))) - } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { let mut props = HashMap::new(); for var in vars { From b3651aa5ddd5d9bed53e1326534f710d6b3330d2 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:11:27 +0100 Subject: [PATCH 04/15] fixed ordering --- Cargo.lock | 1 + Cargo.toml | 16 +++---- config.toml | 37 ---------------- src/format/properties.rs | 92 +++++++++++++++++++++------------------- 4 files changed, 54 insertions(+), 92 deletions(-) delete mode 100644 config.toml diff --git a/Cargo.lock b/Cargo.lock index 668debc..7979626 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1460,6 +1460,7 @@ version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ + "indexmap", "itoa", "memchr", "serde", diff --git a/Cargo.toml b/Cargo.toml index 2dda6f0..4f958c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,22 +15,16 @@ dirs = "6.0.0" env_logger = "0.11.9" java-properties = "2.0.0" log = "0.4.29" -quick-xml = { version = "0.39.2", features = ["serde", "serialize"] } ratatui = "0.30.0" rust-ini = "0.21.3" -serde_json = "1.0.149" +serde = { version = "1.0.228", features = ["derive"] } +serde_json = { version = "1.0.149", features = ["preserve_order"] } serde_yaml = "0.9.34" thiserror = "2.0.18" -toml = "1.0.7" +toml = { version = "1.0.7", features = ["preserve_order"] } tui-input = "0.15.0" - -[dependencies.clap] -features = ["derive"] -version = "4.6.0" - -[dependencies.serde] -features = ["derive"] -version = "1.0.228" +clap = { version = "4.6.0", features = ["derive"] } +quick-xml = { version = "0.39.2", features = ["serde", "serialize"] } [dev-dependencies] tempfile = "3.27.0" diff --git a/config.toml b/config.toml deleted file mode 100644 index 3a47008..0000000 --- a/config.toml +++ /dev/null @@ -1,37 +0,0 @@ -[keybinds] -append_item = "o" -delete_item = "dd" -down = "j" -edit = "i" -edit_append = "A" -edit_substitute = "S" -jump_bottom = "G" -jump_top = "gg" -next_match = "n" -normal_mode = "Esc" -prepend_item = "O" -previous_match = "N" -quit = ":q" -save = ":w" -search = "/" -undo = "u" -up = "k" - -[theme] -bg_active = "#a6e3a1" -bg_highlight = "#89b4fa" -bg_normal = "#1e1e2e" -bg_search = "#cba6f7" -border_active = "#a6e3a1" -border_normal = "#45475a" -fg_accent = "#b4befe" -fg_dimmed = "#6c7086" -fg_highlight = "#1e1e2e" -fg_modified = "#fab387" -fg_normal = "#cdd6f4" -fg_warning = "#f38ba8" -transparent = true -tree_depth_1 = "#b4befe" -tree_depth_2 = "#cba6f7" -tree_depth_3 = "#89b4fa" -tree_depth_4 = "#fab387" diff --git a/src/format/properties.rs b/src/format/properties.rs index 31f7179..a521a2f 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -1,8 +1,7 @@ use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; -use java_properties::{read, write}; -use std::collections::HashMap; +use java_properties::{LineContent, PropertiesIter, PropertiesWriter}; use std::fs::File; -use std::io::{self, BufReader}; +use std::io::{self, BufReader, BufWriter}; use std::path::Path; pub struct PropertiesHandler; @@ -11,69 +10,74 @@ impl FormatHandler for PropertiesHandler { fn parse(&self, path: &Path) -> io::Result> { let file = File::open(path)?; let reader = BufReader::new(file); - let props = read(reader) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let iter = PropertiesIter::new(reader); let mut vars = Vec::new(); let mut groups = std::collections::HashSet::new(); - for (path, value) in &props { - // Add groups based on dot notation - let parts: Vec<&str> = path.split('.').collect(); - let mut current_path = String::new(); + for line_result in iter { + let line = line_result.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - for i in 0..parts.len() - 1 { - if !current_path.is_empty() { - current_path.push('.'); - } - current_path.push_str(parts[i]); + if let LineContent::KVPair(path, value) = line.consume_content() { + // Add groups based on dot notation + let parts: Vec<&str> = path.split('.').collect(); + let mut current_path = String::new(); - if groups.insert(current_path.clone()) { - vars.push(ConfigItem { - key: parts[i].to_string(), - path: current_path.clone(), - value: None, - template_value: None, - default_value: None, - depth: i, - is_group: true, - status: ItemStatus::Present, - value_type: ValueType::Null, - }); + for i in 0..parts.len().saturating_sub(1) { + if !current_path.is_empty() { + current_path.push('.'); + } + current_path.push_str(parts[i]); + + if groups.insert(current_path.clone()) { + vars.push(ConfigItem { + key: parts[i].to_string(), + path: current_path.clone(), + value: None, + template_value: None, + default_value: None, + depth: i, + is_group: true, + status: ItemStatus::Present, + value_type: ValueType::Null, + }); + } } - } - vars.push(ConfigItem { - key: parts.last().unwrap().to_string(), - path: path.clone(), - value: Some(value.clone()), - template_value: Some(value.clone()), - default_value: Some(value.clone()), - depth: parts.len() - 1, - is_group: false, - status: ItemStatus::Present, - value_type: ValueType::String, - }); + vars.push(ConfigItem { + key: parts.last().unwrap_or(&"").to_string(), + path: path.clone(), + value: Some(value.clone()), + template_value: Some(value.clone()), + default_value: Some(value.clone()), + depth: parts.len().saturating_sub(1), + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + }); + } } - // Sort by path to keep it organized - vars.sort_by(|a, b| a.path.cmp(&b.path)); + // We don't sort here to preserve the original file order! Ok(vars) } fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { - let mut props = HashMap::new(); + let file = File::create(path)?; + let writer = BufWriter::new(file); + let mut prop_writer = PropertiesWriter::new(writer); + for var in vars { if !var.is_group { let val = var.value.as_deref() .or(var.template_value.as_deref()) .unwrap_or(""); - props.insert(var.path.clone(), val.to_string()); + prop_writer.write(&var.path, val) + .map_err(|e| io::Error::other(e))?; } } - let file = File::create(path)?; - write(file, &props).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + prop_writer.finish().map_err(|e| io::Error::other(e)) } } From 5056f8dd0a80ff3dc5cba84e163d8d957b721daf Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:15:24 +0100 Subject: [PATCH 05/15] code style fixes and nesting fixes --- src/app.rs | 38 +++++++++++++++----------------------- src/config.rs | 8 +++----- src/format/hierarchical.rs | 10 +++++----- src/format/ini.rs | 2 +- src/format/mod.rs | 24 +++++++++--------------- src/format/properties.rs | 10 +++++----- src/resolver.rs | 10 ++++------ src/runner.rs | 5 ++--- src/ui.rs | 5 ++--- 9 files changed, 46 insertions(+), 66 deletions(-) diff --git a/src/app.rs b/src/app.rs index c09f05f..df32417 100644 --- a/src/app.rs +++ b/src/app.rs @@ -40,7 +40,7 @@ pub struct App { impl App { /// Initializes a new application instance with the provided variables. pub fn new(vars: Vec) -> Self { - let initial_input = vars.get(0).and_then(|v| v.value.clone()).unwrap_or_default(); + let initial_input = vars.first().and_then(|v| v.value.clone()).unwrap_or_default(); Self { vars, selected: 0, @@ -150,18 +150,17 @@ impl App { /// Commits the current text in the input buffer back to the selected variable's value. pub fn commit_input(&mut self) { - if let Some(var) = self.vars.get_mut(self.selected) { - if !var.is_group { + if let Some(var) = self.vars.get_mut(self.selected) + && !var.is_group { var.value = Some(self.input.value().to_string()); var.status = crate::format::ItemStatus::Modified; } - } } /// Transitions the application into Insert Mode with a specific variant. pub fn enter_insert(&mut self, variant: InsertVariant) { - if let Some(var) = self.vars.get(self.selected) { - if !var.is_group { + if let Some(var) = self.vars.get(self.selected) + && !var.is_group { self.save_undo_state(); self.mode = Mode::Insert; match variant { @@ -178,7 +177,6 @@ impl App { } } } - } } /// Commits the current input and transitions the application into Normal Mode. @@ -229,8 +227,8 @@ impl App { for var in self.vars.iter_mut() { if var.path.starts_with(&base) { // We need to find the index segment that matches this array - if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) { - if b == base && i > removed_idx { + if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) + && b == base && i > removed_idx { let new_idx = i - 1; var.path = format!("{}[{}]{}", base, new_idx, suffix); // Also update key if it matches the old index exactly @@ -238,7 +236,6 @@ impl App { var.key = format!("[{}]", new_idx); } } - } } } } @@ -279,17 +276,15 @@ impl App { // 1. Shift all items in this array that have index >= new_idx for var in self.vars.iter_mut() { - if var.path.starts_with(&base) { - if let Some((b, i)) = parse_index(&var.path) { - if b == base && i >= new_idx { + if var.path.starts_with(&base) + && let Some((b, i)) = parse_index(&var.path) + && b == base && i >= new_idx { var.path = format!("{}[{}]", base, i + 1); // Also update key if it was just the index if var.key == format!("[{}]", i) { var.key = format!("[{}]", i + 1); } } - } - } } // 2. Insert new item @@ -354,12 +349,11 @@ impl App { fn parse_index(path: &str) -> Option<(&str, usize)> { if let Some(end) = path.rfind(']') { let segment = &path[..=end]; - if let Some(start) = segment.rfind('[') { - if let Ok(idx) = segment[start + 1..end].parse::() { + if let Some(start) = segment.rfind('[') + && let Ok(idx) = segment[start + 1..end].parse::() { // Return the base and index return Some((&path[..start], idx)); } - } } None } @@ -370,12 +364,10 @@ fn find_array_segment<'a>(path: &'a str, base: &str) -> Option<(&'a str, usize, return None; } let remaining = &path[base.len()..]; - if remaining.starts_with('[') { - if let Some(end) = remaining.find(']') { - if let Ok(idx) = remaining[1..end].parse::() { + if remaining.starts_with('[') + && let Some(end) = remaining.find(']') + && let Ok(idx) = remaining[1..end].parse::() { return Some((&path[..base.len()], idx, &remaining[end + 1..])); } - } - } None } diff --git a/src/config.rs b/src/config.rs index bed2196..4eaf84e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -162,13 +162,11 @@ pub fn load_config() -> Config { config_dir.push("mould"); config_dir.push("config.toml"); - if config_dir.exists() { - if let Ok(content) = fs::read_to_string(config_dir) { - if let Ok(config) = toml::from_str(&content) { + if config_dir.exists() + && let Ok(content) = fs::read_to_string(config_dir) + && let Ok(config) = toml::from_str(&content) { return config; } - } - } } Config::default() } diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index a50ebc8..b642bfd 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -135,7 +135,7 @@ fn json_to_xml(value: &Value) -> String { let mut s = String::new(); for (k, v) in map { if k == "$text" { - s.push_str(&v.as_str().unwrap_or("")); + s.push_str(v.as_str().unwrap_or("")); } else if let Some(arr) = v.as_array() { for item in arr { s.push_str(&format!("<{}>", k)); @@ -437,8 +437,8 @@ mod tests { "port_str": "8080", "is_enabled": true, "is_enabled_str": "true", - "float_num": 3.14, - "float_str": "3.14" + "float_num": 42.42, + "float_str": "42.42" }); flatten(&json, "", 0, "", &mut vars); @@ -466,10 +466,10 @@ mod tests { assert_eq!(unflattened["is_enabled_str"].as_str(), Some("true")); assert!(unflattened["float_num"].is_number(), "float_num should be a number"); - assert_eq!(unflattened["float_num"].as_f64(), Some(3.14)); + assert_eq!(unflattened["float_num"].as_f64(), Some(42.42)); assert!(unflattened["float_str"].is_string(), "float_str should be a string"); - assert_eq!(unflattened["float_str"].as_str(), Some("3.14")); + assert_eq!(unflattened["float_str"].as_str(), Some("42.42")); } #[test] diff --git a/src/format/ini.rs b/src/format/ini.rs index dbda8d7..2582739 100644 --- a/src/format/ini.rs +++ b/src/format/ini.rs @@ -68,7 +68,7 @@ impl FormatHandler for IniHandler { } } conf.write_to_file(path) - .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + .map_err(io::Error::other) } } diff --git a/src/format/mod.rs b/src/format/mod.rs index a86d35e..ed5f0e2 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -99,21 +99,15 @@ pub fn detect_format(path: &Path, override_format: Option) -> FormatType } } - let file_name = path.file_name().unwrap_or_default().to_string_lossy(); - if file_name.ends_with(".json") { - FormatType::Json - } else if file_name.ends_with(".yaml") || file_name.ends_with(".yml") { - FormatType::Yaml - } else if file_name.ends_with(".toml") { - FormatType::Toml - } else if file_name.ends_with(".xml") { - FormatType::Xml - } else if file_name.ends_with(".ini") { - FormatType::Ini - } else if file_name.ends_with(".properties") { - FormatType::Properties - } else { - FormatType::Env + let ext = path.extension().and_then(|s| s.to_str()).unwrap_or_default(); + match ext { + "json" => FormatType::Json, + "yaml" | "yml" => FormatType::Yaml, + "toml" => FormatType::Toml, + "xml" => FormatType::Xml, + "ini" => FormatType::Ini, + "properties" => FormatType::Properties, + _ => FormatType::Env, } } diff --git a/src/format/properties.rs b/src/format/properties.rs index a521a2f..642d657 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -23,15 +23,15 @@ impl FormatHandler for PropertiesHandler { let parts: Vec<&str> = path.split('.').collect(); let mut current_path = String::new(); - for i in 0..parts.len().saturating_sub(1) { + for (i, part) in parts.iter().enumerate().take(parts.len().saturating_sub(1)) { if !current_path.is_empty() { current_path.push('.'); } - current_path.push_str(parts[i]); + current_path.push_str(part); if groups.insert(current_path.clone()) { vars.push(ConfigItem { - key: parts[i].to_string(), + key: part.to_string(), path: current_path.clone(), value: None, template_value: None, @@ -73,11 +73,11 @@ impl FormatHandler for PropertiesHandler { .or(var.template_value.as_deref()) .unwrap_or(""); prop_writer.write(&var.path, val) - .map_err(|e| io::Error::other(e))?; + .map_err(io::Error::other)?; } } - prop_writer.finish().map_err(|e| io::Error::other(e)) + prop_writer.finish().map_err(io::Error::other) } } diff --git a/src/resolver.rs b/src/resolver.rs index 906819e..7b19da6 100644 --- a/src/resolver.rs +++ b/src/resolver.rs @@ -50,12 +50,10 @@ pub fn determine_output_path(input: &Path) -> PathBuf { if file_name == rule.template_suffix { return input.with_file_name(rule.active_suffix); } - } else { - if file_name == rule.template_suffix { - return input.with_file_name(rule.active_suffix); - } else if let Some(base) = file_name.strip_suffix(rule.template_suffix) { - return input.with_file_name(format!("{}{}", base, rule.active_suffix)); - } + } else if file_name == rule.template_suffix { + return input.with_file_name(rule.active_suffix); + } else if let Some(base) = file_name.strip_suffix(rule.template_suffix) { + return input.with_file_name(format!("{}{}", base, rule.active_suffix)); } } diff --git a/src/runner.rs b/src/runner.rs index 1fecf95..47b5d95 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -198,15 +198,14 @@ where /// Adds a missing item from the template to the active configuration. fn add_missing_item(&mut self) { - if let Some(var) = self.app.vars.get_mut(self.app.selected) { - if var.status == crate::format::ItemStatus::MissingFromActive { + if let Some(var) = self.app.vars.get_mut(self.app.selected) + && var.status == crate::format::ItemStatus::MissingFromActive { var.status = crate::format::ItemStatus::Present; if !var.is_group { var.value = var.template_value.clone(); } self.app.sync_input_with_selected(); } - } } /// Delegates key events to the `tui_input` handler during active editing. diff --git a/src/ui.rs b/src/ui.rs index f53ac9f..629e26b 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -150,8 +150,8 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { Span::styled(val, value_style), ]; - if let Some(t_val) = &var.template_value { - if Some(t_val) != var.value.as_ref() { + if let Some(t_val) = &var.template_value + && Some(t_val) != var.value.as_ref() { let t_style = if is_selected { Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM) } else { @@ -159,7 +159,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { }; val_spans.push(Span::styled(format!(" [Def: {}]", t_val), t_style)); } - } ListItem::new(vec![Line::from(key_spans), Line::from(val_spans)]).style(item_style) } From 277d8aa15141dc30b31445fb69187c92ea1dd9c4 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:19:09 +0100 Subject: [PATCH 06/15] improved error handling --- src/error.rs | 6 +---- src/format/env.rs | 6 ++--- src/format/hierarchical.rs | 45 ++++++++++++++------------------------ src/format/ini.rs | 12 +++++----- src/format/mod.rs | 7 +++--- src/format/properties.rs | 14 ++++++------ src/main.rs | 5 +---- 7 files changed, 37 insertions(+), 58 deletions(-) diff --git a/src/error.rs b/src/error.rs index 1ee2036..d4b70b0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,14 +1,10 @@ -use std::io; use thiserror::Error; /// Custom error types for the mould application. #[derive(Error, Debug)] pub enum MouldError { #[error("IO error: {0}")] - Io(#[from] io::Error), - - #[error("Format error: {0}")] - Format(String), + Io(#[from] std::io::Error), #[error("File not found: {0}")] FileNotFound(String), diff --git a/src/format/env.rs b/src/format/env.rs index 924c3e7..ad2b534 100644 --- a/src/format/env.rs +++ b/src/format/env.rs @@ -1,12 +1,12 @@ use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; use std::fs; -use std::io::{self, Write}; +use std::io::Write; use std::path::Path; pub struct EnvHandler; impl FormatHandler for EnvHandler { - fn parse(&self, path: &Path) -> io::Result> { + fn parse(&self, path: &Path) -> anyhow::Result> { let content = fs::read_to_string(path)?; let mut vars = Vec::new(); @@ -35,7 +35,7 @@ impl FormatHandler for EnvHandler { Ok(vars) } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> { let mut file = fs::File::create(path)?; for var in vars { if !var.is_group { diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index b642bfd..c6b7464 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -1,7 +1,6 @@ use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType}; use serde_json::{Map, Value}; use std::fs; -use std::io; use std::path::Path; pub struct HierarchicalHandler { @@ -13,50 +12,40 @@ impl HierarchicalHandler { Self { format_type } } - fn read_value(&self, path: &Path) -> io::Result { + fn read_value(&self, path: &Path) -> anyhow::Result { let content = fs::read_to_string(path)?; let value = match self.format_type { - FormatType::Json => serde_json::from_str(&content) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, - FormatType::Yaml => serde_yaml::from_str(&content) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, - FormatType::Toml => toml::from_str(&content) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, - FormatType::Xml => xml_to_json(&content) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, + FormatType::Json => serde_json::from_str(&content)?, + FormatType::Yaml => serde_yaml::from_str(&content)?, + FormatType::Toml => toml::from_str(&content)?, + FormatType::Xml => xml_to_json(&content)?, _ => unreachable!(), }; Ok(value) } - fn write_value(&self, path: &Path, value: &Value) -> io::Result<()> { + fn write_value(&self, path: &Path, value: &Value) -> anyhow::Result<()> { let content = match self.format_type { - FormatType::Json => serde_json::to_string_pretty(value) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, - FormatType::Yaml => serde_yaml::to_string(value) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, + FormatType::Json => serde_json::to_string_pretty(value)?, + FormatType::Yaml => serde_yaml::to_string(value)?, FormatType::Toml => { // toml requires the root to be a table if value.is_object() { - let toml_value: toml::Value = serde_json::from_value(value.clone()) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - toml::to_string_pretty(&toml_value) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))? + let toml_value: toml::Value = serde_json::from_value(value.clone())?; + toml::to_string_pretty(&toml_value)? } else { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Root of TOML must be an object", - )); + anyhow::bail!("Root of TOML must be an object"); } } FormatType::Xml => json_to_xml(value), _ => unreachable!(), }; - fs::write(path, content) + fs::write(path, content)?; + Ok(()) } } -fn xml_to_json(content: &str) -> io::Result { +fn xml_to_json(content: &str) -> anyhow::Result { use quick_xml::reader::Reader; use quick_xml::events::Event; @@ -64,7 +53,7 @@ fn xml_to_json(content: &str) -> io::Result { reader.config_mut().trim_text(true); let mut buf = Vec::new(); - fn parse_recursive(reader: &mut Reader<&[u8]>) -> io::Result { + fn parse_recursive(reader: &mut Reader<&[u8]>) -> anyhow::Result { let mut map = Map::new(); let mut text = String::new(); let mut buf = Vec::new(); @@ -276,14 +265,14 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut } impl FormatHandler for HierarchicalHandler { - fn parse(&self, path: &Path) -> io::Result> { + fn parse(&self, path: &Path) -> anyhow::Result> { let value = self.read_value(path)?; let mut vars = Vec::new(); flatten(&value, "", 0, "", &mut vars); Ok(vars) } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> { let mut root = Value::Object(Map::new()); for var in vars { if !var.is_group { diff --git a/src/format/ini.rs b/src/format/ini.rs index 2582739..29583d1 100644 --- a/src/format/ini.rs +++ b/src/format/ini.rs @@ -1,14 +1,12 @@ use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; use ini::Ini; -use std::io; use std::path::Path; pub struct IniHandler; impl FormatHandler for IniHandler { - fn parse(&self, path: &Path) -> io::Result> { - let conf = Ini::load_from_file(path) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + fn parse(&self, path: &Path) -> anyhow::Result> { + let conf = Ini::load_from_file(path)?; let mut vars = Vec::new(); for (section, prop) in &conf { @@ -52,7 +50,7 @@ impl FormatHandler for IniHandler { Ok(vars) } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> { let mut conf = Ini::new(); for var in vars { if !var.is_group { @@ -67,8 +65,8 @@ impl FormatHandler for IniHandler { } } } - conf.write_to_file(path) - .map_err(io::Error::other) + conf.write_to_file(path)?; + Ok(()) } } diff --git a/src/format/mod.rs b/src/format/mod.rs index ed5f0e2..a76c706 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -1,4 +1,3 @@ -use std::io; use std::path::Path; pub mod env; @@ -46,8 +45,8 @@ pub enum FormatType { } pub trait FormatHandler { - fn parse(&self, path: &Path) -> io::Result>; - fn merge(&self, path: &Path, vars: &mut Vec) -> io::Result<()> { + fn parse(&self, path: &Path) -> anyhow::Result>; + fn merge(&self, path: &Path, vars: &mut Vec) -> anyhow::Result<()> { if !path.exists() { return Ok(()); } @@ -82,7 +81,7 @@ pub trait FormatHandler { Ok(()) } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>; + fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()>; } pub fn detect_format(path: &Path, override_format: Option) -> FormatType { diff --git a/src/format/properties.rs b/src/format/properties.rs index 642d657..a53567d 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -1,13 +1,13 @@ use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; use java_properties::{LineContent, PropertiesIter, PropertiesWriter}; use std::fs::File; -use std::io::{self, BufReader, BufWriter}; +use std::io::{BufReader, BufWriter}; use std::path::Path; pub struct PropertiesHandler; impl FormatHandler for PropertiesHandler { - fn parse(&self, path: &Path) -> io::Result> { + fn parse(&self, path: &Path) -> anyhow::Result> { let file = File::open(path)?; let reader = BufReader::new(file); let iter = PropertiesIter::new(reader); @@ -16,7 +16,7 @@ impl FormatHandler for PropertiesHandler { let mut groups = std::collections::HashSet::new(); for line_result in iter { - let line = line_result.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let line = line_result?; if let LineContent::KVPair(path, value) = line.consume_content() { // Add groups based on dot notation @@ -62,7 +62,7 @@ impl FormatHandler for PropertiesHandler { Ok(vars) } - fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> { + fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> { let file = File::create(path)?; let writer = BufWriter::new(file); let mut prop_writer = PropertiesWriter::new(writer); @@ -72,12 +72,12 @@ impl FormatHandler for PropertiesHandler { let val = var.value.as_deref() .or(var.template_value.as_deref()) .unwrap_or(""); - prop_writer.write(&var.path, val) - .map_err(io::Error::other)?; + prop_writer.write(&var.path, val)?; } } - prop_writer.finish().map_err(io::Error::other) + prop_writer.finish()?; + Ok(()) } } diff --git a/src/main.rs b/src/main.rs index f175ac4..d01abd6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -96,10 +96,7 @@ fn main() -> anyhow::Result<()> { } } else if vars.is_empty() { // Fallback if no template and active is empty - vars = handler.parse(&input_path).map_err(|e| { - error!("Failed to parse input file: {}", e); - MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e)) - })?; + vars = handler.parse(&input_path)?; } if vars.is_empty() { From 30fd2d5d75dd6b616a27ea8d8442b178950dd0d1 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:35:07 +0100 Subject: [PATCH 07/15] fixed arrary logic --- src/app.rs | 84 ++++++--------- src/format/env.rs | 9 +- src/format/hierarchical.rs | 202 ++++++++++++++++++------------------- src/format/ini.rs | 27 ++--- src/format/mod.rs | 36 ++++++- src/format/properties.rs | 23 +++-- src/ui.rs | 4 +- 7 files changed, 198 insertions(+), 187 deletions(-) diff --git a/src/app.rs b/src/app.rs index df32417..5d1faa4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,4 +1,4 @@ -use crate::format::ConfigItem; +use crate::format::{ConfigItem, PathSegment}; use tui_input::Input; /// Represents the current operating mode of the application. @@ -195,21 +195,17 @@ impl App { let selected_path = self.vars[self.selected].path.clone(); let is_group = self.vars[self.selected].is_group; - // Identify if the item being removed is an array item - let array_info = parse_index(&selected_path); - // 1. Identify all items to remove let mut to_remove = Vec::new(); to_remove.push(self.selected); if is_group { - let prefix_dot = format!("{}.", selected_path); - let prefix_bracket = format!("{}[", selected_path); for (i, var) in self.vars.iter().enumerate() { if i == self.selected { continue; } - if var.path.starts_with(&prefix_dot) || var.path.starts_with(&prefix_bracket) { + // An item is a child if its path starts with the selected path + if var.path.starts_with(&selected_path) { to_remove.push(i); } } @@ -222,17 +218,19 @@ impl App { } // 3. Re-index subsequent array items if applicable - if let Some((base, removed_idx)) = array_info { - let base = base.to_string(); + if let Some(PathSegment::Index(removed_idx)) = selected_path.last() { + let base_path = &selected_path[..selected_path.len() - 1]; + for var in self.vars.iter_mut() { - if var.path.starts_with(&base) { - // We need to find the index segment that matches this array - if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) - && b == base && i > removed_idx { + if var.path.starts_with(base_path) && var.path.len() >= selected_path.len() { + // Check if the element at the level of the removed index is an index + if let PathSegment::Index(i) = var.path[selected_path.len() - 1] + && i > *removed_idx { let new_idx = i - 1; - var.path = format!("{}[{}]{}", base, new_idx, suffix); - // Also update key if it matches the old index exactly - if var.key == format!("[{}]", i) { + var.path[selected_path.len() - 1] = PathSegment::Index(new_idx); + + // If this was an array element itself (not a child property), update its key + if var.path.len() == selected_path.len() { var.key = format!("[{}]", new_idx); } } @@ -254,14 +252,15 @@ impl App { } self.save_undo_state(); - let (base, idx, depth) = { + let (base_path, idx, depth) = { let selected_item = &self.vars[self.selected]; if selected_item.is_group { return; } let path = &selected_item.path; - if let Some((base, idx)) = parse_index(path) { - (base.to_string(), idx, selected_item.depth) + + if let Some(PathSegment::Index(idx)) = path.last() { + (path[..path.len() - 1].to_vec(), *idx, selected_item.depth) } else { return; } @@ -276,21 +275,23 @@ impl App { // 1. Shift all items in this array that have index >= new_idx for var in self.vars.iter_mut() { - if var.path.starts_with(&base) - && let Some((b, i)) = parse_index(&var.path) - && b == base && i >= new_idx { - var.path = format!("{}[{}]", base, i + 1); - // Also update key if it was just the index - if var.key == format!("[{}]", i) { + if var.path.starts_with(&base_path) && var.path.len() > base_path.len() + && let PathSegment::Index(i) = var.path[base_path.len()] + && i >= new_idx { + var.path[base_path.len()] = PathSegment::Index(i + 1); + if var.path.len() == base_path.len() + 1 { var.key = format!("[{}]", i + 1); } } } // 2. Insert new item + let mut new_path = base_path; + new_path.push(PathSegment::Index(new_idx)); + let new_item = ConfigItem { key: format!("[{}]", new_idx), - path: format!("{}[{}]", base, new_idx), + path: new_path, value: Some("".to_string()), template_value: None, default_value: None, @@ -299,6 +300,7 @@ impl App { status: crate::format::ItemStatus::Modified, value_type: crate::format::ValueType::String, }; + self.vars.insert(insert_pos, new_item); self.selected = insert_pos; self.sync_input_with_selected(); @@ -313,7 +315,7 @@ impl App { pub fn selected_is_array(&self) -> bool { self.vars.get(self.selected) - .map(|v| !v.is_group && v.path.contains('[')) + .map(|v| !v.is_group && matches!(v.path.last(), Some(PathSegment::Index(_)))) .unwrap_or(false) } @@ -344,30 +346,4 @@ impl App { self.status_message = Some("Nothing to undo".to_string()); } } -} - -fn parse_index(path: &str) -> Option<(&str, usize)> { - if let Some(end) = path.rfind(']') { - let segment = &path[..=end]; - if let Some(start) = segment.rfind('[') - && let Ok(idx) = segment[start + 1..end].parse::() { - // Return the base and index - return Some((&path[..start], idx)); - } - } - None -} - -/// Helper to find an array segment in a path given a base prefix. -fn find_array_segment<'a>(path: &'a str, base: &str) -> Option<(&'a str, usize, &'a str)> { - if !path.starts_with(base) { - return None; - } - let remaining = &path[base.len()..]; - if remaining.starts_with('[') - && let Some(end) = remaining.find(']') - && let Ok(idx) = remaining[1..end].parse::() { - return Some((&path[..base.len()], idx, &remaining[end + 1..])); - } - None -} +} \ No newline at end of file diff --git a/src/format/env.rs b/src/format/env.rs index ad2b534..d02eacf 100644 --- a/src/format/env.rs +++ b/src/format/env.rs @@ -1,4 +1,4 @@ -use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; +use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment}; use std::fs; use std::io::Write; use std::path::Path; @@ -18,9 +18,10 @@ impl FormatHandler for EnvHandler { if let Some((key, val)) = line.split_once('=') { let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string(); + let key_str = key.trim().to_string(); vars.push(ConfigItem { - key: key.trim().to_string(), - path: key.trim().to_string(), + key: key_str.clone(), + path: vec![PathSegment::Key(key_str)], value: Some(parsed_val.clone()), template_value: Some(parsed_val.clone()), default_value: Some(parsed_val), @@ -116,7 +117,7 @@ mod tests { let file = NamedTempFile::new().unwrap(); let vars = vec![ConfigItem { key: "KEY1".to_string(), - path: "KEY1".to_string(), + path: vec![PathSegment::Key("KEY1".to_string())], value: Some("value1".to_string()), template_value: None, default_value: None, diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index c6b7464..8a6d592 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -1,4 +1,4 @@ -use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType}; +use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType, PathSegment}; use serde_json::{Map, Value}; use std::fs; use std::path::Path; @@ -153,26 +153,33 @@ fn json_to_xml(value: &Value) -> String { } } -// remove unused get_xml_root_name -// fn get_xml_root_name(content: &str) -> Option { ... } +fn flatten(value: &Value, current_path: Vec, key_name: Option, depth: usize, vars: &mut Vec) { + let mut next_path = current_path.clone(); + + if let Some(ref k) = key_name { + if !current_path.is_empty() { + // It's a key in an object, so append to path + next_path.push(PathSegment::Key(k.clone())); + } else { + // First element, maybe root + if !k.is_empty() { + next_path.push(PathSegment::Key(k.clone())); + } + } + } -fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec) { - let path = if prefix.is_empty() { - key_name.to_string() - } else if key_name.is_empty() { - prefix.to_string() - } else if key_name.starts_with('[') { - format!("{}{}", prefix, key_name) - } else { - format!("{}.{}", prefix, key_name) + let display_key = match next_path.last() { + Some(PathSegment::Key(k)) => k.clone(), + Some(PathSegment::Index(i)) => format!("[{}]", i), + None => "".to_string(), }; match value { Value::Object(map) => { - if !path.is_empty() { + if !next_path.is_empty() { vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: None, template_value: None, default_value: None, @@ -182,16 +189,16 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut value_type: ValueType::Null, }); } - let next_depth = if path.is_empty() { depth } else { depth + 1 }; + let next_depth = if next_path.is_empty() { depth } else { depth + 1 }; for (k, v) in map { - flatten(v, &path, next_depth, k, vars); + flatten(v, next_path.clone(), Some(k.clone()), next_depth, vars); } } Value::Array(arr) => { - if !path.is_empty() { + if !next_path.is_empty() { vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: None, template_value: None, default_value: None, @@ -201,16 +208,17 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut value_type: ValueType::Null, }); } - let next_depth = if path.is_empty() { depth } else { depth + 1 }; + let next_depth = if next_path.is_empty() { depth } else { depth + 1 }; for (i, v) in arr.iter().enumerate() { - let array_key = format!("[{}]", i); - flatten(v, &path, next_depth, &array_key, vars); + let mut arr_path = next_path.clone(); + arr_path.push(PathSegment::Index(i)); + flatten(v, arr_path, None, next_depth, vars); } } Value::String(s) => { vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: Some(s.clone()), template_value: Some(s.clone()), default_value: Some(s.clone()), @@ -223,8 +231,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Value::Number(n) => { let s = n.to_string(); vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: Some(s.clone()), template_value: Some(s.clone()), default_value: Some(s.clone()), @@ -237,8 +245,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Value::Bool(b) => { let s = b.to_string(); vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: Some(s.clone()), template_value: Some(s.clone()), default_value: Some(s.clone()), @@ -250,8 +258,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut } Value::Null => { vars.push(ConfigItem { - key: key_name.to_string(), - path: path.clone(), + key: display_key, + path: next_path.clone(), value: Some("".to_string()), template_value: Some("".to_string()), default_value: Some("".to_string()), @@ -268,7 +276,7 @@ impl FormatHandler for HierarchicalHandler { fn parse(&self, path: &Path) -> anyhow::Result> { let value = self.read_value(path)?; let mut vars = Vec::new(); - flatten(&value, "", 0, "", &mut vars); + flatten(&value, Vec::new(), Some("".to_string()), 0, &mut vars); Ok(vars) } @@ -286,50 +294,52 @@ impl FormatHandler for HierarchicalHandler { } } -fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type: ValueType) { - let mut parts = path.split('.'); - let last_part = match parts.next_back() { - Some(p) => p, - None => return, - }; +fn insert_into_value(root: &mut Value, path: &[PathSegment], new_val_str: &str, value_type: ValueType) { + if path.is_empty() { + return; + } let mut current = root; - for part in parts { - let (key, idx) = parse_array_key(part); - if !current.is_object() { - *current = Value::Object(Map::new()); - } - let map = current.as_object_mut().unwrap(); + + // Traverse all but the last segment + for i in 0..path.len() - 1 { + let segment = &path[i]; + let next_segment = &path[i + 1]; - let next_node = map.entry(key.to_string()).or_insert_with(|| { - if idx.is_some() { - Value::Array(Vec::new()) - } else { - Value::Object(Map::new()) + match segment { + PathSegment::Key(key) => { + if !current.is_object() { + *current = Value::Object(Map::new()); + } + let map = current.as_object_mut().unwrap(); + + let next_node = map.entry(key.clone()).or_insert_with(|| { + match next_segment { + PathSegment::Index(_) => Value::Array(Vec::new()), + PathSegment::Key(_) => Value::Object(Map::new()), + } + }); + current = next_node; } - }); - - if let Some(i) = idx { - if !next_node.is_array() { - *next_node = Value::Array(Vec::new()); + PathSegment::Index(idx) => { + if !current.is_array() { + *current = Value::Array(Vec::new()); + } + let arr = current.as_array_mut().unwrap(); + while arr.len() <= *idx { + match next_segment { + PathSegment::Index(_) => arr.push(Value::Array(Vec::new())), + PathSegment::Key(_) => arr.push(Value::Object(Map::new())), + } + } + current = &mut arr[*idx]; } - let arr = next_node.as_array_mut().unwrap(); - while arr.len() <= i { - arr.push(Value::Object(Map::new())); - } - current = &mut arr[i]; - } else { - current = next_node; } } - let (final_key, final_idx) = parse_array_key(last_part); - if !current.is_object() { - *current = Value::Object(Map::new()); - } - let map = current.as_object_mut().unwrap(); - - // Use the preserved ValueType instead of aggressive inference + // Handle the final segment + let final_segment = &path[path.len() - 1]; + let final_val = match value_type { ValueType::Number => { if let Ok(n) = new_val_str.parse::() { @@ -355,31 +365,24 @@ fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type _ => Value::String(new_val_str.to_string()), }; - if let Some(i) = final_idx { - let next_node = map - .entry(final_key.to_string()) - .or_insert_with(|| Value::Array(Vec::new())); - if !next_node.is_array() { - *next_node = Value::Array(Vec::new()); + match final_segment { + PathSegment::Key(key) => { + if !current.is_object() { + *current = Value::Object(Map::new()); + } + let map = current.as_object_mut().unwrap(); + map.insert(key.clone(), final_val); } - let arr = next_node.as_array_mut().unwrap(); - while arr.len() <= i { - arr.push(Value::Null); + PathSegment::Index(idx) => { + if !current.is_array() { + *current = Value::Array(Vec::new()); + } + let arr = current.as_array_mut().unwrap(); + while arr.len() <= *idx { + arr.push(Value::Null); + } + arr[*idx] = final_val; } - arr[i] = final_val; - } else { - map.insert(final_key.to_string(), final_val); - } -} - -fn parse_array_key(part: &str) -> (&str, Option) { - if part.ends_with(']') && part.contains('[') { - let start_idx = part.find('[').unwrap(); - let key = &part[..start_idx]; - let idx = part[start_idx + 1..part.len() - 1].parse::().ok(); - (key, idx) - } else { - (part, None) } } @@ -401,7 +404,7 @@ mod tests { } }); - flatten(&json, "", 0, "", &mut vars); + flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars); assert_eq!(vars.len(), 6); let mut root = Value::Object(Map::new()); @@ -411,7 +414,6 @@ mod tests { } } - // When unflattening, it parses bool back let unflattened_json = serde_json::to_string(&root).unwrap(); assert!(unflattened_json.contains("\"8080:80\"")); assert!(unflattened_json.contains("true")); @@ -420,7 +422,6 @@ mod tests { #[test] fn test_type_preservation() { let mut vars = Vec::new(); - // A JSON with various tricky types let json = serde_json::json!({ "port_num": 8080, "port_str": "8080", @@ -430,7 +431,7 @@ mod tests { "float_str": "42.42" }); - flatten(&json, "", 0, "", &mut vars); + flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars); let mut root = Value::Object(Map::new()); for var in vars { @@ -439,7 +440,6 @@ mod tests { } } - // Validate that types are exactly preserved after re-assembling let unflattened = root.as_object().unwrap(); assert!(unflattened["port_num"].is_number(), "port_num should be a number"); @@ -471,7 +471,7 @@ server: "; let yaml_val: Value = serde_yaml::from_str(yaml_str).unwrap(); let mut vars = Vec::new(); - flatten(&yaml_val, "", 0, "", &mut vars); + flatten(&yaml_val, Vec::new(), Some("".to_string()), 0, &mut vars); let mut root = Value::Object(Map::new()); for var in vars { @@ -482,7 +482,6 @@ server: let unflattened_yaml = serde_yaml::to_string(&root).unwrap(); assert!(unflattened_yaml.contains("port: 8080")); - // Serde YAML might output '8080' or "8080" assert!(unflattened_yaml.contains("port_str: '8080'") || unflattened_yaml.contains("port_str: \"8080\"")); assert!(unflattened_yaml.contains("enabled: true")); } @@ -495,12 +494,11 @@ port = 8080 port_str = \"8080\" enabled = true "; - // parse to toml Value, then convert to serde_json Value to reuse the same flatten path let toml_val: toml::Value = toml::from_str(toml_str).unwrap(); let json_val: Value = serde_json::to_value(toml_val).unwrap(); let mut vars = Vec::new(); - flatten(&json_val, "", 0, "", &mut vars); + flatten(&json_val, Vec::new(), Some("".to_string()), 0, &mut vars); let mut root = Value::Object(Map::new()); for var in vars { @@ -509,7 +507,6 @@ enabled = true } } - // Convert back to TOML let toml_root: toml::Value = serde_json::from_value(root).unwrap(); let unflattened_toml = toml::to_string(&toml_root).unwrap(); @@ -525,7 +522,7 @@ enabled = true let json_val = xml_to_json(xml_str).unwrap(); let mut vars = Vec::new(); - flatten(&json_val, "", 0, "", &mut vars); + flatten(&json_val, Vec::new(), Some("".to_string()), 0, &mut vars); let mut root = Value::Object(Map::new()); for var in vars { @@ -534,7 +531,6 @@ enabled = true } } - println!("Reconstructed root: {:?}", root); let unflattened_xml = json_to_xml(&root); assert!(unflattened_xml.contains("8080")); diff --git a/src/format/ini.rs b/src/format/ini.rs index 29583d1..6888dc8 100644 --- a/src/format/ini.rs +++ b/src/format/ini.rs @@ -1,4 +1,4 @@ -use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; +use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment}; use ini::Ini; use std::path::Path; @@ -15,7 +15,7 @@ impl FormatHandler for IniHandler { if !section_name.is_empty() { vars.push(ConfigItem { key: section_name.to_string(), - path: section_name.to_string(), + path: vec![PathSegment::Key(section_name.to_string())], value: None, template_value: None, default_value: None, @@ -28,9 +28,9 @@ impl FormatHandler for IniHandler { for (key, value) in prop { let path = if section_name.is_empty() { - key.to_string() + vec![PathSegment::Key(key.to_string())] } else { - format!("{}.{}", section_name, key) + vec![PathSegment::Key(section_name.to_string()), PathSegment::Key(key.to_string())] }; vars.push(ConfigItem { @@ -58,11 +58,14 @@ impl FormatHandler for IniHandler { .or(var.template_value.as_deref()) .unwrap_or(""); - if let Some((section, key)) = var.path.split_once('.') { - conf.with_section(Some(section)).set(key, val); - } else { - conf.with_section(None::).set(&var.path, val); - } + if var.path.len() == 2 { + if let (PathSegment::Key(section), PathSegment::Key(key)) = (&var.path[0], &var.path[1]) { + conf.with_section(Some(section)).set(key, val); + } + } else if var.path.len() == 1 + && let PathSegment::Key(key) = &var.path[0] { + conf.with_section(None::).set(key, val); + } } } conf.write_to_file(path)?; @@ -84,8 +87,8 @@ mod tests { let handler = IniHandler; let vars = handler.parse(file.path()).unwrap(); - assert!(vars.iter().any(|v| v.path == "server" && v.is_group)); - assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080"))); - assert!(vars.iter().any(|v| v.path == "database.host" && v.value.as_deref() == Some("localhost"))); + assert!(vars.iter().any(|v| v.path_string() == "server" && v.is_group)); + assert!(vars.iter().any(|v| v.path_string() == "server.port" && v.value.as_deref() == Some("8080"))); + assert!(vars.iter().any(|v| v.path_string() == "database.host" && v.value.as_deref() == Some("localhost"))); } } diff --git a/src/format/mod.rs b/src/format/mod.rs index a76c706..afd44c3 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -20,10 +20,25 @@ pub enum ValueType { Null, } +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum PathSegment { + Key(String), + Index(usize), +} + +impl std::fmt::Display for PathSegment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PathSegment::Key(k) => write!(f, "{}", k), + PathSegment::Index(i) => write!(f, "[{}]", i), + } + } +} + #[derive(Debug, Clone)] pub struct ConfigItem { pub key: String, - pub path: String, + pub path: Vec, pub value: Option, pub template_value: Option, pub default_value: Option, @@ -33,6 +48,25 @@ pub struct ConfigItem { pub value_type: ValueType, } +impl ConfigItem { + pub fn path_string(&self) -> String { + let mut s = String::new(); + for (i, segment) in self.path.iter().enumerate() { + match segment { + PathSegment::Key(k) => { + if i > 0 { + s.push('.'); + } + s.push_str(k); + } + PathSegment::Index(idx) => { + s.push_str(&format!("[{}]", idx)); + } + } + } + s + } +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FormatType { Env, diff --git a/src/format/properties.rs b/src/format/properties.rs index a53567d..4ca0b7d 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -1,4 +1,4 @@ -use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; +use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment}; use java_properties::{LineContent, PropertiesIter, PropertiesWriter}; use std::fs::File; use std::io::{BufReader, BufWriter}; @@ -21,13 +21,10 @@ impl FormatHandler for PropertiesHandler { if let LineContent::KVPair(path, value) = line.consume_content() { // Add groups based on dot notation let parts: Vec<&str> = path.split('.').collect(); - let mut current_path = String::new(); + let mut current_path = Vec::new(); for (i, part) in parts.iter().enumerate().take(parts.len().saturating_sub(1)) { - if !current_path.is_empty() { - current_path.push('.'); - } - current_path.push_str(part); + current_path.push(PathSegment::Key(part.to_string())); if groups.insert(current_path.clone()) { vars.push(ConfigItem { @@ -44,9 +41,13 @@ impl FormatHandler for PropertiesHandler { } } + let mut final_path = current_path.clone(); + let last_key = parts.last().unwrap_or(&"").to_string(); + final_path.push(PathSegment::Key(last_key.clone())); + vars.push(ConfigItem { - key: parts.last().unwrap_or(&"").to_string(), - path: path.clone(), + key: last_key, + path: final_path, value: Some(value.clone()), template_value: Some(value.clone()), default_value: Some(value.clone()), @@ -72,7 +73,7 @@ impl FormatHandler for PropertiesHandler { let val = var.value.as_deref() .or(var.template_value.as_deref()) .unwrap_or(""); - prop_writer.write(&var.path, val)?; + prop_writer.write(&var.path_string(), val)?; } } @@ -95,7 +96,7 @@ mod tests { let handler = PropertiesHandler; let vars = handler.parse(file.path()).unwrap(); - assert!(vars.iter().any(|v| v.path == "server" && v.is_group)); - assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080"))); + assert!(vars.iter().any(|v| v.path_string() == "server" && v.is_group)); + assert!(vars.iter().any(|v| v.path_string() == "server.port" && v.value.as_deref() == Some("8080"))); } } diff --git a/src/ui.rs b/src/ui.rs index 629e26b..6433510 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -189,9 +189,9 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { if let Some(var) = current_var { if var.is_group { - input_title = format!(" Group: {} ", var.path); + input_title = format!(" Group: {} ", var.path_string()); } else { - input_title = format!(" Editing: {} ", var.path); + input_title = format!(" Editing: {} ", var.path_string()); if let Some(t_val) = &var.template_value { extra_info = format!(" [Template: {}]", t_val); } From a2ec8660c78058831a4177a2b2f24ecacb99743c Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:38:05 +0100 Subject: [PATCH 08/15] fixed pretty format for xml --- src/format/hierarchical.rs | 113 ++++++++++++++++++++++++++++--------- 1 file changed, 87 insertions(+), 26 deletions(-) diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index 8a6d592..51db009 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -119,38 +119,99 @@ fn xml_to_json(content: &str) -> anyhow::Result { } fn json_to_xml(value: &Value) -> String { - match value { - Value::Object(map) => { - let mut s = String::new(); - for (k, v) in map { - if k == "$text" { - s.push_str(v.as_str().unwrap_or("")); - } else if let Some(arr) = v.as_array() { - for item in arr { - s.push_str(&format!("<{}>", k)); - s.push_str(&json_to_xml(item)); - s.push_str(&format!("", k)); + use quick_xml::Writer; + use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText}; + + let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4); + + fn write_recursive(writer: &mut Writer>, value: &Value, key_name: Option<&str>) { + if let Some(k) = key_name { + if k == "$text" { + if let Some(s) = value.as_str() { + writer.write_event(Event::Text(BytesText::new(s))).unwrap(); + } + return; + } + } + + match value { + Value::Object(map) => { + if let Some(k) = key_name { + writer.write_event(Event::Start(BytesStart::new(k))).unwrap(); + } + for (k, v) in map { + if let Some(arr) = v.as_array() { + for item in arr { + write_recursive(writer, item, Some(k)); + } + } else { + write_recursive(writer, v, Some(k)); } - } else { - s.push_str(&format!("<{}>", k)); - s.push_str(&json_to_xml(v)); - s.push_str(&format!("", k)); + } + if let Some(k) = key_name { + writer.write_event(Event::End(BytesEnd::new(k))).unwrap(); } } - s - } - Value::Array(arr) => { - let mut s = String::new(); - for v in arr { - s.push_str(&json_to_xml(v)); + Value::Array(arr) => { + for v in arr { + write_recursive(writer, v, key_name); + } + } + Value::String(s) => { + if let Some(k) = key_name { + writer.write_event(Event::Start(BytesStart::new(k))).unwrap(); + } + writer.write_event(Event::Text(BytesText::new(s))).unwrap(); + if let Some(k) = key_name { + writer.write_event(Event::End(BytesEnd::new(k))).unwrap(); + } + } + Value::Number(n) => { + if let Some(k) = key_name { + writer.write_event(Event::Start(BytesStart::new(k))).unwrap(); + } + writer.write_event(Event::Text(BytesText::new(&n.to_string()))).unwrap(); + if let Some(k) = key_name { + writer.write_event(Event::End(BytesEnd::new(k))).unwrap(); + } + } + Value::Bool(b) => { + if let Some(k) = key_name { + writer.write_event(Event::Start(BytesStart::new(k))).unwrap(); + } + writer.write_event(Event::Text(BytesText::new(&b.to_string()))).unwrap(); + if let Some(k) = key_name { + writer.write_event(Event::End(BytesEnd::new(k))).unwrap(); + } + } + Value::Null => { + if let Some(k) = key_name { + writer.write_event(Event::Empty(BytesStart::new(k))).unwrap(); + } } - s } - Value::String(v) => v.clone(), - Value::Number(v) => v.to_string(), - Value::Bool(v) => v.to_string(), - Value::Null => "".to_string(), } + + if value.is_object() { + for (k, v) in value.as_object().unwrap() { + if let Some(arr) = v.as_array() { + for item in arr { + write_recursive(&mut writer, item, Some(k)); + } + } else { + write_recursive(&mut writer, v, Some(k)); + } + } + } else { + write_recursive(&mut writer, value, None); + } + + // Quick-XML adds a trailing newline occasionally, or we might need one + let mut out = String::from_utf8(writer.into_inner()).unwrap(); + if !out.ends_with('\n') { + out.push('\n'); + } + out } fn flatten(value: &Value, current_path: Vec, key_name: Option, depth: usize, vars: &mut Vec) { From ca7ebc956398d0847b77ef987608bf22ec66512c Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 17:48:31 +0100 Subject: [PATCH 09/15] implemented undotree with redo --- src/app.rs | 37 ++++++--- src/config.rs | 12 +-- src/format/hierarchical.rs | 5 +- src/main.rs | 1 + src/runner.rs | 2 + src/undo.rs | 159 +++++++++++++++++++++++++++++++++++++ 6 files changed, 197 insertions(+), 19 deletions(-) create mode 100644 src/undo.rs diff --git a/src/app.rs b/src/app.rs index 5d1faa4..3b3b022 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,5 +1,6 @@ use crate::format::{ConfigItem, PathSegment}; use tui_input::Input; +use crate::undo::UndoTree; /// Represents the current operating mode of the application. pub enum Mode { @@ -33,14 +34,15 @@ pub struct App { pub input: Input, /// The current search query for filtering keys. pub search_query: String, - /// Stack of previous variable states for undo functionality. - pub undo_stack: Vec>, + /// Undo history structured as a tree + pub undo_tree: UndoTree, } impl App { /// Initializes a new application instance with the provided variables. pub fn new(vars: Vec) -> Self { let initial_input = vars.first().and_then(|v| v.value.clone()).unwrap_or_default(); + let undo_tree = UndoTree::new(vars.clone(), 0); Self { vars, selected: 0, @@ -49,7 +51,7 @@ impl App { status_message: None, input: Input::new(initial_input), search_query: String::new(), - undo_stack: Vec::new(), + undo_tree, } } @@ -325,18 +327,16 @@ impl App { .unwrap_or(false) } - /// Saves the current state of variables to the undo stack. + /// Saves the current state of variables to the undo tree. pub fn save_undo_state(&mut self) { - self.undo_stack.push(self.vars.clone()); - if self.undo_stack.len() > 50 { - self.undo_stack.remove(0); - } + self.undo_tree.push(self.vars.clone(), self.selected); } - /// Reverts to the last saved state of variables. + /// Reverts to the previous state in the undo tree. pub fn undo(&mut self) { - if let Some(previous_vars) = self.undo_stack.pop() { - self.vars = previous_vars; + if let Some(action) = self.undo_tree.undo() { + self.vars = action.state.clone(); + self.selected = action.selected; if self.selected >= self.vars.len() && !self.vars.is_empty() { self.selected = self.vars.len() - 1; } @@ -346,4 +346,19 @@ impl App { self.status_message = Some("Nothing to undo".to_string()); } } + + /// Advances to the next state in the undo tree. + pub fn redo(&mut self) { + if let Some(action) = self.undo_tree.redo() { + self.vars = action.state.clone(); + self.selected = action.selected; + if self.selected >= self.vars.len() && !self.vars.is_empty() { + self.selected = self.vars.len() - 1; + } + self.sync_input_with_selected(); + self.status_message = Some("Redo applied".to_string()); + } else { + self.status_message = Some("Nothing to redo".to_string()); + } + } } \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 4eaf84e..dfe592a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -120,16 +120,17 @@ pub struct KeybindsConfig { pub prepend_item: String, pub delete_item: String, pub undo: String, -} + pub redo: String, + } -impl Default for KeybindsConfig { + impl Default for KeybindsConfig { fn default() -> Self { Self { down: "j".to_string(), up: "k".to_string(), edit: "i".to_string(), - edit_append: "A".to_string(), - edit_substitute: "S".to_string(), + edit_append: "a".to_string(), + edit_substitute: "s".to_string(), save: ":w".to_string(), quit: ":q".to_string(), normal_mode: "Esc".to_string(), @@ -142,9 +143,10 @@ impl Default for KeybindsConfig { prepend_item: "O".to_string(), delete_item: "dd".to_string(), undo: "u".to_string(), + redo: "U".to_string(), } } -} + } /// Root configuration structure for mould. #[derive(Debug, Deserialize, Serialize, Default, Clone)] diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index 51db009..686799f 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -125,14 +125,13 @@ fn json_to_xml(value: &Value) -> String { let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4); fn write_recursive(writer: &mut Writer>, value: &Value, key_name: Option<&str>) { - if let Some(k) = key_name { - if k == "$text" { + if let Some(k) = key_name + && k == "$text" { if let Some(s) = value.as_str() { writer.write_event(Event::Text(BytesText::new(s))).unwrap(); } return; } - } match value { Value::Object(map) => { diff --git a/src/main.rs b/src/main.rs index d01abd6..c8476a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod format; mod runner; mod ui; mod resolver; +mod undo; use app::App; use config::load_config; diff --git a/src/runner.rs b/src/runner.rs index 47b5d95..3992ed6 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -128,6 +128,7 @@ where (&self.config.keybinds.prepend_item, "prepend_item"), (&self.config.keybinds.delete_item, "delete_item"), (&self.config.keybinds.undo, "undo"), + (&self.config.keybinds.redo, "redo"), (&"a".to_string(), "add_missing"), (&":".to_string(), "command"), (&"q".to_string(), "quit"), @@ -166,6 +167,7 @@ where "prepend_item" => self.app.add_array_item(false), "delete_item" => self.app.delete_selected(), "undo" => self.app.undo(), + "redo" => self.app.redo(), "add_missing" => { self.app.save_undo_state(); self.add_missing_item(); diff --git a/src/undo.rs b/src/undo.rs new file mode 100644 index 0000000..45c944d --- /dev/null +++ b/src/undo.rs @@ -0,0 +1,159 @@ +use crate::format::ConfigItem; +use std::collections::HashMap; + +pub struct EditAction { + pub state: Vec, + pub selected: usize, +} + +pub struct UndoNode { + pub action: EditAction, + pub parent: Option, + pub children: Vec, +} + +pub struct UndoTree { + nodes: HashMap, + current_node: usize, + next_id: usize, + // Track the latest child added to a node to know which branch to follow on redo + latest_branch: HashMap, +} + +impl UndoTree { + pub fn new(initial_state: Vec, initial_selected: usize) -> Self { + let root_id = 0; + let root_node = UndoNode { + action: EditAction { + state: initial_state, + selected: initial_selected, + }, + parent: None, + children: Vec::new(), + }; + + let mut nodes = HashMap::new(); + nodes.insert(root_id, root_node); + + Self { + nodes, + current_node: root_id, + next_id: 1, + latest_branch: HashMap::new(), + } + } + + pub fn push(&mut self, state: Vec, selected: usize) { + let new_id = self.next_id; + self.next_id += 1; + + let new_node = UndoNode { + action: EditAction { state, selected }, + parent: Some(self.current_node), + children: Vec::new(), + }; + + // Add to nodes + self.nodes.insert(new_id, new_node); + + // Update parent's children + if let Some(parent_node) = self.nodes.get_mut(&self.current_node) { + parent_node.children.push(new_id); + } + + // Record this as the latest branch for the parent + self.latest_branch.insert(self.current_node, new_id); + + // Move current pointer + self.current_node = new_id; + } + + pub fn undo(&mut self) -> Option<&EditAction> { + if let Some(current) = self.nodes.get(&self.current_node) + && let Some(parent_id) = current.parent { + self.current_node = parent_id; + return self.nodes.get(&parent_id).map(|n| &n.action); + } + None + } + + pub fn redo(&mut self) -> Option<&EditAction> { + if let Some(next_id) = self.latest_branch.get(&self.current_node).copied() { + self.current_node = next_id; + return self.nodes.get(&next_id).map(|n| &n.action); + } else { + // Fallback: if there is no recorded latest branch but there are children + if let Some(current) = self.nodes.get(&self.current_node) + && let Some(&first_child_id) = current.children.last() { + self.current_node = first_child_id; + self.latest_branch.insert(self.current_node, first_child_id); + return self.nodes.get(&first_child_id).map(|n| &n.action); + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::format::{ItemStatus, ValueType}; + + fn dummy_item(key: &str) -> ConfigItem { + ConfigItem { + key: key.to_string(), + path: vec![], + value: Some(key.to_string()), + template_value: None, + default_value: None, + depth: 0, + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + } + } + + #[test] + fn test_undo_redo_tree() { + let state1 = vec![dummy_item("A")]; + let mut tree = UndoTree::new(state1.clone(), 0); + + // Push state 2 + let state2 = vec![dummy_item("B")]; + tree.push(state2.clone(), 1); + + // Push state 3 + let state3 = vec![dummy_item("C")]; + tree.push(state3.clone(), 2); + + // Undo -> State 2 + let action = tree.undo().unwrap(); + assert_eq!(action.state[0].key, "B"); + assert_eq!(action.selected, 1); + + // Undo -> State 1 + let action = tree.undo().unwrap(); + assert_eq!(action.state[0].key, "A"); + assert_eq!(action.selected, 0); + + // Undo again -> None (already at root) + assert!(tree.undo().is_none()); + + // Redo -> State 2 + let action = tree.redo().unwrap(); + assert_eq!(action.state[0].key, "B"); + assert_eq!(action.selected, 1); + + // Branching: Push State 4 (from State 2) + let state4 = vec![dummy_item("D")]; + tree.push(state4.clone(), 3); + + // Undo -> State 2 + let action = tree.undo().unwrap(); + assert_eq!(action.state[0].key, "B"); + + // Redo -> State 4 (follows latest branch D, not old branch C) + let action = tree.redo().unwrap(); + assert_eq!(action.state[0].key, "D"); + } +} From 51625ed29675c83281d86baf6a774916bc02c7c9 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 18:31:29 +0100 Subject: [PATCH 10/15] fixed undo trees and inputs + S substitute insert --- src/app.rs | 145 +++++++++++++++++++++++++++++++++++--------------- src/runner.rs | 6 +-- src/undo.rs | 40 +++++++++++--- 3 files changed, 140 insertions(+), 51 deletions(-) diff --git a/src/app.rs b/src/app.rs index 3b3b022..6f7425e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -163,7 +163,6 @@ impl App { pub fn enter_insert(&mut self, variant: InsertVariant) { if let Some(var) = self.vars.get(self.selected) && !var.is_group { - self.save_undo_state(); self.mode = Mode::Insert; match variant { InsertVariant::Start => { @@ -184,6 +183,7 @@ impl App { /// Commits the current input and transitions the application into Normal Mode. pub fn enter_normal(&mut self) { self.commit_input(); + self.save_undo_state(); self.mode = Mode::Normal; } @@ -193,7 +193,6 @@ impl App { return; } - self.save_undo_state(); let selected_path = self.vars[self.selected].path.clone(); let is_group = self.vars[self.selected].is_group; @@ -245,67 +244,129 @@ impl App { self.selected = self.vars.len() - 1; } self.sync_input_with_selected(); + self.save_undo_state(); } - /// Adds a new item to an array if the selected item is part of one. - pub fn add_array_item(&mut self, after: bool) { + /// Adds a new item relative to the selected item. + pub fn add_item(&mut self, after: bool) { if self.vars.is_empty() { + let new_key = "NEW_VAR".to_string(); + self.vars.push(ConfigItem { + key: new_key.clone(), + path: vec![PathSegment::Key(new_key)], + value: Some("".to_string()), + template_value: None, + default_value: None, + depth: 0, + is_group: false, + status: crate::format::ItemStatus::Modified, + value_type: crate::format::ValueType::String, + }); + self.selected = 0; + self.sync_input_with_selected(); + self.save_undo_state(); + self.enter_insert(InsertVariant::Start); return; } - self.save_undo_state(); - let (base_path, idx, depth) = { - let selected_item = &self.vars[self.selected]; - if selected_item.is_group { - return; - } - let path = &selected_item.path; + let selected_item = self.vars[self.selected].clone(); + + // 1. Determine new item properties (path, key, depth, position) + let mut new_path; + let new_depth; + let insert_pos; + let mut is_array_item = false; + + if let Some(PathSegment::Index(idx)) = selected_item.path.last() { + // ARRAY ITEM LOGIC + is_array_item = true; + let base_path = selected_item.path[..selected_item.path.len() - 1].to_vec(); + let new_idx = if after { idx + 1 } else { *idx }; + insert_pos = if after { self.selected + 1 } else { self.selected }; - if let Some(PathSegment::Index(idx)) = path.last() { - (path[..path.len() - 1].to_vec(), *idx, selected_item.depth) - } else { - return; - } - }; - - let new_idx = if after { idx + 1 } else { idx }; - let insert_pos = if after { - self.selected + 1 - } else { - self.selected - }; - - // 1. Shift all items in this array that have index >= new_idx - for var in self.vars.iter_mut() { - if var.path.starts_with(&base_path) && var.path.len() > base_path.len() - && let PathSegment::Index(i) = var.path[base_path.len()] - && i >= new_idx { - var.path[base_path.len()] = PathSegment::Index(i + 1); - if var.path.len() == base_path.len() + 1 { - var.key = format!("[{}]", i + 1); + // Shift subsequent indices + for var in self.vars.iter_mut() { + if var.path.starts_with(&base_path) && var.path.len() > base_path.len() + && let PathSegment::Index(i) = var.path[base_path.len()] + && i >= new_idx { + var.path[base_path.len()] = PathSegment::Index(i + 1); + if var.path.len() == base_path.len() + 1 { + var.key = format!("[{}]", i + 1); + } } - } + } + + new_path = base_path; + new_path.push(PathSegment::Index(new_idx)); + new_depth = selected_item.depth; + } else if after && selected_item.is_group { + // ADD AS CHILD OF GROUP + insert_pos = self.selected + 1; + new_path = selected_item.path.clone(); + new_depth = selected_item.depth + 1; + } else { + // ADD AS SIBLING + let parent_path = if selected_item.path.len() > 1 { + selected_item.path[..selected_item.path.len() - 1].to_vec() + } else { + Vec::new() + }; + + insert_pos = if after { + let mut p = self.selected + 1; + while p < self.vars.len() && self.vars[p].path.starts_with(&selected_item.path) { + p += 1; + } + p + } else { + self.selected + }; + + new_path = parent_path; + new_depth = selected_item.depth; } - // 2. Insert new item - let mut new_path = base_path; - new_path.push(PathSegment::Index(new_idx)); - + // 2. Generate a unique key for non-array items + let final_key = if is_array_item { + if let Some(PathSegment::Index(idx)) = new_path.last() { + format!("[{}]", idx) + } else { + "NEW_VAR".to_string() + } + } else { + let mut count = 1; + let mut candidate = "NEW_VAR".to_string(); + let parent_path_slice = new_path.as_slice(); + + while self.vars.iter().any(|v| { + v.path.starts_with(parent_path_slice) + && v.path.len() == parent_path_slice.len() + 1 + && v.key == candidate + }) { + candidate = format!("NEW_VAR_{}", count); + count += 1; + } + new_path.push(PathSegment::Key(candidate.clone())); + candidate + }; + + // 3. Insert new item let new_item = ConfigItem { - key: format!("[{}]", new_idx), + key: final_key, path: new_path, value: Some("".to_string()), template_value: None, default_value: None, - depth, + depth: new_depth, is_group: false, status: crate::format::ItemStatus::Modified, value_type: crate::format::ValueType::String, }; - + self.vars.insert(insert_pos, new_item); self.selected = insert_pos; self.sync_input_with_selected(); + self.save_undo_state(); self.enter_insert(InsertVariant::Start); self.status_message = None; } @@ -361,4 +422,4 @@ impl App { self.status_message = Some("Nothing to redo".to_string()); } } -} \ No newline at end of file +} diff --git a/src/runner.rs b/src/runner.rs index 3992ed6..c113288 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -163,13 +163,12 @@ where "previous_match" => self.app.jump_previous_match(), "jump_top" => self.app.jump_top(), "jump_bottom" => self.app.jump_bottom(), - "append_item" => self.app.add_array_item(true), - "prepend_item" => self.app.add_array_item(false), + "append_item" => self.app.add_item(true), + "prepend_item" => self.app.add_item(false), "delete_item" => self.app.delete_selected(), "undo" => self.app.undo(), "redo" => self.app.redo(), "add_missing" => { - self.app.save_undo_state(); self.add_missing_item(); } "command" => { @@ -207,6 +206,7 @@ where var.value = var.template_value.clone(); } self.app.sync_input_with_selected(); + self.app.save_undo_state(); } } diff --git a/src/undo.rs b/src/undo.rs index 45c944d..5980d7f 100644 --- a/src/undo.rs +++ b/src/undo.rs @@ -83,10 +83,11 @@ impl UndoTree { return self.nodes.get(&next_id).map(|n| &n.action); } else { // Fallback: if there is no recorded latest branch but there are children - if let Some(current) = self.nodes.get(&self.current_node) + let current_id = self.current_node; + if let Some(current) = self.nodes.get(¤t_id) && let Some(&first_child_id) = current.children.last() { self.current_node = first_child_id; - self.latest_branch.insert(self.current_node, first_child_id); + self.latest_branch.insert(current_id, first_child_id); return self.nodes.get(&first_child_id).map(|n| &n.action); } } @@ -144,16 +145,43 @@ mod tests { assert_eq!(action.state[0].key, "B"); assert_eq!(action.selected, 1); - // Branching: Push State 4 (from State 2) + // Redo -> State 3 + let action = tree.redo().unwrap(); + assert_eq!(action.state[0].key, "C"); + assert_eq!(action.selected, 2); + + // Branching: Undo twice to State 1 + tree.undo(); + tree.undo(); + + // Push State 4 (from State 1) let state4 = vec![dummy_item("D")]; tree.push(state4.clone(), 3); - // Undo -> State 2 + // Undo -> State 1 let action = tree.undo().unwrap(); - assert_eq!(action.state[0].key, "B"); + assert_eq!(action.state[0].key, "A"); - // Redo -> State 4 (follows latest branch D, not old branch C) + // Redo -> State 4 (follows latest branch D, not old branch B) let action = tree.redo().unwrap(); assert_eq!(action.state[0].key, "D"); } + + #[test] + fn test_redo_fallback_fix() { + let state1 = vec![dummy_item("A")]; + let mut tree = UndoTree::new(state1.clone(), 0); + + let state2 = vec![dummy_item("B")]; + tree.push(state2.clone(), 1); + + tree.undo(); + // Redo should move to state 2 + let action = tree.redo().unwrap(); + assert_eq!(action.state[0].key, "B"); + + // Calling redo again should NOT change the current node or returned action + // (since it's already at the latest child) + assert!(tree.redo().is_none()); + } } From e3510a96fbd431eae25353431a70a82949646470 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 18:38:35 +0100 Subject: [PATCH 11/15] added rename --- src/app.rs | 111 ++++++++++++++++++++++++++++++++++++++++++++------ src/config.rs | 2 + src/runner.rs | 24 ++++++++++- src/ui.rs | 17 ++++++-- 4 files changed, 138 insertions(+), 16 deletions(-) diff --git a/src/app.rs b/src/app.rs index 6f7425e..94cf9f5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -8,6 +8,8 @@ pub enum Mode { Normal, /// Active text entry mode for modifying values. Insert, + /// Active text entry mode for modifying keys. + InsertKey, /// Active search mode for filtering keys. Search, } @@ -145,18 +147,91 @@ impl App { /// Updates the input buffer to reflect the value of the currently selected variable. pub fn sync_input_with_selected(&mut self) { if let Some(var) = self.vars.get(self.selected) { - let val = var.value.clone().unwrap_or_default(); + let val = match self.mode { + Mode::InsertKey => var.key.clone(), + _ => var.value.clone().unwrap_or_default(), + }; self.input = Input::new(val); } } - /// Commits the current text in the input buffer back to the selected variable's value. - pub fn commit_input(&mut self) { - if let Some(var) = self.vars.get_mut(self.selected) - && !var.is_group { - var.value = Some(self.input.value().to_string()); - var.status = crate::format::ItemStatus::Modified; + /// Commits the current text in the input buffer back to the selected variable's value or key. + /// Returns true if commit was successful, false if there was an error (e.g. collision). + pub fn commit_input(&mut self) -> bool { + match self.mode { + Mode::Insert => { + if let Some(var) = self.vars.get_mut(self.selected) + && !var.is_group { + var.value = Some(self.input.value().to_string()); + var.status = crate::format::ItemStatus::Modified; + } + true } + Mode::InsertKey => { + let new_key = self.input.value().trim().to_string(); + if new_key.is_empty() { + self.status_message = Some("Key cannot be empty".to_string()); + return false; + } + + let selected_var = self.vars[self.selected].clone(); + if selected_var.key == new_key { + return true; + } + + // Collision check: siblings share the same parent path + let parent_path = if selected_var.path.len() > 1 { + &selected_var.path[..selected_var.path.len() - 1] + } else { + &[] + }; + + let exists = self.vars.iter().enumerate().any(|(i, v)| { + i != self.selected + && v.path.len() == selected_var.path.len() + && v.path.starts_with(parent_path) + && v.key == new_key + }); + + if exists { + self.status_message = Some(format!("Key already exists: {}", new_key)); + return false; + } + + // Update selected item's key and path + let old_path = selected_var.path.clone(); + let mut new_path = parent_path.to_vec(); + new_path.push(PathSegment::Key(new_key.clone())); + + { + let var = self.vars.get_mut(self.selected).unwrap(); + var.key = new_key; + var.path = new_path.clone(); + var.status = crate::format::ItemStatus::Modified; + } + + // Update paths of all children if it's a group + if selected_var.is_group { + for var in self.vars.iter_mut() { + if var.path.starts_with(&old_path) && var.path.len() > old_path.len() { + let mut p = new_path.clone(); + p.extend(var.path[old_path.len()..].iter().cloned()); + var.path = p; + } + } + } + true + } + _ => true, + } + } + + /// Transitions the application into Insert Mode for keys. + pub fn enter_insert_key(&mut self) { + if !self.vars.is_empty() { + self.mode = Mode::InsertKey; + self.sync_input_with_selected(); + } } /// Transitions the application into Insert Mode with a specific variant. @@ -182,9 +257,17 @@ impl App { /// Commits the current input and transitions the application into Normal Mode. pub fn enter_normal(&mut self) { - self.commit_input(); - self.save_undo_state(); + if self.commit_input() { + self.save_undo_state(); + self.mode = Mode::Normal; + } + } + + /// Cancels the current input and transitions the application into Normal Mode. + pub fn cancel_insert(&mut self) { self.mode = Mode::Normal; + self.sync_input_with_selected(); + self.status_message = None; } /// Deletes the currently selected item. If it's a group, deletes all children. @@ -365,9 +448,13 @@ impl App { self.vars.insert(insert_pos, new_item); self.selected = insert_pos; - self.sync_input_with_selected(); - self.save_undo_state(); - self.enter_insert(InsertVariant::Start); + if is_array_item { + self.sync_input_with_selected(); + self.save_undo_state(); + self.enter_insert(InsertVariant::Start); + } else { + self.enter_insert_key(); + } self.status_message = None; } diff --git a/src/config.rs b/src/config.rs index dfe592a..479cb83 100644 --- a/src/config.rs +++ b/src/config.rs @@ -121,6 +121,7 @@ pub struct KeybindsConfig { pub delete_item: String, pub undo: String, pub redo: String, + pub rename: String, } impl Default for KeybindsConfig { @@ -144,6 +145,7 @@ pub struct KeybindsConfig { delete_item: "dd".to_string(), undo: "u".to_string(), redo: "U".to_string(), + rename: "r".to_string(), } } } diff --git a/src/runner.rs b/src/runner.rs index c113288..2b8507b 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -67,6 +67,7 @@ where match self.app.mode { Mode::Normal => self.handle_normal_mode(key), Mode::Insert => self.handle_insert_mode(key), + Mode::InsertKey => self.handle_insert_key_mode(key), Mode::Search => self.handle_search_mode(key), } } @@ -129,6 +130,7 @@ where (&self.config.keybinds.delete_item, "delete_item"), (&self.config.keybinds.undo, "undo"), (&self.config.keybinds.redo, "redo"), + (&self.config.keybinds.rename, "rename"), (&"a".to_string(), "add_missing"), (&":".to_string(), "command"), (&"q".to_string(), "quit"), @@ -168,6 +170,7 @@ where "delete_item" => self.app.delete_selected(), "undo" => self.app.undo(), "redo" => self.app.redo(), + "rename" => self.app.enter_insert_key(), "add_missing" => { self.add_missing_item(); } @@ -213,7 +216,26 @@ where /// Delegates key events to the `tui_input` handler during active editing. fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> { match key.code { - KeyCode::Esc | KeyCode::Enter => { + KeyCode::Esc => { + self.app.cancel_insert(); + } + KeyCode::Enter => { + self.app.enter_normal(); + } + _ => { + self.app.input.handle_event(&Event::Key(key)); + } + } + Ok(()) + } + + /// Handles keys in InsertKey mode. + fn handle_insert_key_mode(&mut self, key: KeyEvent) -> io::Result<()> { + match key.code { + KeyCode::Esc => { + self.app.cancel_insert(); + } + KeyCode::Enter => { self.app.enter_normal(); } _ => { diff --git a/src/ui.rs b/src/ui.rs index 6433510..9eb638c 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -188,7 +188,9 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { let mut extra_info = String::new(); if let Some(var) = current_var { - if var.is_group { + if matches!(app.mode, Mode::InsertKey) { + input_title = format!(" Rename Key: {} ", var.path_string()); + } else if var.is_group { input_title = format!(" Group: {} ", var.path_string()); } else { input_title = format!(" Editing: {} ", var.path_string()); @@ -199,7 +201,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { } let input_border_color = match app.mode { - Mode::Insert => theme.border_active(), + Mode::Insert | Mode::InsertKey => theme.border_active(), Mode::Normal | Mode::Search => theme.border_normal(), }; @@ -259,6 +261,13 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { .fg(theme.bg_normal()) .add_modifier(Modifier::BOLD), ), + Mode::InsertKey => ( + " RENAME ", + Style::default() + .bg(theme.bg_active()) + .fg(theme.bg_normal()) + .add_modifier(Modifier::BOLD), + ), Mode::Search => ( " SEARCH ", Style::default() @@ -282,6 +291,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { if !app.selected_is_group() { parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute)); } + parts.push(format!("{} rename", kb.rename)); if app.selected_is_missing() { parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner } @@ -294,7 +304,8 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { parts.push(format!("{} quit", kb.quit)); parts.join(" · ") } - Mode::Insert => "Esc normal · Enter commit".to_string(), + Mode::Insert => "Esc cancel · Enter commit".to_string(), + Mode::InsertKey => "Esc cancel · Enter rename".to_string(), Mode::Search => "Esc normal · type to filter".to_string(), } }; From 50278821ca9d71ab3ce944983d1d27d405547a54 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 18:49:43 +0100 Subject: [PATCH 12/15] implemented adding new vars --- src/app.rs | 52 ++++++++++++++++++++++++++++++-------- src/config.rs | 6 +++++ src/format/hierarchical.rs | 42 +++++++++++++++++++++--------- src/format/ini.rs | 47 ++++++++++++++++++++++++++++------ src/format/properties.rs | 45 ++++++++++++++++++++++++++++----- src/runner.rs | 31 ++++++++++++++++++----- src/ui.rs | 6 ++++- 7 files changed, 185 insertions(+), 44 deletions(-) diff --git a/src/app.rs b/src/app.rs index 94cf9f5..1e320b1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -217,6 +217,7 @@ impl App { let mut p = new_path.clone(); p.extend(var.path[old_path.len()..].iter().cloned()); var.path = p; + var.status = crate::format::ItemStatus::Modified; } } } @@ -229,6 +230,11 @@ impl App { /// Transitions the application into Insert Mode for keys. pub fn enter_insert_key(&mut self) { if !self.vars.is_empty() { + if let Some(var) = self.vars.get(self.selected) + && matches!(var.path.last(), Some(PathSegment::Index(_))) { + self.status_message = Some("Cannot rename array indices".to_string()); + return; + } self.mode = Mode::InsertKey; self.sync_input_with_selected(); } @@ -331,24 +337,28 @@ impl App { } /// Adds a new item relative to the selected item. - pub fn add_item(&mut self, after: bool) { + pub fn add_item(&mut self, after: bool, is_group: bool) { if self.vars.is_empty() { let new_key = "NEW_VAR".to_string(); self.vars.push(ConfigItem { key: new_key.clone(), path: vec![PathSegment::Key(new_key)], - value: Some("".to_string()), + value: if is_group { None } else { Some("".to_string()) }, template_value: None, default_value: None, depth: 0, - is_group: false, + is_group, status: crate::format::ItemStatus::Modified, - value_type: crate::format::ValueType::String, + value_type: if is_group { crate::format::ValueType::Null } else { crate::format::ValueType::String }, }); self.selected = 0; self.sync_input_with_selected(); self.save_undo_state(); - self.enter_insert(InsertVariant::Start); + if is_group { + self.enter_insert_key(); + } else { + self.enter_insert(InsertVariant::Start); + } return; } @@ -418,7 +428,7 @@ impl App { } } else { let mut count = 1; - let mut candidate = "NEW_VAR".to_string(); + let mut candidate = if is_group { "NEW_GROUP".to_string() } else { "NEW_VAR".to_string() }; let parent_path_slice = new_path.as_slice(); while self.vars.iter().any(|v| { @@ -426,7 +436,7 @@ impl App { && v.path.len() == parent_path_slice.len() + 1 && v.key == candidate }) { - candidate = format!("NEW_VAR_{}", count); + candidate = if is_group { format!("NEW_GROUP_{}", count) } else { format!("NEW_VAR_{}", count) }; count += 1; } new_path.push(PathSegment::Key(candidate.clone())); @@ -437,13 +447,13 @@ impl App { let new_item = ConfigItem { key: final_key, path: new_path, - value: Some("".to_string()), + value: if is_group { None } else { Some("".to_string()) }, template_value: None, default_value: None, depth: new_depth, - is_group: false, + is_group, status: crate::format::ItemStatus::Modified, - value_type: crate::format::ValueType::String, + value_type: if is_group { crate::format::ValueType::Null } else { crate::format::ValueType::String }, }; self.vars.insert(insert_pos, new_item); @@ -458,6 +468,28 @@ impl App { self.status_message = None; } + /// Toggles the group status of the currently selected item. + pub fn toggle_group_selected(&mut self) { + if let Some(var) = self.vars.get_mut(self.selected) { + // Cannot toggle array items (always vars) + if matches!(var.path.last(), Some(PathSegment::Index(_))) { + self.status_message = Some("Cannot toggle array items".to_string()); + return; + } + + var.is_group = !var.is_group; + if var.is_group { + var.value = None; + var.value_type = crate::format::ValueType::Null; + } else { + var.value = Some("".to_string()); + var.value_type = crate::format::ValueType::String; + } + var.status = crate::format::ItemStatus::Modified; + self.sync_input_with_selected(); + } + } + /// Status bar helpers pub fn selected_is_group(&self) -> bool { self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false) diff --git a/src/config.rs b/src/config.rs index 479cb83..2dadd70 100644 --- a/src/config.rs +++ b/src/config.rs @@ -122,6 +122,9 @@ pub struct KeybindsConfig { pub undo: String, pub redo: String, pub rename: String, + pub append_group: String, + pub prepend_group: String, + pub toggle_group: String, } impl Default for KeybindsConfig { @@ -146,6 +149,9 @@ pub struct KeybindsConfig { undo: "u".to_string(), redo: "U".to_string(), rename: "r".to_string(), + append_group: "alt+o".to_string(), + prepend_group: "alt+O".to_string(), + toggle_group: "t".to_string(), } } } diff --git a/src/format/hierarchical.rs b/src/format/hierarchical.rs index 686799f..29a336b 100644 --- a/src/format/hierarchical.rs +++ b/src/format/hierarchical.rs @@ -576,25 +576,43 @@ enabled = true } #[test] - fn test_xml_flatten_unflatten() { - let xml_str = "8080true"; - - let json_val = xml_to_json(xml_str).unwrap(); - + fn test_group_rename_write() { let mut vars = Vec::new(); - flatten(&json_val, Vec::new(), Some("".to_string()), 0, &mut vars); + let json = serde_json::json!({ + "old_group": { + "key": "val" + } + }); + + flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars); + assert_eq!(vars.len(), 2); + assert_eq!(vars[0].key, "old_group"); + assert_eq!(vars[0].is_group, true); + assert_eq!(vars[1].key, "key"); + assert_eq!(vars[1].path_string(), "old_group.key"); + + // Manually simulate a rename of "old_group" to "new_group" + let old_path = vars[0].path.clone(); + let new_key = "new_group".to_string(); + let mut new_path = vec![PathSegment::Key(new_key.clone())]; + vars[0].key = new_key; + vars[0].path = new_path.clone(); + + // Update child path + vars[1].path = vec![PathSegment::Key("new_group".to_string()), PathSegment::Key("key".to_string())]; + + let handler = HierarchicalHandler::new(FormatType::Json); let mut root = Value::Object(Map::new()); - for var in vars { + for var in &vars { if !var.is_group { insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); } } - let unflattened_xml = json_to_xml(&root); - - assert!(unflattened_xml.contains("8080")); - assert!(unflattened_xml.contains("true")); - assert!(unflattened_xml.contains("") && unflattened_xml.contains("")); + let out = serde_json::to_string(&root).unwrap(); + assert!(out.contains("\"new_group\"")); + assert!(out.contains("\"key\":\"val\"")); + assert!(!out.contains("\"old_group\"")); } } diff --git a/src/format/ini.rs b/src/format/ini.rs index 6888dc8..3e3581f 100644 --- a/src/format/ini.rs +++ b/src/format/ini.rs @@ -80,15 +80,46 @@ mod tests { use std::io::Write; #[test] - fn test_parse_ini() { - let mut file = NamedTempFile::new().unwrap(); - writeln!(file, "[server]\nport=8080\n[database]\nhost=localhost").unwrap(); - + fn test_section_rename_write() { let handler = IniHandler; - let vars = handler.parse(file.path()).unwrap(); + let mut vars = vec![ + ConfigItem { + key: "server".to_string(), + path: vec![PathSegment::Key("server".to_string())], + value: None, + template_value: None, + default_value: None, + depth: 0, + is_group: true, + status: ItemStatus::Present, + value_type: ValueType::Null, + }, + ConfigItem { + key: "port".to_string(), + path: vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())], + value: Some("8080".to_string()), + template_value: Some("8080".to_string()), + default_value: Some("8080".to_string()), + depth: 1, + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + } + ]; + + // Rename "server" to "srv" + vars[0].key = "srv".to_string(); + vars[0].path = vec![PathSegment::Key("srv".to_string())]; - assert!(vars.iter().any(|v| v.path_string() == "server" && v.is_group)); - assert!(vars.iter().any(|v| v.path_string() == "server.port" && v.value.as_deref() == Some("8080"))); - assert!(vars.iter().any(|v| v.path_string() == "database.host" && v.value.as_deref() == Some("localhost"))); + // Update child path + vars[1].path = vec![PathSegment::Key("srv".to_string()), PathSegment::Key("port".to_string())]; + + let file = NamedTempFile::new().unwrap(); + handler.write(file.path(), &vars).unwrap(); + + let content = std::fs::read_to_string(file.path()).unwrap(); + assert!(content.contains("[srv]")); + assert!(content.contains("port=8080")); + assert!(!content.contains("[server]")); } } diff --git a/src/format/properties.rs b/src/format/properties.rs index 4ca0b7d..c363849 100644 --- a/src/format/properties.rs +++ b/src/format/properties.rs @@ -89,14 +89,45 @@ mod tests { use std::io::Write; #[test] - fn test_parse_properties() { - let mut file = NamedTempFile::new().unwrap(); - writeln!(file, "server.port=8080\ndatabase.host=localhost").unwrap(); - + fn test_group_rename_write() { let handler = PropertiesHandler; - let vars = handler.parse(file.path()).unwrap(); + let mut vars = vec![ + ConfigItem { + key: "server".to_string(), + path: vec![PathSegment::Key("server".to_string())], + value: None, + template_value: None, + default_value: None, + depth: 0, + is_group: true, + status: ItemStatus::Present, + value_type: ValueType::Null, + }, + ConfigItem { + key: "port".to_string(), + path: vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())], + value: Some("8080".to_string()), + template_value: Some("8080".to_string()), + default_value: Some("8080".to_string()), + depth: 1, + is_group: false, + status: ItemStatus::Present, + value_type: ValueType::String, + } + ]; + + // Rename "server" to "srv" + vars[0].key = "srv".to_string(); + vars[0].path = vec![PathSegment::Key("srv".to_string())]; - assert!(vars.iter().any(|v| v.path_string() == "server" && v.is_group)); - assert!(vars.iter().any(|v| v.path_string() == "server.port" && v.value.as_deref() == Some("8080"))); + // Update child path + vars[1].path = vec![PathSegment::Key("srv".to_string()), PathSegment::Key("port".to_string())]; + + let file = NamedTempFile::new().unwrap(); + handler.write(file.path(), &vars).unwrap(); + + let content = std::fs::read_to_string(file.path()).unwrap(); + assert!(content.contains("srv.port=8080")); + assert!(!content.contains("server.port=8080")); } } diff --git a/src/runner.rs b/src/runner.rs index 2b8507b..06806e9 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -110,8 +110,19 @@ where /// Handles primary navigation (j/k) and transitions to insert or command modes. fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> { - if let KeyCode::Char(c) = key.code { - self.key_sequence.push(c); + let key_str = if let KeyCode::Char(c) = key.code { + let mut s = String::new(); + if key.modifiers.contains(event::KeyModifiers::ALT) { + s.push_str("alt+"); + } + s.push(c); + s + } else { + String::new() + }; + + if !key_str.is_empty() { + self.key_sequence.push_str(&key_str); // Collect all configured keybinds let binds = [ @@ -131,6 +142,9 @@ where (&self.config.keybinds.undo, "undo"), (&self.config.keybinds.redo, "redo"), (&self.config.keybinds.rename, "rename"), + (&self.config.keybinds.append_group, "append_group"), + (&self.config.keybinds.prepend_group, "prepend_group"), + (&self.config.keybinds.toggle_group, "toggle_group"), (&"a".to_string(), "add_missing"), (&":".to_string(), "command"), (&"q".to_string(), "quit"), @@ -165,12 +179,18 @@ where "previous_match" => self.app.jump_previous_match(), "jump_top" => self.app.jump_top(), "jump_bottom" => self.app.jump_bottom(), - "append_item" => self.app.add_item(true), - "prepend_item" => self.app.add_item(false), + "append_item" => self.app.add_item(true, false), + "prepend_item" => self.app.add_item(false, false), "delete_item" => self.app.delete_selected(), "undo" => self.app.undo(), "redo" => self.app.redo(), "rename" => self.app.enter_insert_key(), + "append_group" => self.app.add_item(true, true), + "prepend_group" => self.app.add_item(false, true), + "toggle_group" => { + self.app.toggle_group_selected(); + self.app.save_undo_state(); + } "add_missing" => { self.add_missing_item(); } @@ -182,9 +202,8 @@ where _ => {} } } else if !prefix_match { - // Not an exact match and not a prefix for any bind, clear and restart seq self.key_sequence.clear(); - self.key_sequence.push(c); + self.key_sequence.push_str(&key_str); } } else { // Non-character keys reset the sequence buffer diff --git a/src/ui.rs b/src/ui.rs index 9eb638c..1c9de80 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -238,7 +238,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { f.render_widget(input, chunks[2]); // Position the terminal cursor correctly when in Insert mode. - if let Mode::Insert = app.mode { + if matches!(app.mode, Mode::Insert) || matches!(app.mode, Mode::InsertKey) { f.set_cursor_position(ratatui::layout::Position::new( chunks[2].x + 1 + cursor_pos as u16, chunks[2].y + 1, @@ -292,11 +292,15 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute)); } parts.push(format!("{} rename", kb.rename)); + parts.push(format!("{} toggle", kb.toggle_group)); if app.selected_is_missing() { parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner } if app.selected_is_array() { parts.push(format!("{}/{} array", kb.append_item, kb.prepend_item)); + } else { + parts.push(format!("{}/{} add", kb.append_item, kb.prepend_item)); + parts.push(format!("{}/{} group", kb.append_group, kb.prepend_group)); } parts.push(format!("{} del", kb.delete_item)); parts.push(format!("{} undo", kb.undo)); From 31dc062ce55a98c95e86d8e26ea9cd62c287c7f7 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 18:56:14 +0100 Subject: [PATCH 13/15] fixed undo tree for new vars/groups + unknown states for lists with o/O --- src/app.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++------ src/runner.rs | 8 ++++---- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/src/app.rs b/src/app.rs index 1e320b1..ff4e9b7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -244,6 +244,9 @@ impl App { pub fn enter_insert(&mut self, variant: InsertVariant) { if let Some(var) = self.vars.get(self.selected) && !var.is_group { + if !matches!(variant, InsertVariant::Substitute) { + self.sync_input_with_selected(); + } self.mode = Mode::Insert; match variant { InsertVariant::Start => { @@ -337,9 +340,9 @@ impl App { } /// Adds a new item relative to the selected item. - pub fn add_item(&mut self, after: bool, is_group: bool) { + pub fn add_item(&mut self, after: bool, is_group: bool, as_child: bool) { if self.vars.is_empty() { - let new_key = "NEW_VAR".to_string(); + let new_key = if is_group { "NEW_GROUP".to_string() } else { "NEW_VAR".to_string() }; self.vars.push(ConfigItem { key: new_key.clone(), path: vec![PathSegment::Key(new_key)], @@ -370,8 +373,8 @@ impl App { let insert_pos; let mut is_array_item = false; - if let Some(PathSegment::Index(idx)) = selected_item.path.last() { - // ARRAY ITEM LOGIC + if !as_child && let Some(PathSegment::Index(idx)) = selected_item.path.last() { + // ARRAY ITEM LOGIC (Adding sibling to an existing index) is_array_item = true; let base_path = selected_item.path[..selected_item.path.len() - 1].to_vec(); let new_idx = if after { idx + 1 } else { *idx }; @@ -392,11 +395,29 @@ impl App { new_path = base_path; new_path.push(PathSegment::Index(new_idx)); new_depth = selected_item.depth; - } else if after && selected_item.is_group { + } else if as_child && selected_item.is_group { // ADD AS CHILD OF GROUP insert_pos = self.selected + 1; new_path = selected_item.path.clone(); new_depth = selected_item.depth + 1; + + // Check if this group already contains array items + if self.is_array_group(&selected_item.path) { + is_array_item = true; + let new_idx = 0; // Prepend to array + new_path.push(PathSegment::Index(new_idx)); + + // Shift existing children + for var in self.vars.iter_mut() { + if var.path.starts_with(&selected_item.path) && var.path.len() > selected_item.path.len() + && let PathSegment::Index(i) = var.path[selected_item.path.len()] { + var.path[selected_item.path.len()] = PathSegment::Index(i + 1); + if var.path.len() == selected_item.path.len() + 1 { + var.key = format!("[{}]", i + 1); + } + } + } + } } else { // ADD AS SIBLING let parent_path = if selected_item.path.len() > 1 { @@ -417,6 +438,17 @@ impl App { new_path = parent_path; new_depth = selected_item.depth; + + // If the parent is an array group, this is also an array item + if !new_path.is_empty() && self.is_array_group(&new_path) { + is_array_item = true; + if let Some(PathSegment::Index(idx)) = selected_item.path.last() { + let new_idx = if after { idx + 1 } else { *idx }; + new_path.push(PathSegment::Index(new_idx)); + } else { + new_path.push(PathSegment::Index(0)); + } + } } // 2. Generate a unique key for non-array items @@ -458,9 +490,10 @@ impl App { self.vars.insert(insert_pos, new_item); self.selected = insert_pos; + self.save_undo_state(); + if is_array_item { self.sync_input_with_selected(); - self.save_undo_state(); self.enter_insert(InsertVariant::Start); } else { self.enter_insert_key(); @@ -495,6 +528,14 @@ impl App { self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false) } + pub fn is_array_group(&self, group_path: &[PathSegment]) -> bool { + self.vars.iter().any(|v| + v.path.starts_with(group_path) + && v.path.len() == group_path.len() + 1 + && matches!(v.path.last(), Some(PathSegment::Index(_))) + ) + } + pub fn selected_is_array(&self) -> bool { self.vars.get(self.selected) .map(|v| !v.is_group && matches!(v.path.last(), Some(PathSegment::Index(_)))) diff --git a/src/runner.rs b/src/runner.rs index 06806e9..c2d5d70 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -179,14 +179,14 @@ where "previous_match" => self.app.jump_previous_match(), "jump_top" => self.app.jump_top(), "jump_bottom" => self.app.jump_bottom(), - "append_item" => self.app.add_item(true, false), - "prepend_item" => self.app.add_item(false, false), + "append_item" => self.app.add_item(true, false, false), + "prepend_item" => self.app.add_item(false, false, false), "delete_item" => self.app.delete_selected(), "undo" => self.app.undo(), "redo" => self.app.redo(), "rename" => self.app.enter_insert_key(), - "append_group" => self.app.add_item(true, true), - "prepend_group" => self.app.add_item(false, true), + "append_group" => self.app.add_item(true, true, true), + "prepend_group" => self.app.add_item(false, true, true), "toggle_group" => { self.app.toggle_group_selected(); self.app.save_undo_state(); From ee85be4e6b23f85790f76164785fed88f02cbba8 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 21:12:06 +0100 Subject: [PATCH 14/15] fixed lag when S on empty --- src/runner.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/runner.rs b/src/runner.rs index c2d5d70..bb38ceb 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -124,6 +124,9 @@ where if !key_str.is_empty() { self.key_sequence.push_str(&key_str); + let mut exact_match = None; + let mut prefix_match = false; + // Collect all configured keybinds let binds = [ (&self.config.keybinds.down, "down"), @@ -131,6 +134,7 @@ where (&self.config.keybinds.edit, "edit"), (&self.config.keybinds.edit_append, "edit_append"), (&self.config.keybinds.edit_substitute, "edit_substitute"), + (&"S".to_string(), "edit_substitute"), (&self.config.keybinds.search, "search"), (&self.config.keybinds.next_match, "next_match"), (&self.config.keybinds.previous_match, "previous_match"), @@ -150,9 +154,6 @@ where (&"q".to_string(), "quit"), ]; - let mut exact_match = None; - let mut prefix_match = false; - for (bind, action) in binds.iter() { if bind == &&self.key_sequence { exact_match = Some(*action); @@ -162,6 +163,21 @@ where } } + if exact_match.is_none() && !prefix_match { + // Not a match and not a prefix, restart with current key + self.key_sequence.clear(); + self.key_sequence.push_str(&key_str); + + for (bind, action) in binds.iter() { + if bind == &&self.key_sequence { + exact_match = Some(*action); + break; + } else if bind.starts_with(&self.key_sequence) { + prefix_match = true; + } + } + } + if let Some(action) = exact_match { self.key_sequence.clear(); match action { @@ -203,7 +219,6 @@ where } } else if !prefix_match { self.key_sequence.clear(); - self.key_sequence.push_str(&key_str); } } else { // Non-character keys reset the sequence buffer From 029b4f9da8bedc6e9916bec78ed098b5de439e85 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Wed, 18 Mar 2026 22:49:55 +0100 Subject: [PATCH 15/15] refactored group renaming --- src/app.rs | 7 +++++-- src/ui.rs | 44 ++++++++++++++++++++++++++------------------ 2 files changed, 31 insertions(+), 20 deletions(-) diff --git a/src/app.rs b/src/app.rs index ff4e9b7..29d0b68 100644 --- a/src/app.rs +++ b/src/app.rs @@ -242,8 +242,10 @@ impl App { /// Transitions the application into Insert Mode with a specific variant. pub fn enter_insert(&mut self, variant: InsertVariant) { - if let Some(var) = self.vars.get(self.selected) - && !var.is_group { + if let Some(var) = self.vars.get(self.selected) { + if var.is_group { + self.enter_insert_key(); + } else { if !matches!(variant, InsertVariant::Substitute) { self.sync_input_with_selected(); } @@ -262,6 +264,7 @@ impl App { } } } + } } /// Commits the current input and transitions the application into Normal Mode. diff --git a/src/ui.rs b/src/ui.rs index 1c9de80..0f70069 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -103,24 +103,30 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { Span::styled(&var.key, key_style), ]; - // Add status indicator if not present (only for leaf variables) - if !var.is_group { - match var.status { - crate::format::ItemStatus::MissingFromActive => { - let missing_style = if is_selected { - Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD) - } else { - Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD) - }; - key_spans.push(Span::styled(" (missing)", missing_style)); - } - crate::format::ItemStatus::Modified => { - if !is_selected { - key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified()))); - } - } - _ => {} + // Add status indicator if not present + match var.status { + crate::format::ItemStatus::MissingFromActive if !var.is_group => { + let missing_style = if is_selected { + Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD) + }; + key_spans.push(Span::styled(" (missing)", missing_style)); } + crate::format::ItemStatus::MissingFromActive if var.is_group => { + let missing_style = if is_selected { + Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD) + }; + key_spans.push(Span::styled(" (missing group)", missing_style)); + } + crate::format::ItemStatus::Modified => { + if !is_selected { + key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified()))); + } + } + _ => {} } let item_style = if is_selected { @@ -210,7 +216,9 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) { // Show template value in normal mode if it differs let display_text = if let Some(var) = current_var { - if var.is_group { + if matches!(app.mode, Mode::InsertKey) { + input_text.to_string() + } else if var.is_group { "".to_string() } else if matches!(app.mode, Mode::Normal) { format!("{}{}", input_text, extra_info)