Compare commits
18 Commits
14f1be5a2a
...
v0.4.3
| Author | SHA1 | Date | |
|---|---|---|---|
| fca84f5820 | |||
| 1bc4c00e23 | |||
| 0d15c61d67 | |||
| 0f26f7ac76 | |||
| 184386a96b | |||
| 69d4963e4f | |||
| 87ced5a47c | |||
| f85dac3b25 | |||
| 1d9342186a | |||
| f6a84416e6 | |||
| 01a7bd44b7 | |||
| f123f2d6df | |||
| 94ff632b39 | |||
| e09cc3f2d7 | |||
| f09dbc8321 | |||
| 4e5c0e3b07 | |||
| c270d37585 | |||
| 7aa45974a7 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -853,7 +853,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
version = "0.2.1"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
|
|||||||
18
Cargo.toml
18
Cargo.toml
@@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mould"
|
|
||||||
version = "0.3.0"
|
|
||||||
edition = "2024"
|
|
||||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||||
|
edition = "2024"
|
||||||
|
name = "mould"
|
||||||
|
version = "0.4.3"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
@@ -10,18 +10,24 @@ path = "src/main.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.102"
|
anyhow = "1.0.102"
|
||||||
clap = { version = "4.6.0", features = ["derive"] }
|
|
||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
env_logger = "0.11.9"
|
env_logger = "0.11.9"
|
||||||
log = "0.4.29"
|
log = "0.4.29"
|
||||||
ratatui = "0.30.0"
|
ratatui = "0.30.0"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
serde_json = "1.0.149"
|
serde_json = "1.0.149"
|
||||||
serde_yaml = "0.9.34"
|
serde_yaml = "0.9.34"
|
||||||
thiserror = "2.0.18"
|
thiserror = "2.0.18"
|
||||||
toml = "1.0.6"
|
toml = "1.0.6"
|
||||||
tui-input = "0.15.0"
|
tui-input = "0.15.0"
|
||||||
|
|
||||||
|
[dependencies.clap]
|
||||||
|
features = ["derive"]
|
||||||
|
version = "4.6.0"
|
||||||
|
|
||||||
|
[dependencies.serde]
|
||||||
|
features = ["derive"]
|
||||||
|
version = "1.0.228"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.27.0"
|
tempfile = "3.27.0"
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
[[bin]]
|
|
||||||
name = "mould"
|
|
||||||
path = "src/main.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = "1.0.102"
|
|
||||||
crossterm = "0.29.0"
|
|
||||||
dirs = "6.0.0"
|
|
||||||
env_logger = "0.11.9"
|
|
||||||
log = "0.4.29"
|
|
||||||
ratatui = "0.30.0"
|
|
||||||
serde_json = "1.0.149"
|
|
||||||
serde_yaml = "0.9.34"
|
|
||||||
thiserror = "2.0.18"
|
|
||||||
toml = "1.0.6"
|
|
||||||
tui-input = "0.15.0"
|
|
||||||
|
|
||||||
[dependencies.clap]
|
|
||||||
features = ["derive"]
|
|
||||||
version = "4.6.0"
|
|
||||||
|
|
||||||
[dependencies.serde]
|
|
||||||
features = ["derive"]
|
|
||||||
version = "1.0.228"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tempfile = "3.27.0"
|
|
||||||
|
|
||||||
[package]
|
|
||||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
|
||||||
edition = 2024
|
|
||||||
name = "mould"
|
|
||||||
version = "0.3.0"
|
|
||||||
70
README.md
70
README.md
@@ -5,17 +5,18 @@ mould is a modern Terminal User Interface (TUI) tool designed for interactively
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly.
|
- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly.
|
||||||
- **Hierarchical Flattening**: Edit nested data structures (JSON, YAML, TOML) in a flat, searchable list.
|
- **Tree View Navigation**: Edit nested data structures (JSON, YAML, TOML) in a beautiful, depth-colored tree view.
|
||||||
|
- **Smart Template Comparison**: Automatically discovers `.env.example` vs `.env` relationships and highlights missing or modified keys.
|
||||||
|
- **Add Missing Keys**: Instantly pull missing keys and their default values from your template into your active configuration with a single keystroke.
|
||||||
|
- **Neovim Integration**: Comes with a built-in Neovim plugin for seamless in-editor configuration management.
|
||||||
- **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
|
- **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
|
||||||
- **Vim-inspired Workflow**: Navigate with `j`/`k`, edit with `i`, 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 the Catppuccin Mocha palette.
|
- **Modern UI**: A polished, rounded interface featuring a semantic Catppuccin Mocha palette.
|
||||||
- **Highly Configurable**: Customize keybindings and themes via a simple TOML configuration.
|
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML configuration.
|
||||||
- **Dynamic Alignment**: Automatically aligns keys and values for perfect vertical readability.
|
|
||||||
- **Default Value Visibility**: Keep track of original template values while editing.
|
|
||||||
- **Incremental Merging**: Load existing values from an output file to continue where you left off.
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
### CLI Application
|
||||||
Ensure you have Rust and Cargo installed, then run:
|
Ensure you have Rust and Cargo installed, then run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -30,11 +31,19 @@ cd mould
|
|||||||
cargo build --release
|
cargo build --release
|
||||||
```
|
```
|
||||||
|
|
||||||
The binary will be installed as `mould`.
|
### Neovim Plugin
|
||||||
|
If you use a plugin manager like `mini.deps`, you can add the repository directly:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
add({
|
||||||
|
source = 'https://git.narl.io/nvrl/mould-rs',
|
||||||
|
checkout = 'main',
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Provide an input template file to start editing:
|
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.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
mould .env.example
|
mould .env.example
|
||||||
@@ -47,7 +56,16 @@ mould config.template.json -o config.json
|
|||||||
- **Normal Mode**
|
- **Normal Mode**
|
||||||
- `j` / `Down`: Move selection down
|
- `j` / `Down`: Move selection down
|
||||||
- `k` / `Up`: Move selection up
|
- `k` / `Up`: Move selection up
|
||||||
- `i`: Edit the value of the currently selected key (Enter Insert Mode)
|
- `gg`: Jump to the top
|
||||||
|
- `G`: Jump to the bottom
|
||||||
|
- `i`: Edit value (cursor at start)
|
||||||
|
- `A`: Edit value (cursor at end)
|
||||||
|
- `S`: Substitute value (clear and edit)
|
||||||
|
- `o`: Append a new item to the current array
|
||||||
|
- `O`: Prepend a new item to the current array
|
||||||
|
- `dd`: Delete the currently selected variable or group
|
||||||
|
- `u`: Undo the last change
|
||||||
|
- `a`: Add missing value from template to active config
|
||||||
- `/`: Search for configuration keys (Jump to matches)
|
- `/`: Search for configuration keys (Jump to matches)
|
||||||
- `n`: Jump to the next search match
|
- `n`: Jump to the next search match
|
||||||
- `N`: Jump to the previous search match
|
- `N`: Jump to the previous search match
|
||||||
@@ -75,21 +93,33 @@ edit = "i"
|
|||||||
save = ":w"
|
save = ":w"
|
||||||
quit = ":q"
|
quit = ":q"
|
||||||
normal_mode = "Esc"
|
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
|
# Enable transparency to let your terminal background show through
|
||||||
transparent = false
|
transparent = false
|
||||||
|
|
||||||
# Custom color palette (Catppuccin Mocha defaults)
|
# Custom color palette (Semantic Catppuccin Mocha defaults)
|
||||||
crust = "#11111b"
|
bg_normal = "#1e1e2e"
|
||||||
surface0 = "#313244"
|
bg_highlight = "#89b4fa"
|
||||||
surface1 = "#45475a"
|
bg_active = "#a6e3a1"
|
||||||
text = "#cdd6f4"
|
bg_search = "#cba6f7"
|
||||||
blue = "#89b4fa"
|
fg_normal = "#cdd6f4"
|
||||||
green = "#a6e3a1"
|
fg_dimmed = "#6c7086"
|
||||||
lavender = "#b4befe"
|
fg_highlight = "#1e1e2e"
|
||||||
mauve = "#cba6f7"
|
fg_warning = "#f38ba8"
|
||||||
peach = "#fab387"
|
fg_modified = "#fab387"
|
||||||
|
fg_accent = "#b4befe"
|
||||||
|
border_normal = "#45475a"
|
||||||
|
border_active = "#a6e3a1"
|
||||||
|
tree_depth_1 = "#b4befe"
|
||||||
|
tree_depth_2 = "#cba6f7"
|
||||||
|
tree_depth_3 = "#89b4fa"
|
||||||
|
tree_depth_4 = "#fab387"
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
@@ -7,43 +7,41 @@
|
|||||||
transparent = false
|
transparent = false
|
||||||
|
|
||||||
# Colors are specified in hex format ("#RRGGBB").
|
# Colors are specified in hex format ("#RRGGBB").
|
||||||
# Default values follow the Catppuccin Mocha palette.
|
# Default values follow the Semantic Catppuccin Mocha palette.
|
||||||
|
|
||||||
# Main background color (used when transparent = false).
|
bg_normal = "#1e1e2e"
|
||||||
crust = "#11111b"
|
bg_highlight = "#89b4fa"
|
||||||
|
bg_active = "#a6e3a1"
|
||||||
# Status bar background and other secondary UI elements.
|
bg_search = "#cba6f7"
|
||||||
surface0 = "#313244"
|
fg_normal = "#cdd6f4"
|
||||||
|
fg_dimmed = "#6c7086"
|
||||||
# Border and separator color.
|
fg_highlight = "#1e1e2e"
|
||||||
surface1 = "#45475a"
|
fg_warning = "#f38ba8"
|
||||||
|
fg_modified = "#fab387"
|
||||||
# Default text color.
|
fg_accent = "#b4befe"
|
||||||
text = "#cdd6f4"
|
border_normal = "#45475a"
|
||||||
|
border_active = "#a6e3a1"
|
||||||
# Selection highlight and "NORMAL" mode tag color.
|
tree_depth_1 = "#b4befe"
|
||||||
blue = "#89b4fa"
|
tree_depth_2 = "#cba6f7"
|
||||||
|
tree_depth_3 = "#89b4fa"
|
||||||
# Insert mode highlight and "INSERT" mode tag color.
|
tree_depth_4 = "#fab387"
|
||||||
green = "#a6e3a1"
|
|
||||||
|
|
||||||
# Keys/labels color.
|
|
||||||
lavender = "#b4befe"
|
|
||||||
|
|
||||||
# Section titles color.
|
|
||||||
mauve = "#cba6f7"
|
|
||||||
|
|
||||||
# Input field titles color.
|
|
||||||
peach = "#fab387"
|
|
||||||
|
|
||||||
[keybinds]
|
[keybinds]
|
||||||
# Keybindings for navigation and application control.
|
# Keybindings for navigation and application control.
|
||||||
down = "j"
|
down = "j"
|
||||||
up = "k"
|
up = "k"
|
||||||
edit = "i"
|
edit = "i"
|
||||||
|
edit_append = "A"
|
||||||
|
edit_substitute = "S"
|
||||||
save = ":w"
|
save = ":w"
|
||||||
quit = ":q"
|
quit = ":q"
|
||||||
normal_mode = "Esc"
|
normal_mode = "Esc"
|
||||||
search = "/"
|
search = "/"
|
||||||
next_match = "n"
|
next_match = "n"
|
||||||
previous_match = "N"
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
|
jump_bottom = "G"
|
||||||
|
append_item = "o"
|
||||||
|
prepend_item = "O"
|
||||||
|
delete_item = "dd"
|
||||||
|
undo = "u"
|
||||||
|
|||||||
54
lua/mould/init.lua
Normal file
54
lua/mould/init.lua
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
local M = {}
|
||||||
|
|
||||||
|
local function open_floating_terminal(cmd)
|
||||||
|
local buf = vim.api.nvim_create_buf(false, true)
|
||||||
|
local width = math.floor(vim.o.columns * 0.9)
|
||||||
|
local height = math.floor(vim.o.lines * 0.9)
|
||||||
|
local col = math.floor((vim.o.columns - width) / 2)
|
||||||
|
local row = math.floor((vim.o.lines - height) / 2)
|
||||||
|
|
||||||
|
local win_config = {
|
||||||
|
relative = "editor",
|
||||||
|
width = width,
|
||||||
|
height = height,
|
||||||
|
col = col,
|
||||||
|
row = row,
|
||||||
|
style = "minimal",
|
||||||
|
border = "rounded",
|
||||||
|
}
|
||||||
|
|
||||||
|
local win = vim.api.nvim_open_win(buf, true, win_config)
|
||||||
|
|
||||||
|
-- Record the original buffer to reload it later
|
||||||
|
local original_buf = vim.api.nvim_get_current_buf()
|
||||||
|
local original_file = vim.api.nvim_buf_get_name(original_buf)
|
||||||
|
|
||||||
|
vim.fn.termopen(cmd, {
|
||||||
|
on_exit = function()
|
||||||
|
vim.api.nvim_win_close(win, true)
|
||||||
|
vim.api.nvim_buf_delete(buf, { force = true })
|
||||||
|
|
||||||
|
-- Reload the original file if it exists
|
||||||
|
if vim.fn.filereadable(original_file) == 1 then
|
||||||
|
vim.schedule(function()
|
||||||
|
vim.cmd("checktime " .. vim.fn.fnameescape(original_file))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
end,
|
||||||
|
})
|
||||||
|
|
||||||
|
vim.cmd("startinsert")
|
||||||
|
end
|
||||||
|
|
||||||
|
function M.open()
|
||||||
|
local filepath = vim.api.nvim_buf_get_name(0)
|
||||||
|
if filepath == "" then
|
||||||
|
vim.notify("mould.nvim: Cannot open mould for an unnamed buffer.", vim.log.levels.ERROR)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
||||||
|
open_floating_terminal(cmd)
|
||||||
|
end
|
||||||
|
|
||||||
|
return M
|
||||||
8
plugin/mould.lua
Normal file
8
plugin/mould.lua
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
if vim.g.loaded_mould == 1 then
|
||||||
|
return
|
||||||
|
end
|
||||||
|
vim.g.loaded_mould = 1
|
||||||
|
|
||||||
|
vim.api.nvim_create_user_command("Mould", function()
|
||||||
|
require("mould").open()
|
||||||
|
end, { desc = "Open mould for the current buffer" })
|
||||||
258
src/app.rs
258
src/app.rs
@@ -1,4 +1,4 @@
|
|||||||
use crate::format::EnvVar;
|
use crate::format::ConfigItem;
|
||||||
use tui_input::Input;
|
use tui_input::Input;
|
||||||
|
|
||||||
/// Represents the current operating mode of the application.
|
/// Represents the current operating mode of the application.
|
||||||
@@ -11,10 +11,16 @@ pub enum Mode {
|
|||||||
Search,
|
Search,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub enum InsertVariant {
|
||||||
|
Start,
|
||||||
|
End,
|
||||||
|
Substitute,
|
||||||
|
}
|
||||||
|
|
||||||
/// The core application state, holding all configuration variables and UI status.
|
/// The core application state, holding all configuration variables and UI status.
|
||||||
pub struct App {
|
pub struct App {
|
||||||
/// The list of configuration variables being edited.
|
/// The list of configuration variables being edited.
|
||||||
pub vars: Vec<EnvVar>,
|
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 or Insert).
|
||||||
@@ -27,12 +33,14 @@ pub struct App {
|
|||||||
pub input: Input,
|
pub input: Input,
|
||||||
/// The current search query for filtering keys.
|
/// The current search query for filtering keys.
|
||||||
pub search_query: String,
|
pub search_query: String,
|
||||||
|
/// Stack of previous variable states for undo functionality.
|
||||||
|
pub undo_stack: Vec<Vec<ConfigItem>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
/// Initializes a new application instance with the provided variables.
|
/// Initializes a new application instance with the provided variables.
|
||||||
pub fn new(vars: Vec<EnvVar>) -> Self {
|
pub fn new(vars: Vec<ConfigItem>) -> Self {
|
||||||
let initial_input = vars.get(0).map(|v| v.value.clone()).unwrap_or_default();
|
let initial_input = vars.get(0).and_then(|v| v.value.clone()).unwrap_or_default();
|
||||||
Self {
|
Self {
|
||||||
vars,
|
vars,
|
||||||
selected: 0,
|
selected: 0,
|
||||||
@@ -41,6 +49,7 @@ 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(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,6 +87,22 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Jumps to the top of the list.
|
||||||
|
pub fn jump_top(&mut self) {
|
||||||
|
if !self.vars.is_empty() {
|
||||||
|
self.selected = 0;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to the bottom of the list.
|
||||||
|
pub fn jump_bottom(&mut self) {
|
||||||
|
if !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Jumps to the next variable that matches the search query.
|
/// Jumps to the next variable that matches the search query.
|
||||||
pub fn jump_next_match(&mut self) {
|
pub fn jump_next_match(&mut self) {
|
||||||
let indices = self.matching_indices();
|
let indices = self.matching_indices();
|
||||||
@@ -118,21 +143,42 @@ impl App {
|
|||||||
/// Updates the input buffer to reflect the value of the currently selected variable.
|
/// Updates the input buffer to reflect the value of the currently selected variable.
|
||||||
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) {
|
||||||
self.input = Input::new(var.value.clone());
|
let val = var.value.clone().unwrap_or_default();
|
||||||
|
self.input = Input::new(val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Commits the current text in the input buffer back to the selected variable's value.
|
/// Commits the current text in the input buffer back to the selected variable's value.
|
||||||
pub fn commit_input(&mut self) {
|
pub fn commit_input(&mut self) {
|
||||||
if let Some(var) = self.vars.get_mut(self.selected) {
|
if let Some(var) = self.vars.get_mut(self.selected) {
|
||||||
var.value = self.input.value().to_string();
|
if !var.is_group {
|
||||||
|
var.value = Some(self.input.value().to_string());
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transitions the application into Insert Mode.
|
/// Transitions the application into Insert Mode with a specific variant.
|
||||||
pub fn enter_insert(&mut self) {
|
pub fn enter_insert(&mut self, variant: InsertVariant) {
|
||||||
self.mode = Mode::Insert;
|
if let Some(var) = self.vars.get(self.selected) {
|
||||||
self.status_message = None;
|
if !var.is_group {
|
||||||
|
self.save_undo_state();
|
||||||
|
self.mode = Mode::Insert;
|
||||||
|
match variant {
|
||||||
|
InsertVariant::Start => {
|
||||||
|
use tui_input::InputRequest;
|
||||||
|
self.input.handle(InputRequest::GoToStart);
|
||||||
|
}
|
||||||
|
InsertVariant::End => {
|
||||||
|
use tui_input::InputRequest;
|
||||||
|
self.input.handle(InputRequest::GoToEnd);
|
||||||
|
}
|
||||||
|
InsertVariant::Substitute => {
|
||||||
|
self.input = Input::new(String::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Commits the current input and transitions the application into Normal Mode.
|
/// Commits the current input and transitions the application into Normal Mode.
|
||||||
@@ -140,4 +186,196 @@ impl App {
|
|||||||
self.commit_input();
|
self.commit_input();
|
||||||
self.mode = Mode::Normal;
|
self.mode = Mode::Normal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Deletes the currently selected item. If it's a group, deletes all children.
|
||||||
|
pub fn delete_selected(&mut self) {
|
||||||
|
if self.vars.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.save_undo_state();
|
||||||
|
let selected_path = self.vars[self.selected].path.clone();
|
||||||
|
let is_group = self.vars[self.selected].is_group;
|
||||||
|
|
||||||
|
// Identify if the item being removed is an array item
|
||||||
|
let array_info = parse_index(&selected_path);
|
||||||
|
|
||||||
|
// 1. Identify all items to remove
|
||||||
|
let mut to_remove = Vec::new();
|
||||||
|
to_remove.push(self.selected);
|
||||||
|
|
||||||
|
if is_group {
|
||||||
|
let prefix_dot = format!("{}.", selected_path);
|
||||||
|
let prefix_bracket = format!("{}[", selected_path);
|
||||||
|
for (i, var) in self.vars.iter().enumerate() {
|
||||||
|
if i == self.selected {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if var.path.starts_with(&prefix_dot) || var.path.starts_with(&prefix_bracket) {
|
||||||
|
to_remove.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Perform removal (reverse order to preserve indices)
|
||||||
|
to_remove.sort_unstable_by(|a, b| b.cmp(a));
|
||||||
|
for i in to_remove {
|
||||||
|
self.vars.remove(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Re-index subsequent array items if applicable
|
||||||
|
if let Some((base, removed_idx)) = array_info {
|
||||||
|
let base = base.to_string();
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(&base) {
|
||||||
|
// We need to find the index segment that matches this array
|
||||||
|
if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) {
|
||||||
|
if b == base && i > removed_idx {
|
||||||
|
let new_idx = i - 1;
|
||||||
|
var.path = format!("{}[{}]{}", base, new_idx, suffix);
|
||||||
|
// Also update key if it matches the old index exactly
|
||||||
|
if var.key == format!("[{}]", i) {
|
||||||
|
var.key = format!("[{}]", new_idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Adjust selection
|
||||||
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a new item to an array if the selected item is part of one.
|
||||||
|
pub fn add_array_item(&mut self, after: bool) {
|
||||||
|
if self.vars.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.save_undo_state();
|
||||||
|
let (base, idx, depth) = {
|
||||||
|
let selected_item = &self.vars[self.selected];
|
||||||
|
if selected_item.is_group {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let path = &selected_item.path;
|
||||||
|
if let Some((base, idx)) = parse_index(path) {
|
||||||
|
(base.to_string(), idx, selected_item.depth)
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let new_idx = if after { idx + 1 } else { idx };
|
||||||
|
let insert_pos = if after {
|
||||||
|
self.selected + 1
|
||||||
|
} else {
|
||||||
|
self.selected
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Shift all items in this array that have index >= new_idx
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(&base) {
|
||||||
|
if let Some((b, i)) = parse_index(&var.path) {
|
||||||
|
if b == base && i >= new_idx {
|
||||||
|
var.path = format!("{}[{}]", base, i + 1);
|
||||||
|
// Also update key if it was just the index
|
||||||
|
if var.key == format!("[{}]", i) {
|
||||||
|
var.key = format!("[{}]", i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Insert new item
|
||||||
|
let new_item = ConfigItem {
|
||||||
|
key: format!("[{}]", new_idx),
|
||||||
|
path: format!("{}[{}]", base, new_idx),
|
||||||
|
value: Some("".to_string()),
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: crate::format::ItemStatus::Modified,
|
||||||
|
value_type: crate::format::ValueType::String,
|
||||||
|
};
|
||||||
|
self.vars.insert(insert_pos, new_item);
|
||||||
|
self.selected = insert_pos;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.enter_insert(InsertVariant::Start);
|
||||||
|
self.status_message = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Status bar helpers
|
||||||
|
pub fn selected_is_group(&self) -> bool {
|
||||||
|
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn selected_is_array(&self) -> bool {
|
||||||
|
self.vars.get(self.selected)
|
||||||
|
.map(|v| !v.is_group && v.path.contains('['))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn selected_is_missing(&self) -> bool {
|
||||||
|
self.vars.get(self.selected)
|
||||||
|
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves the current state of variables to the undo stack.
|
||||||
|
pub fn save_undo_state(&mut self) {
|
||||||
|
self.undo_stack.push(self.vars.clone());
|
||||||
|
if self.undo_stack.len() > 50 {
|
||||||
|
self.undo_stack.remove(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reverts to the last saved state of variables.
|
||||||
|
pub fn undo(&mut self) {
|
||||||
|
if let Some(previous_vars) = self.undo_stack.pop() {
|
||||||
|
self.vars = previous_vars;
|
||||||
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.status_message = Some("Undo applied".to_string());
|
||||||
|
} else {
|
||||||
|
self.status_message = Some("Nothing to undo".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_index(path: &str) -> Option<(&str, usize)> {
|
||||||
|
if let Some(end) = path.rfind(']') {
|
||||||
|
let segment = &path[..=end];
|
||||||
|
if let Some(start) = segment.rfind('[') {
|
||||||
|
if let Ok(idx) = segment[start + 1..end].parse::<usize>() {
|
||||||
|
// Return the base and index
|
||||||
|
return Some((&path[..start], idx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper to find an array segment in a path given a base prefix.
|
||||||
|
fn find_array_segment<'a>(path: &'a str, base: &str) -> Option<(&'a str, usize, &'a str)> {
|
||||||
|
if !path.starts_with(base) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let remaining = &path[base.len()..];
|
||||||
|
if remaining.starts_with('[') {
|
||||||
|
if let Some(end) = remaining.find(']') {
|
||||||
|
if let Ok(idx) = remaining[1..end].parse::<usize>() {
|
||||||
|
return Some((&path[..base.len()], idx, &remaining[end + 1..]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
136
src/config.rs
136
src/config.rs
@@ -8,24 +8,38 @@ use std::fs;
|
|||||||
pub struct ThemeConfig {
|
pub struct ThemeConfig {
|
||||||
/// If true, skip rendering the background block to let the terminal's transparency show.
|
/// If true, skip rendering the background block to let the terminal's transparency show.
|
||||||
pub transparent: bool,
|
pub transparent: bool,
|
||||||
/// Color for standard background areas (when not transparent).
|
/// Default background.
|
||||||
pub crust: String,
|
pub bg_normal: String,
|
||||||
/// Dark surface color for UI elements like the status bar.
|
/// Background for selected items and standard UI elements.
|
||||||
pub surface0: String,
|
pub bg_highlight: String,
|
||||||
/// Light surface color for borders and dividers.
|
/// Active element background (e.g., insert mode).
|
||||||
pub surface1: String,
|
pub bg_active: String,
|
||||||
/// Default text color.
|
/// Active element background (e.g., search mode).
|
||||||
pub text: String,
|
pub bg_search: String,
|
||||||
/// Color for selection highlighting and normal mode tag.
|
/// Standard text.
|
||||||
pub blue: String,
|
pub fg_normal: String,
|
||||||
/// Color for insert mode highlighting and success status.
|
/// Secondary/inactive text.
|
||||||
pub green: String,
|
pub fg_dimmed: String,
|
||||||
/// Accent color for configuration keys.
|
/// Text on selected items.
|
||||||
pub lavender: String,
|
pub fg_highlight: String,
|
||||||
/// Accent color for primary section titles.
|
/// Red/Alert color for missing items.
|
||||||
pub mauve: String,
|
pub fg_warning: String,
|
||||||
/// Accent color for input field titles.
|
/// Accent color for modified items.
|
||||||
pub peach: String,
|
pub fg_modified: String,
|
||||||
|
/// High-contrast accent for titles and active UI elements.
|
||||||
|
pub fg_accent: String,
|
||||||
|
/// Borders.
|
||||||
|
pub border_normal: String,
|
||||||
|
/// Active borders (e.g., input mode).
|
||||||
|
pub border_active: String,
|
||||||
|
/// Color for tree indentation depth 1.
|
||||||
|
pub tree_depth_1: String,
|
||||||
|
/// Color for tree indentation depth 2.
|
||||||
|
pub tree_depth_2: String,
|
||||||
|
/// Color for tree indentation depth 3.
|
||||||
|
pub tree_depth_3: String,
|
||||||
|
/// Color for tree indentation depth 4.
|
||||||
|
pub tree_depth_4: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ThemeConfig {
|
impl ThemeConfig {
|
||||||
@@ -42,49 +56,45 @@ impl ThemeConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn crust(&self) -> Color {
|
pub fn bg_normal(&self) -> Color { Self::parse_hex(&self.bg_normal) }
|
||||||
Self::parse_hex(&self.crust)
|
pub fn bg_highlight(&self) -> Color { Self::parse_hex(&self.bg_highlight) }
|
||||||
}
|
pub fn bg_active(&self) -> Color { Self::parse_hex(&self.bg_active) }
|
||||||
pub fn surface0(&self) -> Color {
|
pub fn bg_search(&self) -> Color { Self::parse_hex(&self.bg_search) }
|
||||||
Self::parse_hex(&self.surface0)
|
pub fn fg_normal(&self) -> Color { Self::parse_hex(&self.fg_normal) }
|
||||||
}
|
pub fn fg_dimmed(&self) -> Color { Self::parse_hex(&self.fg_dimmed) }
|
||||||
pub fn surface1(&self) -> Color {
|
pub fn fg_highlight(&self) -> Color { Self::parse_hex(&self.fg_highlight) }
|
||||||
Self::parse_hex(&self.surface1)
|
pub fn fg_warning(&self) -> Color { Self::parse_hex(&self.fg_warning) }
|
||||||
}
|
pub fn fg_modified(&self) -> Color { Self::parse_hex(&self.fg_modified) }
|
||||||
pub fn text(&self) -> Color {
|
pub fn fg_accent(&self) -> Color { Self::parse_hex(&self.fg_accent) }
|
||||||
Self::parse_hex(&self.text)
|
pub fn border_normal(&self) -> Color { Self::parse_hex(&self.border_normal) }
|
||||||
}
|
pub fn border_active(&self) -> Color { Self::parse_hex(&self.border_active) }
|
||||||
pub fn blue(&self) -> Color {
|
pub fn tree_depth_1(&self) -> Color { Self::parse_hex(&self.tree_depth_1) }
|
||||||
Self::parse_hex(&self.blue)
|
pub fn tree_depth_2(&self) -> Color { Self::parse_hex(&self.tree_depth_2) }
|
||||||
}
|
pub fn tree_depth_3(&self) -> Color { Self::parse_hex(&self.tree_depth_3) }
|
||||||
pub fn green(&self) -> Color {
|
pub fn tree_depth_4(&self) -> Color { Self::parse_hex(&self.tree_depth_4) }
|
||||||
Self::parse_hex(&self.green)
|
|
||||||
}
|
|
||||||
pub fn lavender(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.lavender)
|
|
||||||
}
|
|
||||||
pub fn mauve(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.mauve)
|
|
||||||
}
|
|
||||||
pub fn peach(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.peach)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ThemeConfig {
|
impl Default for ThemeConfig {
|
||||||
/// Default theme: Catppuccin Mocha.
|
/// Default theme: Semantic Catppuccin Mocha.
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
transparent: false,
|
transparent: false,
|
||||||
crust: "#11111b".to_string(),
|
bg_normal: "#1e1e2e".to_string(), // base
|
||||||
surface0: "#313244".to_string(),
|
bg_highlight: "#89b4fa".to_string(), // blue
|
||||||
surface1: "#45475a".to_string(),
|
bg_active: "#a6e3a1".to_string(), // green
|
||||||
text: "#cdd6f4".to_string(),
|
bg_search: "#cba6f7".to_string(), // mauve
|
||||||
blue: "#89b4fa".to_string(),
|
fg_normal: "#cdd6f4".to_string(), // text
|
||||||
green: "#a6e3a1".to_string(),
|
fg_dimmed: "#6c7086".to_string(), // overlay0
|
||||||
lavender: "#b4befe".to_string(),
|
fg_highlight: "#1e1e2e".to_string(), // base (dark for contrast against highlights)
|
||||||
mauve: "#cba6f7".to_string(),
|
fg_warning: "#f38ba8".to_string(), // red
|
||||||
peach: "#fab387".to_string(),
|
fg_modified: "#fab387".to_string(), // peach
|
||||||
|
fg_accent: "#b4befe".to_string(), // lavender
|
||||||
|
border_normal: "#45475a".to_string(), // surface1
|
||||||
|
border_active: "#a6e3a1".to_string(), // green
|
||||||
|
tree_depth_1: "#b4befe".to_string(), // lavender
|
||||||
|
tree_depth_2: "#cba6f7".to_string(), // mauve
|
||||||
|
tree_depth_3: "#89b4fa".to_string(), // blue
|
||||||
|
tree_depth_4: "#fab387".to_string(), // peach
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,12 +106,20 @@ pub struct KeybindsConfig {
|
|||||||
pub down: String,
|
pub down: String,
|
||||||
pub up: String,
|
pub up: String,
|
||||||
pub edit: String,
|
pub edit: String,
|
||||||
|
pub edit_append: String,
|
||||||
|
pub edit_substitute: String,
|
||||||
pub save: String,
|
pub save: String,
|
||||||
pub quit: String,
|
pub quit: String,
|
||||||
pub normal_mode: String,
|
pub normal_mode: String,
|
||||||
pub search: String,
|
pub search: String,
|
||||||
pub next_match: String,
|
pub next_match: String,
|
||||||
pub previous_match: String,
|
pub previous_match: String,
|
||||||
|
pub jump_top: String,
|
||||||
|
pub jump_bottom: String,
|
||||||
|
pub append_item: String,
|
||||||
|
pub prepend_item: String,
|
||||||
|
pub delete_item: String,
|
||||||
|
pub undo: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for KeybindsConfig {
|
impl Default for KeybindsConfig {
|
||||||
@@ -110,12 +128,20 @@ impl Default for KeybindsConfig {
|
|||||||
down: "j".to_string(),
|
down: "j".to_string(),
|
||||||
up: "k".to_string(),
|
up: "k".to_string(),
|
||||||
edit: "i".to_string(),
|
edit: "i".to_string(),
|
||||||
|
edit_append: "A".to_string(),
|
||||||
|
edit_substitute: "S".to_string(),
|
||||||
save: ":w".to_string(),
|
save: ":w".to_string(),
|
||||||
quit: ":q".to_string(),
|
quit: ":q".to_string(),
|
||||||
normal_mode: "Esc".to_string(),
|
normal_mode: "Esc".to_string(),
|
||||||
search: "/".to_string(),
|
search: "/".to_string(),
|
||||||
next_match: "n".to_string(),
|
next_match: "n".to_string(),
|
||||||
previous_match: "N".to_string(),
|
previous_match: "N".to_string(),
|
||||||
|
jump_top: "gg".to_string(),
|
||||||
|
jump_bottom: "G".to_string(),
|
||||||
|
append_item: "o".to_string(),
|
||||||
|
prepend_item: "O".to_string(),
|
||||||
|
delete_item: "dd".to_string(),
|
||||||
|
undo: "u".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{EnvVar, FormatHandler};
|
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -6,7 +6,7 @@ use std::path::Path;
|
|||||||
pub struct EnvHandler;
|
pub struct EnvHandler;
|
||||||
|
|
||||||
impl FormatHandler for EnvHandler {
|
impl FormatHandler for EnvHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
|
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
||||||
let content = fs::read_to_string(path)?;
|
let content = fs::read_to_string(path)?;
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
|
|
||||||
@@ -18,10 +18,16 @@ impl FormatHandler for EnvHandler {
|
|||||||
|
|
||||||
if let Some((key, val)) = line.split_once('=') {
|
if let Some((key, val)) = line.split_once('=') {
|
||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: key.trim().to_string(),
|
key: key.trim().to_string(),
|
||||||
value: parsed_val.clone(),
|
path: key.trim().to_string(),
|
||||||
default_value: parsed_val,
|
value: Some(parsed_val.clone()),
|
||||||
|
template_value: Some(parsed_val.clone()),
|
||||||
|
default_value: Some(parsed_val),
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,7 +35,7 @@ impl FormatHandler for EnvHandler {
|
|||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -46,24 +52,45 @@ impl FormatHandler for EnvHandler {
|
|||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||||
|
|
||||||
if let Some(var) = vars.iter_mut().find(|v| v.key == key) {
|
if let Some(var) = vars.iter_mut().find(|v| v.key == key) {
|
||||||
var.value = parsed_val;
|
if var.value.as_deref() != Some(&parsed_val) {
|
||||||
|
var.value = Some(parsed_val);
|
||||||
|
var.status = ItemStatus::Modified;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: key.to_string(),
|
key: key.to_string(),
|
||||||
value: parsed_val.clone(),
|
path: key.to_string(),
|
||||||
default_value: String::new(),
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
|
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 {
|
||||||
writeln!(file, "{}={}", var.key, var.value)?;
|
if !var.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
writeln!(file, "{}={}", var.key, val)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -88,14 +115,13 @@ mod tests {
|
|||||||
let vars = handler.parse(file.path()).unwrap();
|
let vars = handler.parse(file.path()).unwrap();
|
||||||
assert_eq!(vars.len(), 4);
|
assert_eq!(vars.len(), 4);
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
assert_eq!(vars[0].value, "value1");
|
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
||||||
assert_eq!(vars[0].default_value, "value1");
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
assert_eq!(vars[1].key, "KEY2");
|
||||||
assert_eq!(vars[1].value, "value2");
|
assert_eq!(vars[1].value.as_deref(), Some("value2"));
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
assert_eq!(vars[2].key, "KEY3");
|
||||||
assert_eq!(vars[2].value, "value3");
|
assert_eq!(vars[2].value.as_deref(), Some("value3"));
|
||||||
assert_eq!(vars[3].key, "EMPTY");
|
assert_eq!(vars[3].key, "EMPTY");
|
||||||
assert_eq!(vars[3].value, "");
|
assert_eq!(vars[3].value.as_deref(), Some(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -112,25 +138,30 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(vars.len(), 3);
|
assert_eq!(vars.len(), 3);
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
assert_eq!(vars[0].value, "custom1");
|
assert_eq!(vars[0].value.as_deref(), Some("custom1"));
|
||||||
assert_eq!(vars[0].default_value, "default1");
|
assert_eq!(vars[0].status, ItemStatus::Modified);
|
||||||
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
assert_eq!(vars[1].key, "KEY2");
|
||||||
assert_eq!(vars[1].value, "default2");
|
assert_eq!(vars[1].value.as_deref(), Some("default2"));
|
||||||
assert_eq!(vars[1].default_value, "default2");
|
|
||||||
|
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
assert_eq!(vars[2].key, "KEY3");
|
||||||
assert_eq!(vars[2].value, "custom3");
|
assert_eq!(vars[2].value.as_deref(), Some("custom3"));
|
||||||
assert_eq!(vars[2].default_value, "");
|
assert_eq!(vars[2].status, ItemStatus::MissingFromTemplate);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_write_env() {
|
fn test_write_env() {
|
||||||
let file = NamedTempFile::new().unwrap();
|
let file = NamedTempFile::new().unwrap();
|
||||||
let vars = vec![EnvVar {
|
let vars = vec![ConfigItem {
|
||||||
key: "KEY1".to_string(),
|
key: "KEY1".to_string(),
|
||||||
value: "value1".to_string(),
|
path: "KEY1".to_string(),
|
||||||
default_value: "def".to_string(),
|
value: Some("value1".to_string()),
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
let handler = EnvHandler;
|
let handler = EnvHandler;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{EnvVar, FormatHandler, FormatType};
|
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType};
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io;
|
use std::io;
|
||||||
@@ -53,93 +53,174 @@ impl HierarchicalHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flatten(value: &Value, prefix: &str, vars: &mut Vec<EnvVar>) {
|
fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) {
|
||||||
|
let path = if prefix.is_empty() {
|
||||||
|
key_name.to_string()
|
||||||
|
} else if key_name.is_empty() {
|
||||||
|
prefix.to_string()
|
||||||
|
} else if key_name.starts_with('[') {
|
||||||
|
format!("{}{}", prefix, key_name)
|
||||||
|
} else {
|
||||||
|
format!("{}.{}", prefix, key_name)
|
||||||
|
};
|
||||||
|
|
||||||
match value {
|
match value {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
|
if !path.is_empty() {
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: key_name.to_string(),
|
||||||
|
path: path.clone(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let next_depth = if path.is_empty() { depth } else { depth + 1 };
|
||||||
for (k, v) in map {
|
for (k, v) in map {
|
||||||
let new_prefix = if prefix.is_empty() {
|
flatten(v, &path, next_depth, k, vars);
|
||||||
k.clone()
|
|
||||||
} else {
|
|
||||||
format!("{}.{}", prefix, k)
|
|
||||||
};
|
|
||||||
flatten(v, &new_prefix, vars);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Value::Array(arr) => {
|
Value::Array(arr) => {
|
||||||
|
if !path.is_empty() {
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: key_name.to_string(),
|
||||||
|
path: path.clone(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let next_depth = if path.is_empty() { depth } else { depth + 1 };
|
||||||
for (i, v) in arr.iter().enumerate() {
|
for (i, v) in arr.iter().enumerate() {
|
||||||
let new_prefix = format!("{}[{}]", prefix, i);
|
let array_key = format!("[{}]", i);
|
||||||
flatten(v, &new_prefix, vars);
|
flatten(v, &path, next_depth, &array_key, vars);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Value::String(s) => {
|
Value::String(s) => {
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: prefix.to_string(),
|
key: key_name.to_string(),
|
||||||
value: s.clone(),
|
path: path.clone(),
|
||||||
default_value: s.clone(),
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Value::Number(n) => {
|
Value::Number(n) => {
|
||||||
let s = n.to_string();
|
let s = n.to_string();
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: prefix.to_string(),
|
key: key_name.to_string(),
|
||||||
value: s.clone(),
|
path: path.clone(),
|
||||||
default_value: s.clone(),
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Number,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Value::Bool(b) => {
|
Value::Bool(b) => {
|
||||||
let s = b.to_string();
|
let s = b.to_string();
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: prefix.to_string(),
|
key: key_name.to_string(),
|
||||||
value: s.clone(),
|
path: path.clone(),
|
||||||
default_value: s.clone(),
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Bool,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Value::Null => {
|
Value::Null => {
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem {
|
||||||
key: prefix.to_string(),
|
key: key_name.to_string(),
|
||||||
value: "".to_string(),
|
path: path.clone(),
|
||||||
default_value: "".to_string(),
|
value: Some("".to_string()),
|
||||||
|
template_value: Some("".to_string()),
|
||||||
|
default_value: Some("".to_string()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Removed unused update_leaf and update_leaf_value functions
|
|
||||||
|
|
||||||
impl FormatHandler for HierarchicalHandler {
|
impl FormatHandler for HierarchicalHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
|
fn parse(&self, path: &Path) -> io::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, "", &mut vars);
|
flatten(&value, "", 0, "", &mut vars);
|
||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let existing_value = self.read_value(path)?;
|
let existing_value = self.read_value(path)?;
|
||||||
let mut existing_vars = Vec::new();
|
let mut existing_vars = Vec::new();
|
||||||
flatten(&existing_value, "", &mut existing_vars);
|
flatten(&existing_value, "", 0, "", &mut existing_vars);
|
||||||
|
|
||||||
for var in vars.iter_mut() {
|
for var in vars.iter_mut() {
|
||||||
if let Some(existing) = existing_vars.iter().find(|v| v.key == var.key) {
|
if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) {
|
||||||
var.value = existing.value.clone();
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
|
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 {
|
||||||
insert_into_value(&mut root, &var.key, &var.value);
|
if !var.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
insert_into_value(&mut root, &var.path, val, var.value_type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
self.write_value(path, &root)
|
self.write_value(path, &root)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str) {
|
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type: ValueType) {
|
||||||
let mut parts = path.split('.');
|
let mut parts = path.split('.');
|
||||||
let last_part = match parts.next_back() {
|
let last_part = match parts.next_back() {
|
||||||
Some(p) => p,
|
Some(p) => p,
|
||||||
@@ -182,13 +263,30 @@ fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str) {
|
|||||||
}
|
}
|
||||||
let map = current.as_object_mut().unwrap();
|
let map = current.as_object_mut().unwrap();
|
||||||
|
|
||||||
// Attempt basic type inference
|
// Use the preserved ValueType instead of aggressive inference
|
||||||
let final_val = if let Ok(n) = new_val_str.parse::<i64>() {
|
let final_val = match value_type {
|
||||||
Value::Number(n.into())
|
ValueType::Number => {
|
||||||
} else if let Ok(b) = new_val_str.parse::<bool>() {
|
if let Ok(n) = new_val_str.parse::<i64>() {
|
||||||
Value::Bool(b)
|
Value::Number(n.into())
|
||||||
} else {
|
} else if let Ok(f) = new_val_str.parse::<f64>() {
|
||||||
Value::String(new_val_str.to_string())
|
if let Some(n) = serde_json::Number::from_f64(f) {
|
||||||
|
Value::Number(n)
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ValueType::Bool => {
|
||||||
|
if let Ok(b) = new_val_str.parse::<bool>() {
|
||||||
|
Value::Bool(b)
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ValueType::Null if new_val_str.is_empty() => Value::Null,
|
||||||
|
_ => Value::String(new_val_str.to_string()),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(i) = final_idx {
|
if let Some(i) = final_idx {
|
||||||
@@ -237,12 +335,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
flatten(&json, "", &mut vars);
|
flatten(&json, "", 0, "", &mut vars);
|
||||||
assert_eq!(vars.len(), 2);
|
assert_eq!(vars.len(), 6);
|
||||||
|
|
||||||
let mut root = Value::Object(Map::new());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
insert_into_value(&mut root, &var.key, &var.value);
|
if !var.is_group {
|
||||||
|
insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// When unflattening, it parses bool back
|
// When unflattening, it parses bool back
|
||||||
|
|||||||
@@ -4,11 +4,33 @@ use std::path::Path;
|
|||||||
pub mod env;
|
pub mod env;
|
||||||
pub mod hierarchical;
|
pub mod hierarchical;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ItemStatus {
|
||||||
|
Present,
|
||||||
|
MissingFromActive,
|
||||||
|
MissingFromTemplate,
|
||||||
|
Modified,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ValueType {
|
||||||
|
String,
|
||||||
|
Number,
|
||||||
|
Bool,
|
||||||
|
Null,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct EnvVar {
|
pub struct ConfigItem {
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub value: String,
|
pub path: String,
|
||||||
pub default_value: String,
|
pub value: Option<String>,
|
||||||
|
pub template_value: Option<String>,
|
||||||
|
pub default_value: Option<String>,
|
||||||
|
pub depth: usize,
|
||||||
|
pub is_group: bool,
|
||||||
|
pub status: ItemStatus,
|
||||||
|
pub value_type: ValueType,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -20,9 +42,9 @@ pub enum FormatType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait FormatHandler {
|
pub trait FormatHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>>;
|
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>>;
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()>;
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()>;
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()>;
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
||||||
|
|||||||
156
src/main.rs
156
src/main.rs
@@ -5,6 +5,7 @@ mod error;
|
|||||||
mod format;
|
mod format;
|
||||||
mod runner;
|
mod runner;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
mod resolver;
|
||||||
|
|
||||||
use app::App;
|
use app::App;
|
||||||
use config::load_config;
|
use config::load_config;
|
||||||
@@ -13,7 +14,6 @@ use format::{detect_format, get_handler};
|
|||||||
use log::{error, info, warn};
|
use log::{error, info, warn};
|
||||||
use runner::AppRunner;
|
use runner::AppRunner;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
event::{DisableMouseCapture, EnableMouseCapture},
|
event::{DisableMouseCapture, EnableMouseCapture},
|
||||||
@@ -22,114 +22,6 @@ use crossterm::{
|
|||||||
};
|
};
|
||||||
use ratatui::{Terminal, backend::CrosstermBackend};
|
use ratatui::{Terminal, backend::CrosstermBackend};
|
||||||
|
|
||||||
/// Helper to automatically determine the output file path based on common naming conventions.
|
|
||||||
fn determine_output_path(input: &Path) -> PathBuf {
|
|
||||||
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
|
||||||
|
|
||||||
// Standard mappings
|
|
||||||
if file_name == ".env.example" || file_name == ".env.template" {
|
|
||||||
return input.with_file_name(".env");
|
|
||||||
}
|
|
||||||
|
|
||||||
if file_name == "docker-compose.yml" || file_name == "compose.yml" {
|
|
||||||
return input.with_file_name("compose.override.yml");
|
|
||||||
}
|
|
||||||
if file_name == "docker-compose.yaml" || file_name == "compose.yaml" {
|
|
||||||
return input.with_file_name("compose.override.yaml");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pattern-based mappings
|
|
||||||
if let Some(base) = file_name.strip_suffix(".env.example") {
|
|
||||||
return input.with_file_name(format!("{}.env", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".env.template") {
|
|
||||||
return input.with_file_name(format!("{}.env", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".example.json") {
|
|
||||||
return input.with_file_name(format!("{}.json", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".template.json") {
|
|
||||||
return input.with_file_name(format!("{}.json", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".example.yml") {
|
|
||||||
return input.with_file_name(format!("{}.yml", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".template.yml") {
|
|
||||||
return input.with_file_name(format!("{}.yml", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".example.yaml") {
|
|
||||||
return input.with_file_name(format!("{}.yaml", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".template.yaml") {
|
|
||||||
return input.with_file_name(format!("{}.yaml", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".example.toml") {
|
|
||||||
return input.with_file_name(format!("{}.toml", base));
|
|
||||||
}
|
|
||||||
if let Some(base) = file_name.strip_suffix(".template.toml") {
|
|
||||||
return input.with_file_name(format!("{}.toml", base));
|
|
||||||
}
|
|
||||||
|
|
||||||
input.with_extension(format!(
|
|
||||||
"{}.out",
|
|
||||||
input.extension().unwrap_or_default().to_string_lossy()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discovers common configuration template files in the current directory.
|
|
||||||
fn find_input_file() -> Option<PathBuf> {
|
|
||||||
let candidates = [
|
|
||||||
".env.example",
|
|
||||||
"compose.yml",
|
|
||||||
"docker-compose.yml",
|
|
||||||
".env.template",
|
|
||||||
"compose.yaml",
|
|
||||||
"docker-compose.yaml",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Priority 1: Exact matches for well-known defaults
|
|
||||||
for name in &candidates {
|
|
||||||
let path = PathBuf::from(name);
|
|
||||||
if path.exists() {
|
|
||||||
return Some(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Priority 2: Pattern matches
|
|
||||||
if let Ok(entries) = std::fs::read_dir(".") {
|
|
||||||
let mut fallback = None;
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let name = entry.file_name();
|
|
||||||
let name_str = name.to_string_lossy();
|
|
||||||
|
|
||||||
if name_str.ends_with(".env.example")
|
|
||||||
|| name_str.ends_with(".env.template")
|
|
||||||
|| name_str.ends_with(".example.json")
|
|
||||||
|| name_str.ends_with(".template.json")
|
|
||||||
|| name_str.ends_with(".example.yml")
|
|
||||||
|| name_str.ends_with(".template.yml")
|
|
||||||
|| name_str.ends_with(".example.yaml")
|
|
||||||
|| name_str.ends_with(".template.yaml")
|
|
||||||
|| name_str.ends_with(".example.toml")
|
|
||||||
|| name_str.ends_with(".template.toml")
|
|
||||||
{
|
|
||||||
// Prefer .env.* or compose.* if multiple matches
|
|
||||||
if name_str.contains(".env") || name_str.contains("compose") {
|
|
||||||
return Some(entry.path());
|
|
||||||
}
|
|
||||||
if fallback.is_none() {
|
|
||||||
fallback = Some(entry.path());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(path) = fallback {
|
|
||||||
return Some(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> anyhow::Result<()> {
|
fn main() -> anyhow::Result<()> {
|
||||||
let args = cli::parse();
|
let args = cli::parse();
|
||||||
|
|
||||||
@@ -152,7 +44,7 @@ fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
path
|
path
|
||||||
}
|
}
|
||||||
None => match find_input_file() {
|
None => match resolver::find_input_file() {
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
info!("Discovered template: {}", path.display());
|
info!("Discovered template: {}", path.display());
|
||||||
path
|
path
|
||||||
@@ -171,23 +63,47 @@ fn main() -> anyhow::Result<()> {
|
|||||||
let format_type = detect_format(&input_path, args.format);
|
let format_type = detect_format(&input_path, args.format);
|
||||||
let handler = get_handler(format_type);
|
let handler = get_handler(format_type);
|
||||||
|
|
||||||
|
// Smart Comparison Logic
|
||||||
|
let (active_path, template_path) = resolver::resolve_paths(&input_path);
|
||||||
|
|
||||||
let output_path = args
|
let output_path = args
|
||||||
.output
|
.output
|
||||||
.unwrap_or_else(|| determine_output_path(&input_path));
|
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| resolver::determine_output_path(&input_path)));
|
||||||
|
|
||||||
info!("Output: {}", output_path.display());
|
info!("Output: {}", output_path.display());
|
||||||
|
|
||||||
let mut vars = handler.parse(&input_path).map_err(|e| {
|
// 1. Load active config if it exists
|
||||||
error!("Failed to parse input file: {}", e);
|
let mut vars = if let Some(active) = &active_path {
|
||||||
MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e))
|
handler.parse(active).unwrap_or_default()
|
||||||
})?;
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
|
||||||
if vars.is_empty() {
|
// 2. Load template config and merge
|
||||||
warn!("No variables found in {}", input_path.display());
|
if let Some(template) = &template_path {
|
||||||
|
info!("Comparing with template: {}", template.display());
|
||||||
|
let template_vars = handler.parse(template).unwrap_or_default();
|
||||||
|
if vars.is_empty() {
|
||||||
|
vars = template_vars;
|
||||||
|
// If we only have template, everything is missing from active initially
|
||||||
|
for v in vars.iter_mut() {
|
||||||
|
v.status = crate::format::ItemStatus::MissingFromActive;
|
||||||
|
v.value = None;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Merge template into active
|
||||||
|
handler.merge(template, &mut vars).unwrap_or_default();
|
||||||
|
}
|
||||||
|
} else if vars.is_empty() {
|
||||||
|
// Fallback if no template and active is empty
|
||||||
|
vars = handler.parse(&input_path).map_err(|e| {
|
||||||
|
error!("Failed to parse input file: {}", e);
|
||||||
|
MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e))
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(e) = handler.merge(&output_path, &mut vars) {
|
if vars.is_empty() {
|
||||||
warn!("Could not merge existing output file: {}", e);
|
warn!("No variables found.");
|
||||||
}
|
}
|
||||||
|
|
||||||
let config = load_config();
|
let config = load_config();
|
||||||
@@ -232,4 +148,4 @@ fn main() -> anyhow::Result<()> {
|
|||||||
Err(e.into())
|
Err(e.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
193
src/resolver.rs
Normal file
193
src/resolver.rs
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub struct Rule {
|
||||||
|
pub template_suffix: &'static str,
|
||||||
|
pub active_suffix: &'static str,
|
||||||
|
pub is_exact_match: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const RULES: &[Rule] = &[
|
||||||
|
// Exact matches
|
||||||
|
Rule { template_suffix: "compose.yml", active_suffix: "compose.override.yml", is_exact_match: true },
|
||||||
|
Rule { template_suffix: "compose.yaml", active_suffix: "compose.override.yaml", is_exact_match: true },
|
||||||
|
Rule { template_suffix: "docker-compose.yml", active_suffix: "docker-compose.override.yml", is_exact_match: true },
|
||||||
|
Rule { template_suffix: "docker-compose.yaml", active_suffix: "docker-compose.override.yaml", is_exact_match: true },
|
||||||
|
|
||||||
|
// Pattern matches
|
||||||
|
Rule { template_suffix: ".env.example", active_suffix: ".env", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".env.template", active_suffix: ".env", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".example.json", active_suffix: ".json", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".template.json", active_suffix: ".json", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".example.yml", active_suffix: ".yml", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".template.yml", active_suffix: ".yml", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".example.yaml", active_suffix: ".yaml", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".template.yaml", active_suffix: ".yaml", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".example.toml", active_suffix: ".toml", is_exact_match: false },
|
||||||
|
Rule { template_suffix: ".template.toml", active_suffix: ".toml", is_exact_match: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
pub const DEFAULT_CANDIDATES: &[&str] = &[
|
||||||
|
".env.example",
|
||||||
|
"compose.yml",
|
||||||
|
"docker-compose.yml",
|
||||||
|
".env.template",
|
||||||
|
"compose.yaml",
|
||||||
|
"docker-compose.yaml",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Helper to automatically determine the output file path based on common naming conventions.
|
||||||
|
pub fn determine_output_path(input: &Path) -> PathBuf {
|
||||||
|
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
||||||
|
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.template_suffix {
|
||||||
|
return input.with_file_name(rule.active_suffix);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if file_name == rule.template_suffix {
|
||||||
|
return input.with_file_name(rule.active_suffix);
|
||||||
|
} else if let Some(base) = file_name.strip_suffix(rule.template_suffix) {
|
||||||
|
return input.with_file_name(format!("{}{}", base, rule.active_suffix));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
input.with_extension(format!(
|
||||||
|
"{}.out",
|
||||||
|
input.extension().unwrap_or_default().to_string_lossy()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discovers common configuration template files in the current directory.
|
||||||
|
pub fn find_input_file() -> Option<PathBuf> {
|
||||||
|
// Priority 1: Exact matches for well-known defaults
|
||||||
|
for &name in DEFAULT_CANDIDATES {
|
||||||
|
let path = PathBuf::from(name);
|
||||||
|
if path.exists() {
|
||||||
|
return Some(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Priority 2: Pattern matches
|
||||||
|
if let Ok(entries) = std::fs::read_dir(".") {
|
||||||
|
let mut fallback = None;
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
let name_str = name.to_string_lossy();
|
||||||
|
|
||||||
|
for rule in RULES {
|
||||||
|
if !rule.is_exact_match && name_str.ends_with(rule.template_suffix) {
|
||||||
|
if name_str.contains(".env") || name_str.contains("compose") {
|
||||||
|
return Some(entry.path());
|
||||||
|
}
|
||||||
|
if fallback.is_none() {
|
||||||
|
fallback = Some(entry.path());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(path) = fallback {
|
||||||
|
return Some(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves the active and template paths given an input path.
|
||||||
|
/// Returns `(active_path, template_path)`.
|
||||||
|
pub fn resolve_paths(input: &Path) -> (Option<PathBuf>, Option<PathBuf>) {
|
||||||
|
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
||||||
|
|
||||||
|
// Check if the input matches any known template pattern
|
||||||
|
let mut is_template = false;
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.template_suffix {
|
||||||
|
is_template = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if file_name.ends_with(rule.template_suffix) {
|
||||||
|
is_template = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback template detection
|
||||||
|
if !is_template && (file_name.contains(".example") || file_name.contains(".template")) {
|
||||||
|
is_template = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_template {
|
||||||
|
let expected_active = determine_output_path(input);
|
||||||
|
let active = if expected_active.exists() {
|
||||||
|
Some(expected_active)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
(active, Some(input.to_path_buf()))
|
||||||
|
} else {
|
||||||
|
// Input is treated as the active config
|
||||||
|
let active = Some(input.to_path_buf());
|
||||||
|
let mut template = None;
|
||||||
|
|
||||||
|
// Try to reverse match rules to find a template
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.active_suffix {
|
||||||
|
let t = input.with_file_name(rule.template_suffix);
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if file_name.ends_with(rule.active_suffix) {
|
||||||
|
if file_name == rule.active_suffix {
|
||||||
|
let t = input.with_file_name(rule.template_suffix);
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if let Some(base) = file_name.strip_suffix(rule.active_suffix) {
|
||||||
|
let t = input.with_file_name(format!("{}{}", base, rule.template_suffix));
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback reverse detection
|
||||||
|
if template.is_none() {
|
||||||
|
let possible_templates = [
|
||||||
|
format!("{}.example", file_name),
|
||||||
|
format!("{}.template", file_name),
|
||||||
|
];
|
||||||
|
for t in possible_templates {
|
||||||
|
let p = input.with_file_name(t);
|
||||||
|
if p.exists() {
|
||||||
|
template = Some(p);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(active, template)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_determine_output_path() {
|
||||||
|
assert_eq!(determine_output_path(Path::new(".env.example")), PathBuf::from(".env"));
|
||||||
|
assert_eq!(determine_output_path(Path::new("compose.yml")), PathBuf::from("compose.override.yml"));
|
||||||
|
assert_eq!(determine_output_path(Path::new("config.template.json")), PathBuf::from("config.json"));
|
||||||
|
assert_eq!(determine_output_path(Path::new("config.example")), PathBuf::from("config.example.out"));
|
||||||
|
}
|
||||||
|
}
|
||||||
112
src/runner.rs
112
src/runner.rs
@@ -1,4 +1,4 @@
|
|||||||
use crate::app::{App, Mode};
|
use crate::app::{App, InsertVariant, Mode};
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::format::FormatHandler;
|
use crate::format::FormatHandler;
|
||||||
use crossterm::event::{self, Event, KeyCode, KeyEvent};
|
use crossterm::event::{self, Event, KeyCode, KeyEvent};
|
||||||
@@ -22,6 +22,8 @@ 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").
|
||||||
|
key_sequence: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, B: Backend> AppRunner<'a, B>
|
impl<'a, B: Backend> AppRunner<'a, B>
|
||||||
@@ -43,6 +45,7 @@ where
|
|||||||
output_path,
|
output_path,
|
||||||
handler,
|
handler,
|
||||||
command_buffer: String::new(),
|
command_buffer: String::new(),
|
||||||
|
key_sequence: String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,38 +110,105 @@ where
|
|||||||
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
||||||
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 {
|
if let KeyCode::Char(c) = key.code {
|
||||||
let c_str = c.to_string();
|
self.key_sequence.push(c);
|
||||||
if c_str == self.config.keybinds.down {
|
|
||||||
self.app.next();
|
// Collect all configured keybinds
|
||||||
} else if c_str == self.config.keybinds.up {
|
let binds = [
|
||||||
self.app.previous();
|
(&self.config.keybinds.down, "down"),
|
||||||
} else if c_str == self.config.keybinds.edit {
|
(&self.config.keybinds.up, "up"),
|
||||||
self.app.enter_insert();
|
(&self.config.keybinds.edit, "edit"),
|
||||||
} else if c_str == ":" {
|
(&self.config.keybinds.edit_append, "edit_append"),
|
||||||
self.command_buffer.push(':');
|
(&self.config.keybinds.edit_substitute, "edit_substitute"),
|
||||||
self.sync_command_status();
|
(&self.config.keybinds.search, "search"),
|
||||||
} else if c_str == "q" {
|
(&self.config.keybinds.next_match, "next_match"),
|
||||||
self.app.running = false;
|
(&self.config.keybinds.previous_match, "previous_match"),
|
||||||
} else if c_str == self.config.keybinds.search {
|
(&self.config.keybinds.jump_top, "jump_top"),
|
||||||
self.app.mode = Mode::Search;
|
(&self.config.keybinds.jump_bottom, "jump_bottom"),
|
||||||
self.app.search_query.clear();
|
(&self.config.keybinds.append_item, "append_item"),
|
||||||
self.app.status_message = Some(format!("{} ", self.config.keybinds.search));
|
(&self.config.keybinds.prepend_item, "prepend_item"),
|
||||||
} else if c_str == self.config.keybinds.next_match {
|
(&self.config.keybinds.delete_item, "delete_item"),
|
||||||
self.app.jump_next_match();
|
(&self.config.keybinds.undo, "undo"),
|
||||||
} else if c_str == self.config.keybinds.previous_match {
|
(&"a".to_string(), "add_missing"),
|
||||||
self.app.jump_previous_match();
|
(&":".to_string(), "command"),
|
||||||
|
(&"q".to_string(), "quit"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut exact_match = None;
|
||||||
|
let mut prefix_match = false;
|
||||||
|
|
||||||
|
for (bind, action) in binds.iter() {
|
||||||
|
if bind == &&self.key_sequence {
|
||||||
|
exact_match = Some(*action);
|
||||||
|
break;
|
||||||
|
} else if bind.starts_with(&self.key_sequence) {
|
||||||
|
prefix_match = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(action) = exact_match {
|
||||||
|
self.key_sequence.clear();
|
||||||
|
match action {
|
||||||
|
"down" => self.app.next(),
|
||||||
|
"up" => self.app.previous(),
|
||||||
|
"edit" => self.app.enter_insert(InsertVariant::Start),
|
||||||
|
"edit_append" => self.app.enter_insert(InsertVariant::End),
|
||||||
|
"edit_substitute" => self.app.enter_insert(InsertVariant::Substitute),
|
||||||
|
"search" => {
|
||||||
|
self.app.mode = Mode::Search;
|
||||||
|
self.app.search_query.clear();
|
||||||
|
self.app.status_message = Some(format!("{} ", self.config.keybinds.search));
|
||||||
|
}
|
||||||
|
"next_match" => self.app.jump_next_match(),
|
||||||
|
"previous_match" => self.app.jump_previous_match(),
|
||||||
|
"jump_top" => self.app.jump_top(),
|
||||||
|
"jump_bottom" => self.app.jump_bottom(),
|
||||||
|
"append_item" => self.app.add_array_item(true),
|
||||||
|
"prepend_item" => self.app.add_array_item(false),
|
||||||
|
"delete_item" => self.app.delete_selected(),
|
||||||
|
"undo" => self.app.undo(),
|
||||||
|
"add_missing" => {
|
||||||
|
self.app.save_undo_state();
|
||||||
|
self.add_missing_item();
|
||||||
|
}
|
||||||
|
"command" => {
|
||||||
|
self.command_buffer.push(':');
|
||||||
|
self.sync_command_status();
|
||||||
|
}
|
||||||
|
"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
|
||||||
|
self.key_sequence.clear();
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Down => self.app.next(),
|
KeyCode::Down => self.app.next(),
|
||||||
KeyCode::Up => self.app.previous(),
|
KeyCode::Up => self.app.previous(),
|
||||||
KeyCode::Enter => self.save_file()?,
|
KeyCode::Enter => self.save_file()?,
|
||||||
|
KeyCode::Esc => self.app.status_message = None,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds a missing item from the template to the active configuration.
|
||||||
|
fn add_missing_item(&mut self) {
|
||||||
|
if let Some(var) = self.app.vars.get_mut(self.app.selected) {
|
||||||
|
if var.status == crate::format::ItemStatus::MissingFromActive {
|
||||||
|
var.status = crate::format::ItemStatus::Present;
|
||||||
|
if !var.is_group {
|
||||||
|
var.value = var.template_value.clone();
|
||||||
|
}
|
||||||
|
self.app.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Delegates key events to the `tui_input` handler during active editing.
|
/// Delegates key events to the `tui_input` handler during active 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 {
|
||||||
|
|||||||
241
src/ui.rs
241
src/ui.rs
@@ -16,7 +16,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
// Render the main background (optional based on transparency config).
|
// Render the main background (optional based on transparency config).
|
||||||
if !theme.transparent {
|
if !theme.transparent {
|
||||||
f.render_widget(
|
f.render_widget(
|
||||||
Block::default().style(Style::default().bg(theme.crust())),
|
Block::default().style(Style::default().bg(theme.bg_normal())),
|
||||||
size,
|
size,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -53,76 +53,116 @@ 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);
|
||||||
|
|
||||||
// Show live input text for the selected item if in Insert mode.
|
// Indentation based on depth
|
||||||
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
let indent = " ".repeat(var.depth);
|
||||||
app.input.value()
|
let prefix = if var.is_group { "+ " } else { " " };
|
||||||
|
|
||||||
|
// Determine colors based on depth
|
||||||
|
let depth_color = if is_selected {
|
||||||
|
theme.bg_normal()
|
||||||
} else {
|
} else {
|
||||||
&var.value
|
match var.depth % 4 {
|
||||||
|
0 => theme.tree_depth_1(),
|
||||||
|
1 => theme.tree_depth_2(),
|
||||||
|
2 => theme.tree_depth_3(),
|
||||||
|
3 => theme.tree_depth_4(),
|
||||||
|
_ => theme.fg_normal(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Determine colors based on status and selection
|
||||||
|
let text_color = if is_selected {
|
||||||
|
theme.fg_highlight()
|
||||||
|
} else {
|
||||||
|
match var.status {
|
||||||
|
crate::format::ItemStatus::MissingFromActive if !var.is_group => theme.fg_dimmed(),
|
||||||
|
crate::format::ItemStatus::Modified => theme.fg_modified(),
|
||||||
|
_ => theme.fg_normal(),
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let key_style = if is_selected {
|
let key_style = if is_selected {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.crust())
|
.fg(theme.fg_highlight())
|
||||||
.add_modifier(Modifier::BOLD)
|
.add_modifier(Modifier::BOLD)
|
||||||
} else if is_match {
|
} else if is_match {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.mauve())
|
.fg(theme.bg_search())
|
||||||
.add_modifier(Modifier::UNDERLINED)
|
.add_modifier(Modifier::UNDERLINED)
|
||||||
|
} else if var.status == crate::format::ItemStatus::MissingFromActive && !var.is_group {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_dimmed())
|
||||||
|
.add_modifier(Modifier::DIM)
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.lavender())
|
Style::default().fg(depth_color)
|
||||||
};
|
};
|
||||||
|
|
||||||
let value_style = if is_selected {
|
let mut key_spans = vec![
|
||||||
Style::default().fg(theme.crust())
|
Span::raw(indent),
|
||||||
} else {
|
Span::styled(prefix, Style::default().fg(theme.border_normal())),
|
||||||
Style::default().fg(theme.text())
|
Span::styled(&var.key, key_style),
|
||||||
};
|
];
|
||||||
|
|
||||||
// Path styling for nested keys (e.g., a.b.c)
|
// Add status indicator if not present (only for leaf variables)
|
||||||
let mut key_spans = Vec::new();
|
if !var.is_group {
|
||||||
if let Some(last_dot) = var.key.rfind('.') {
|
match var.status {
|
||||||
let path = &var.key[..=last_dot];
|
crate::format::ItemStatus::MissingFromActive => {
|
||||||
let key = &var.key[last_dot + 1..];
|
let missing_style = if is_selected {
|
||||||
|
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
||||||
let path_style = if is_selected {
|
} else {
|
||||||
Style::default()
|
Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD)
|
||||||
.fg(theme.crust())
|
};
|
||||||
.add_modifier(Modifier::DIM)
|
key_spans.push(Span::styled(" (missing)", missing_style));
|
||||||
} else {
|
}
|
||||||
Style::default().fg(theme.surface1())
|
crate::format::ItemStatus::Modified => {
|
||||||
};
|
if !is_selected {
|
||||||
|
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
|
||||||
key_spans.push(Span::styled(path, path_style));
|
}
|
||||||
key_spans.push(Span::styled(key, key_style));
|
}
|
||||||
} else {
|
_ => {}
|
||||||
key_spans.push(Span::styled(&var.key, key_style));
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let item_style = if is_selected {
|
let item_style = if is_selected {
|
||||||
Style::default().bg(theme.blue())
|
Style::default().bg(theme.bg_highlight())
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.text())
|
Style::default().fg(text_color)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Two-line layout for better readability:
|
if var.is_group {
|
||||||
// Line 1: Key (path.key)
|
ListItem::new(Line::from(key_spans)).style(item_style)
|
||||||
// Line 2: Value
|
} else {
|
||||||
let lines = vec![
|
// Show live input text for the selected item if in Insert mode.
|
||||||
Line::from(key_spans),
|
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
||||||
Line::from(vec![
|
app.input.value()
|
||||||
Span::styled(
|
} else {
|
||||||
" └─ ",
|
var.value.as_deref().unwrap_or("")
|
||||||
if is_selected {
|
};
|
||||||
Style::default().fg(theme.crust())
|
|
||||||
} else {
|
|
||||||
Style::default().fg(theme.surface1())
|
|
||||||
},
|
|
||||||
),
|
|
||||||
Span::styled(val, value_style),
|
|
||||||
]),
|
|
||||||
];
|
|
||||||
|
|
||||||
ListItem::new(lines).style(item_style)
|
let value_style = if is_selected {
|
||||||
|
Style::default().fg(theme.fg_highlight())
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_normal())
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut val_spans = vec![
|
||||||
|
Span::raw(format!("{} └─ ", " ".repeat(var.depth))),
|
||||||
|
Span::styled(val, value_style),
|
||||||
|
];
|
||||||
|
|
||||||
|
if let Some(t_val) = &var.template_value {
|
||||||
|
if Some(t_val) != var.value.as_ref() {
|
||||||
|
let t_style = if is_selected {
|
||||||
|
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_dimmed()).add_modifier(Modifier::ITALIC)
|
||||||
|
};
|
||||||
|
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)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -133,10 +173,10 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
.title(" Config Variables ")
|
.title(" Config Variables ")
|
||||||
.title_style(
|
.title_style(
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.mauve())
|
.fg(theme.fg_accent())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
)
|
)
|
||||||
.border_style(Style::default().fg(theme.surface1())),
|
.border_style(Style::default().fg(theme.border_normal())),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut state = ListState::default();
|
let mut state = ListState::default();
|
||||||
@@ -145,26 +185,43 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
|
|
||||||
// Render the focused input area.
|
// Render the focused input area.
|
||||||
let current_var = app.vars.get(app.selected);
|
let current_var = app.vars.get(app.selected);
|
||||||
let input_title = if let Some(var) = current_var {
|
let mut input_title = " Input ".to_string();
|
||||||
if var.default_value.is_empty() {
|
let mut extra_info = String::new();
|
||||||
format!(" Editing: {} ", var.key)
|
|
||||||
|
if let Some(var) = current_var {
|
||||||
|
if var.is_group {
|
||||||
|
input_title = format!(" Group: {} ", var.path);
|
||||||
} else {
|
} else {
|
||||||
format!(" Editing: {} (Default: {}) ", var.key, var.default_value)
|
input_title = format!(" Editing: {} ", var.path);
|
||||||
|
if let Some(t_val) = &var.template_value {
|
||||||
|
extra_info = format!(" [Template: {}]", t_val);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
" Input ".to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
let input_border_color = match app.mode {
|
let input_border_color = match app.mode {
|
||||||
Mode::Insert => theme.green(),
|
Mode::Insert => theme.border_active(),
|
||||||
Mode::Normal | Mode::Search => theme.surface1(),
|
Mode::Normal | Mode::Search => 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();
|
||||||
|
|
||||||
let input = Paragraph::new(input_text)
|
// Show template value in normal mode if it differs
|
||||||
.style(Style::default().fg(theme.text()))
|
let display_text = if let Some(var) = current_var {
|
||||||
|
if var.is_group {
|
||||||
|
"<group>".to_string()
|
||||||
|
} else if matches!(app.mode, Mode::Normal) {
|
||||||
|
format!("{}{}", input_text, extra_info)
|
||||||
|
} else {
|
||||||
|
input_text.to_string()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
input_text.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
let input = Paragraph::new(display_text)
|
||||||
|
.style(Style::default().fg(theme.fg_normal()))
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
@@ -172,7 +229,7 @@ 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.peach())
|
.fg(theme.fg_accent()) // Make title pop
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
)
|
)
|
||||||
.border_style(Style::default().fg(input_border_color)),
|
.border_style(Style::default().fg(input_border_color)),
|
||||||
@@ -192,43 +249,65 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
Mode::Normal => (
|
Mode::Normal => (
|
||||||
" NORMAL ",
|
" NORMAL ",
|
||||||
Style::default()
|
Style::default()
|
||||||
.bg(theme.blue())
|
.bg(theme.bg_highlight())
|
||||||
.fg(theme.crust())
|
.fg(theme.bg_normal())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
Mode::Insert => (
|
Mode::Insert => (
|
||||||
" INSERT ",
|
" INSERT ",
|
||||||
Style::default()
|
Style::default()
|
||||||
.bg(theme.green())
|
.bg(theme.bg_active())
|
||||||
.fg(theme.crust())
|
.fg(theme.bg_normal())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
Mode::Search => (
|
Mode::Search => (
|
||||||
" SEARCH ",
|
" SEARCH ",
|
||||||
Style::default()
|
Style::default()
|
||||||
.bg(theme.mauve())
|
.bg(theme.bg_search())
|
||||||
.fg(theme.crust())
|
.fg(theme.bg_normal())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let status_msg = app
|
let status_msg = if let Some(msg) = &app.status_message {
|
||||||
.status_message
|
msg.clone()
|
||||||
.as_deref()
|
} else {
|
||||||
.unwrap_or_else(|| match app.mode {
|
let kb = &config.keybinds;
|
||||||
Mode::Normal => " navigation | i: edit | /: search | :w: save | :q: quit ",
|
match app.mode {
|
||||||
Mode::Insert => " Esc: back to normal | Enter: commit ",
|
Mode::Normal => {
|
||||||
Mode::Search => " Esc: back to normal | type to filter ",
|
let mut parts = vec![
|
||||||
});
|
format!("{}/{} move", kb.down, kb.up),
|
||||||
|
format!("{}/{} jump", kb.jump_top, kb.jump_bottom),
|
||||||
|
format!("{} search", kb.search),
|
||||||
|
];
|
||||||
|
if !app.selected_is_group() {
|
||||||
|
parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute));
|
||||||
|
}
|
||||||
|
if app.selected_is_missing() {
|
||||||
|
parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner
|
||||||
|
}
|
||||||
|
if app.selected_is_array() {
|
||||||
|
parts.push(format!("{}/{} array", kb.append_item, kb.prepend_item));
|
||||||
|
}
|
||||||
|
parts.push(format!("{} del", kb.delete_item));
|
||||||
|
parts.push(format!("{} undo", kb.undo));
|
||||||
|
parts.push(format!("{} save", kb.save));
|
||||||
|
parts.push(format!("{} quit", kb.quit));
|
||||||
|
parts.join(" · ")
|
||||||
|
}
|
||||||
|
Mode::Insert => "Esc normal · Enter commit".to_string(),
|
||||||
|
Mode::Search => "Esc normal · type to filter".to_string(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let status_line = Line::from(vec![
|
let status_line = Line::from(vec![
|
||||||
Span::styled(mode_str, mode_style),
|
Span::styled(mode_str, mode_style),
|
||||||
Span::styled(
|
Span::styled(
|
||||||
format!(" {} ", status_msg),
|
format!(" {} ", status_msg),
|
||||||
Style::default().bg(theme.surface0()).fg(theme.text()),
|
Style::default().bg(theme.border_normal()).fg(theme.fg_normal()),
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let status = Paragraph::new(status_line).style(Style::default().bg(theme.surface0()));
|
let status = Paragraph::new(status_line).style(Style::default().bg(theme.border_normal()));
|
||||||
f.render_widget(status, chunks[4]);
|
f.render_widget(status, chunks[4]);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user