Compare commits
21 Commits
b88d93c800
...
v0.5.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e974e0503 | |||
| 8dc96d4605 | |||
| 37798d5deb | |||
| 311f514414 | |||
| 53dc317d7d | |||
| f959509538 | |||
| b07a2d8f75 | |||
| c773fdf472 | |||
| 029b4f9da8 | |||
| ee85be4e6b | |||
| 31dc062ce5 | |||
| 50278821ca | |||
| e3510a96fb | |||
| 51625ed296 | |||
| ca7ebc9563 | |||
| a2ec8660c7 | |||
| 30fd2d5d75 | |||
| 277d8aa151 | |||
| 5056f8dd0a | |||
| b3651aa5dd | |||
| b8c49d4c13 |
3
Cargo.lock
generated
3
Cargo.lock
generated
@@ -914,7 +914,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
version = "0.4.3"
|
version = "0.5.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -1460,6 +1460,7 @@ version = "1.0.149"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
"itoa",
|
"itoa",
|
||||||
"memchr",
|
"memchr",
|
||||||
"serde",
|
"serde",
|
||||||
|
|||||||
30
Cargo.toml
30
Cargo.toml
@@ -2,7 +2,7 @@
|
|||||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
name = "mould"
|
name = "mould"
|
||||||
version = "0.5.0"
|
version = "0.5.1"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
@@ -15,22 +15,34 @@ dirs = "6.0.0"
|
|||||||
env_logger = "0.11.9"
|
env_logger = "0.11.9"
|
||||||
java-properties = "2.0.0"
|
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"
|
rust-ini = "0.21.3"
|
||||||
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"
|
|
||||||
tui-input = "0.15.0"
|
tui-input = "0.15.0"
|
||||||
|
|
||||||
[dependencies.clap]
|
|
||||||
features = ["derive"]
|
|
||||||
version = "4.6.0"
|
|
||||||
|
|
||||||
[dependencies.serde]
|
[dependencies.serde]
|
||||||
features = ["derive"]
|
|
||||||
version = "1.0.228"
|
version = "1.0.228"
|
||||||
|
features = ["derive"]
|
||||||
|
|
||||||
|
[dependencies.serde_json]
|
||||||
|
version = "1.0.149"
|
||||||
|
features = ["preserve_order"]
|
||||||
|
|
||||||
|
[dependencies.toml]
|
||||||
|
version = "1.0.7"
|
||||||
|
features = ["preserve_order"]
|
||||||
|
|
||||||
|
[dependencies.clap]
|
||||||
|
version = "4.6.0"
|
||||||
|
features = ["derive"]
|
||||||
|
|
||||||
|
[dependencies.quick-xml]
|
||||||
|
version = "0.39.2"
|
||||||
|
features = [
|
||||||
|
"serde",
|
||||||
|
"serialize",
|
||||||
|
]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.27.0"
|
tempfile = "3.27.0"
|
||||||
|
|||||||
172
README.md
172
README.md
@@ -1,40 +1,47 @@
|
|||||||
# 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`, `TOML`, `XML`, `INI`, or `Properties` 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**: Read, edit, and write `.env`, `JSON`, `YAML`, `TOML`, `XML`, `INI`, and `Properties` files seamlessly.
|
||||||
- **Tree View Navigation**: Edit nested data structures in a beautiful, depth-colored tree view.
|
- **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.
|
- **Smart Template Discovery**: Rule-based resolver automatically discovers relationships (e.g., `.env.example` vs `.env`, `config.template.properties` vs `config.properties`) and highlights missing keys.
|
||||||
- **Strict Type Preservation**: Intelligently preserves data types (integers, booleans, strings) during edit-save cycles, ensuring your configuration stays valid.
|
- **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.
|
- **Advanced Undo/Redo Engine**: Features a tree-based undo/redo history that ensures you never lose changes during complex branching edits. It properly tracks all modifications, including nested renames and item additions/deletions.
|
||||||
- **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
|
|
||||||
- **Vim-inspired Workflow**: Navigate with `j`/`k`, `gg`/`G`, edit with `i`, search with `/`, and save with `:w`.
|
- **Vim-inspired Workflow**: Navigate with `j`/`k`, `gg`/`G`, edit with `i`, search with `/`, and save with `:w`.
|
||||||
- **Modern UI**: A polished, rounded interface featuring a semantic Catppuccin Mocha palette.
|
- **Modern UI**: A polished, rounded interface featuring a semantic Catppuccin Mocha palette with support for terminal transparency.
|
||||||
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML configuration.
|
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML user configuration.
|
||||||
|
- **Neovim Integration**: Comes with a built-in Neovim plugin for seamless in-editor configuration management.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### CLI Application
|
### 1. CLI Application
|
||||||
|
|
||||||
Ensure you have Rust and Cargo installed, then run:
|
Ensure you have Rust and Cargo installed, then run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
# Install directly from the local path
|
||||||
cargo install --path .
|
cargo install --path .
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternatively, you can build from source:
|
Alternatively, you can build from source:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone <repository_url>
|
git clone https://git.narl.io/nvrl/mould-rs
|
||||||
cd mould
|
cd mould-rs
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
# The executable will be located in target/release/mould
|
||||||
```
|
```
|
||||||
|
|
||||||
### Neovim Plugin
|
### 2. Neovim Plugin
|
||||||
If you use a plugin manager like `mini.deps`, you can add the repository directly:
|
|
||||||
|
|
||||||
|
If you want to use `mould` directly inside Neovim, the repository includes a built-in Lua plugin that opens `mould` in a floating terminal buffer and synchronizes the file upon exit.
|
||||||
|
|
||||||
|
**Using `mini.deps`:**
|
||||||
```lua
|
```lua
|
||||||
add({
|
add({
|
||||||
source = 'https://git.narl.io/nvrl/mould-rs',
|
source = 'https://git.narl.io/nvrl/mould-rs',
|
||||||
@@ -42,9 +49,11 @@ add({
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Provide an input template file to start editing. `mould` is smart enough to figure out if it's looking at a template or an active file, and will search for its counterpart to provide diffing.
|
Provide an input template file to start editing. `mould` is smart enough to figure out if it's looking at a template or an active file, and will search for its counterpart to provide live diffing.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
mould .env.example
|
mould .env.example
|
||||||
@@ -52,6 +61,12 @@ mould docker-compose.yml
|
|||||||
mould config.template.json -o config.json
|
mould config.template.json -o config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you just run `mould` in a directory, it will automatically look for common template patterns like `.env.example` or `docker-compose.yml`.
|
||||||
|
|
||||||
|
### Inside Neovim
|
||||||
|
|
||||||
|
Open any configuration file in Neovim and run `:Mould`. It will launch a floating window targeting your active buffer.
|
||||||
|
|
||||||
### Keybindings (Default)
|
### Keybindings (Default)
|
||||||
|
|
||||||
- **Normal Mode**
|
- **Normal Mode**
|
||||||
@@ -59,52 +74,45 @@ 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 value (cursor at start). If selected is a group, enters rename mode.
|
||||||
- `A`: Edit value (cursor at end)
|
- `a`: Edit value (cursor at end)
|
||||||
- `S`: Substitute value (clear and edit)
|
- `s` / `S`: Substitute value (clear and edit)
|
||||||
- `o`: Append a new item to the current array
|
- `r`: Rename the current key or group. (Cannot rename array indices).
|
||||||
- `O`: Prepend a new item to the current array
|
- `o`: Append a new item (as a sibling or array element). Enters rename mode for non-array items.
|
||||||
- `dd`: Delete the currently selected variable or group
|
- `O`: Prepend a new item (as a sibling or array element). Enters rename mode for non-array items.
|
||||||
|
- `alt+o`: Append a new group/object as a child. Enters rename mode for the new group.
|
||||||
|
- `alt+O`: Prepend a new group/object as a child. Enters rename mode for the new group.
|
||||||
|
- `t`: Toggle the selected item between a group/object and a standard variable.
|
||||||
|
- `dd`: Delete the currently selected variable or group (removes all nested children).
|
||||||
- `u`: Undo the last change
|
- `u`: Undo the last change
|
||||||
|
- `U`: Redo the reverted 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
|
||||||
- `n`: Jump to the next search match
|
- `n` / `N`: Jump to next / previous search match
|
||||||
- `N`: Jump to the previous search match
|
- `:w` or `Enter`: Save the current configuration
|
||||||
- `:w` or `Enter`: Save the current configuration to the output file
|
|
||||||
- `:q` or `q`: Quit the application
|
- `:q` or `q`: Quit the application
|
||||||
- `:wq`: Save and quit
|
- `:wq`: Save and quit
|
||||||
- `Esc`: Clear current command prompt
|
- `Esc`: Clear current command prompt
|
||||||
|
|
||||||
- **Insert Mode**
|
- **Insert / Rename Modes**
|
||||||
- Type your value for the selected key.
|
- Type your value/key string.
|
||||||
- Arrow keys: Navigate within the input field
|
- Arrow keys: Navigate within the input field
|
||||||
- `Enter` / `Esc`: Commit the value and return to Normal Mode
|
- `Enter`: Commit the value/key and return to Normal Mode. If renaming, checks for key collisions.
|
||||||
|
- `Esc`: Cancel edits and return to Normal Mode. Reverts changes to the current field.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
mould can be configured using a `config.toml` file located in your user configuration directory (e.g., `~/.config/mould/config.toml` on Linux/macOS).
|
`mould` can be configured using a `config.toml` file located in your user configuration directory:
|
||||||
|
- **Linux/macOS**: `~/.config/mould/config.toml`
|
||||||
|
- **Windows**: `%AppData%\mould\config.toml`
|
||||||
|
|
||||||
Example configuration:
|
Example configuration:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[keybinds]
|
|
||||||
down = "j"
|
|
||||||
up = "k"
|
|
||||||
edit = "i"
|
|
||||||
save = ":w"
|
|
||||||
quit = ":q"
|
|
||||||
normal_mode = "Esc"
|
|
||||||
search = "/"
|
|
||||||
next_match = "n"
|
|
||||||
previous_match = "N"
|
|
||||||
jump_top = "gg"
|
|
||||||
jump_bottom = "G"
|
|
||||||
|
|
||||||
[theme]
|
[theme]
|
||||||
# Enable transparency to let your terminal background show through
|
|
||||||
transparent = false
|
transparent = false
|
||||||
|
|
||||||
# Custom color palette (Semantic Catppuccin Mocha defaults)
|
|
||||||
bg_normal = "#1e1e2e"
|
bg_normal = "#1e1e2e"
|
||||||
bg_highlight = "#89b4fa"
|
bg_highlight = "#89b4fa"
|
||||||
bg_active = "#a6e3a1"
|
bg_active = "#a6e3a1"
|
||||||
@@ -121,8 +129,86 @@ tree_depth_1 = "#b4befe"
|
|||||||
tree_depth_2 = "#cba6f7"
|
tree_depth_2 = "#cba6f7"
|
||||||
tree_depth_3 = "#89b4fa"
|
tree_depth_3 = "#89b4fa"
|
||||||
tree_depth_4 = "#fab387"
|
tree_depth_4 = "#fab387"
|
||||||
|
|
||||||
|
[keybinds]
|
||||||
|
down = "j"
|
||||||
|
up = "k"
|
||||||
|
edit = "i"
|
||||||
|
edit_append = "a"
|
||||||
|
edit_substitute = "s"
|
||||||
|
save = ":w"
|
||||||
|
quit = ":q"
|
||||||
|
normal_mode = "Esc"
|
||||||
|
search = "/"
|
||||||
|
next_match = "n"
|
||||||
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
|
jump_bottom = "G"
|
||||||
|
append_item = "o"
|
||||||
|
prepend_item = "O"
|
||||||
|
delete_item = "dd"
|
||||||
|
undo = "u"
|
||||||
|
redo = "U"
|
||||||
|
rename = "r"
|
||||||
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Development & Architecture
|
||||||
|
|
||||||
|
`mould` is written in Rust and architected to decouple the file format parsing from the UI representation. This allows the TUI to render complex, nested configuration files in a unified tree-view.
|
||||||
|
|
||||||
|
### Core Architectural Principles:
|
||||||
|
|
||||||
|
- **Separation of Concerns**: Clear boundaries between UI rendering, application state, input handling, and file format logic.
|
||||||
|
- **Unified Data Model**: All parsed configuration data is normalized into a single `Vec<ConfigItem>` structure, simplifying application logic across different file types.
|
||||||
|
- **Vim-inspired Modality**: The application operates in distinct modes (`Normal`, `Insert`, `InsertKey`, `Search`), each with specific keybinding behaviors, enabling efficient interaction.
|
||||||
|
- **Non-linear Undo/Redo**: A robust undo tree allows users to revert and re-apply changes across complex branching edit histories.
|
||||||
|
|
||||||
|
### Key Components
|
||||||
|
|
||||||
|
1. **State Management & Undo Tree (`src/app.rs` & `src/undo.rs`)**
|
||||||
|
* The central state is maintained in the `App` struct, which tracks the currently loaded configuration variables, application modes, and user input buffer.
|
||||||
|
* It integrates an **UndoTree**, providing non-linear, branching history tracking for complex edits (additions, deletions, nested renaming). Each significant state change (`save_undo_state`) pushes a snapshot to this tree.
|
||||||
|
|
||||||
|
2. **Unified Data Model (`src/format/mod.rs`)**
|
||||||
|
* Regardless of the underlying file format (JSON, YAML, .env, etc.), all data is translated into a flattened `Vec<ConfigItem>`.
|
||||||
|
* A `ConfigItem` represents a single configuration entry. It contains:
|
||||||
|
* `key`: The display key (e.g., `port` or `[0]`).
|
||||||
|
* `path`: A `Vec<PathSegment>` (composed of `PathSegment::Key(String)` for object keys and `PathSegment::Index(usize)` for array indices) that defines its full hierarchical location.
|
||||||
|
* `value`: `Option<String>` holding the actual value.
|
||||||
|
* `is_group`: A boolean indicating if this item is a structural node (object or array).
|
||||||
|
* `status`: (`ItemStatus::Present`, `MissingFromActive`, `Modified`) reflecting comparison with a template.
|
||||||
|
* `value_type`: (`ValueType::String`, `Number`, `Bool`, `Null`) to ensure type preservation during writes.
|
||||||
|
|
||||||
|
3. **Format Handlers (`src/format/*`)**
|
||||||
|
* Each file format has a dedicated handler (`EnvHandler`, `IniHandler`, `HierarchicalHandler`, `PropertiesHandler`) implementing the `FormatHandler` trait.
|
||||||
|
* **`HierarchicalHandler`**: A generalized processor leveraging `serde_json::Value` as an intermediary layer to parse and write nested `JSON`, `YAML`, `TOML`, and even `XML` (via `quick-xml` transposition). This allows complex structures to be flattened for editing and then re-nested accurately.
|
||||||
|
* These handlers are responsible for translating between the file's native format and the `Vec<ConfigItem>` internal representation.
|
||||||
|
|
||||||
|
4. **Template Resolver (`src/resolver.rs`)**
|
||||||
|
* Automatically determines template-active file pairings without explicit user instruction.
|
||||||
|
* Uses hardcoded exact rules (e.g., `compose.yml` -> `compose.override.yml`) and generic fallback rules to strip `.example` or `.template` suffixes to find target output files dynamically.
|
||||||
|
|
||||||
|
5. **Terminal UI & Event Loop (`src/ui.rs` & `src/runner.rs`)**
|
||||||
|
* **UI Rendering (`src/ui.rs`)**: Powered by the `ratatui` library. Renders a flexible layout consisting of a styled hierarchical list, an active input field for editing, and a dynamic status bar.
|
||||||
|
* **Event Runner (`src/runner.rs`)**: Powered by `crossterm`. It intercepts raw keyboard events, resolves multi-key sequences (like `dd` or `gg`), delegates character input to the `tui-input` backend during active editing, and dispatches actions to mutate the `App` state. It includes logic to prevent "one-key-behind" issues and manage complex keybindings like `alt+o`.
|
||||||
|
|
||||||
|
6. **Neovim Plugin (`lua/mould/init.lua`)**
|
||||||
|
* Implements a Lua wrapper that calculates terminal geometries and launches the CLI `mould` binary inside an ephemeral, floating terminal buffer, ensuring automatic Neovim `checktime` synchronization upon `mould`'s exit.
|
||||||
|
|
||||||
|
### Development Process Highlights:
|
||||||
|
|
||||||
|
- **Iterative Refinement**: Features like key renaming, group creation, and advanced undo/redo were developed iteratively, responding to user feedback and progressively enhancing the core data model and interaction logic.
|
||||||
|
- **Robust Error Handling**: Key functions (`commit_input`, `enter_insert_key`) include collision detection and validation to ensure data integrity during user modifications.
|
||||||
|
- **Modality-driven Design**: The introduction of `InsertKey` mode and careful handling of `InsertVariant` demonstrates a commitment to a precise, context-aware user experience, minimizing ambiguity during editing.
|
||||||
|
- **Debugging and Performance**: Issues like UI "hangs" were traced to subtle interactions in key event processing and input buffer management, leading to refactored key sequence logic for improved responsiveness.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 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.
|
||||||
|
|||||||
@@ -31,8 +31,8 @@ tree_depth_4 = "#fab387"
|
|||||||
down = "j"
|
down = "j"
|
||||||
up = "k"
|
up = "k"
|
||||||
edit = "i"
|
edit = "i"
|
||||||
edit_append = "A"
|
edit_append = "a"
|
||||||
edit_substitute = "S"
|
edit_substitute = "s"
|
||||||
save = ":w"
|
save = ":w"
|
||||||
quit = ":q"
|
quit = ":q"
|
||||||
normal_mode = "Esc"
|
normal_mode = "Esc"
|
||||||
@@ -45,3 +45,8 @@ append_item = "o"
|
|||||||
prepend_item = "O"
|
prepend_item = "O"
|
||||||
delete_item = "dd"
|
delete_item = "dd"
|
||||||
undo = "u"
|
undo = "u"
|
||||||
|
redo = "U"
|
||||||
|
rename = "r"
|
||||||
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
|
|||||||
37
config.toml
37
config.toml
@@ -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"
|
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
local M = {}
|
local M = {}
|
||||||
|
|
||||||
local function open_floating_terminal(cmd)
|
-- Helper function to get a set of files currently in a directory
|
||||||
|
local function get_dir_files(dir)
|
||||||
|
local files = {}
|
||||||
|
if vim.fn.isdirectory(dir) == 1 then
|
||||||
|
for _, f in ipairs(vim.fn.readdir(dir)) do
|
||||||
|
files[f] = true
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return files
|
||||||
|
end
|
||||||
|
|
||||||
|
local function open_floating_terminal(cmd, target_dir)
|
||||||
local buf = vim.api.nvim_create_buf(false, true)
|
local buf = vim.api.nvim_create_buf(false, true)
|
||||||
local width = math.floor(vim.o.columns * 0.9)
|
local width = math.floor(vim.o.columns * 0.9)
|
||||||
local height = math.floor(vim.o.lines * 0.9)
|
local height = math.floor(vim.o.lines * 0.9)
|
||||||
@@ -23,8 +34,12 @@ local function open_floating_terminal(cmd)
|
|||||||
local original_buf = vim.api.nvim_get_current_buf()
|
local original_buf = vim.api.nvim_get_current_buf()
|
||||||
local original_file = vim.api.nvim_buf_get_name(original_buf)
|
local original_file = vim.api.nvim_buf_get_name(original_buf)
|
||||||
|
|
||||||
|
-- Snapshot the directory contents BEFORE the command runs
|
||||||
|
local files_before = get_dir_files(target_dir)
|
||||||
|
|
||||||
vim.fn.termopen(cmd, {
|
vim.fn.termopen(cmd, {
|
||||||
on_exit = function()
|
on_exit = function()
|
||||||
|
-- Close the floating window and delete the terminal buffer
|
||||||
vim.api.nvim_win_close(win, true)
|
vim.api.nvim_win_close(win, true)
|
||||||
vim.api.nvim_buf_delete(buf, { force = true })
|
vim.api.nvim_buf_delete(buf, { force = true })
|
||||||
|
|
||||||
@@ -34,6 +49,25 @@ local function open_floating_terminal(cmd)
|
|||||||
vim.cmd("checktime " .. vim.fn.fnameescape(original_file))
|
vim.cmd("checktime " .. vim.fn.fnameescape(original_file))
|
||||||
end)
|
end)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
-- Snapshot the directory AFTER the command finishes
|
||||||
|
local files_after = get_dir_files(target_dir)
|
||||||
|
|
||||||
|
-- Compare to find the newly created file
|
||||||
|
for f, _ in pairs(files_after) do
|
||||||
|
if not files_before[f] then
|
||||||
|
local new_filepath = target_dir .. "/" .. f
|
||||||
|
|
||||||
|
-- Open the new file (wrapped in schedule to ensure it runs safely after term closes)
|
||||||
|
vim.schedule(function()
|
||||||
|
vim.cmd("edit " .. vim.fn.fnameescape(new_filepath))
|
||||||
|
-- Optional: Let the user know it worked
|
||||||
|
vim.notify("mould.nvim: Opened " .. f, vim.log.levels.INFO)
|
||||||
|
end)
|
||||||
|
|
||||||
|
break -- Assuming only one file is generated; we can stop looking
|
||||||
|
end
|
||||||
|
end
|
||||||
end,
|
end,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -47,8 +81,12 @@ function M.open()
|
|||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
|
-- Get the directory of the current file
|
||||||
|
local target_dir = vim.fn.fnamemodify(filepath, ":p:h")
|
||||||
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
||||||
open_floating_terminal(cmd)
|
|
||||||
|
-- Pass the target directory to our terminal function
|
||||||
|
open_floating_terminal(cmd, target_dir)
|
||||||
end
|
end
|
||||||
|
|
||||||
return M
|
return M
|
||||||
|
|||||||
470
src/app.rs
470
src/app.rs
@@ -1,46 +1,62 @@
|
|||||||
use crate::format::ConfigItem;
|
use crate::format::{ConfigItem, PathSegment};
|
||||||
use tui_input::Input;
|
use tui_input::Input;
|
||||||
|
use crate::undo::UndoTree;
|
||||||
|
|
||||||
/// Represents the current operating mode of the application.
|
/// Represents the current operating mode of the application.
|
||||||
|
///
|
||||||
|
/// Modality allows the application to reuse the same keyboard events
|
||||||
|
/// for different contextual actions (navigation vs. text entry).
|
||||||
pub enum Mode {
|
pub enum Mode {
|
||||||
/// Standard navigation and command mode.
|
/// Standard navigation and command mode.
|
||||||
Normal,
|
Normal,
|
||||||
/// Active text entry mode for modifying values.
|
/// Active text entry mode for modifying values.
|
||||||
Insert,
|
Insert,
|
||||||
|
/// Active text entry mode for modifying keys.
|
||||||
|
InsertKey,
|
||||||
/// Active search mode for filtering keys.
|
/// Active search mode for filtering keys.
|
||||||
Search,
|
Search,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Defines where the cursor starts when entering Insert mode.
|
||||||
pub enum InsertVariant {
|
pub enum InsertVariant {
|
||||||
|
/// Cursor at the beginning of the text.
|
||||||
Start,
|
Start,
|
||||||
|
/// Cursor at the end of the text.
|
||||||
End,
|
End,
|
||||||
|
/// Text is cleared before entry.
|
||||||
Substitute,
|
Substitute,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The core application state, holding all configuration variables and UI status.
|
/// The core application state, holding all configuration variables and UI status.
|
||||||
|
///
|
||||||
|
/// This struct is the "Single Source of Truth" for the TUI. It manages
|
||||||
|
/// selection, filtering, history, and structural mutations.
|
||||||
pub struct App {
|
pub struct App {
|
||||||
/// The list of configuration variables being edited.
|
/// The flattened list of configuration variables being edited.
|
||||||
pub vars: Vec<ConfigItem>,
|
pub vars: Vec<ConfigItem>,
|
||||||
/// Index of the currently selected variable in the list.
|
/// Index of the currently selected variable in the list.
|
||||||
pub selected: usize,
|
pub selected: usize,
|
||||||
/// The current interaction mode (Normal or Insert).
|
/// The current interaction mode (Normal, Insert, etc.).
|
||||||
pub mode: Mode,
|
pub mode: Mode,
|
||||||
/// Whether the main application loop should continue running.
|
/// Whether the main application loop should continue running.
|
||||||
pub running: bool,
|
pub running: bool,
|
||||||
/// An optional message to display in the status bar (e.g., "Saved to .env").
|
/// An optional message to display in the status bar.
|
||||||
pub status_message: Option<String>,
|
pub status_message: Option<String>,
|
||||||
/// The active text input buffer for the selected variable.
|
/// The active text input buffer for the selected variable.
|
||||||
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.
|
/// Undo history structured as a tree.
|
||||||
pub undo_stack: Vec<Vec<ConfigItem>>,
|
pub undo_tree: UndoTree,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
/// Initializes a new application instance with the provided variables.
|
/// Initializes a new application instance with the provided variables.
|
||||||
|
///
|
||||||
|
/// It automatically initializes the undo tree with the starting state.
|
||||||
pub fn new(vars: Vec<ConfigItem>) -> Self {
|
pub fn new(vars: Vec<ConfigItem>) -> 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();
|
||||||
|
let undo_tree = UndoTree::new(vars.clone(), 0);
|
||||||
Self {
|
Self {
|
||||||
vars,
|
vars,
|
||||||
selected: 0,
|
selected: 0,
|
||||||
@@ -49,11 +65,11 @@ 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(),
|
undo_tree,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the indices of variables that match the search query.
|
/// Returns the indices of variables that match the search query (case-insensitive).
|
||||||
pub fn matching_indices(&self) -> Vec<usize> {
|
pub fn matching_indices(&self) -> Vec<usize> {
|
||||||
if self.search_query.is_empty() {
|
if self.search_query.is_empty() {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
@@ -87,7 +103,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Jumps to the top of the list.
|
/// Jumps the selection to the top of the list.
|
||||||
pub fn jump_top(&mut self) {
|
pub fn jump_top(&mut self) {
|
||||||
if !self.vars.is_empty() {
|
if !self.vars.is_empty() {
|
||||||
self.selected = 0;
|
self.selected = 0;
|
||||||
@@ -95,7 +111,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Jumps to the bottom of the list.
|
/// Jumps the selection to the bottom of the list.
|
||||||
pub fn jump_bottom(&mut self) {
|
pub fn jump_bottom(&mut self) {
|
||||||
if !self.vars.is_empty() {
|
if !self.vars.is_empty() {
|
||||||
self.selected = self.vars.len() - 1;
|
self.selected = self.vars.len() - 1;
|
||||||
@@ -140,29 +156,122 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates the input buffer to reflect the value of the currently selected variable.
|
/// Updates the input buffer to reflect the current state of the selected item.
|
||||||
|
///
|
||||||
|
/// If in `InsertKey` mode, the buffer is synced with the item's `key`.
|
||||||
|
/// Otherwise, it is synced with the item's `value`.
|
||||||
pub fn sync_input_with_selected(&mut self) {
|
pub fn sync_input_with_selected(&mut self) {
|
||||||
if let Some(var) = self.vars.get(self.selected) {
|
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);
|
self.input = Input::new(val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Commits the current text in the input buffer back to the selected variable's value.
|
/// Commits the current text in the input buffer back to the selected variable.
|
||||||
pub fn commit_input(&mut self) {
|
///
|
||||||
if let Some(var) = self.vars.get_mut(self.selected) {
|
/// Returns true if commit was successful, false if there was an error
|
||||||
if !var.is_group {
|
/// (e.g., a key name collision or empty key).
|
||||||
|
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.value = Some(self.input.value().to_string());
|
||||||
var.status = crate::format::ItemStatus::Modified;
|
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: ensure siblings don't already have this key.
|
||||||
|
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 its full internal 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively update paths of all children if the renamed item is 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;
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transitions the application into Insert Mode with a specific variant.
|
/// Transitions the application into `InsertKey` mode to modify item names.
|
||||||
|
///
|
||||||
|
/// Renaming is blocked for array indices (e.g., `[0]`) as they are
|
||||||
|
/// managed automatically by the application logic.
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transitions the application into `Insert` mode to modify variable values.
|
||||||
|
///
|
||||||
|
/// If the selected item is a group, it automatically routes to
|
||||||
|
/// `enter_insert_key` instead.
|
||||||
pub fn enter_insert(&mut self, variant: InsertVariant) {
|
pub fn enter_insert(&mut self, variant: InsertVariant) {
|
||||||
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.enter_insert_key();
|
||||||
|
} else {
|
||||||
|
if !matches!(variant, InsertVariant::Substitute) {
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
self.mode = Mode::Insert;
|
self.mode = Mode::Insert;
|
||||||
match variant {
|
match variant {
|
||||||
InsertVariant::Start => {
|
InsertVariant::Start => {
|
||||||
@@ -181,37 +290,43 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Commits the current input and transitions the application into Normal Mode.
|
/// Commits the current input and transitions back to `Normal` mode.
|
||||||
pub fn enter_normal(&mut self) {
|
pub fn enter_normal(&mut self) {
|
||||||
self.commit_input();
|
if self.commit_input() {
|
||||||
|
self.save_undo_state();
|
||||||
self.mode = Mode::Normal;
|
self.mode = Mode::Normal;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Deletes the currently selected item. If it's a group, deletes all children.
|
/// Aborts the current input and reverts to `Normal` mode without saving changes.
|
||||||
|
pub fn cancel_insert(&mut self) {
|
||||||
|
self.mode = Mode::Normal;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.status_message = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the currently selected item and all its nested children.
|
||||||
|
///
|
||||||
|
/// If the deleted item is part of an array, subsequent indices are
|
||||||
|
/// automatically shifted and renamed to maintain a continuous sequence.
|
||||||
pub fn delete_selected(&mut self) {
|
pub fn delete_selected(&mut self) {
|
||||||
if self.vars.is_empty() {
|
if self.vars.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.save_undo_state();
|
|
||||||
let selected_path = self.vars[self.selected].path.clone();
|
let selected_path = self.vars[self.selected].path.clone();
|
||||||
let is_group = self.vars[self.selected].is_group;
|
let is_group = self.vars[self.selected].is_group;
|
||||||
|
|
||||||
// Identify if the item being removed is an array item
|
// 1. Identify all items to remove (the item itself + all children)
|
||||||
let array_info = parse_index(&selected_path);
|
|
||||||
|
|
||||||
// 1. Identify all items to remove
|
|
||||||
let mut to_remove = Vec::new();
|
let mut to_remove = Vec::new();
|
||||||
to_remove.push(self.selected);
|
to_remove.push(self.selected);
|
||||||
|
|
||||||
if is_group {
|
if is_group {
|
||||||
let prefix_dot = format!("{}.", selected_path);
|
|
||||||
let prefix_bracket = format!("{}[", selected_path);
|
|
||||||
for (i, var) in self.vars.iter().enumerate() {
|
for (i, var) in self.vars.iter().enumerate() {
|
||||||
if i == self.selected {
|
if i == self.selected {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if var.path.starts_with(&prefix_dot) || var.path.starts_with(&prefix_bracket) {
|
if var.path.starts_with(&selected_path) {
|
||||||
to_remove.push(i);
|
to_remove.push(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,122 +339,261 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Re-index subsequent array items if applicable
|
// 3. Re-index subsequent array items if applicable
|
||||||
if let Some((base, removed_idx)) = array_info {
|
if let Some(PathSegment::Index(removed_idx)) = selected_path.last() {
|
||||||
let base = base.to_string();
|
let base_path = &selected_path[..selected_path.len() - 1];
|
||||||
|
|
||||||
for var in self.vars.iter_mut() {
|
for var in self.vars.iter_mut() {
|
||||||
if var.path.starts_with(&base) {
|
if var.path.starts_with(base_path) && var.path.len() >= selected_path.len() {
|
||||||
// We need to find the index segment that matches this array
|
if let PathSegment::Index(i) = var.path[selected_path.len() - 1]
|
||||||
if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) {
|
&& i > *removed_idx {
|
||||||
if b == base && i > removed_idx {
|
|
||||||
let new_idx = i - 1;
|
let new_idx = i - 1;
|
||||||
var.path = format!("{}[{}]{}", base, new_idx, suffix);
|
var.path[selected_path.len() - 1] = PathSegment::Index(new_idx);
|
||||||
// Also update key if it matches the old index exactly
|
|
||||||
if var.key == format!("[{}]", i) {
|
if var.path.len() == selected_path.len() {
|
||||||
var.key = format!("[{}]", new_idx);
|
var.key = format!("[{}]", new_idx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Adjust selection
|
// 4. Adjust selection
|
||||||
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
self.selected = self.vars.len() - 1;
|
self.selected = self.vars.len() - 1;
|
||||||
}
|
}
|
||||||
self.sync_input_with_selected();
|
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();
|
self.save_undo_state();
|
||||||
let (base, idx, depth) = {
|
}
|
||||||
let selected_item = &self.vars[self.selected];
|
|
||||||
if selected_item.is_group {
|
/// Adds a new item relative to the selected item.
|
||||||
|
///
|
||||||
|
/// - `after`: If true, adds below the selection; otherwise adds above.
|
||||||
|
/// - `is_group`: If true, creates a new structural node (object/array).
|
||||||
|
/// - `as_child`: If true, adds inside the selected group.
|
||||||
|
///
|
||||||
|
/// The method automatically detects if the parent is an array and
|
||||||
|
/// formats the new key accordingly (e.g., `[1]`).
|
||||||
|
pub fn add_item(&mut self, after: bool, is_group: bool, as_child: bool) {
|
||||||
|
if self.vars.is_empty() {
|
||||||
|
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)],
|
||||||
|
value: if is_group { None } else { Some("".to_string()) },
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group,
|
||||||
|
status: crate::format::ItemStatus::Modified,
|
||||||
|
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();
|
||||||
|
if is_group {
|
||||||
|
self.enter_insert_key();
|
||||||
|
} else {
|
||||||
|
self.enter_insert(InsertVariant::Start);
|
||||||
|
}
|
||||||
return;
|
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 selected_item = self.vars[self.selected].clone();
|
||||||
let insert_pos = if after {
|
|
||||||
self.selected + 1
|
|
||||||
} else {
|
|
||||||
self.selected
|
|
||||||
};
|
|
||||||
|
|
||||||
// 1. Shift all items in this array that have index >= new_idx
|
// 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 !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 };
|
||||||
|
insert_pos = if after { self.selected + 1 } else { self.selected };
|
||||||
|
|
||||||
|
// Shift subsequent indices
|
||||||
for var in self.vars.iter_mut() {
|
for var in self.vars.iter_mut() {
|
||||||
if var.path.starts_with(&base) {
|
if var.path.starts_with(&base_path) && var.path.len() > base_path.len()
|
||||||
if let Some((b, i)) = parse_index(&var.path) {
|
&& let PathSegment::Index(i) = var.path[base_path.len()]
|
||||||
if b == base && i >= new_idx {
|
&& i >= new_idx {
|
||||||
var.path = format!("{}[{}]", base, i + 1);
|
var.path[base_path.len()] = PathSegment::Index(i + 1);
|
||||||
// Also update key if it was just the index
|
if var.path.len() == base_path.len() + 1 {
|
||||||
if var.key == format!("[{}]", i) {
|
var.key = format!("[{}]", i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new_path = base_path;
|
||||||
|
new_path.push(PathSegment::Index(new_idx));
|
||||||
|
new_depth = selected_item.depth;
|
||||||
|
} 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;
|
||||||
|
|
||||||
|
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);
|
var.key = format!("[{}]", i + 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;
|
||||||
|
|
||||||
|
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. Insert new item
|
// 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 = 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| {
|
||||||
|
v.path.starts_with(parent_path_slice)
|
||||||
|
&& v.path.len() == parent_path_slice.len() + 1
|
||||||
|
&& v.key == candidate
|
||||||
|
}) {
|
||||||
|
candidate = if is_group { format!("NEW_GROUP_{}", count) } else { format!("NEW_VAR_{}", count) };
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
new_path.push(PathSegment::Key(candidate.clone()));
|
||||||
|
candidate
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Insert new item
|
||||||
let new_item = ConfigItem {
|
let new_item = ConfigItem {
|
||||||
key: format!("[{}]", new_idx),
|
key: final_key,
|
||||||
path: format!("{}[{}]", base, new_idx),
|
path: new_path,
|
||||||
value: Some("".to_string()),
|
value: if is_group { None } else { Some("".to_string()) },
|
||||||
template_value: None,
|
template_value: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
depth,
|
depth: new_depth,
|
||||||
is_group: false,
|
is_group,
|
||||||
status: crate::format::ItemStatus::Modified,
|
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);
|
self.vars.insert(insert_pos, new_item);
|
||||||
self.selected = insert_pos;
|
self.selected = insert_pos;
|
||||||
|
self.save_undo_state();
|
||||||
|
|
||||||
|
if is_array_item {
|
||||||
self.sync_input_with_selected();
|
self.sync_input_with_selected();
|
||||||
self.enter_insert(InsertVariant::Start);
|
self.enter_insert(InsertVariant::Start);
|
||||||
|
} else {
|
||||||
|
self.enter_insert_key();
|
||||||
|
}
|
||||||
self.status_message = None;
|
self.status_message = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Status bar helpers
|
/// Toggles the group status of the currently selected item.
|
||||||
|
///
|
||||||
|
/// Changing a group to a variable clears its children (visually)
|
||||||
|
/// and resets its value. Changing a variable to a group removes its value.
|
||||||
|
pub fn toggle_group_selected(&mut self) {
|
||||||
|
if let Some(var) = self.vars.get_mut(self.selected) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the selected item is a structural node (group/object).
|
||||||
pub fn selected_is_group(&self) -> bool {
|
pub fn selected_is_group(&self) -> bool {
|
||||||
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
|
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns true if the provided path identifies a node that contains array elements.
|
||||||
|
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(_)))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the selected item is an indexed array element.
|
||||||
pub fn selected_is_array(&self) -> bool {
|
pub fn selected_is_array(&self) -> bool {
|
||||||
self.vars.get(self.selected)
|
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)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns true if the selected item exists in the template but not the active config.
|
||||||
pub fn selected_is_missing(&self) -> bool {
|
pub fn selected_is_missing(&self) -> bool {
|
||||||
self.vars.get(self.selected)
|
self.vars.get(self.selected)
|
||||||
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
|
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Saves the current state of variables to the undo stack.
|
/// Saves a snapshot of the current state to the undo history tree.
|
||||||
pub fn save_undo_state(&mut self) {
|
pub fn save_undo_state(&mut self) {
|
||||||
self.undo_stack.push(self.vars.clone());
|
self.undo_tree.push(self.vars.clone(), self.selected);
|
||||||
if self.undo_stack.len() > 50 {
|
|
||||||
self.undo_stack.remove(0);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reverts to the last saved state of variables.
|
/// Reverts the application state to the previous history point.
|
||||||
pub fn undo(&mut self) {
|
pub fn undo(&mut self) {
|
||||||
if let Some(previous_vars) = self.undo_stack.pop() {
|
if let Some(action) = self.undo_tree.undo() {
|
||||||
self.vars = previous_vars;
|
self.vars = action.state.clone();
|
||||||
|
self.selected = action.selected;
|
||||||
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
self.selected = self.vars.len() - 1;
|
self.selected = self.vars.len() - 1;
|
||||||
}
|
}
|
||||||
@@ -349,33 +603,19 @@ impl App {
|
|||||||
self.status_message = Some("Nothing to undo".to_string());
|
self.status_message = Some("Nothing to undo".to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_index(path: &str) -> Option<(&str, usize)> {
|
/// Advances the application state to the next history point in the active branch.
|
||||||
if let Some(end) = path.rfind(']') {
|
pub fn redo(&mut self) {
|
||||||
let segment = &path[..=end];
|
if let Some(action) = self.undo_tree.redo() {
|
||||||
if let Some(start) = segment.rfind('[') {
|
self.vars = action.state.clone();
|
||||||
if let Ok(idx) = segment[start + 1..end].parse::<usize>() {
|
self.selected = action.selected;
|
||||||
// Return the base and index
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
return Some((&path[..start], idx));
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,16 +120,21 @@ pub struct KeybindsConfig {
|
|||||||
pub prepend_item: String,
|
pub prepend_item: String,
|
||||||
pub delete_item: String,
|
pub delete_item: String,
|
||||||
pub undo: String,
|
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 {
|
impl Default for KeybindsConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
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_append: "a".to_string(),
|
||||||
edit_substitute: "S".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(),
|
||||||
@@ -142,9 +147,14 @@ impl Default for KeybindsConfig {
|
|||||||
prepend_item: "O".to_string(),
|
prepend_item: "O".to_string(),
|
||||||
delete_item: "dd".to_string(),
|
delete_item: "dd".to_string(),
|
||||||
undo: "u".to_string(),
|
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(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Root configuration structure for mould.
|
/// Root configuration structure for mould.
|
||||||
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
||||||
@@ -162,13 +172,11 @@ pub fn load_config() -> Config {
|
|||||||
config_dir.push("mould");
|
config_dir.push("mould");
|
||||||
config_dir.push("config.toml");
|
config_dir.push("config.toml");
|
||||||
|
|
||||||
if config_dir.exists() {
|
if config_dir.exists()
|
||||||
if let Ok(content) = fs::read_to_string(config_dir) {
|
&& let Ok(content) = fs::read_to_string(config_dir)
|
||||||
if let Ok(config) = toml::from_str(&content) {
|
&& let Ok(config) = toml::from_str(&content) {
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
Config::default()
|
Config::default()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
use std::io;
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
/// Custom error types for the mould application.
|
/// Custom error types for the mould application.
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum MouldError {
|
pub enum MouldError {
|
||||||
#[error("IO error: {0}")]
|
#[error("IO error: {0}")]
|
||||||
Io(#[from] io::Error),
|
Io(#[from] std::io::Error),
|
||||||
|
|
||||||
#[error("Format error: {0}")]
|
|
||||||
Format(String),
|
|
||||||
|
|
||||||
#[error("File not found: {0}")]
|
#[error("File not found: {0}")]
|
||||||
FileNotFound(String),
|
FileNotFound(String),
|
||||||
|
|||||||
@@ -1,29 +1,43 @@
|
|||||||
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType};
|
//! Handler for flat `.env` (Environment) configuration files.
|
||||||
|
//!
|
||||||
|
//! This handler manages simple `KEY=VALUE` pairs. It does not support
|
||||||
|
//! native nesting or grouping, treating all entries as root-level variables.
|
||||||
|
|
||||||
|
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, Write};
|
use std::io::Write;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// A format handler for parsing and writing `.env` files.
|
||||||
pub struct EnvHandler;
|
pub struct EnvHandler;
|
||||||
|
|
||||||
impl FormatHandler for EnvHandler {
|
impl FormatHandler for EnvHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
/// Parses an environment file into a flat list of `ConfigItem`s.
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
let content = fs::read_to_string(path)?;
|
let content = fs::read_to_string(path)?;
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
|
|
||||||
for line in content.lines() {
|
for line in content.lines() {
|
||||||
let line = line.trim();
|
let line = line.trim();
|
||||||
|
// Skip empty lines and comments.
|
||||||
if line.is_empty() || line.starts_with('#') {
|
if line.is_empty() || line.starts_with('#') {
|
||||||
continue; // Skip comments and empty lines
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some((key, val)) = line.split_once('=') {
|
if let Some((key, value)) = line.split_once('=') {
|
||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
let key = key.trim().to_string();
|
||||||
|
let value = value.trim().to_string();
|
||||||
|
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key.trim().to_string(),
|
key: key.clone(),
|
||||||
path: key.trim().to_string(),
|
path: vec![PathSegment::Key(key)],
|
||||||
value: Some(parsed_val.clone()),
|
value: Some(value.clone()),
|
||||||
template_value: Some(parsed_val.clone()),
|
template_value: Some(value.clone()),
|
||||||
default_value: Some(parsed_val),
|
default_value: Some(value.clone()),
|
||||||
depth: 0,
|
depth: 0,
|
||||||
is_group: false,
|
is_group: false,
|
||||||
status: ItemStatus::Present,
|
status: ItemStatus::Present,
|
||||||
@@ -35,56 +49,11 @@ impl FormatHandler for EnvHandler {
|
|||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
/// Writes the list of variables back to a flat `.env` file.
|
||||||
if !path.exists() {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
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)?;
|
let mut file = fs::File::create(path)?;
|
||||||
for var in vars {
|
for var in vars {
|
||||||
|
// .env files ignore structural groups.
|
||||||
if !var.is_group {
|
if !var.is_group {
|
||||||
let val = var.value.as_deref()
|
let val = var.value.as_deref()
|
||||||
.or(var.template_value.as_deref())
|
.or(var.template_value.as_deref())
|
||||||
@@ -99,54 +68,21 @@ impl FormatHandler for EnvHandler {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::io::Write;
|
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_env_example() {
|
fn test_parse_env_example() {
|
||||||
let mut file = NamedTempFile::new().unwrap();
|
let mut file = NamedTempFile::new().unwrap();
|
||||||
writeln!(
|
writeln!(file, "# Comment\nKEY1=value1\n KEY2 = value2 ").unwrap();
|
||||||
file,
|
|
||||||
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let handler = EnvHandler;
|
let handler = EnvHandler;
|
||||||
let vars = handler.parse(file.path()).unwrap();
|
let vars = handler.parse(file.path()).unwrap();
|
||||||
assert_eq!(vars.len(), 4);
|
|
||||||
|
assert_eq!(vars.len(), 2);
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
assert_eq!(vars[1].key, "KEY2");
|
||||||
assert_eq!(vars[1].value.as_deref(), Some("value2"));
|
assert_eq!(vars[1].value.as_deref(), Some("value2"));
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
|
||||||
assert_eq!(vars[2].value.as_deref(), Some("value3"));
|
|
||||||
assert_eq!(vars[3].key, "EMPTY");
|
|
||||||
assert_eq!(vars[3].value.as_deref(), Some(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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();
|
|
||||||
|
|
||||||
handler.merge(env_file.path(), &mut vars).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(vars.len(), 3);
|
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
|
||||||
assert_eq!(vars[0].value.as_deref(), Some("custom1"));
|
|
||||||
assert_eq!(vars[0].status, ItemStatus::Modified);
|
|
||||||
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
|
||||||
assert_eq!(vars[1].value.as_deref(), Some("default2"));
|
|
||||||
|
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
|
||||||
assert_eq!(vars[2].value.as_deref(), Some("custom3"));
|
|
||||||
assert_eq!(vars[2].status, ItemStatus::MissingFromTemplate);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -154,7 +90,7 @@ mod tests {
|
|||||||
let file = NamedTempFile::new().unwrap();
|
let file = NamedTempFile::new().unwrap();
|
||||||
let vars = vec![ConfigItem {
|
let vars = vec![ConfigItem {
|
||||||
key: "KEY1".to_string(),
|
key: "KEY1".to_string(),
|
||||||
path: "KEY1".to_string(),
|
path: vec![PathSegment::Key("KEY1".to_string())],
|
||||||
value: Some("value1".to_string()),
|
value: Some("value1".to_string()),
|
||||||
template_value: None,
|
template_value: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
@@ -170,4 +106,39 @@ mod tests {
|
|||||||
let content = fs::read_to_string(file.path()).unwrap();
|
let content = fs::read_to_string(file.path()).unwrap();
|
||||||
assert_eq!(content.trim(), "KEY1=value1");
|
assert_eq!(content.trim(), "KEY1=value1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_merge_env() {
|
||||||
|
let template = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(template.as_file(), "KEY1=template_val\nKEY2=default_val").unwrap();
|
||||||
|
|
||||||
|
let mut active_vars = vec![ConfigItem {
|
||||||
|
key: "KEY1".to_string(),
|
||||||
|
path: vec![PathSegment::Key("KEY1".to_string())],
|
||||||
|
value: Some("active_val".to_string()),
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
}];
|
||||||
|
|
||||||
|
let handler = EnvHandler;
|
||||||
|
handler.merge(template.path(), &mut active_vars).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(active_vars.len(), 2);
|
||||||
|
|
||||||
|
// KEY1 should be marked modified
|
||||||
|
let key1 = active_vars.iter().find(|v| v.key == "KEY1").unwrap();
|
||||||
|
assert_eq!(key1.status, ItemStatus::Modified);
|
||||||
|
assert_eq!(key1.value.as_deref(), Some("active_val"));
|
||||||
|
assert_eq!(key1.template_value.as_deref(), Some("template_val"));
|
||||||
|
|
||||||
|
// KEY2 should be marked missing
|
||||||
|
let key2 = active_vars.iter().find(|v| v.key == "KEY2").unwrap();
|
||||||
|
assert_eq!(key2.status, ItemStatus::MissingFromActive);
|
||||||
|
assert_eq!(key2.value, None);
|
||||||
|
assert_eq!(key2.template_value.as_deref(), Some("default_val"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +1,68 @@
|
|||||||
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType};
|
//! Provides a generalized handler for hierarchical configuration formats
|
||||||
|
//! (JSON, YAML, TOML, XML).
|
||||||
|
//!
|
||||||
|
//! This handler works by using `serde_json::Value` as an intermediary
|
||||||
|
//! representation. It "flattens" nested structures into a list of
|
||||||
|
//! `ConfigItem`s for the TUI, and "unflattens" them back into their
|
||||||
|
//! nested form when saving.
|
||||||
|
|
||||||
|
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType, PathSegment};
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// A format handler capable of processing nested configuration structures.
|
||||||
pub struct HierarchicalHandler {
|
pub struct HierarchicalHandler {
|
||||||
|
/// The specific file format this instance is configured to handle.
|
||||||
format_type: FormatType,
|
format_type: FormatType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HierarchicalHandler {
|
impl HierarchicalHandler {
|
||||||
|
/// Creates a new hierarchical handler for the specified format.
|
||||||
pub fn new(format_type: FormatType) -> Self {
|
pub fn new(format_type: FormatType) -> Self {
|
||||||
Self { format_type }
|
Self { format_type }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_value(&self, path: &Path) -> io::Result<Value> {
|
/// Reads a file and parses it into an intermediary `serde_json::Value`.
|
||||||
|
fn read_value(&self, path: &Path) -> anyhow::Result<Value> {
|
||||||
let content = fs::read_to_string(path)?;
|
let content = fs::read_to_string(path)?;
|
||||||
let value = match self.format_type {
|
let value = match self.format_type {
|
||||||
FormatType::Json => serde_json::from_str(&content)
|
FormatType::Json => serde_json::from_str(&content)?,
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
FormatType::Yaml => serde_yaml::from_str(&content)?,
|
||||||
FormatType::Yaml => serde_yaml::from_str(&content)
|
FormatType::Toml => toml::from_str(&content)?,
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
FormatType::Xml => xml_to_json(&content)?,
|
||||||
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!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_value(&self, path: &Path, value: &Value) -> io::Result<()> {
|
/// Serializes a `serde_json::Value` and writes it to the specified path.
|
||||||
|
fn write_value(&self, path: &Path, value: &Value) -> anyhow::Result<()> {
|
||||||
let content = match self.format_type {
|
let content = match self.format_type {
|
||||||
FormatType::Json => serde_json::to_string_pretty(value)
|
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)?,
|
||||||
FormatType::Yaml => serde_yaml::to_string(value)
|
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
|
||||||
FormatType::Toml => {
|
FormatType::Toml => {
|
||||||
// toml requires the root to be a table
|
// TOML requires the root to be a table (Object).
|
||||||
if value.is_object() {
|
if value.is_object() {
|
||||||
let toml_value: toml::Value = serde_json::from_value(value.clone())
|
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)?
|
||||||
toml::to_string_pretty(&toml_value)
|
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
|
|
||||||
} else {
|
} else {
|
||||||
return Err(io::Error::new(
|
anyhow::bail!("Root of TOML must be an object");
|
||||||
io::ErrorKind::InvalidData,
|
|
||||||
"Root of TOML must be an object",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FormatType::Xml => json_to_xml(value),
|
FormatType::Xml => json_to_xml(value),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
fs::write(path, content)
|
fs::write(path, content)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn xml_to_json(content: &str) -> io::Result<Value> {
|
/// Converts an XML string into an intermediary `serde_json::Value`.
|
||||||
|
///
|
||||||
|
/// This implementation handles basic element nesting and text content.
|
||||||
|
/// Attributes are currently not supported.
|
||||||
|
fn xml_to_json(content: &str) -> anyhow::Result<Value> {
|
||||||
use quick_xml::reader::Reader;
|
use quick_xml::reader::Reader;
|
||||||
use quick_xml::events::Event;
|
use quick_xml::events::Event;
|
||||||
|
|
||||||
@@ -64,7 +70,8 @@ fn xml_to_json(content: &str) -> io::Result<Value> {
|
|||||||
reader.config_mut().trim_text(true);
|
reader.config_mut().trim_text(true);
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
|
|
||||||
fn parse_recursive(reader: &mut Reader<&[u8]>) -> io::Result<Value> {
|
/// Recursively parses XML elements into a nested Map structure.
|
||||||
|
fn parse_recursive(reader: &mut Reader<&[u8]>) -> anyhow::Result<Value> {
|
||||||
let mut map = Map::new();
|
let mut map = Map::new();
|
||||||
let mut text = String::new();
|
let mut text = String::new();
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
@@ -75,6 +82,7 @@ fn xml_to_json(content: &str) -> io::Result<Value> {
|
|||||||
let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
|
let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
|
||||||
let val = parse_recursive(reader)?;
|
let val = parse_recursive(reader)?;
|
||||||
|
|
||||||
|
// If multiple elements have the same name, they are collected into an Array.
|
||||||
if let Some(existing) = map.get_mut(&name) {
|
if let Some(existing) = map.get_mut(&name) {
|
||||||
if let Some(arr) = existing.as_array_mut() {
|
if let Some(arr) = existing.as_array_mut() {
|
||||||
arr.push(val);
|
arr.push(val);
|
||||||
@@ -104,6 +112,7 @@ fn xml_to_json(content: &str) -> io::Result<Value> {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if !text.is_empty() {
|
if !text.is_empty() {
|
||||||
|
// Special key used to store raw text content of an element that also has children.
|
||||||
map.insert("$text".to_string(), Value::String(text));
|
map.insert("$text".to_string(), Value::String(text));
|
||||||
}
|
}
|
||||||
Ok(Value::Object(map))
|
Ok(Value::Object(map))
|
||||||
@@ -129,61 +138,133 @@ fn xml_to_json(content: &str) -> io::Result<Value> {
|
|||||||
Ok(Value::Object(Map::new()))
|
Ok(Value::Object(Map::new()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts a nested `serde_json::Value` back into an XML string.
|
||||||
fn json_to_xml(value: &Value) -> String {
|
fn json_to_xml(value: &Value) -> String {
|
||||||
|
use quick_xml::Writer;
|
||||||
|
use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText};
|
||||||
|
|
||||||
|
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
|
||||||
|
|
||||||
|
/// Recursively writes JSON values as XML elements.
|
||||||
|
fn write_recursive(writer: &mut Writer<Vec<u8>>, value: &Value, key_name: Option<&str>) {
|
||||||
|
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 {
|
match value {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
let mut s = String::new();
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
for (k, v) in map {
|
for (k, v) in map {
|
||||||
if k == "$text" {
|
if let Some(arr) = v.as_array() {
|
||||||
s.push_str(&v.as_str().unwrap_or(""));
|
|
||||||
} else if let Some(arr) = v.as_array() {
|
|
||||||
for item in arr {
|
for item in arr {
|
||||||
s.push_str(&format!("<{}>", k));
|
write_recursive(writer, item, Some(k));
|
||||||
s.push_str(&json_to_xml(item));
|
|
||||||
s.push_str(&format!("</{}>", k));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
s.push_str(&format!("<{}>", k));
|
write_recursive(writer, v, Some(k));
|
||||||
s.push_str(&json_to_xml(v));
|
|
||||||
s.push_str(&format!("</{}>", k));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Value::Array(arr) => {
|
Value::Array(arr) => {
|
||||||
let mut s = String::new();
|
|
||||||
for v in arr {
|
for v in arr {
|
||||||
s.push_str(&json_to_xml(v));
|
write_recursive(writer, v, key_name);
|
||||||
}
|
}
|
||||||
s
|
|
||||||
}
|
}
|
||||||
Value::String(v) => v.clone(),
|
Value::String(s) => {
|
||||||
Value::Number(v) => v.to_string(),
|
if let Some(k) = key_name {
|
||||||
Value::Bool(v) => v.to_string(),
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
Value::Null => "".to_string(),
|
|
||||||
}
|
}
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut out = String::from_utf8(writer.into_inner()).unwrap();
|
||||||
|
if !out.ends_with('\n') {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove unused get_xml_root_name
|
/// Recursively flattens a nested `serde_json::Value` into a list of `ConfigItem`s.
|
||||||
// fn get_xml_root_name(content: &str) -> Option<String> { ... }
|
///
|
||||||
|
/// This function translates the structural hierarchy of the JSON into
|
||||||
|
/// linear entries with associated paths and depth levels for UI rendering.
|
||||||
|
fn flatten(value: &Value, current_path: Vec<PathSegment>, key_name: Option<String>, depth: usize, vars: &mut Vec<ConfigItem>) {
|
||||||
|
let mut next_path = current_path.clone();
|
||||||
|
|
||||||
fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) {
|
if let Some(ref k) = key_name {
|
||||||
let path = if prefix.is_empty() {
|
if !current_path.is_empty() {
|
||||||
key_name.to_string()
|
// It's a key in an object, so append to path
|
||||||
} else if key_name.is_empty() {
|
next_path.push(PathSegment::Key(k.clone()));
|
||||||
prefix.to_string()
|
|
||||||
} else if key_name.starts_with('[') {
|
|
||||||
format!("{}{}", prefix, key_name)
|
|
||||||
} else {
|
} else {
|
||||||
format!("{}.{}", prefix, key_name)
|
// First element, maybe root
|
||||||
|
if !k.is_empty() {
|
||||||
|
next_path.push(PathSegment::Key(k.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let display_key = match next_path.last() {
|
||||||
|
Some(PathSegment::Key(k)) => k.clone(),
|
||||||
|
Some(PathSegment::Index(i)) => format!("[{}]", i),
|
||||||
|
None => "".to_string(),
|
||||||
};
|
};
|
||||||
|
|
||||||
match value {
|
match value {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
if !path.is_empty() {
|
if !next_path.is_empty() {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: None,
|
value: None,
|
||||||
template_value: None,
|
template_value: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
@@ -193,16 +274,16 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
value_type: ValueType::Null,
|
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 {
|
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) => {
|
Value::Array(arr) => {
|
||||||
if !path.is_empty() {
|
if !next_path.is_empty() {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: None,
|
value: None,
|
||||||
template_value: None,
|
template_value: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
@@ -212,16 +293,17 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
value_type: ValueType::Null,
|
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() {
|
for (i, v) in arr.iter().enumerate() {
|
||||||
let array_key = format!("[{}]", i);
|
let mut arr_path = next_path.clone();
|
||||||
flatten(v, &path, next_depth, &array_key, vars);
|
arr_path.push(PathSegment::Index(i));
|
||||||
|
flatten(v, arr_path, None, next_depth, vars);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Value::String(s) => {
|
Value::String(s) => {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: Some(s.clone()),
|
value: Some(s.clone()),
|
||||||
template_value: Some(s.clone()),
|
template_value: Some(s.clone()),
|
||||||
default_value: Some(s.clone()),
|
default_value: Some(s.clone()),
|
||||||
@@ -234,8 +316,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
Value::Number(n) => {
|
Value::Number(n) => {
|
||||||
let s = n.to_string();
|
let s = n.to_string();
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: Some(s.clone()),
|
value: Some(s.clone()),
|
||||||
template_value: Some(s.clone()),
|
template_value: Some(s.clone()),
|
||||||
default_value: Some(s.clone()),
|
default_value: Some(s.clone()),
|
||||||
@@ -248,8 +330,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
Value::Bool(b) => {
|
Value::Bool(b) => {
|
||||||
let s = b.to_string();
|
let s = b.to_string();
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: Some(s.clone()),
|
value: Some(s.clone()),
|
||||||
template_value: Some(s.clone()),
|
template_value: Some(s.clone()),
|
||||||
default_value: Some(s.clone()),
|
default_value: Some(s.clone()),
|
||||||
@@ -261,8 +343,8 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
}
|
}
|
||||||
Value::Null => {
|
Value::Null => {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: key_name.to_string(),
|
key: display_key,
|
||||||
path: path.clone(),
|
path: next_path.clone(),
|
||||||
value: Some("".to_string()),
|
value: Some("".to_string()),
|
||||||
template_value: Some("".to_string()),
|
template_value: Some("".to_string()),
|
||||||
default_value: Some("".to_string()),
|
default_value: Some("".to_string()),
|
||||||
@@ -276,51 +358,14 @@ fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FormatHandler for HierarchicalHandler {
|
impl FormatHandler for HierarchicalHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
let value = self.read_value(path)?;
|
let value = self.read_value(path)?;
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
flatten(&value, "", 0, "", &mut vars);
|
flatten(&value, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::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());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
if !var.is_group {
|
if !var.is_group {
|
||||||
@@ -334,50 +379,56 @@ impl FormatHandler for HierarchicalHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type: ValueType) {
|
/// Reconstructs a nested `serde_json::Value` from a hierarchical path and a leaf value.
|
||||||
let mut parts = path.split('.');
|
///
|
||||||
let last_part = match parts.next_back() {
|
/// This is the core "unflattening" logic used when saving modified configuration.
|
||||||
Some(p) => p,
|
fn insert_into_value(root: &mut Value, path: &[PathSegment], new_val_str: &str, value_type: ValueType) {
|
||||||
None => return,
|
if path.is_empty() {
|
||||||
};
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let mut current = root;
|
let mut current = root;
|
||||||
for part in parts {
|
|
||||||
let (key, idx) = parse_array_key(part);
|
// Traverse all but the last segment to build the intermediate structure.
|
||||||
|
for i in 0..path.len() - 1 {
|
||||||
|
let segment = &path[i];
|
||||||
|
let next_segment = &path[i + 1];
|
||||||
|
|
||||||
|
match segment {
|
||||||
|
PathSegment::Key(key) => {
|
||||||
if !current.is_object() {
|
if !current.is_object() {
|
||||||
*current = Value::Object(Map::new());
|
*current = Value::Object(Map::new());
|
||||||
}
|
}
|
||||||
let map = current.as_object_mut().unwrap();
|
let map = current.as_object_mut().unwrap();
|
||||||
|
|
||||||
let next_node = map.entry(key.to_string()).or_insert_with(|| {
|
let next_node = map.entry(key.clone()).or_insert_with(|| {
|
||||||
if idx.is_some() {
|
match next_segment {
|
||||||
Value::Array(Vec::new())
|
PathSegment::Index(_) => Value::Array(Vec::new()),
|
||||||
} else {
|
PathSegment::Key(_) => Value::Object(Map::new()),
|
||||||
Value::Object(Map::new())
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if let Some(i) = idx {
|
|
||||||
if !next_node.is_array() {
|
|
||||||
*next_node = Value::Array(Vec::new());
|
|
||||||
}
|
|
||||||
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;
|
current = next_node;
|
||||||
}
|
}
|
||||||
|
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 (final_key, final_idx) = parse_array_key(last_part);
|
// Insert the actual leaf value at the end of the path.
|
||||||
if !current.is_object() {
|
let final_segment = &path[path.len() - 1];
|
||||||
*current = Value::Object(Map::new());
|
|
||||||
}
|
|
||||||
let map = current.as_object_mut().unwrap();
|
|
||||||
|
|
||||||
// Use the preserved ValueType instead of aggressive inference
|
// Attempt to preserve the original data type during insertion.
|
||||||
let final_val = match value_type {
|
let final_val = match value_type {
|
||||||
ValueType::Number => {
|
ValueType::Number => {
|
||||||
if let Ok(n) = new_val_str.parse::<i64>() {
|
if let Ok(n) = new_val_str.parse::<i64>() {
|
||||||
@@ -403,31 +454,24 @@ fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type
|
|||||||
_ => Value::String(new_val_str.to_string()),
|
_ => Value::String(new_val_str.to_string()),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(i) = final_idx {
|
match final_segment {
|
||||||
let next_node = map
|
PathSegment::Key(key) => {
|
||||||
.entry(final_key.to_string())
|
if !current.is_object() {
|
||||||
.or_insert_with(|| Value::Array(Vec::new()));
|
*current = Value::Object(Map::new());
|
||||||
if !next_node.is_array() {
|
|
||||||
*next_node = Value::Array(Vec::new());
|
|
||||||
}
|
}
|
||||||
let arr = next_node.as_array_mut().unwrap();
|
let map = current.as_object_mut().unwrap();
|
||||||
while arr.len() <= i {
|
map.insert(key.clone(), final_val);
|
||||||
|
}
|
||||||
|
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.push(Value::Null);
|
||||||
}
|
}
|
||||||
arr[i] = final_val;
|
arr[*idx] = final_val;
|
||||||
} else {
|
|
||||||
map.insert(final_key.to_string(), final_val);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_array_key(part: &str) -> (&str, Option<usize>) {
|
|
||||||
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::<usize>().ok();
|
|
||||||
(key, idx)
|
|
||||||
} else {
|
|
||||||
(part, None)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,7 +493,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
flatten(&json, "", 0, "", &mut vars);
|
flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
assert_eq!(vars.len(), 6);
|
assert_eq!(vars.len(), 6);
|
||||||
|
|
||||||
let mut root = Value::Object(Map::new());
|
let mut root = Value::Object(Map::new());
|
||||||
@@ -459,7 +503,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// When unflattening, it parses bool back
|
|
||||||
let unflattened_json = serde_json::to_string(&root).unwrap();
|
let unflattened_json = serde_json::to_string(&root).unwrap();
|
||||||
assert!(unflattened_json.contains("\"8080:80\""));
|
assert!(unflattened_json.contains("\"8080:80\""));
|
||||||
assert!(unflattened_json.contains("true"));
|
assert!(unflattened_json.contains("true"));
|
||||||
@@ -468,17 +511,16 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_type_preservation() {
|
fn test_type_preservation() {
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
// A JSON with various tricky types
|
|
||||||
let json = serde_json::json!({
|
let json = serde_json::json!({
|
||||||
"port_num": 8080,
|
"port_num": 8080,
|
||||||
"port_str": "8080",
|
"port_str": "8080",
|
||||||
"is_enabled": true,
|
"is_enabled": true,
|
||||||
"is_enabled_str": "true",
|
"is_enabled_str": "true",
|
||||||
"float_num": 3.14,
|
"float_num": 42.42,
|
||||||
"float_str": "3.14"
|
"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());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
@@ -487,7 +529,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate that types are exactly preserved after re-assembling
|
|
||||||
let unflattened = root.as_object().unwrap();
|
let unflattened = root.as_object().unwrap();
|
||||||
|
|
||||||
assert!(unflattened["port_num"].is_number(), "port_num should be a number");
|
assert!(unflattened["port_num"].is_number(), "port_num should be a number");
|
||||||
@@ -503,10 +544,10 @@ mod tests {
|
|||||||
assert_eq!(unflattened["is_enabled_str"].as_str(), Some("true"));
|
assert_eq!(unflattened["is_enabled_str"].as_str(), Some("true"));
|
||||||
|
|
||||||
assert!(unflattened["float_num"].is_number(), "float_num should be a number");
|
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!(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]
|
#[test]
|
||||||
@@ -519,7 +560,7 @@ server:
|
|||||||
";
|
";
|
||||||
let yaml_val: Value = serde_yaml::from_str(yaml_str).unwrap();
|
let yaml_val: Value = serde_yaml::from_str(yaml_str).unwrap();
|
||||||
let mut vars = Vec::new();
|
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());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
@@ -530,7 +571,6 @@ server:
|
|||||||
|
|
||||||
let unflattened_yaml = serde_yaml::to_string(&root).unwrap();
|
let unflattened_yaml = serde_yaml::to_string(&root).unwrap();
|
||||||
assert!(unflattened_yaml.contains("port: 8080"));
|
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("port_str: '8080'") || unflattened_yaml.contains("port_str: \"8080\""));
|
||||||
assert!(unflattened_yaml.contains("enabled: true"));
|
assert!(unflattened_yaml.contains("enabled: true"));
|
||||||
}
|
}
|
||||||
@@ -543,12 +583,11 @@ port = 8080
|
|||||||
port_str = \"8080\"
|
port_str = \"8080\"
|
||||||
enabled = true
|
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 toml_val: toml::Value = toml::from_str(toml_str).unwrap();
|
||||||
let json_val: Value = serde_json::to_value(toml_val).unwrap();
|
let json_val: Value = serde_json::to_value(toml_val).unwrap();
|
||||||
|
|
||||||
let mut vars = Vec::new();
|
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());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
@@ -557,7 +596,6 @@ enabled = true
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert back to TOML
|
|
||||||
let toml_root: toml::Value = serde_json::from_value(root).unwrap();
|
let toml_root: toml::Value = serde_json::from_value(root).unwrap();
|
||||||
let unflattened_toml = toml::to_string(&toml_root).unwrap();
|
let unflattened_toml = toml::to_string(&toml_root).unwrap();
|
||||||
|
|
||||||
@@ -567,26 +605,43 @@ enabled = true
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_xml_flatten_unflatten() {
|
fn test_group_rename_write() {
|
||||||
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();
|
let mut vars = Vec::new();
|
||||||
flatten(&json_val, "", 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());
|
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(""), var.value_type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("Reconstructed root: {:?}", root);
|
let out = serde_json::to_string(&root).unwrap();
|
||||||
let unflattened_xml = json_to_xml(&root);
|
assert!(out.contains("\"new_group\""));
|
||||||
|
assert!(out.contains("\"key\":\"val\""));
|
||||||
assert!(unflattened_xml.contains("<port>8080</port>"));
|
assert!(!out.contains("\"old_group\""));
|
||||||
assert!(unflattened_xml.contains("<enabled>true</enabled>"));
|
|
||||||
assert!(unflattened_xml.contains("<config>") && unflattened_xml.contains("</config>"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType};
|
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment};
|
||||||
use ini::Ini;
|
use ini::Ini;
|
||||||
use std::io;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
pub struct IniHandler;
|
pub struct IniHandler;
|
||||||
|
|
||||||
impl FormatHandler for IniHandler {
|
impl FormatHandler for IniHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
let conf = Ini::load_from_file(path)
|
let conf = Ini::load_from_file(path)?;
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
|
|
||||||
for (section, prop) in &conf {
|
for (section, prop) in &conf {
|
||||||
@@ -17,7 +15,7 @@ impl FormatHandler for IniHandler {
|
|||||||
if !section_name.is_empty() {
|
if !section_name.is_empty() {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: section_name.to_string(),
|
key: section_name.to_string(),
|
||||||
path: section_name.to_string(),
|
path: vec![PathSegment::Key(section_name.to_string())],
|
||||||
value: None,
|
value: None,
|
||||||
template_value: None,
|
template_value: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
@@ -30,9 +28,9 @@ impl FormatHandler for IniHandler {
|
|||||||
|
|
||||||
for (key, value) in prop {
|
for (key, value) in prop {
|
||||||
let path = if section_name.is_empty() {
|
let path = if section_name.is_empty() {
|
||||||
key.to_string()
|
vec![PathSegment::Key(key.to_string())]
|
||||||
} else {
|
} else {
|
||||||
format!("{}.{}", section_name, key)
|
vec![PathSegment::Key(section_name.to_string()), PathSegment::Key(key.to_string())]
|
||||||
};
|
};
|
||||||
|
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
@@ -52,39 +50,7 @@ impl FormatHandler for IniHandler {
|
|||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::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();
|
let mut conf = Ini::new();
|
||||||
for var in vars {
|
for var in vars {
|
||||||
if !var.is_group {
|
if !var.is_group {
|
||||||
@@ -92,15 +58,18 @@ impl FormatHandler for IniHandler {
|
|||||||
.or(var.template_value.as_deref())
|
.or(var.template_value.as_deref())
|
||||||
.unwrap_or("");
|
.unwrap_or("");
|
||||||
|
|
||||||
if let Some((section, key)) = var.path.split_once('.') {
|
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);
|
conf.with_section(Some(section)).set(key, val);
|
||||||
} else {
|
}
|
||||||
conf.with_section(None::<String>).set(&var.path, val);
|
} else if var.path.len() == 1
|
||||||
|
&& let PathSegment::Key(key) = &var.path[0] {
|
||||||
|
conf.with_section(None::<String>).set(key, val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
conf.write_to_file(path)
|
conf.write_to_file(path)?;
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,15 +80,46 @@ mod tests {
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_ini() {
|
fn test_section_rename_write() {
|
||||||
let mut file = NamedTempFile::new().unwrap();
|
|
||||||
writeln!(file, "[server]\nport=8080\n[database]\nhost=localhost").unwrap();
|
|
||||||
|
|
||||||
let handler = IniHandler;
|
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,
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
assert!(vars.iter().any(|v| v.path == "server" && v.is_group));
|
// Rename "server" to "srv"
|
||||||
assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080")));
|
vars[0].key = "srv".to_string();
|
||||||
assert!(vars.iter().any(|v| v.path == "database.host" && v.value.as_deref() == Some("localhost")));
|
vars[0].path = vec![PathSegment::Key("srv".to_string())];
|
||||||
|
|
||||||
|
// 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]"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
use std::io;
|
//! This module defines the unified data model used by `mould` to represent
|
||||||
|
//! configuration data across all supported file formats.
|
||||||
|
//!
|
||||||
|
//! By normalizing heterogeneous structures (like nested YAML or flat .env)
|
||||||
|
//! into a standard tree-like representation, the TUI logic remains
|
||||||
|
//! independent of the underlying file format.
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
pub mod env;
|
pub mod env;
|
||||||
@@ -6,35 +12,100 @@ pub mod hierarchical;
|
|||||||
pub mod ini;
|
pub mod ini;
|
||||||
pub mod properties;
|
pub mod properties;
|
||||||
|
|
||||||
|
/// Represents the status of a configuration item relative to a template.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum ItemStatus {
|
pub enum ItemStatus {
|
||||||
|
/// Item exists in the active configuration and matches the template (or no template exists).
|
||||||
Present,
|
Present,
|
||||||
|
/// Item exists in the template but is missing from the active configuration.
|
||||||
MissingFromActive,
|
MissingFromActive,
|
||||||
MissingFromTemplate,
|
/// Item has been changed by the user during the current session.
|
||||||
Modified,
|
Modified,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hints about the original data type to ensure correct serialization during writes.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ValueType {
|
pub enum ValueType {
|
||||||
|
/// Standard text.
|
||||||
String,
|
String,
|
||||||
|
/// Numeric values (integers or floats).
|
||||||
Number,
|
Number,
|
||||||
|
/// True/False values.
|
||||||
Bool,
|
Bool,
|
||||||
|
/// Representing an explicit null or empty value.
|
||||||
Null,
|
Null,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A single segment in a hierarchical configuration path.
|
||||||
|
///
|
||||||
|
/// For example, `services[0].image` would be represented as:
|
||||||
|
/// `[Key("services"), Index(0), Key("image")]`
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub enum PathSegment {
|
||||||
|
/// A named key in an object/map.
|
||||||
|
Key(String),
|
||||||
|
/// A numeric index in an array/list.
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unified representation of a single configuration entry.
|
||||||
|
///
|
||||||
|
/// This model is used for UI rendering and internal manipulation.
|
||||||
|
/// Format-specific handlers are responsible for translating their native
|
||||||
|
/// data into this structure.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ConfigItem {
|
pub struct ConfigItem {
|
||||||
|
/// The short display name of the key (e.g., `port`).
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub path: String,
|
/// The full hierarchical path defining this item's location in the config tree.
|
||||||
|
pub path: Vec<PathSegment>,
|
||||||
|
/// The active value of the configuration entry.
|
||||||
pub value: Option<String>,
|
pub value: Option<String>,
|
||||||
|
/// The value found in the template file (if any).
|
||||||
pub template_value: Option<String>,
|
pub template_value: Option<String>,
|
||||||
|
/// A fallback value to use if the item is missing.
|
||||||
pub default_value: Option<String>,
|
pub default_value: Option<String>,
|
||||||
|
/// Visual depth in the tree (used for indentation in the TUI).
|
||||||
pub depth: usize,
|
pub depth: usize,
|
||||||
|
/// True if this item represents a structural node (object or array) rather than a leaf value.
|
||||||
pub is_group: bool,
|
pub is_group: bool,
|
||||||
|
/// Comparison status relative to the template.
|
||||||
pub status: ItemStatus,
|
pub status: ItemStatus,
|
||||||
|
/// Metadata about the original data type.
|
||||||
pub value_type: ValueType,
|
pub value_type: ValueType,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ConfigItem {
|
||||||
|
/// Returns a human-readable string representation of the full path (e.g., `server.port`).
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Supported configuration file formats.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum FormatType {
|
pub enum FormatType {
|
||||||
Env,
|
Env,
|
||||||
@@ -46,12 +117,57 @@ pub enum FormatType {
|
|||||||
Properties,
|
Properties,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Defines the interface for parsing, merging, and writing configuration files.
|
||||||
|
///
|
||||||
|
/// Implementing this trait allows `mould` to support new file formats.
|
||||||
pub trait FormatHandler {
|
pub trait FormatHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>>;
|
/// Parses a file into the unified `Vec<ConfigItem>` representation.
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()>;
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>>;
|
||||||
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>;
|
|
||||||
|
/// Merges an active configuration with a template file.
|
||||||
|
///
|
||||||
|
/// This identifies missing keys, marks modifications, and syncs default values.
|
||||||
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> anyhow::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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the unified representation back to the original file format.
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Automatically detects the configuration format based on file extension or an explicit override.
|
||||||
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
||||||
if let Some(fmt) = override_format {
|
if let Some(fmt) = override_format {
|
||||||
match fmt.to_lowercase().as_str() {
|
match fmt.to_lowercase().as_str() {
|
||||||
@@ -66,24 +182,19 @@ pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
|
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or_default();
|
||||||
if file_name.ends_with(".json") {
|
match ext {
|
||||||
FormatType::Json
|
"json" => FormatType::Json,
|
||||||
} else if file_name.ends_with(".yaml") || file_name.ends_with(".yml") {
|
"yaml" | "yml" => FormatType::Yaml,
|
||||||
FormatType::Yaml
|
"toml" => FormatType::Toml,
|
||||||
} else if file_name.ends_with(".toml") {
|
"xml" => FormatType::Xml,
|
||||||
FormatType::Toml
|
"ini" => FormatType::Ini,
|
||||||
} else if file_name.ends_with(".xml") {
|
"properties" => FormatType::Properties,
|
||||||
FormatType::Xml
|
_ => FormatType::Env,
|
||||||
} else if file_name.ends_with(".ini") {
|
|
||||||
FormatType::Ini
|
|
||||||
} else if file_name.ends_with(".properties") {
|
|
||||||
FormatType::Properties
|
|
||||||
} else {
|
|
||||||
FormatType::Env
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Factory function to return the appropriate handler implementation for a given format.
|
||||||
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
||||||
match format {
|
match format {
|
||||||
FormatType::Env => Box::new(env::EnvHandler),
|
FormatType::Env => Box::new(env::EnvHandler),
|
||||||
|
|||||||
@@ -1,36 +1,34 @@
|
|||||||
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType};
|
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment};
|
||||||
use java_properties::{read, write};
|
use java_properties::{LineContent, PropertiesIter, PropertiesWriter};
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{self, BufReader};
|
use std::io::{BufReader, BufWriter};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
pub struct PropertiesHandler;
|
pub struct PropertiesHandler;
|
||||||
|
|
||||||
impl FormatHandler for PropertiesHandler {
|
impl FormatHandler for PropertiesHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
let file = File::open(path)?;
|
let file = File::open(path)?;
|
||||||
let reader = BufReader::new(file);
|
let reader = BufReader::new(file);
|
||||||
let props = read(reader)
|
let iter = PropertiesIter::new(reader);
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
|
||||||
|
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
let mut groups = std::collections::HashSet::new();
|
let mut groups = std::collections::HashSet::new();
|
||||||
|
|
||||||
for (path, value) in &props {
|
for line_result in iter {
|
||||||
|
let line = line_result?;
|
||||||
|
|
||||||
|
if let LineContent::KVPair(path, value) = line.consume_content() {
|
||||||
// Add groups based on dot notation
|
// Add groups based on dot notation
|
||||||
let parts: Vec<&str> = path.split('.').collect();
|
let parts: Vec<&str> = path.split('.').collect();
|
||||||
let mut current_path = String::new();
|
let mut current_path = Vec::new();
|
||||||
|
|
||||||
for i in 0..parts.len() - 1 {
|
for (i, part) in parts.iter().enumerate().take(parts.len().saturating_sub(1)) {
|
||||||
if !current_path.is_empty() {
|
current_path.push(PathSegment::Key(part.to_string()));
|
||||||
current_path.push('.');
|
|
||||||
}
|
|
||||||
current_path.push_str(parts[i]);
|
|
||||||
|
|
||||||
if groups.insert(current_path.clone()) {
|
if groups.insert(current_path.clone()) {
|
||||||
vars.push(ConfigItem {
|
vars.push(ConfigItem {
|
||||||
key: parts[i].to_string(),
|
key: part.to_string(),
|
||||||
path: current_path.clone(),
|
path: current_path.clone(),
|
||||||
value: None,
|
value: None,
|
||||||
template_value: None,
|
template_value: None,
|
||||||
@@ -43,69 +41,44 @@ 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 {
|
vars.push(ConfigItem {
|
||||||
key: parts.last().unwrap().to_string(),
|
key: last_key,
|
||||||
path: path.clone(),
|
path: final_path,
|
||||||
value: Some(value.clone()),
|
value: Some(value.clone()),
|
||||||
template_value: Some(value.clone()),
|
template_value: Some(value.clone()),
|
||||||
default_value: Some(value.clone()),
|
default_value: Some(value.clone()),
|
||||||
depth: parts.len() - 1,
|
depth: parts.len().saturating_sub(1),
|
||||||
is_group: false,
|
is_group: false,
|
||||||
status: ItemStatus::Present,
|
status: ItemStatus::Present,
|
||||||
value_type: ValueType::String,
|
value_type: ValueType::String,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// Sort by path to keep it organized
|
|
||||||
vars.sort_by(|a, b| a.path.cmp(&b.path));
|
|
||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
if !path.exists() {
|
let file = File::create(path)?;
|
||||||
return Ok(());
|
let writer = BufWriter::new(file);
|
||||||
}
|
let mut prop_writer = PropertiesWriter::new(writer);
|
||||||
|
|
||||||
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 {
|
for var in vars {
|
||||||
if !var.is_group {
|
if !var.is_group {
|
||||||
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("");
|
||||||
props.insert(var.path.clone(), val.to_string());
|
prop_writer.write(&var.path_string(), val)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let file = File::create(path)?;
|
prop_writer.finish()?;
|
||||||
write(file, &props).map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,14 +89,45 @@ mod tests {
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_properties() {
|
fn test_group_rename_write() {
|
||||||
let mut file = NamedTempFile::new().unwrap();
|
|
||||||
writeln!(file, "server.port=8080\ndatabase.host=localhost").unwrap();
|
|
||||||
|
|
||||||
let handler = PropertiesHandler;
|
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,
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
assert!(vars.iter().any(|v| v.path == "server" && v.is_group));
|
// Rename "server" to "srv"
|
||||||
assert!(vars.iter().any(|v| v.path == "server.port" && v.value.as_deref() == Some("8080")));
|
vars[0].key = "srv".to_string();
|
||||||
|
vars[0].path = vec![PathSegment::Key("srv".to_string())];
|
||||||
|
|
||||||
|
// 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"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ mod format;
|
|||||||
mod runner;
|
mod runner;
|
||||||
mod ui;
|
mod ui;
|
||||||
mod resolver;
|
mod resolver;
|
||||||
|
mod undo;
|
||||||
|
|
||||||
use app::App;
|
use app::App;
|
||||||
use config::load_config;
|
use config::load_config;
|
||||||
@@ -96,10 +97,7 @@ fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
} else if vars.is_empty() {
|
} else if vars.is_empty() {
|
||||||
// Fallback if no template and active is empty
|
// Fallback if no template and active is empty
|
||||||
vars = handler.parse(&input_path).map_err(|e| {
|
vars = handler.parse(&input_path)?;
|
||||||
error!("Failed to parse input file: {}", e);
|
|
||||||
MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e))
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if vars.is_empty() {
|
if vars.is_empty() {
|
||||||
|
|||||||
151
src/resolver.rs
151
src/resolver.rs
@@ -1,3 +1,9 @@
|
|||||||
|
//! Automatically resolves relationships between template and active configuration files.
|
||||||
|
//!
|
||||||
|
//! The resolver allows `mould` to be run without explicit output arguments
|
||||||
|
//! by intelligently guessing the counterpart of a given input file based
|
||||||
|
//! on common naming conventions.
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
pub struct Rule {
|
pub struct Rule {
|
||||||
@@ -8,28 +14,107 @@ pub struct Rule {
|
|||||||
|
|
||||||
pub const RULES: &[Rule] = &[
|
pub const RULES: &[Rule] = &[
|
||||||
// Exact matches
|
// Exact matches
|
||||||
Rule { template_suffix: "compose.yml", active_suffix: "compose.override.yml", is_exact_match: true },
|
Rule {
|
||||||
Rule { template_suffix: "compose.yaml", active_suffix: "compose.override.yaml", is_exact_match: true },
|
template_suffix: "compose.yml",
|
||||||
Rule { template_suffix: "docker-compose.yml", active_suffix: "docker-compose.override.yml", is_exact_match: true },
|
active_suffix: "compose.override.yml",
|
||||||
Rule { template_suffix: "docker-compose.yaml", active_suffix: "docker-compose.override.yaml", is_exact_match: true },
|
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
|
// Pattern matches
|
||||||
Rule { template_suffix: ".env.example", active_suffix: ".env", is_exact_match: false },
|
Rule {
|
||||||
Rule { template_suffix: ".env.template", active_suffix: ".env", is_exact_match: false },
|
template_suffix: ".env.example",
|
||||||
Rule { template_suffix: ".example.json", active_suffix: ".json", is_exact_match: false },
|
active_suffix: ".env",
|
||||||
Rule { template_suffix: ".template.json", active_suffix: ".json", is_exact_match: false },
|
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 {
|
||||||
Rule { template_suffix: ".example.yaml", active_suffix: ".yaml", is_exact_match: false },
|
template_suffix: ".env.template",
|
||||||
Rule { template_suffix: ".template.yaml", active_suffix: ".yaml", is_exact_match: false },
|
active_suffix: ".env",
|
||||||
Rule { template_suffix: ".example.toml", active_suffix: ".toml", is_exact_match: false },
|
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 {
|
||||||
Rule { template_suffix: ".template.xml", active_suffix: ".xml", is_exact_match: false },
|
template_suffix: ".example.json",
|
||||||
Rule { template_suffix: ".example.ini", active_suffix: ".ini", is_exact_match: false },
|
active_suffix: ".json",
|
||||||
Rule { template_suffix: ".template.ini", active_suffix: ".ini", is_exact_match: false },
|
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 },
|
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] = &[
|
pub const DEFAULT_CANDIDATES: &[&str] = &[
|
||||||
@@ -50,14 +135,12 @@ pub fn determine_output_path(input: &Path) -> PathBuf {
|
|||||||
if file_name == rule.template_suffix {
|
if file_name == rule.template_suffix {
|
||||||
return input.with_file_name(rule.active_suffix);
|
return input.with_file_name(rule.active_suffix);
|
||||||
}
|
}
|
||||||
} else {
|
} else if file_name == rule.template_suffix {
|
||||||
if file_name == rule.template_suffix {
|
|
||||||
return input.with_file_name(rule.active_suffix);
|
return input.with_file_name(rule.active_suffix);
|
||||||
} else if let Some(base) = file_name.strip_suffix(rule.template_suffix) {
|
} else if let Some(base) = file_name.strip_suffix(rule.template_suffix) {
|
||||||
return input.with_file_name(format!("{}{}", base, rule.active_suffix));
|
return input.with_file_name(format!("{}{}", base, rule.active_suffix));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
input.with_extension(format!(
|
input.with_extension(format!(
|
||||||
"{}.out",
|
"{}.out",
|
||||||
@@ -191,9 +274,21 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_determine_output_path() {
|
fn test_determine_output_path() {
|
||||||
assert_eq!(determine_output_path(Path::new(".env.example")), PathBuf::from(".env"));
|
assert_eq!(
|
||||||
assert_eq!(determine_output_path(Path::new("compose.yml")), PathBuf::from("compose.override.yml"));
|
determine_output_path(Path::new(".env.example")),
|
||||||
assert_eq!(determine_output_path(Path::new("config.template.json")), PathBuf::from("config.json"));
|
PathBuf::from(".env")
|
||||||
assert_eq!(determine_output_path(Path::new("config.example")), PathBuf::from("config.example.out"));
|
);
|
||||||
|
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")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
197
src/runner.rs
197
src/runner.rs
@@ -1,3 +1,8 @@
|
|||||||
|
//! Orchestrates the main application execution, terminal events, and TUI rendering.
|
||||||
|
//!
|
||||||
|
//! The `AppRunner` is responsible for the event loop, intercepting raw
|
||||||
|
//! keyboard input, and translating it into high-level application actions.
|
||||||
|
|
||||||
use crate::app::{App, InsertVariant, Mode};
|
use crate::app::{App, InsertVariant, Mode};
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::format::FormatHandler;
|
use crate::format::FormatHandler;
|
||||||
@@ -14,7 +19,7 @@ pub struct AppRunner<'a, B: Backend> {
|
|||||||
terminal: &'a mut Terminal<B>,
|
terminal: &'a mut Terminal<B>,
|
||||||
/// Mutable reference to the application state.
|
/// Mutable reference to the application state.
|
||||||
app: &'a mut App,
|
app: &'a mut App,
|
||||||
/// Loaded user configuration.
|
/// Loaded user configuration (keybinds, theme).
|
||||||
config: &'a Config,
|
config: &'a Config,
|
||||||
/// Path where the final configuration will be saved.
|
/// Path where the final configuration will be saved.
|
||||||
output_path: &'a Path,
|
output_path: &'a Path,
|
||||||
@@ -22,7 +27,7 @@ pub struct AppRunner<'a, B: Backend> {
|
|||||||
handler: &'a dyn FormatHandler,
|
handler: &'a dyn FormatHandler,
|
||||||
/// Buffer for storing active command entry (e.g., ":w").
|
/// Buffer for storing active command entry (e.g., ":w").
|
||||||
command_buffer: String,
|
command_buffer: String,
|
||||||
/// Buffer for storing sequence of key presses (e.g., "gg").
|
/// Buffer for storing multi-key sequence of presses (e.g., "gg").
|
||||||
key_sequence: String,
|
key_sequence: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +35,7 @@ impl<'a, B: Backend> AppRunner<'a, B>
|
|||||||
where
|
where
|
||||||
io::Error: From<B::Error>,
|
io::Error: From<B::Error>,
|
||||||
{
|
{
|
||||||
/// Creates a new runner instance.
|
/// Creates a new runner instance with all required dependencies.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
terminal: &'a mut Terminal<B>,
|
terminal: &'a mut Terminal<B>,
|
||||||
app: &'a mut App,
|
app: &'a mut App,
|
||||||
@@ -50,6 +55,9 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the main application loop.
|
/// Starts the main application loop.
|
||||||
|
///
|
||||||
|
/// This loop continues until `self.app.running` is set to false.
|
||||||
|
/// Each iteration draws the UI and waits for a keyboard event.
|
||||||
pub fn run(&mut self) -> io::Result<()> {
|
pub fn run(&mut self) -> io::Result<()> {
|
||||||
while self.app.running {
|
while self.app.running {
|
||||||
self.terminal
|
self.terminal
|
||||||
@@ -63,10 +71,14 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Primary dispatcher for all keyboard events.
|
/// Primary dispatcher for all keyboard events.
|
||||||
|
///
|
||||||
|
/// It delegates handling to specialized methods based on the
|
||||||
|
/// current application mode.
|
||||||
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match self.app.mode {
|
match self.app.mode {
|
||||||
Mode::Normal => self.handle_normal_mode(key),
|
Mode::Normal => self.handle_normal_mode(key),
|
||||||
Mode::Insert => self.handle_insert_mode(key),
|
Mode::Insert => self.handle_insert_mode(key),
|
||||||
|
Mode::InsertKey => self.handle_insert_key_mode(key),
|
||||||
Mode::Search => self.handle_search_mode(key),
|
Mode::Search => self.handle_search_mode(key),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,45 +119,40 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
/// Handles primary navigation and transitions to insert or command modes.
|
||||||
|
///
|
||||||
|
/// This method manages multi-key sequences (like `gg`) and immediate
|
||||||
|
/// actions (like `i`). It correctly re-evaluates sequences to prevent
|
||||||
|
/// "one-key-behind" responsiveness bugs.
|
||||||
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
if let KeyCode::Char(c) = key.code {
|
let key_str = if let KeyCode::Char(c) = key.code {
|
||||||
self.key_sequence.push(c);
|
let mut s = String::new();
|
||||||
|
if key.modifiers.contains(event::KeyModifiers::ALT) {
|
||||||
|
s.push_str("alt+");
|
||||||
|
}
|
||||||
|
s.push(c);
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
// Collect all configured keybinds
|
if !key_str.is_empty() {
|
||||||
let binds = [
|
self.key_sequence.push_str(&key_str);
|
||||||
(&self.config.keybinds.down, "down"),
|
|
||||||
(&self.config.keybinds.up, "up"),
|
|
||||||
(&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.next_match, "next_match"),
|
|
||||||
(&self.config.keybinds.previous_match, "previous_match"),
|
|
||||||
(&self.config.keybinds.jump_top, "jump_top"),
|
|
||||||
(&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"),
|
|
||||||
(&":".to_string(), "command"),
|
|
||||||
(&"q".to_string(), "quit"),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut exact_match = None;
|
let mut match_result = self.find_binding();
|
||||||
let mut prefix_match = false;
|
if match_result.is_none() {
|
||||||
|
if self.is_prefix_binding() {
|
||||||
for (bind, action) in binds.iter() {
|
// It's a prefix for a multi-key bind (like first 'g' in 'gg'), wait for more.
|
||||||
if bind == &&self.key_sequence {
|
return Ok(());
|
||||||
exact_match = Some(*action);
|
} else {
|
||||||
break;
|
// Not a match and not a prefix, restart the buffer with the current key.
|
||||||
} else if bind.starts_with(&self.key_sequence) {
|
self.key_sequence.clear();
|
||||||
prefix_match = true;
|
self.key_sequence.push_str(&key_str);
|
||||||
|
match_result = self.find_binding();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(action) = exact_match {
|
if let Some(action) = match_result {
|
||||||
self.key_sequence.clear();
|
self.key_sequence.clear();
|
||||||
match action {
|
match action {
|
||||||
"down" => self.app.next(),
|
"down" => self.app.next(),
|
||||||
@@ -162,12 +169,19 @@ 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),
|
"append_item" => self.app.add_item(true, false, false),
|
||||||
"prepend_item" => self.app.add_array_item(false),
|
"prepend_item" => self.app.add_item(false, false, false),
|
||||||
"delete_item" => self.app.delete_selected(),
|
"delete_item" => self.app.delete_selected(),
|
||||||
"undo" => self.app.undo(),
|
"undo" => self.app.undo(),
|
||||||
"add_missing" => {
|
"redo" => self.app.redo(),
|
||||||
|
"rename" => self.app.enter_insert_key(),
|
||||||
|
"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();
|
self.app.save_undo_state();
|
||||||
|
}
|
||||||
|
"add_missing" => {
|
||||||
self.add_missing_item();
|
self.add_missing_item();
|
||||||
}
|
}
|
||||||
"command" => {
|
"command" => {
|
||||||
@@ -177,13 +191,9 @@ where
|
|||||||
"quit" => self.app.running = false,
|
"quit" => self.app.running = false,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
} 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);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Non-character keys reset the sequence buffer
|
// Reset the sequence buffer if a non-character key (like Arrow Keys) is pressed.
|
||||||
self.key_sequence.clear();
|
self.key_sequence.clear();
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Down => self.app.next(),
|
KeyCode::Down => self.app.next(),
|
||||||
@@ -196,23 +206,94 @@ where
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Looks up the current `key_sequence` in the configured keybindings.
|
||||||
|
fn find_binding(&self) -> Option<&'static str> {
|
||||||
|
let binds = [
|
||||||
|
(&self.config.keybinds.down, "down"),
|
||||||
|
(&self.config.keybinds.up, "up"),
|
||||||
|
(&self.config.keybinds.edit, "edit"),
|
||||||
|
(&self.config.keybinds.edit_append, "edit_append"),
|
||||||
|
(&self.config.keybinds.edit_substitute, "edit_substitute"),
|
||||||
|
(&"S".to_string(), "edit_substitute"), // Semantic alias for Vim compatibility.
|
||||||
|
(&self.config.keybinds.search, "search"),
|
||||||
|
(&self.config.keybinds.next_match, "next_match"),
|
||||||
|
(&self.config.keybinds.previous_match, "previous_match"),
|
||||||
|
(&self.config.keybinds.jump_top, "jump_top"),
|
||||||
|
(&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"),
|
||||||
|
(&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"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (bind, action) in binds.iter() {
|
||||||
|
if bind == &&self.key_sequence {
|
||||||
|
return Some(*action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the current `key_sequence` is a partial prefix of any configured bind.
|
||||||
|
fn is_prefix_binding(&self) -> bool {
|
||||||
|
let binds = [
|
||||||
|
&self.config.keybinds.down,
|
||||||
|
&self.config.keybinds.up,
|
||||||
|
&self.config.keybinds.edit,
|
||||||
|
&self.config.keybinds.edit_append,
|
||||||
|
&self.config.keybinds.edit_substitute,
|
||||||
|
&self.config.keybinds.search,
|
||||||
|
&self.config.keybinds.next_match,
|
||||||
|
&self.config.keybinds.previous_match,
|
||||||
|
&self.config.keybinds.jump_top,
|
||||||
|
&self.config.keybinds.jump_bottom,
|
||||||
|
&self.config.keybinds.append_item,
|
||||||
|
&self.config.keybinds.prepend_item,
|
||||||
|
&self.config.keybinds.delete_item,
|
||||||
|
&self.config.keybinds.undo,
|
||||||
|
&self.config.keybinds.redo,
|
||||||
|
&self.config.keybinds.rename,
|
||||||
|
&self.config.keybinds.append_group,
|
||||||
|
&self.config.keybinds.prepend_group,
|
||||||
|
&self.config.keybinds.toggle_group,
|
||||||
|
];
|
||||||
|
|
||||||
|
for bind in binds.iter() {
|
||||||
|
if bind.starts_with(&self.key_sequence) && bind.as_str() != self.key_sequence {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
/// Adds a missing item from the template to the active configuration.
|
/// Adds a missing item from the template to the active configuration.
|
||||||
fn add_missing_item(&mut self) {
|
fn add_missing_item(&mut self) {
|
||||||
if let Some(var) = self.app.vars.get_mut(self.app.selected) {
|
if let Some(var) = self.app.vars.get_mut(self.app.selected)
|
||||||
if var.status == crate::format::ItemStatus::MissingFromActive {
|
&& var.status == crate::format::ItemStatus::MissingFromActive {
|
||||||
var.status = crate::format::ItemStatus::Present;
|
var.status = crate::format::ItemStatus::Present;
|
||||||
if !var.is_group {
|
if !var.is_group {
|
||||||
var.value = var.template_value.clone();
|
var.value = var.template_value.clone();
|
||||||
}
|
}
|
||||||
self.app.sync_input_with_selected();
|
self.app.sync_input_with_selected();
|
||||||
}
|
self.app.save_undo_state();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delegates key events to the `tui_input` handler during active editing.
|
/// Delegates key events to the `tui_input` handler during active value editing.
|
||||||
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Esc | KeyCode::Enter => {
|
KeyCode::Esc => {
|
||||||
|
self.app.cancel_insert();
|
||||||
|
}
|
||||||
|
KeyCode::Enter => {
|
||||||
self.app.enter_normal();
|
self.app.enter_normal();
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
@@ -222,7 +303,23 @@ where
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles search mode key events.
|
/// Delegates key events to the `tui_input` handler during active key renaming.
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.app.input.handle_event(&Event::Key(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles search mode key events and live-updates search filtering.
|
||||||
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Enter | KeyCode::Esc => {
|
KeyCode::Enter | KeyCode::Esc => {
|
||||||
|
|||||||
93
src/ui.rs
93
src/ui.rs
@@ -1,3 +1,8 @@
|
|||||||
|
//! Renders the hierarchical Terminal User Interface (TUI).
|
||||||
|
//!
|
||||||
|
//! This module uses `ratatui` to compose the visual layout of the application,
|
||||||
|
//! providing a navigable tree-view of configuration items.
|
||||||
|
|
||||||
use crate::app::{App, Mode};
|
use crate::app::{App, Mode};
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
@@ -9,11 +14,16 @@ use ratatui::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// Renders the main application interface using ratatui.
|
/// Renders the main application interface using ratatui.
|
||||||
|
///
|
||||||
|
/// The interface is composed of:
|
||||||
|
/// 1. A hierarchical list of configuration items.
|
||||||
|
/// 2. An active input field for editing values/keys.
|
||||||
|
/// 3. A status bar showing the current mode and available keybinds.
|
||||||
pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
||||||
let theme = &config.theme;
|
let theme = &config.theme;
|
||||||
let size = f.area();
|
let size = f.area();
|
||||||
|
|
||||||
// Render the main background (optional based on transparency config).
|
// Render the main background.
|
||||||
if !theme.transparent {
|
if !theme.transparent {
|
||||||
f.render_widget(
|
f.render_widget(
|
||||||
Block::default().style(Style::default().bg(theme.bg_normal())),
|
Block::default().style(Style::default().bg(theme.bg_normal())),
|
||||||
@@ -21,7 +31,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Horizontal layout with 1-character side margins.
|
// Define outer margins.
|
||||||
let outer_layout = Layout::default()
|
let outer_layout = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([
|
||||||
@@ -31,19 +41,19 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
])
|
])
|
||||||
.split(size);
|
.split(size);
|
||||||
|
|
||||||
// Vertical layout for the main UI components.
|
// Split the center area vertically.
|
||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Length(1), // Top margin
|
Constraint::Length(1), // Top margin
|
||||||
Constraint::Min(3), // Main list
|
Constraint::Min(3), // Main tree list
|
||||||
Constraint::Length(3), // Focused input field
|
Constraint::Length(3), // Focused input area
|
||||||
Constraint::Length(1), // Spacer
|
Constraint::Length(1), // Spacer
|
||||||
Constraint::Length(1), // Status bar
|
Constraint::Length(1), // Status bar
|
||||||
])
|
])
|
||||||
.split(outer_layout[1]);
|
.split(outer_layout[1]);
|
||||||
|
|
||||||
// Build the interactive list of configuration variables.
|
// Construct the interactive hierarchical list.
|
||||||
let matching_indices = app.matching_indices();
|
let matching_indices = app.matching_indices();
|
||||||
let items: Vec<ListItem> = app
|
let items: Vec<ListItem> = app
|
||||||
.vars
|
.vars
|
||||||
@@ -53,11 +63,11 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
let is_selected = i == app.selected;
|
let is_selected = i == app.selected;
|
||||||
let is_match = matching_indices.contains(&i);
|
let is_match = matching_indices.contains(&i);
|
||||||
|
|
||||||
// Indentation based on depth
|
// Indentation and tree-branch markers.
|
||||||
let indent = " ".repeat(var.depth);
|
let indent = " ".repeat(var.depth);
|
||||||
let prefix = if var.is_group { "+ " } else { " " };
|
let prefix = if var.is_group { "+ " } else { " " };
|
||||||
|
|
||||||
// Determine colors based on depth
|
// Determine depth-based coloring for the key name.
|
||||||
let depth_color = if is_selected {
|
let depth_color = if is_selected {
|
||||||
theme.bg_normal()
|
theme.bg_normal()
|
||||||
} else {
|
} else {
|
||||||
@@ -70,7 +80,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Determine colors based on status and selection
|
|
||||||
let text_color = if is_selected {
|
let text_color = if is_selected {
|
||||||
theme.fg_highlight()
|
theme.fg_highlight()
|
||||||
} else {
|
} else {
|
||||||
@@ -103,10 +112,9 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
Span::styled(&var.key, key_style),
|
Span::styled(&var.key, key_style),
|
||||||
];
|
];
|
||||||
|
|
||||||
// Add status indicator if not present (only for leaf variables)
|
// Add semantic status labels (missing, modified).
|
||||||
if !var.is_group {
|
|
||||||
match var.status {
|
match var.status {
|
||||||
crate::format::ItemStatus::MissingFromActive => {
|
crate::format::ItemStatus::MissingFromActive if !var.is_group => {
|
||||||
let missing_style = if is_selected {
|
let missing_style = if is_selected {
|
||||||
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
||||||
} else {
|
} else {
|
||||||
@@ -114,6 +122,14 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
};
|
};
|
||||||
key_spans.push(Span::styled(" (missing)", missing_style));
|
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 => {
|
crate::format::ItemStatus::Modified => {
|
||||||
if !is_selected {
|
if !is_selected {
|
||||||
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
|
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
|
||||||
@@ -121,7 +137,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let item_style = if is_selected {
|
let item_style = if is_selected {
|
||||||
Style::default().bg(theme.bg_highlight())
|
Style::default().bg(theme.bg_highlight())
|
||||||
@@ -132,7 +147,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
if var.is_group {
|
if var.is_group {
|
||||||
ListItem::new(Line::from(key_spans)).style(item_style)
|
ListItem::new(Line::from(key_spans)).style(item_style)
|
||||||
} else {
|
} else {
|
||||||
// Show live input text for the selected item if in Insert mode.
|
// Determine which value to display (live input vs. stored value).
|
||||||
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
||||||
app.input.value()
|
app.input.value()
|
||||||
} else {
|
} else {
|
||||||
@@ -150,8 +165,9 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
Span::styled(val, value_style),
|
Span::styled(val, value_style),
|
||||||
];
|
];
|
||||||
|
|
||||||
if let Some(t_val) = &var.template_value {
|
// Show default value if it differs from current.
|
||||||
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 {
|
let t_style = if is_selected {
|
||||||
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
|
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
|
||||||
} else {
|
} else {
|
||||||
@@ -159,7 +175,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
};
|
};
|
||||||
val_spans.push(Span::styled(format!(" [Def: {}]", t_val), t_style));
|
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)
|
ListItem::new(vec![Line::from(key_spans), Line::from(val_spans)]).style(item_style)
|
||||||
}
|
}
|
||||||
@@ -183,16 +198,18 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
state.select(Some(app.selected));
|
state.select(Some(app.selected));
|
||||||
f.render_stateful_widget(list, chunks[1], &mut state);
|
f.render_stateful_widget(list, chunks[1], &mut state);
|
||||||
|
|
||||||
// Render the focused input area.
|
// Compose the focused input area details.
|
||||||
let current_var = app.vars.get(app.selected);
|
let current_var = app.vars.get(app.selected);
|
||||||
let mut input_title = " Input ".to_string();
|
let mut input_title = " Input ".to_string();
|
||||||
let mut extra_info = String::new();
|
let mut extra_info = String::new();
|
||||||
|
|
||||||
if let Some(var) = current_var {
|
if let Some(var) = current_var {
|
||||||
if var.is_group {
|
if matches!(app.mode, Mode::InsertKey) {
|
||||||
input_title = format!(" Group: {} ", var.path);
|
input_title = format!(" Rename Key: {} ", var.path_string());
|
||||||
|
} else if var.is_group {
|
||||||
|
input_title = format!(" Group: {} ", var.path_string());
|
||||||
} else {
|
} else {
|
||||||
input_title = format!(" Editing: {} ", var.path);
|
input_title = format!(" Editing: {} ", var.path_string());
|
||||||
if let Some(t_val) = &var.template_value {
|
if let Some(t_val) = &var.template_value {
|
||||||
extra_info = format!(" [Template: {}]", t_val);
|
extra_info = format!(" [Template: {}]", t_val);
|
||||||
}
|
}
|
||||||
@@ -200,16 +217,17 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let input_border_color = match app.mode {
|
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(),
|
_ => theme.border_normal(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let input_text = app.input.value();
|
let input_text = app.input.value();
|
||||||
let cursor_pos = app.input.visual_cursor();
|
let cursor_pos = app.input.visual_cursor();
|
||||||
|
|
||||||
// Show template value in normal mode if it differs
|
|
||||||
let display_text = if let Some(var) = current_var {
|
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 {
|
||||||
"<group>".to_string()
|
"<group>".to_string()
|
||||||
} else if matches!(app.mode, Mode::Normal) {
|
} else if matches!(app.mode, Mode::Normal) {
|
||||||
format!("{}{}", input_text, extra_info)
|
format!("{}{}", input_text, extra_info)
|
||||||
@@ -229,22 +247,22 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
.title(input_title)
|
.title(input_title)
|
||||||
.title_style(
|
.title_style(
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.fg_accent()) // Make title pop
|
.fg(theme.fg_accent())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
)
|
)
|
||||||
.border_style(Style::default().fg(input_border_color)),
|
.border_style(Style::default().fg(input_border_color)),
|
||||||
);
|
);
|
||||||
f.render_widget(input, chunks[2]);
|
f.render_widget(input, chunks[2]);
|
||||||
|
|
||||||
// Position the terminal cursor correctly when in Insert mode.
|
// Position terminal cursor during active input.
|
||||||
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(
|
f.set_cursor_position(ratatui::layout::Position::new(
|
||||||
chunks[2].x + 1 + cursor_pos as u16,
|
chunks[2].x + 1 + cursor_pos as u16,
|
||||||
chunks[2].y + 1,
|
chunks[2].y + 1,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render the modern pill-style status bar.
|
// Render the status bar with mode-specific help hints.
|
||||||
let (mode_str, mode_style) = match app.mode {
|
let (mode_str, mode_style) = match app.mode {
|
||||||
Mode::Normal => (
|
Mode::Normal => (
|
||||||
" NORMAL ",
|
" NORMAL ",
|
||||||
@@ -260,6 +278,13 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
.fg(theme.bg_normal())
|
.fg(theme.bg_normal())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
|
Mode::InsertKey => (
|
||||||
|
" RENAME ",
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.bg_active())
|
||||||
|
.fg(theme.bg_normal())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
Mode::Search => (
|
Mode::Search => (
|
||||||
" SEARCH ",
|
" SEARCH ",
|
||||||
Style::default()
|
Style::default()
|
||||||
@@ -283,11 +308,16 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
if !app.selected_is_group() {
|
if !app.selected_is_group() {
|
||||||
parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute));
|
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() {
|
if app.selected_is_missing() {
|
||||||
parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner
|
parts.push(format!("{} add", "a"));
|
||||||
}
|
}
|
||||||
if app.selected_is_array() {
|
if app.selected_is_array() {
|
||||||
parts.push(format!("{}/{} array", kb.append_item, kb.prepend_item));
|
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!("{} del", kb.delete_item));
|
||||||
parts.push(format!("{} undo", kb.undo));
|
parts.push(format!("{} undo", kb.undo));
|
||||||
@@ -295,7 +325,8 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
parts.push(format!("{} quit", kb.quit));
|
parts.push(format!("{} quit", kb.quit));
|
||||||
parts.join(" · ")
|
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(),
|
Mode::Search => "Esc normal · type to filter".to_string(),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
216
src/undo.rs
Normal file
216
src/undo.rs
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
use crate::format::ConfigItem;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Represents a single snapshot of the application state for undo/redo purposes.
|
||||||
|
pub struct EditAction {
|
||||||
|
/// The complete list of configuration items at the time of the action.
|
||||||
|
pub state: Vec<ConfigItem>,
|
||||||
|
/// The index of the item that was selected during this action.
|
||||||
|
pub selected: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node in the undo tree, representing a point in the application's history.
|
||||||
|
pub struct UndoNode {
|
||||||
|
/// The state data captured at this history point.
|
||||||
|
pub action: EditAction,
|
||||||
|
/// ID of the parent node (previous state). Root node has None.
|
||||||
|
pub parent: Option<usize>,
|
||||||
|
/// IDs of all states that branched off from this one.
|
||||||
|
pub children: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-linear undo/redo system that tracks history as a branching tree.
|
||||||
|
///
|
||||||
|
/// Unlike a simple stack, an UndoTree allows users to undo several steps,
|
||||||
|
/// make a new change (creating a branch), and still navigate through
|
||||||
|
/// the most recent history path.
|
||||||
|
pub struct UndoTree {
|
||||||
|
/// Map of node IDs to their respective history nodes.
|
||||||
|
nodes: HashMap<usize, UndoNode>,
|
||||||
|
/// The ID of the node representing the current application state.
|
||||||
|
current_node: usize,
|
||||||
|
/// Counter for assigning unique IDs to new nodes.
|
||||||
|
next_id: usize,
|
||||||
|
/// Tracks the most recently active branch for each node.
|
||||||
|
/// This allows the 'redo' operation to follow the path the user
|
||||||
|
/// actually took when multiple branches exist.
|
||||||
|
latest_branch: HashMap<usize, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UndoTree {
|
||||||
|
/// Creates a new undo tree initialized with the starting application state.
|
||||||
|
pub fn new(initial_state: Vec<ConfigItem>, 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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes a new state onto the tree, branching off from the current node.
|
||||||
|
///
|
||||||
|
/// This creates a new child node for the current position and updates
|
||||||
|
/// the branch tracking to ensure this new path is preferred during redo.
|
||||||
|
pub fn push(&mut self, state: Vec<ConfigItem>, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the current pointer back to the parent node and returns the previous state.
|
||||||
|
/// Returns None if the current node is the root (no more history to undo).
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the current pointer forward to the latest child branch and returns the state.
|
||||||
|
///
|
||||||
|
/// Redo follows the `latest_branch` map to decide which path to take
|
||||||
|
/// if multiple branches exist. If no branch is recorded, it defaults to the
|
||||||
|
/// most recently created child.
|
||||||
|
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
|
||||||
|
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(current_id, 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);
|
||||||
|
|
||||||
|
// 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 1
|
||||||
|
let action = tree.undo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "A");
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user