2 Commits

Author SHA1 Message Date
e09cc3f2d7 Merge pull request 'fixed tests case' (#9) from release/0.4.0 into main
All checks were successful
Release / Build and Release (push) Successful in 53s
Reviewed-on: #9
2026-03-17 12:39:27 +01:00
c270d37585 Merge pull request 'release/0.4.0' (#8) from release/0.4.0 into main
All checks were successful
Release / Build and Release (push) Successful in 57s
Reviewed-on: #8
2026-03-17 12:30:13 +01:00
16 changed files with 196 additions and 1224 deletions

125
Cargo.lock generated
View File

@@ -247,26 +247,6 @@ dependencies = [
"static_assertions", "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]] [[package]]
name = "convert_case" name = "convert_case"
version = "0.10.0" version = "0.10.0"
@@ -312,12 +292,6 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]] [[package]]
name = "crypto-common" name = "crypto-common"
version = "0.1.7" version = "0.1.7"
@@ -440,15 +414,6 @@ dependencies = [
"windows-sys", "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]] [[package]]
name = "document-features" name = "document-features"
version = "0.2.12" version = "0.2.12"
@@ -464,15 +429,6 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" 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]] [[package]]
name = "env_filter" name = "env_filter"
version = "1.0.0" version = "1.0.0"
@@ -624,12 +580,6 @@ dependencies = [
"wasip3", "wasip3",
] ]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.5" version = "0.15.5"
@@ -729,17 +679,6 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" 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]] [[package]]
name = "jiff" name = "jiff"
version = "0.2.23" version = "0.2.23"
@@ -914,18 +853,15 @@ dependencies = [
[[package]] [[package]]
name = "mould" name = "mould"
version = "0.4.3" version = "0.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
"crossterm", "crossterm",
"dirs", "dirs",
"env_logger", "env_logger",
"java-properties",
"log", "log",
"quick-xml",
"ratatui", "ratatui",
"rust-ini",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
@@ -1020,16 +956,6 @@ dependencies = [
"num-traits", "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]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.5" version = "0.12.5"
@@ -1188,16 +1114,6 @@ dependencies = [
"unicode-ident", "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]] [[package]]
name = "quote" name = "quote"
version = "1.0.45" version = "1.0.45"
@@ -1368,16 +1284,6 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" 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]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.1" version = "0.4.1"
@@ -1735,20 +1641,11 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]] [[package]]
name = "toml" name = "toml"
version = "1.0.7+spec-1.1.0" version = "1.0.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd28d57d8a6f6e458bc0b8784f8fdcc4b99a437936056fa122cb234f18656a96" checksum = "399b1124a3c9e16766831c6bba21e50192572cdd98706ea114f9502509686ffc"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"serde_core", "serde_core",
@@ -1761,27 +1658,27 @@ dependencies = [
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "1.0.1+spec-1.1.0" version = "1.0.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b320e741db58cac564e26c607d3cc1fdc4a88fd36c879568c07856ed83ff3e9" checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
[[package]] [[package]]
name = "toml_parser" name = "toml_parser"
version = "1.0.10+spec-1.1.0" version = "1.0.9+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df25b4befd31c4816df190124375d5a20c6b6921e2cad937316de3fccd63420" checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4"
dependencies = [ dependencies = [
"winnow", "winnow",
] ]
[[package]] [[package]]
name = "toml_writer" name = "toml_writer"
version = "1.0.7+spec-1.1.0" version = "1.0.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17aaa1c6e3dc22b1da4b6bba97d066e354c7945cac2f7852d4e4e7ca7a6b56d" checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
[[package]] [[package]]
name = "tui-input" name = "tui-input"
@@ -2093,9 +1990,9 @@ dependencies = [
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "1.0.0" version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a90e88e4667264a994d34e6d1ab2d26d398dcdca8b7f52bec8668957517fc7d8" checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]] [[package]]
name = "wit-bindgen" name = "wit-bindgen"

View File

@@ -1,8 +1,8 @@
[package] [package]
authors = ["Nils Pukropp <nils@narl.io>"]
edition = "2024" edition = "2024"
name = "mould" name = "mould"
version = "0.5.0" version = "0.4.0"
authors = ["Nils Pukropp <nils@narl.io>"]
[[bin]] [[bin]]
name = "mould" name = "mould"
@@ -13,24 +13,21 @@ anyhow = "1.0.102"
crossterm = "0.29.0" crossterm = "0.29.0"
dirs = "6.0.0" dirs = "6.0.0"
env_logger = "0.11.9" env_logger = "0.11.9"
java-properties = "2.0.0"
log = "0.4.29" log = "0.4.29"
quick-xml = { version = "0.39.2", features = ["serde", "serialize"] }
ratatui = "0.30.0" ratatui = "0.30.0"
rust-ini = "0.21.3"
serde_json = "1.0.149" serde_json = "1.0.149"
serde_yaml = "0.9.34" serde_yaml = "0.9.34"
thiserror = "2.0.18" thiserror = "2.0.18"
toml = "1.0.7" toml = "1.0.6"
tui-input = "0.15.0" tui-input = "0.15.0"
[dependencies.clap] [dependencies.clap]
features = ["derive"]
version = "4.6.0" version = "4.6.0"
features = ["derive"]
[dependencies.serde] [dependencies.serde]
features = ["derive"]
version = "1.0.228" version = "1.0.228"
features = ["derive"]
[dev-dependencies] [dev-dependencies]
tempfile = "3.27.0" tempfile = "3.27.0"

View File

@@ -1,13 +1,12 @@
# mould # 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`, `TOML`, `XML`, `INI`, or `Properties` 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`, or `TOML` configurations, mould provides a fast, Vim-inspired workflow to get your environment ready.
## Features ## Features
- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, `TOML`, `XML`, `INI`, and `Properties` seamlessly. - **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly.
- **Tree View Navigation**: Edit nested data structures in a beautiful, depth-colored tree view. - **Tree View Navigation**: Edit nested data structures (JSON, YAML, TOML) 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. - **Smart Template Comparison**: Automatically discovers `.env.example` vs `.env` relationships and highlights missing or modified keys.
- **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. - **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. - **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`. - **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
@@ -33,13 +32,15 @@ cargo build --release
``` ```
### Neovim Plugin ### Neovim Plugin
If you use a plugin manager like `mini.deps`, you can add the repository directly: If you use a plugin manager like `lazy.nvim`, you can add the local repository (or remote once published) directly:
```lua ```lua
add({ {
source = 'https://git.narl.io/nvrl/mould-rs', "username/mould", -- replace with actual repo path or github url
checkout = 'main', config = function()
}) -- Provides the :Mould command
end
}
``` ```
## Usage ## Usage
@@ -59,13 +60,7 @@ mould config.template.json -o config.json
- `k` / `Up`: Move selection up - `k` / `Up`: Move selection up
- `gg`: Jump to the top - `gg`: Jump to the top
- `G`: Jump to the bottom - `G`: Jump to the bottom
- `i`: Edit value (cursor at start) - `i`: Edit the value of the currently selected key (Enter Insert Mode)
- `A`: Edit value (cursor at end)
- `S`: Substitute value (clear and edit)
- `o`: Append a new item to the current array
- `O`: Prepend a new item to the current array
- `dd`: Delete the currently selected variable or group
- `u`: Undo the last change
- `a`: Add missing value from template to active config - `a`: Add missing value from template to active config
- `/`: Search for configuration keys (Jump to matches) - `/`: Search for configuration keys (Jump to matches)
- `n`: Jump to the next search match - `n`: Jump to the next search match
@@ -125,4 +120,4 @@ tree_depth_4 = "#fab387"
## License ## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

View File

@@ -31,8 +31,6 @@ tree_depth_4 = "#fab387"
down = "j" down = "j"
up = "k" up = "k"
edit = "i" edit = "i"
edit_append = "A"
edit_substitute = "S"
save = ":w" save = ":w"
quit = ":q" quit = ":q"
normal_mode = "Esc" normal_mode = "Esc"
@@ -41,7 +39,3 @@ next_match = "n"
previous_match = "N" previous_match = "N"
jump_top = "gg" jump_top = "gg"
jump_bottom = "G" jump_bottom = "G"
append_item = "o"
prepend_item = "O"
delete_item = "dd"
undo = "u"

View File

@@ -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"

View File

@@ -11,12 +11,6 @@ pub enum Mode {
Search, Search,
} }
pub enum InsertVariant {
Start,
End,
Substitute,
}
/// The core application state, holding all configuration variables and UI status. /// The core application state, holding all configuration variables and UI status.
pub struct App { pub struct App {
/// The list of configuration variables being edited. /// The list of configuration variables being edited.
@@ -33,8 +27,6 @@ pub struct App {
pub input: Input, pub input: Input,
/// The current search query for filtering keys. /// The current search query for filtering keys.
pub search_query: String, pub search_query: String,
/// Stack of previous variable states for undo functionality.
pub undo_stack: Vec<Vec<ConfigItem>>,
} }
impl App { impl App {
@@ -49,7 +41,6 @@ impl App {
status_message: None, status_message: None,
input: Input::new(initial_input), input: Input::new(initial_input),
search_query: String::new(), search_query: String::new(),
undo_stack: Vec::new(),
} }
} }
@@ -158,25 +149,12 @@ impl App {
} }
} }
/// Transitions the application into Insert Mode with a specific variant. /// Transitions the application into Insert Mode.
pub fn enter_insert(&mut self, variant: InsertVariant) { pub fn enter_insert(&mut self) {
if let Some(var) = self.vars.get(self.selected) { if let Some(var) = self.vars.get(self.selected) {
if !var.is_group { if !var.is_group {
self.save_undo_state();
self.mode = Mode::Insert; self.mode = Mode::Insert;
match variant { self.status_message = None;
InsertVariant::Start => {
use tui_input::InputRequest;
self.input.handle(InputRequest::GoToStart);
}
InsertVariant::End => {
use tui_input::InputRequest;
self.input.handle(InputRequest::GoToEnd);
}
InsertVariant::Substitute => {
self.input = Input::new(String::new());
}
}
} }
} }
} }
@@ -186,196 +164,4 @@ impl App {
self.commit_input(); self.commit_input();
self.mode = Mode::Normal; self.mode = Mode::Normal;
} }
/// Deletes the currently selected item. If it's a group, deletes all children.
pub fn delete_selected(&mut self) {
if self.vars.is_empty() {
return;
}
self.save_undo_state();
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) {
to_remove.push(i);
}
}
}
// 2. Perform removal (reverse order to preserve indices)
to_remove.sort_unstable_by(|a, b| b.cmp(a));
for i in to_remove {
self.vars.remove(i);
}
// 3. Re-index subsequent array items if applicable
if let Some((base, removed_idx)) = array_info {
let base = base.to_string();
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 {
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.key = format!("[{}]", new_idx);
}
}
}
}
}
}
// 4. Adjust selection
if self.selected >= self.vars.len() && !self.vars.is_empty() {
self.selected = self.vars.len() - 1;
}
self.sync_input_with_selected();
}
/// Adds a new item to an array if the selected item is part of one.
pub fn add_array_item(&mut self, after: bool) {
if self.vars.is_empty() {
return;
}
self.save_undo_state();
let (base, 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)
} 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) {
if let Some((b, i)) = parse_index(&var.path) {
if 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
let new_item = ConfigItem {
key: format!("[{}]", new_idx),
path: format!("{}[{}]", base, new_idx),
value: Some("".to_string()),
template_value: None,
default_value: None,
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.enter_insert(InsertVariant::Start);
self.status_message = None;
}
/// Status bar helpers
pub fn selected_is_group(&self) -> bool {
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
}
pub fn selected_is_array(&self) -> bool {
self.vars.get(self.selected)
.map(|v| !v.is_group && v.path.contains('['))
.unwrap_or(false)
}
pub fn selected_is_missing(&self) -> bool {
self.vars.get(self.selected)
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
.unwrap_or(false)
}
/// Saves the current state of variables to the undo stack.
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);
}
}
/// Reverts to the last saved state of variables.
pub fn undo(&mut self) {
if let Some(previous_vars) = self.undo_stack.pop() {
self.vars = previous_vars;
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("Undo applied".to_string());
} else {
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('[') {
if let Ok(idx) = segment[start + 1..end].parse::<usize>() {
// 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('[') {
if let Some(end) = remaining.find(']') {
if let Ok(idx) = remaining[1..end].parse::<usize>() {
return Some((&path[..base.len()], idx, &remaining[end + 1..]));
}
}
}
None
} }

View File

@@ -106,8 +106,6 @@ pub struct KeybindsConfig {
pub down: String, pub down: String,
pub up: String, pub up: String,
pub edit: String, pub edit: String,
pub edit_append: String,
pub edit_substitute: String,
pub save: String, pub save: String,
pub quit: String, pub quit: String,
pub normal_mode: String, pub normal_mode: String,
@@ -116,10 +114,6 @@ pub struct KeybindsConfig {
pub previous_match: String, pub previous_match: String,
pub jump_top: String, pub jump_top: String,
pub jump_bottom: String, pub jump_bottom: String,
pub append_item: String,
pub prepend_item: String,
pub delete_item: String,
pub undo: String,
} }
impl Default for KeybindsConfig { impl Default for KeybindsConfig {
@@ -128,8 +122,6 @@ impl Default for KeybindsConfig {
down: "j".to_string(), down: "j".to_string(),
up: "k".to_string(), up: "k".to_string(),
edit: "i".to_string(), edit: "i".to_string(),
edit_append: "A".to_string(),
edit_substitute: "S".to_string(),
save: ":w".to_string(), save: ":w".to_string(),
quit: ":q".to_string(), quit: ":q".to_string(),
normal_mode: "Esc".to_string(), normal_mode: "Esc".to_string(),
@@ -138,10 +130,6 @@ impl Default for KeybindsConfig {
previous_match: "N".to_string(), previous_match: "N".to_string(),
jump_top: "gg".to_string(), jump_top: "gg".to_string(),
jump_bottom: "G".to_string(), jump_bottom: "G".to_string(),
append_item: "o".to_string(),
prepend_item: "O".to_string(),
delete_item: "dd".to_string(),
undo: "u".to_string(),
} }
} }
} }

View File

@@ -1,4 +1,4 @@
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType}; use super::{ConfigItem, FormatHandler, ItemStatus};
use std::fs; use std::fs;
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::Path; use std::path::Path;
@@ -27,7 +27,6 @@ impl FormatHandler for EnvHandler {
depth: 0, depth: 0,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::String,
}); });
} }
} }
@@ -66,7 +65,6 @@ impl FormatHandler for EnvHandler {
depth: 0, depth: 0,
is_group: false, is_group: false,
status: ItemStatus::MissingFromTemplate, status: ItemStatus::MissingFromTemplate,
value_type: ValueType::String,
}); });
} }
} }
@@ -161,7 +159,6 @@ mod tests {
depth: 0, depth: 0,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::String,
}]; }];
let handler = EnvHandler; let handler = EnvHandler;

View File

@@ -1,4 +1,4 @@
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType}; use super::{ConfigItem, FormatHandler, FormatType, ItemStatus};
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use std::fs; use std::fs;
use std::io; use std::io;
@@ -22,8 +22,6 @@ impl HierarchicalHandler {
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
FormatType::Toml => toml::from_str(&content) FormatType::Toml => toml::from_str(&content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, .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!(), _ => unreachable!(),
}; };
Ok(value) Ok(value)
@@ -49,131 +47,17 @@ impl HierarchicalHandler {
)); ));
} }
} }
FormatType::Xml => json_to_xml(value),
_ => unreachable!(), _ => unreachable!(),
}; };
fs::write(path, content) fs::write(path, content)
} }
} }
fn xml_to_json(content: &str) -> io::Result<Value> {
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<Value> {
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<String> { ... }
fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) { fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) {
let path = if prefix.is_empty() { let path = if prefix.is_empty() {
key_name.to_string() key_name.to_string()
} else if key_name.is_empty() { } else if key_name.is_empty() {
prefix.to_string() prefix.to_string()
} else if key_name.starts_with('[') {
format!("{}{}", prefix, key_name)
} else { } else {
format!("{}.{}", prefix, key_name) format!("{}.{}", prefix, key_name)
}; };
@@ -190,7 +74,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: true, is_group: true,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::Null,
}); });
} }
let next_depth = if path.is_empty() { depth } else { depth + 1 }; let next_depth = if path.is_empty() { depth } else { depth + 1 };
@@ -209,7 +92,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: true, is_group: true,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::Null,
}); });
} }
let next_depth = if path.is_empty() { depth } else { depth + 1 }; let next_depth = if path.is_empty() { depth } else { depth + 1 };
@@ -228,7 +110,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::String,
}); });
} }
Value::Number(n) => { Value::Number(n) => {
@@ -242,7 +123,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::Number,
}); });
} }
Value::Bool(b) => { Value::Bool(b) => {
@@ -256,7 +136,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::Bool,
}); });
} }
Value::Null => { Value::Null => {
@@ -269,7 +148,6 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
depth, depth,
is_group: false, is_group: false,
status: ItemStatus::Present, status: ItemStatus::Present,
value_type: ValueType::Null,
}); });
} }
} }
@@ -327,14 +205,14 @@ impl FormatHandler for HierarchicalHandler {
let val = var.value.as_deref() let val = var.value.as_deref()
.or(var.template_value.as_deref()) .or(var.template_value.as_deref())
.unwrap_or(""); .unwrap_or("");
insert_into_value(&mut root, &var.path, val, var.value_type); insert_into_value(&mut root, &var.path, val);
} }
} }
self.write_value(path, &root) self.write_value(path, &root)
} }
} }
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type: ValueType) { fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str) {
let mut parts = path.split('.'); let mut parts = path.split('.');
let last_part = match parts.next_back() { let last_part = match parts.next_back() {
Some(p) => p, Some(p) => p,
@@ -377,30 +255,13 @@ fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type
} }
let map = current.as_object_mut().unwrap(); let map = current.as_object_mut().unwrap();
// Use the preserved ValueType instead of aggressive inference // Attempt basic type inference
let final_val = match value_type { let final_val = if let Ok(n) = new_val_str.parse::<i64>() {
ValueType::Number => { Value::Number(n.into())
if let Ok(n) = new_val_str.parse::<i64>() { } else if let Ok(b) = new_val_str.parse::<bool>() {
Value::Number(n.into()) Value::Bool(b)
} else if let Ok(f) = new_val_str.parse::<f64>() { } else {
if let Some(n) = serde_json::Number::from_f64(f) { Value::String(new_val_str.to_string())
Value::Number(n)
} else {
Value::String(new_val_str.to_string())
}
} else {
Value::String(new_val_str.to_string())
}
}
ValueType::Bool => {
if let Ok(b) = new_val_str.parse::<bool>() {
Value::Bool(b)
} else {
Value::String(new_val_str.to_string())
}
}
ValueType::Null if new_val_str.is_empty() => Value::Null,
_ => Value::String(new_val_str.to_string()),
}; };
if let Some(i) = final_idx { if let Some(i) = final_idx {
@@ -436,7 +297,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_json_flatten_unflatten() { fn test_flatten_unflatten() {
let mut vars = Vec::new(); let mut vars = Vec::new();
let json = serde_json::json!({ let json = serde_json::json!({
"services": { "services": {
@@ -455,7 +316,7 @@ mod tests {
let mut root = Value::Object(Map::new()); let mut root = Value::Object(Map::new());
for var in vars { for var in vars {
if !var.is_group { if !var.is_group {
insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type); insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""));
} }
} }
@@ -464,129 +325,4 @@ mod tests {
assert!(unflattened_json.contains("\"8080:80\"")); assert!(unflattened_json.contains("\"8080:80\""));
assert!(unflattened_json.contains("true")); 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 = "<config><server><port>8080</port><enabled>true</enabled></server></config>";
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("<port>8080</port>"));
assert!(unflattened_xml.contains("<enabled>true</enabled>"));
assert!(unflattened_xml.contains("<config>") && unflattened_xml.contains("</config>"));
}
} }

View File

@@ -1,125 +0,0 @@
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<Vec<ConfigItem>> {
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<ConfigItem>) -> 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::<String>).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")));
}
}

View File

@@ -3,8 +3,6 @@ use std::path::Path;
pub mod env; pub mod env;
pub mod hierarchical; pub mod hierarchical;
pub mod ini;
pub mod properties;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ItemStatus { pub enum ItemStatus {
@@ -14,14 +12,6 @@ pub enum ItemStatus {
Modified, Modified,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueType {
String,
Number,
Bool,
Null,
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ConfigItem { pub struct ConfigItem {
pub key: String, pub key: String,
@@ -32,7 +22,6 @@ pub struct ConfigItem {
pub depth: usize, pub depth: usize,
pub is_group: bool, pub is_group: bool,
pub status: ItemStatus, pub status: ItemStatus,
pub value_type: ValueType,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -41,9 +30,6 @@ pub enum FormatType {
Json, Json,
Yaml, Yaml,
Toml, Toml,
Xml,
Ini,
Properties,
} }
pub trait FormatHandler { pub trait FormatHandler {
@@ -59,9 +45,6 @@ pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType
"json" => return FormatType::Json, "json" => return FormatType::Json,
"yaml" | "yml" => return FormatType::Yaml, "yaml" | "yml" => return FormatType::Yaml,
"toml" => return FormatType::Toml, "toml" => return FormatType::Toml,
"xml" => return FormatType::Xml,
"ini" => return FormatType::Ini,
"properties" => return FormatType::Properties,
_ => {} _ => {}
} }
} }
@@ -73,12 +56,6 @@ pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType
FormatType::Yaml FormatType::Yaml
} else if file_name.ends_with(".toml") { } else if file_name.ends_with(".toml") {
FormatType::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 { } else {
FormatType::Env FormatType::Env
} }
@@ -90,8 +67,5 @@ pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)), FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)),
FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)), FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)),
FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)), 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),
} }
} }

View File

@@ -1,129 +0,0 @@
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<Vec<ConfigItem>> {
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<ConfigItem>) -> 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")));
}
}

View File

@@ -5,7 +5,6 @@ mod error;
mod format; mod format;
mod runner; mod runner;
mod ui; mod ui;
mod resolver;
use app::App; use app::App;
use config::load_config; use config::load_config;
@@ -14,6 +13,7 @@ use format::{detect_format, get_handler};
use log::{error, info, warn}; use log::{error, info, warn};
use runner::AppRunner; use runner::AppRunner;
use std::io; use std::io;
use std::path::{Path, PathBuf};
use crossterm::{ use crossterm::{
event::{DisableMouseCapture, EnableMouseCapture}, event::{DisableMouseCapture, EnableMouseCapture},
@@ -22,6 +22,114 @@ use crossterm::{
}; };
use ratatui::{Terminal, backend::CrosstermBackend}; use ratatui::{Terminal, backend::CrosstermBackend};
/// Helper to automatically determine the output file path based on common naming conventions.
fn determine_output_path(input: &Path) -> PathBuf {
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
// Standard mappings
if file_name == ".env.example" || file_name == ".env.template" {
return input.with_file_name(".env");
}
if file_name == "docker-compose.yml" || file_name == "compose.yml" {
return input.with_file_name("compose.override.yml");
}
if file_name == "docker-compose.yaml" || file_name == "compose.yaml" {
return input.with_file_name("compose.override.yaml");
}
// Pattern-based mappings
if let Some(base) = file_name.strip_suffix(".env.example") {
return input.with_file_name(format!("{}.env", base));
}
if let Some(base) = file_name.strip_suffix(".env.template") {
return input.with_file_name(format!("{}.env", base));
}
if let Some(base) = file_name.strip_suffix(".example.json") {
return input.with_file_name(format!("{}.json", base));
}
if let Some(base) = file_name.strip_suffix(".template.json") {
return input.with_file_name(format!("{}.json", base));
}
if let Some(base) = file_name.strip_suffix(".example.yml") {
return input.with_file_name(format!("{}.yml", base));
}
if let Some(base) = file_name.strip_suffix(".template.yml") {
return input.with_file_name(format!("{}.yml", base));
}
if let Some(base) = file_name.strip_suffix(".example.yaml") {
return input.with_file_name(format!("{}.yaml", base));
}
if let Some(base) = file_name.strip_suffix(".template.yaml") {
return input.with_file_name(format!("{}.yaml", base));
}
if let Some(base) = file_name.strip_suffix(".example.toml") {
return input.with_file_name(format!("{}.toml", base));
}
if let Some(base) = file_name.strip_suffix(".template.toml") {
return input.with_file_name(format!("{}.toml", base));
}
input.with_extension(format!(
"{}.out",
input.extension().unwrap_or_default().to_string_lossy()
))
}
/// Discovers common configuration template files in the current directory.
fn find_input_file() -> Option<PathBuf> {
let candidates = [
".env.example",
"compose.yml",
"docker-compose.yml",
".env.template",
"compose.yaml",
"docker-compose.yaml",
];
// Priority 1: Exact matches for well-known defaults
for name in &candidates {
let path = PathBuf::from(name);
if path.exists() {
return Some(path);
}
}
// Priority 2: Pattern matches
if let Ok(entries) = std::fs::read_dir(".") {
let mut fallback = None;
for entry in entries.flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.ends_with(".env.example")
|| name_str.ends_with(".env.template")
|| name_str.ends_with(".example.json")
|| name_str.ends_with(".template.json")
|| name_str.ends_with(".example.yml")
|| name_str.ends_with(".template.yml")
|| name_str.ends_with(".example.yaml")
|| name_str.ends_with(".template.yaml")
|| name_str.ends_with(".example.toml")
|| name_str.ends_with(".template.toml")
{
// Prefer .env.* or compose.* if multiple matches
if name_str.contains(".env") || name_str.contains("compose") {
return Some(entry.path());
}
if fallback.is_none() {
fallback = Some(entry.path());
}
}
}
if let Some(path) = fallback {
return Some(path);
}
}
None
}
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
let args = cli::parse(); let args = cli::parse();
@@ -44,7 +152,7 @@ fn main() -> anyhow::Result<()> {
} }
path path
} }
None => match resolver::find_input_file() { None => match find_input_file() {
Some(path) => { Some(path) => {
info!("Discovered template: {}", path.display()); info!("Discovered template: {}", path.display());
path path
@@ -64,11 +172,38 @@ fn main() -> anyhow::Result<()> {
let handler = get_handler(format_type); let handler = get_handler(format_type);
// Smart Comparison Logic // Smart Comparison Logic
let (active_path, template_path) = resolver::resolve_paths(&input_path); let input_name = input_path.file_name().unwrap_or_default().to_string_lossy();
let is_template_input = input_name.contains(".example") || input_name.contains(".template") || input_name == "compose.yml" || input_name == "docker-compose.yml";
let mut template_path = None;
let mut active_path = None;
if is_template_input {
template_path = Some(input_path.clone());
let expected_active = determine_output_path(&input_path);
if expected_active.exists() {
active_path = Some(expected_active);
}
} else {
// Input is likely an active config (e.g., .env)
active_path = Some(input_path.clone());
// Try to find a template
let possible_templates = [
format!("{}.example", input_name),
format!("{}.template", input_name),
];
for t in possible_templates {
let p = input_path.with_file_name(t);
if p.exists() {
template_path = Some(p);
break;
}
}
}
let output_path = args let output_path = args
.output .output
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| resolver::determine_output_path(&input_path))); .unwrap_or_else(|| active_path.clone().unwrap_or_else(|| determine_output_path(&input_path)));
info!("Output: {}", output_path.display()); info!("Output: {}", output_path.display());
@@ -148,4 +283,4 @@ fn main() -> anyhow::Result<()> {
Err(e.into()) Err(e.into())
} }
} }
} }

View File

@@ -1,199 +0,0 @@
use std::path::{Path, PathBuf};
pub struct Rule {
pub template_suffix: &'static str,
pub active_suffix: &'static str,
pub is_exact_match: bool,
}
pub const RULES: &[Rule] = &[
// Exact matches
Rule { template_suffix: "compose.yml", active_suffix: "compose.override.yml", is_exact_match: true },
Rule { template_suffix: "compose.yaml", active_suffix: "compose.override.yaml", is_exact_match: true },
Rule { template_suffix: "docker-compose.yml", active_suffix: "docker-compose.override.yml", is_exact_match: true },
Rule { template_suffix: "docker-compose.yaml", active_suffix: "docker-compose.override.yaml", is_exact_match: true },
// Pattern matches
Rule { template_suffix: ".env.example", active_suffix: ".env", is_exact_match: false },
Rule { template_suffix: ".env.template", active_suffix: ".env", is_exact_match: false },
Rule { template_suffix: ".example.json", active_suffix: ".json", is_exact_match: false },
Rule { template_suffix: ".template.json", active_suffix: ".json", is_exact_match: false },
Rule { template_suffix: ".example.yml", active_suffix: ".yml", is_exact_match: false },
Rule { template_suffix: ".template.yml", active_suffix: ".yml", is_exact_match: false },
Rule { template_suffix: ".example.yaml", active_suffix: ".yaml", is_exact_match: false },
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] = &[
".env.example",
"compose.yml",
"docker-compose.yml",
".env.template",
"compose.yaml",
"docker-compose.yaml",
];
/// Helper to automatically determine the output file path based on common naming conventions.
pub fn determine_output_path(input: &Path) -> PathBuf {
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
for rule in RULES {
if rule.is_exact_match {
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));
}
}
}
input.with_extension(format!(
"{}.out",
input.extension().unwrap_or_default().to_string_lossy()
))
}
/// Discovers common configuration template files in the current directory.
pub fn find_input_file() -> Option<PathBuf> {
// Priority 1: Exact matches for well-known defaults
for &name in DEFAULT_CANDIDATES {
let path = PathBuf::from(name);
if path.exists() {
return Some(path);
}
}
// Priority 2: Pattern matches
if let Ok(entries) = std::fs::read_dir(".") {
let mut fallback = None;
for entry in entries.flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
for rule in RULES {
if !rule.is_exact_match && name_str.ends_with(rule.template_suffix) {
if name_str.contains(".env") || name_str.contains("compose") {
return Some(entry.path());
}
if fallback.is_none() {
fallback = Some(entry.path());
}
break;
}
}
}
if let Some(path) = fallback {
return Some(path);
}
}
None
}
/// Resolves the active and template paths given an input path.
/// Returns `(active_path, template_path)`.
pub fn resolve_paths(input: &Path) -> (Option<PathBuf>, Option<PathBuf>) {
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
// Check if the input matches any known template pattern
let mut is_template = false;
for rule in RULES {
if rule.is_exact_match {
if file_name == rule.template_suffix {
is_template = true;
break;
}
} else if file_name.ends_with(rule.template_suffix) {
is_template = true;
break;
}
}
// Fallback template detection
if !is_template && (file_name.contains(".example") || file_name.contains(".template")) {
is_template = true;
}
if is_template {
let expected_active = determine_output_path(input);
let active = if expected_active.exists() {
Some(expected_active)
} else {
None
};
(active, Some(input.to_path_buf()))
} else {
// Input is treated as the active config
let active = Some(input.to_path_buf());
let mut template = None;
// Try to reverse match rules to find a template
for rule in RULES {
if rule.is_exact_match {
if file_name == rule.active_suffix {
let t = input.with_file_name(rule.template_suffix);
if t.exists() {
template = Some(t);
break;
}
}
} else if file_name.ends_with(rule.active_suffix) {
if file_name == rule.active_suffix {
let t = input.with_file_name(rule.template_suffix);
if t.exists() {
template = Some(t);
break;
}
} else if let Some(base) = file_name.strip_suffix(rule.active_suffix) {
let t = input.with_file_name(format!("{}{}", base, rule.template_suffix));
if t.exists() {
template = Some(t);
break;
}
}
}
}
// Fallback reverse detection
if template.is_none() {
let possible_templates = [
format!("{}.example", file_name),
format!("{}.template", file_name),
];
for t in possible_templates {
let p = input.with_file_name(t);
if p.exists() {
template = Some(p);
break;
}
}
}
(active, template)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_determine_output_path() {
assert_eq!(determine_output_path(Path::new(".env.example")), PathBuf::from(".env"));
assert_eq!(determine_output_path(Path::new("compose.yml")), PathBuf::from("compose.override.yml"));
assert_eq!(determine_output_path(Path::new("config.template.json")), PathBuf::from("config.json"));
assert_eq!(determine_output_path(Path::new("config.example")), PathBuf::from("config.example.out"));
}
}

View File

@@ -1,4 +1,4 @@
use crate::app::{App, InsertVariant, Mode}; use crate::app::{App, Mode};
use crate::config::Config; use crate::config::Config;
use crate::format::FormatHandler; use crate::format::FormatHandler;
use crossterm::event::{self, Event, KeyCode, KeyEvent}; use crossterm::event::{self, Event, KeyCode, KeyEvent};
@@ -117,17 +117,11 @@ where
(&self.config.keybinds.down, "down"), (&self.config.keybinds.down, "down"),
(&self.config.keybinds.up, "up"), (&self.config.keybinds.up, "up"),
(&self.config.keybinds.edit, "edit"), (&self.config.keybinds.edit, "edit"),
(&self.config.keybinds.edit_append, "edit_append"),
(&self.config.keybinds.edit_substitute, "edit_substitute"),
(&self.config.keybinds.search, "search"), (&self.config.keybinds.search, "search"),
(&self.config.keybinds.next_match, "next_match"), (&self.config.keybinds.next_match, "next_match"),
(&self.config.keybinds.previous_match, "previous_match"), (&self.config.keybinds.previous_match, "previous_match"),
(&self.config.keybinds.jump_top, "jump_top"), (&self.config.keybinds.jump_top, "jump_top"),
(&self.config.keybinds.jump_bottom, "jump_bottom"), (&self.config.keybinds.jump_bottom, "jump_bottom"),
(&self.config.keybinds.append_item, "append_item"),
(&self.config.keybinds.prepend_item, "prepend_item"),
(&self.config.keybinds.delete_item, "delete_item"),
(&self.config.keybinds.undo, "undo"),
(&"a".to_string(), "add_missing"), (&"a".to_string(), "add_missing"),
(&":".to_string(), "command"), (&":".to_string(), "command"),
(&"q".to_string(), "quit"), (&"q".to_string(), "quit"),
@@ -150,9 +144,7 @@ where
match action { match action {
"down" => self.app.next(), "down" => self.app.next(),
"up" => self.app.previous(), "up" => self.app.previous(),
"edit" => self.app.enter_insert(InsertVariant::Start), "edit" => self.app.enter_insert(),
"edit_append" => self.app.enter_insert(InsertVariant::End),
"edit_substitute" => self.app.enter_insert(InsertVariant::Substitute),
"search" => { "search" => {
self.app.mode = Mode::Search; self.app.mode = Mode::Search;
self.app.search_query.clear(); self.app.search_query.clear();
@@ -162,14 +154,7 @@ where
"previous_match" => self.app.jump_previous_match(), "previous_match" => self.app.jump_previous_match(),
"jump_top" => self.app.jump_top(), "jump_top" => self.app.jump_top(),
"jump_bottom" => self.app.jump_bottom(), "jump_bottom" => self.app.jump_bottom(),
"append_item" => self.app.add_array_item(true), "add_missing" => self.add_missing_item(),
"prepend_item" => self.app.add_array_item(false),
"delete_item" => self.app.delete_selected(),
"undo" => self.app.undo(),
"add_missing" => {
self.app.save_undo_state();
self.add_missing_item();
}
"command" => { "command" => {
self.command_buffer.push(':'); self.command_buffer.push(':');
self.sync_command_status(); self.sync_command_status();

View File

@@ -269,36 +269,14 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
), ),
}; };
let status_msg = if let Some(msg) = &app.status_message { let status_msg = app
msg.clone() .status_message
} else { .as_deref()
let kb = &config.keybinds; .unwrap_or_else(|| match app.mode {
match app.mode { Mode::Normal => " navigation | i: edit | /: search | :w: save | :q: quit ",
Mode::Normal => { Mode::Insert => " Esc: back to normal | Enter: commit ",
let mut parts = vec![ Mode::Search => " Esc: back to normal | type to filter ",
format!("{}/{} move", kb.down, kb.up), });
format!("{}/{} jump", kb.jump_top, kb.jump_bottom),
format!("{} search", kb.search),
];
if !app.selected_is_group() {
parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute));
}
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));
}
parts.push(format!("{} del", kb.delete_item));
parts.push(format!("{} undo", kb.undo));
parts.push(format!("{} save", kb.save));
parts.push(format!("{} quit", kb.quit));
parts.join(" · ")
}
Mode::Insert => "Esc normal · Enter commit".to_string(),
Mode::Search => "Esc normal · type to filter".to_string(),
}
};
let status_line = Line::from(vec![ let status_line = Line::from(vec![
Span::styled(mode_str, mode_style), Span::styled(mode_str, mode_style),