4 Commits

Author SHA1 Message Date
d52422d839 Merge pull request 'release/0.2.0' (#4) from release/0.2.0 into main
All checks were successful
Release / Build and Release (push) Successful in 47s
Reviewed-on: #4
2026-03-16 17:46:58 +01:00
ac7b67748d Merge pull request 'fixed release upload' (#3) from release/0.1.0 into main
All checks were successful
Release / Build and Release (push) Successful in 39s
Reviewed-on: nvrl/cenv-rs#3
2026-03-16 15:56:25 +01:00
361df64b04 Merge pull request 'added version check + fixed release' (#2) from release/0.1.0 into main
Some checks failed
Release / Build and Release (push) Failing after 36s
Reviewed-on: nvrl/cenv-rs#2
2026-03-16 15:54:27 +01:00
6eddd02fb4 Merge pull request 'release/0.1.0' (#1) from release/0.1.0 into main
Some checks failed
Release / Build and Release (push) Failing after 44s
Reviewed-on: nvrl/cenv-rs#1
2026-03-16 15:49:05 +01:00
17 changed files with 293 additions and 1236 deletions

90
Cargo.lock generated
View File

@@ -17,21 +17,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
"anstyle",
"anstyle-parse 0.2.7",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]] [[package]]
name = "anstream" name = "anstream"
version = "1.0.0" version = "1.0.0"
@@ -39,7 +24,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [ dependencies = [
"anstyle", "anstyle",
"anstyle-parse 1.0.0", "anstyle-parse",
"anstyle-query", "anstyle-query",
"anstyle-wincon", "anstyle-wincon",
"colorchoice", "colorchoice",
@@ -53,15 +38,6 @@ version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]] [[package]]
name = "anstyle-parse" name = "anstyle-parse"
version = "1.0.0" version = "1.0.0"
@@ -203,7 +179,7 @@ version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [ dependencies = [
"anstream 1.0.0", "anstream",
"anstyle", "anstyle",
"clap_lex", "clap_lex",
"strsim", "strsim",
@@ -429,29 +405,6 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "env_filter"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d"
dependencies = [
"anstream 0.6.21",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -679,30 +632,6 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "jiff"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
]
[[package]]
name = "jiff-static"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.91" version = "0.3.91"
@@ -853,20 +782,16 @@ dependencies = [
[[package]] [[package]]
name = "mould" name = "mould"
version = "0.2.1" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow",
"clap", "clap",
"crossterm", "crossterm",
"dirs", "dirs",
"env_logger",
"log",
"ratatui", "ratatui",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
"tempfile", "tempfile",
"thiserror 2.0.18",
"toml", "toml",
"tui-input", "tui-input",
] ]
@@ -1080,15 +1005,6 @@ version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]]
name = "portable-atomic-util"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
dependencies = [
"portable-atomic",
]
[[package]] [[package]]
name = "powerfmt" name = "powerfmt"
version = "0.2.0" version = "0.2.0"

View File

@@ -1,39 +1,23 @@
[[bin.""]] [package]
name = "mould"
version = "0.2.0"
edition = "2024"
authors = ["Nils Pukropp <nils@narl.io>"]
[[bin]]
name = "mould" name = "mould"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
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"
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"
toml = "1.0.6" toml = "1.0.6"
tui-input = "0.15.0" tui-input = "0.15.0"
[dependencies.clap]
version = "4.6.0"
[dependencies.clap.features]
"" = ["derive"]
[dependencies.serde]
version = "1.0.228"
[dependencies.serde.features]
"" = ["derive"]
[dev-dependencies] [dev-dependencies]
tempfile = "3.27.0" tempfile = "3.27.0"
[package]
edition = 2024
name = "mould"
version = "0.4.0"
[package.authors]
"" = ["Nils Pukropp <nils@narl.io>"]

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2026 Nils Pukropp <nils@narl.io> Copyright (c) 2026 The mould Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -5,18 +5,15 @@ 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.
- **Tree View Navigation**: Edit nested data structures (JSON, YAML, TOML) in a beautiful, depth-colored tree view. - **Hierarchical Flattening**: Edit nested data structures (JSON, YAML, TOML) in a flat, searchable list.
- **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`, `gg`/`G`, edit with `i`, search with `/`, and save with `:w`. - **Vim-inspired Workflow**: Navigate with `j`/`k`, edit with `i`, and save with `:w`.
- **Modern UI**: A polished, rounded interface featuring a semantic Catppuccin Mocha palette. - **Modern UI**: A polished, rounded interface featuring the Catppuccin Mocha palette.
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML configuration. - **Highly Configurable**: Customize keybindings and themes via a simple TOML configuration.
- **Dynamic Alignment**: Automatically aligns keys and values for perfect vertical readability.
## Installation ## Installation
### CLI Application
Ensure you have Rust and Cargo installed, then run: Ensure you have Rust and Cargo installed, then run:
```sh ```sh
@@ -31,21 +28,11 @@ cd mould
cargo build --release cargo build --release
``` ```
### Neovim Plugin The binary will be installed as `mould`.
If you use a plugin manager like `lazy.nvim`, you can add the local repository (or remote once published) directly:
```lua
{
"username/mould", -- replace with actual repo path or github url
config = function()
-- Provides the :Mould command
end
}
```
## 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:
```sh ```sh
mould .env.example mould .env.example
@@ -58,13 +45,7 @@ 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
- `gg`: Jump to the top
- `G`: Jump to the bottom
- `i`: Edit the value of the currently selected key (Enter Insert Mode) - `i`: Edit the value of the currently selected key (Enter Insert Mode)
- `a`: Add missing value from template to active config
- `/`: Search for configuration keys (Jump to matches)
- `n`: Jump to the next search match
- `N`: Jump to the previous search match
- `:w` or `Enter`: Save the current configuration to the output file - `: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
@@ -89,33 +70,9 @@ 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 name = "catppuccin_mocha"
transparent = false
# Custom color palette (Semantic Catppuccin Mocha defaults)
bg_normal = "#1e1e2e"
bg_highlight = "#89b4fa"
bg_active = "#a6e3a1"
bg_search = "#cba6f7"
fg_normal = "#cdd6f4"
fg_dimmed = "#6c7086"
fg_highlight = "#1e1e2e"
fg_warning = "#f38ba8"
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

View File

@@ -1,40 +0,0 @@
# mould Configuration Example
# Place this file at ~/.config/mould/config.toml (Linux/macOS)
# or %AppData%\mould\config.toml (Windows)
[theme]
# If true, skip rendering the background block to let the terminal's transparency show.
transparent = false
# Colors are specified in hex format ("#RRGGBB").
# Default values follow the Semantic Catppuccin Mocha palette.
bg_normal = "#11111b"
bg_highlight = "#89b4fa"
bg_active = "#a6e3a1"
bg_search = "#cba6f7"
fg_normal = "#cdd6f4"
fg_dimmed = "#a6adc8"
fg_highlight = "#11111b"
fg_warning = "#f38ba8"
fg_modified = "#fab387"
border_normal = "#45475a"
border_active = "#a6e3a1"
tree_depth_1 = "#b4befe"
tree_depth_2 = "#cba6f7"
tree_depth_3 = "#89b4fa"
tree_depth_4 = "#fab387"
[keybinds]
# Keybindings for navigation and application control.
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"

View File

@@ -1,54 +0,0 @@
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

View File

@@ -1,8 +0,0 @@
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" })

View File

@@ -1,38 +1,23 @@
use crate::format::ConfigItem; use crate::format::EnvVar;
use tui_input::Input; use tui_input::Input;
/// Represents the current operating mode of the application.
pub enum Mode { pub enum Mode {
/// Standard navigation and command mode.
Normal, Normal,
/// Active text entry mode for modifying values.
Insert, Insert,
/// Active search mode for filtering keys.
Search,
} }
/// The core application state, holding all configuration variables and UI status.
pub struct App { pub struct App {
/// The list of configuration variables being edited. pub vars: Vec<EnvVar>,
pub vars: Vec<ConfigItem>,
/// Index of the currently selected variable in the list.
pub selected: usize, pub selected: usize,
/// The current interaction mode (Normal or Insert).
pub mode: Mode, pub mode: Mode,
/// 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").
pub status_message: Option<String>, pub status_message: Option<String>,
/// The active text input buffer for the selected variable.
pub input: Input, pub input: Input,
/// The current search query for filtering keys.
pub search_query: String,
} }
impl App { impl App {
/// 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,
@@ -40,25 +25,9 @@ impl App {
running: true, running: true,
status_message: None, status_message: None,
input: Input::new(initial_input), input: Input::new(initial_input),
search_query: String::new(),
} }
} }
/// Returns the indices of variables that match the search query.
pub fn matching_indices(&self) -> Vec<usize> {
if self.search_query.is_empty() {
return Vec::new();
}
let query = self.search_query.to_lowercase();
self.vars
.iter()
.enumerate()
.filter(|(_, v)| v.key.to_lowercase().contains(&query))
.map(|(i, _)| i)
.collect()
}
/// Moves the selection to the next variable in the list, wrapping around if necessary.
pub fn next(&mut self) { pub fn next(&mut self) {
if !self.vars.is_empty() { if !self.vars.is_empty() {
self.selected = (self.selected + 1) % self.vars.len(); self.selected = (self.selected + 1) % self.vars.len();
@@ -66,7 +35,6 @@ impl App {
} }
} }
/// Moves the selection to the previous variable in the list, wrapping around if necessary.
pub fn previous(&mut self) { pub fn previous(&mut self) {
if !self.vars.is_empty() { if !self.vars.is_empty() {
if self.selected == 0 { if self.selected == 0 {
@@ -78,90 +46,30 @@ 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.
pub fn jump_next_match(&mut self) {
let indices = self.matching_indices();
if indices.is_empty() {
return;
}
let next_match = indices
.iter()
.find(|&&i| i > self.selected)
.or_else(|| indices.first());
if let Some(&index) = next_match {
self.selected = index;
self.sync_input_with_selected();
}
}
/// Jumps to the previous variable that matches the search query.
pub fn jump_previous_match(&mut self) {
let indices = self.matching_indices();
if indices.is_empty() {
return;
}
let prev_match = indices
.iter()
.rev()
.find(|&&i| i < self.selected)
.or_else(|| indices.last());
if let Some(&index) = prev_match {
self.selected = index;
self.sync_input_with_selected();
}
}
/// 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) {
let val = var.value.clone().unwrap_or_default(); self.input = Input::new(var.value.clone());
self.input = Input::new(val);
} }
} }
/// Commits the current text in the input buffer back to the selected variable's value.
pub fn commit_input(&mut self) { 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) {
if !var.is_group { var.value = self.input.value().to_string();
var.value = Some(self.input.value().to_string());
var.status = crate::format::ItemStatus::Modified;
}
} }
} }
/// Transitions the application into Insert Mode.
pub fn enter_insert(&mut self) { pub fn enter_insert(&mut self) {
if let Some(var) = self.vars.get(self.selected) {
if !var.is_group {
self.mode = Mode::Insert; self.mode = Mode::Insert;
self.status_message = None; self.status_message = None;
} }
}
}
/// Commits the current input and transitions the application into Normal Mode.
pub fn enter_normal(&mut self) { pub fn enter_normal(&mut self) {
self.commit_input(); self.commit_input();
self.mode = Mode::Normal; self.mode = Mode::Normal;
} }
#[allow(dead_code)]
pub fn quit(&mut self) {
self.running = false;
}
} }

View File

@@ -1,34 +1,21 @@
use clap::Parser; use clap::Parser;
use std::path::PathBuf; use std::path::PathBuf;
/// mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command( #[command(author, version, about = "mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)")]
author,
version,
about = "mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)",
long_about = "mould allows you to interactively edit and generate configuration files using templates. It supports various formats including .env, JSON, YAML, and TOML. It features a modern TUI with Vim-inspired keybindings and out-of-the-box support for theming.",
after_help = "EXAMPLES:\n mould .env.example\n mould docker-compose.yml\n mould config.template.json -o config.json"
)]
pub struct Cli { pub struct Cli {
/// The input template file (e.g., .env.example, config.json.template, docker-compose.yml) /// The input template file (e.g., .env.example, config.json.template, docker-compose.yml)
#[arg(required = false, value_name = "INPUT_FILE")] pub input: PathBuf,
pub input: Option<PathBuf>,
/// Optional output file. If not provided, it will be inferred. /// Optional output file. If not provided, it will be inferred (e.g., .env.example -> .env, docker-compose.yml -> docker-compose.override.yml)
#[arg(short, long, value_name = "OUTPUT_FILE")] #[arg(short, long)]
pub output: Option<PathBuf>, pub output: Option<PathBuf>,
/// Override the format detection (env, json, yaml, toml) /// Override the format detection (env, json, yaml, toml)
#[arg(short, long, value_name = "FORMAT", value_parser = ["env", "json", "yaml", "toml"])] #[arg(short, long)]
pub format: Option<String>, pub format: Option<String>,
/// Increase verbosity for logging (can be used multiple times)
#[arg(short, long, action = clap::ArgAction::Count)]
pub verbose: u8,
} }
/// Parses and returns the command-line arguments.
pub fn parse() -> Cli { pub fn parse() -> Cli {
Cli::parse() Cli::parse()
} }

View File

@@ -1,49 +1,23 @@
use ratatui::style::Color;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs; use std::fs;
use ratatui::style::Color;
/// Configuration for the application's appearance.
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(default)]
pub struct ThemeConfig { pub struct ThemeConfig {
/// If true, skip rendering the background block to let the terminal's transparency show. #[serde(default)]
pub transparent: bool, pub transparent: bool,
/// Default background. pub crust: String,
pub bg_normal: String, pub surface0: String,
/// Background for selected items and standard UI elements. pub surface1: String,
pub bg_highlight: String, pub text: String,
/// Active element background (e.g., insert mode). pub blue: String,
pub bg_active: String, pub green: String,
/// Active element background (e.g., search mode). pub lavender: String,
pub bg_search: String, pub mauve: String,
/// Standard text. pub peach: String,
pub fg_normal: String,
/// Secondary/inactive text.
pub fg_dimmed: String,
/// Text on selected items.
pub fg_highlight: String,
/// Red/Alert color for missing items.
pub fg_warning: String,
/// Accent color for modified items.
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 {
/// Internal helper to parse a hex color string ("#RRGGBB") into a TUI Color.
fn parse_hex(hex: &str) -> Color { fn parse_hex(hex: &str) -> Color {
let hex = hex.trim_start_matches('#'); let hex = hex.trim_start_matches('#');
if hex.len() == 6 { if hex.len() == 6 {
@@ -56,52 +30,35 @@ impl ThemeConfig {
} }
} }
pub fn bg_normal(&self) -> Color { Self::parse_hex(&self.bg_normal) } pub fn crust(&self) -> Color { Self::parse_hex(&self.crust) }
pub fn bg_highlight(&self) -> Color { Self::parse_hex(&self.bg_highlight) } pub fn surface0(&self) -> Color { Self::parse_hex(&self.surface0) }
pub fn bg_active(&self) -> Color { Self::parse_hex(&self.bg_active) } pub fn surface1(&self) -> Color { Self::parse_hex(&self.surface1) }
pub fn bg_search(&self) -> Color { Self::parse_hex(&self.bg_search) } pub fn text(&self) -> Color { Self::parse_hex(&self.text) }
pub fn fg_normal(&self) -> Color { Self::parse_hex(&self.fg_normal) } pub fn blue(&self) -> Color { Self::parse_hex(&self.blue) }
pub fn fg_dimmed(&self) -> Color { Self::parse_hex(&self.fg_dimmed) } pub fn green(&self) -> Color { Self::parse_hex(&self.green) }
pub fn fg_highlight(&self) -> Color { Self::parse_hex(&self.fg_highlight) } pub fn lavender(&self) -> Color { Self::parse_hex(&self.lavender) }
pub fn fg_warning(&self) -> Color { Self::parse_hex(&self.fg_warning) } pub fn mauve(&self) -> Color { Self::parse_hex(&self.mauve) }
pub fn fg_modified(&self) -> Color { Self::parse_hex(&self.fg_modified) } pub fn peach(&self) -> Color { Self::parse_hex(&self.peach) }
pub fn fg_accent(&self) -> Color { Self::parse_hex(&self.fg_accent) }
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 tree_depth_1(&self) -> Color { Self::parse_hex(&self.tree_depth_1) }
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 tree_depth_4(&self) -> Color { Self::parse_hex(&self.tree_depth_4) }
} }
impl Default for ThemeConfig { impl Default for ThemeConfig {
/// Default theme: Semantic Catppuccin Mocha.
fn default() -> Self { fn default() -> Self {
Self { Self {
transparent: false, transparent: false,
bg_normal: "#1e1e2e".to_string(), // base crust: "#11111b".to_string(),
bg_highlight: "#89b4fa".to_string(), // blue surface0: "#313244".to_string(),
bg_active: "#a6e3a1".to_string(), // green surface1: "#45475a".to_string(),
bg_search: "#cba6f7".to_string(), // mauve text: "#cdd6f4".to_string(),
fg_normal: "#cdd6f4".to_string(), // text blue: "#89b4fa".to_string(),
fg_dimmed: "#6c7086".to_string(), // overlay0 green: "#a6e3a1".to_string(),
fg_highlight: "#1e1e2e".to_string(), // base (dark for contrast against highlights) lavender: "#b4befe".to_string(),
fg_warning: "#f38ba8".to_string(), // red mauve: "#cba6f7".to_string(),
fg_modified: "#fab387".to_string(), // peach peach: "#fab387".to_string(),
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
} }
} }
} }
/// Custom keybindings for navigation and application control.
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(default)]
pub struct KeybindsConfig { pub struct KeybindsConfig {
pub down: String, pub down: String,
pub up: String, pub up: String,
@@ -109,11 +66,6 @@ pub struct KeybindsConfig {
pub save: String, pub save: String,
pub quit: String, pub quit: String,
pub normal_mode: String, pub normal_mode: String,
pub search: String,
pub next_match: String,
pub previous_match: String,
pub jump_top: String,
pub jump_bottom: String,
} }
impl Default for KeybindsConfig { impl Default for KeybindsConfig {
@@ -125,16 +77,10 @@ impl Default for KeybindsConfig {
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(),
next_match: "n".to_string(),
previous_match: "N".to_string(),
jump_top: "gg".to_string(),
jump_bottom: "G".to_string(),
} }
} }
} }
/// Root configuration structure for mould.
#[derive(Debug, Deserialize, Serialize, Default, Clone)] #[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct Config { pub struct Config {
#[serde(default)] #[serde(default)]
@@ -143,8 +89,6 @@ pub struct Config {
pub keybinds: KeybindsConfig, pub keybinds: KeybindsConfig,
} }
/// Loads the configuration from the user's home config directory (~/.config/mould/config.toml).
/// Falls back to default settings if no configuration is found.
pub fn load_config() -> Config { pub fn load_config() -> Config {
if let Some(mut config_dir) = dirs::config_dir() { if let Some(mut config_dir) = dirs::config_dir() {
config_dir.push("mould"); config_dir.push("mould");

View File

@@ -1,18 +0,0 @@
use std::io;
use thiserror::Error;
/// Custom error types for the mould application.
#[derive(Error, Debug)]
pub enum MouldError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Format error: {0}")]
Format(String),
#[error("File not found: {0}")]
FileNotFound(String),
#[error("Terminal error: {0}")]
Terminal(String),
}

View File

@@ -1,4 +1,4 @@
use super::{ConfigItem, FormatHandler, ItemStatus}; use super::{EnvVar, FormatHandler};
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<ConfigItem>> { fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
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,15 +18,10 @@ 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(ConfigItem { vars.push(EnvVar {
key: key.trim().to_string(), key: key.trim().to_string(),
path: key.trim().to_string(), value: parsed_val.clone(),
value: Some(parsed_val.clone()), default_value: parsed_val,
template_value: Some(parsed_val.clone()),
default_value: Some(parsed_val),
depth: 0,
is_group: false,
status: ItemStatus::Present,
}); });
} }
} }
@@ -34,7 +29,7 @@ impl FormatHandler for EnvHandler {
Ok(vars) Ok(vars)
} }
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> { fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()> {
if !path.exists() { if !path.exists() {
return Ok(()); return Ok(());
} }
@@ -51,44 +46,24 @@ 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) {
if var.value.as_deref() != Some(&parsed_val) { var.value = parsed_val;
var.value = Some(parsed_val);
var.status = ItemStatus::Modified;
}
} else { } else {
vars.push(ConfigItem { vars.push(EnvVar {
key: key.to_string(), key: key.to_string(),
path: key.to_string(), value: parsed_val.clone(),
value: Some(parsed_val), default_value: String::new(),
template_value: None,
default_value: None,
depth: 0,
is_group: false,
status: ItemStatus::MissingFromTemplate,
}); });
} }
} }
} }
// 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: &[ConfigItem]) -> io::Result<()> { fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
let mut file = fs::File::create(path)?; let mut file = fs::File::create(path)?;
for var in vars { for var in vars {
if !var.is_group { writeln!(file, "{}={}", var.key, var.value)?;
let val = var.value.as_deref()
.or(var.template_value.as_deref())
.unwrap_or("");
writeln!(file, "{}={}", var.key, val)?;
}
} }
Ok(()) Ok(())
} }
@@ -113,13 +88,14 @@ 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.as_deref(), Some("value1")); assert_eq!(vars[0].value, "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.as_deref(), Some("value2")); assert_eq!(vars[1].value, "value2");
assert_eq!(vars[2].key, "KEY3"); assert_eq!(vars[2].key, "KEY3");
assert_eq!(vars[2].value.as_deref(), Some("value3")); assert_eq!(vars[2].value, "value3");
assert_eq!(vars[3].key, "EMPTY"); assert_eq!(vars[3].key, "EMPTY");
assert_eq!(vars[3].value.as_deref(), Some("")); assert_eq!(vars[3].value, "");
} }
#[test] #[test]
@@ -136,29 +112,25 @@ 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.as_deref(), Some("custom1")); assert_eq!(vars[0].value, "custom1");
assert_eq!(vars[0].status, ItemStatus::Modified); assert_eq!(vars[0].default_value, "default1");
assert_eq!(vars[1].key, "KEY2"); assert_eq!(vars[1].key, "KEY2");
assert_eq!(vars[1].value.as_deref(), Some("default2")); assert_eq!(vars[1].value, "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.as_deref(), Some("custom3")); assert_eq!(vars[2].value, "custom3");
assert_eq!(vars[2].status, ItemStatus::MissingFromTemplate); assert_eq!(vars[2].default_value, "");
} }
#[test] #[test]
fn test_write_env() { fn test_write_env() {
let file = NamedTempFile::new().unwrap(); let file = NamedTempFile::new().unwrap();
let vars = vec![ConfigItem { let vars = vec![EnvVar {
key: "KEY1".to_string(), key: "KEY1".to_string(),
path: "KEY1".to_string(), value: "value1".to_string(),
value: Some("value1".to_string()), default_value: "def".to_string(),
template_value: None,
default_value: None,
depth: 0,
is_group: false,
status: ItemStatus::Present,
}]; }];
let handler = EnvHandler; let handler = EnvHandler;

View File

@@ -1,4 +1,4 @@
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus}; use super::{EnvVar, FormatHandler, FormatType};
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use std::fs; use std::fs;
use std::io; use std::io;
@@ -16,12 +16,9 @@ impl HierarchicalHandler {
fn read_value(&self, path: &Path) -> io::Result<Value> { fn read_value(&self, path: &Path) -> io::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))?,
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, FormatType::Yaml => serde_yaml::from_str(&content).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
FormatType::Yaml => serde_yaml::from_str(&content) FormatType::Toml => toml::from_str(&content).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
FormatType::Toml => toml::from_str(&content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
_ => unreachable!(), _ => unreachable!(),
}; };
Ok(value) Ok(value)
@@ -29,22 +26,15 @@ impl HierarchicalHandler {
fn write_value(&self, path: &Path, value: &Value) -> io::Result<()> { fn write_value(&self, path: &Path, value: &Value) -> io::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))?,
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, FormatType::Yaml => serde_yaml::to_string(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
FormatType::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
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))?;
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; toml::to_string_pretty(&toml_value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
toml::to_string_pretty(&toml_value)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
} else { } else {
return Err(io::Error::new( return Err(io::Error::new(io::ErrorKind::InvalidData, "Root of TOML must be an object"));
io::ErrorKind::InvalidData,
"Root of TOML must be an object",
));
} }
} }
_ => unreachable!(), _ => unreachable!(),
@@ -53,160 +43,95 @@ impl HierarchicalHandler {
} }
} }
fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) { fn flatten(value: &Value, prefix: &str, vars: &mut Vec<EnvVar>) {
let path = if prefix.is_empty() {
key_name.to_string()
} else if key_name.is_empty() {
prefix.to_string()
} 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,
});
}
let next_depth = if path.is_empty() { depth } else { depth + 1 };
for (k, v) in map { for (k, v) in map {
flatten(v, &path, next_depth, k, vars); let new_prefix = if prefix.is_empty() {
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,
});
}
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 array_key = format!("[{}]", i); let new_prefix = format!("{}[{}]", prefix, i);
flatten(v, &path, next_depth, &array_key, vars); flatten(v, &new_prefix, vars);
} }
} }
Value::String(s) => { Value::String(s) => {
vars.push(ConfigItem { vars.push(EnvVar {
key: key_name.to_string(), key: prefix.to_string(),
path: path.clone(), value: s.clone(),
value: Some(s.clone()), default_value: s.clone(),
template_value: Some(s.clone()),
default_value: Some(s.clone()),
depth,
is_group: false,
status: ItemStatus::Present,
}); });
} }
Value::Number(n) => { Value::Number(n) => {
let s = n.to_string(); let s = n.to_string();
vars.push(ConfigItem { vars.push(EnvVar {
key: key_name.to_string(), key: prefix.to_string(),
path: path.clone(), value: s.clone(),
value: Some(s.clone()), default_value: s.clone(),
template_value: Some(s.clone()),
default_value: Some(s.clone()),
depth,
is_group: false,
status: ItemStatus::Present,
}); });
} }
Value::Bool(b) => { Value::Bool(b) => {
let s = b.to_string(); let s = b.to_string();
vars.push(ConfigItem { vars.push(EnvVar {
key: key_name.to_string(), key: prefix.to_string(),
path: path.clone(), value: s.clone(),
value: Some(s.clone()), default_value: s.clone(),
template_value: Some(s.clone()),
default_value: Some(s.clone()),
depth,
is_group: false,
status: ItemStatus::Present,
}); });
} }
Value::Null => { Value::Null => {
vars.push(ConfigItem { vars.push(EnvVar {
key: key_name.to_string(), key: prefix.to_string(),
path: path.clone(), value: "".to_string(),
value: Some("".to_string()), default_value: "".to_string(),
template_value: Some("".to_string()),
default_value: Some("".to_string()),
depth,
is_group: false,
status: ItemStatus::Present,
}); });
} }
} }
} }
// 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<ConfigItem>> { fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
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, "", &mut vars);
Ok(vars) Ok(vars)
} }
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> { fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> 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, "", 0, "", &mut existing_vars); flatten(&existing_value, "", &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.path == var.path) { if let Some(existing) = existing_vars.iter().find(|v| v.key == var.key) {
if var.value != existing.value {
var.value = existing.value.clone(); 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: &[ConfigItem]) -> io::Result<()> { fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
// For writing hierarchical formats, we ideally want to preserve the original structure.
// But we don't have it here. We should parse the template again to get the structure!
// Oh wait, `write` is called with only `vars`.
// If we want to construct the tree from scratch, it's very difficult to guess array vs object
// and data types without the original template.
// Let's change the trait or just keep a copy of the template?
// Actually, if we require the user to have the template, we can just parse the template, update the leaves, and write.
// We'll write a reconstruction algorithm that just creates objects based on keys.
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 { insert_into_value(&mut root, &var.key, &var.value);
let val = var.value.as_deref()
.or(var.template_value.as_deref())
.unwrap_or("");
insert_into_value(&mut root, &var.path, val);
}
} }
self.write_value(path, &root) self.write_value(path, &root)
} }
@@ -265,9 +190,7 @@ fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str) {
}; };
if let Some(i) = final_idx { if let Some(i) = final_idx {
let next_node = map let next_node = map.entry(final_key.to_string()).or_insert_with(|| Value::Array(Vec::new()));
.entry(final_key.to_string())
.or_insert_with(|| Value::Array(Vec::new()));
if !next_node.is_array() { if !next_node.is_array() {
*next_node = Value::Array(Vec::new()); *next_node = Value::Array(Vec::new());
} }

View File

@@ -1,27 +1,14 @@
use std::io;
use std::path::Path; use std::path::Path;
use std::io;
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)] #[derive(Debug, Clone)]
pub struct ConfigItem { pub struct EnvVar {
pub key: String, pub key: String,
pub path: String, pub value: String,
pub value: Option<String>, pub default_value: String,
pub template_value: Option<String>,
pub default_value: Option<String>,
pub depth: usize,
pub is_group: bool,
pub status: ItemStatus,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -33,9 +20,9 @@ pub enum FormatType {
} }
pub trait FormatHandler { pub trait FormatHandler {
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>>; fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>>;
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()>; fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()>;
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>; fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()>;
} }
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType { pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {

View File

@@ -1,286 +1,104 @@
mod app; mod app;
mod cli; mod cli;
mod config; mod config;
mod error;
mod format; mod format;
mod runner; mod runner;
mod ui; mod ui;
use app::App; use app::App;
use config::load_config; use config::load_config;
use error::MouldError;
use format::{detect_format, get_handler}; use format::{detect_format, get_handler};
use log::{error, info, warn};
use runner::AppRunner; use runner::AppRunner;
use std::error::Error;
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crossterm::{ use crossterm::{
event::{DisableMouseCapture, EnableMouseCapture}, event::{DisableMouseCapture, EnableMouseCapture},
execute, execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
}; };
use ratatui::{Terminal, backend::CrosstermBackend}; use ratatui::{backend::CrosstermBackend, Terminal};
/// Helper to automatically determine the output file path based on common naming conventions.
fn determine_output_path(input: &Path) -> PathBuf { fn determine_output_path(input: &Path) -> PathBuf {
let file_name = input.file_name().unwrap_or_default().to_string_lossy(); let file_name = input.file_name().unwrap_or_default().to_string_lossy();
if file_name == ".env.example" {
// Standard mappings
if file_name == ".env.example" || file_name == ".env.template" {
return input.with_file_name(".env"); return input.with_file_name(".env");
} }
if file_name == "docker-compose.yml" {
if file_name == "docker-compose.yml" || file_name == "compose.yml" { return input.with_file_name("docker-compose.override.yml");
return input.with_file_name("compose.override.yml");
} }
if file_name == "docker-compose.yaml" || file_name == "compose.yaml" { if file_name == "docker-compose.yaml" {
return input.with_file_name("compose.override.yaml"); return input.with_file_name("docker-compose.override.yaml");
} }
if file_name.ends_with(".example.json") {
// Pattern-based mappings return input.with_file_name(file_name.replace(".example.json", ".json"));
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") { if file_name.ends_with(".template.json") {
return input.with_file_name(format!("{}.env", base)); return input.with_file_name(file_name.replace(".template.json", ".json"));
} }
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!( input.with_extension(format!(
"{}.out", "{}.out",
input.extension().unwrap_or_default().to_string_lossy() input.extension().unwrap_or_default().to_string_lossy()
)) ))
} }
/// Discovers common configuration template files in the current directory. fn main() -> Result<(), Box<dyn Error>> {
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<()> {
let args = cli::parse(); let args = cli::parse();
// Initialize logger with verbosity from CLI let input_path = args.input;
let log_level = match args.verbose { if !input_path.exists() {
0 => log::LevelFilter::Warn, println!("Input file does not exist: {}", input_path.display());
1 => log::LevelFilter::Info, return Ok(());
_ => log::LevelFilter::Debug,
};
env_logger::Builder::new()
.filter_level(log_level)
.format_timestamp(None)
.init();
let input_path = match args.input {
Some(path) => {
if !path.exists() {
error!("Input file not found: {}", path.display());
return Err(MouldError::FileNotFound(path.display().to_string()).into());
} }
path
}
None => match find_input_file() {
Some(path) => {
info!("Discovered template: {}", path.display());
path
}
None => {
error!("No template file provided and none discovered in current directory.");
println!("Usage: mould <INPUT_FILE>");
println!("Supported defaults: .env.example, compose.yml, docker-compose.yml, etc.");
return Err(MouldError::FileNotFound("None".to_string()).into());
}
},
};
info!("Input: {}", input_path.display());
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 input_name = input_path.file_name().unwrap_or_default().to_string_lossy();
let is_template_input = input_name.contains(".example") || input_name.contains(".template") || input_name == "compose.yml" || input_name == "docker-compose.yml";
let mut template_path = None;
let mut active_path = None;
if is_template_input {
template_path = Some(input_path.clone());
let expected_active = determine_output_path(&input_path);
if expected_active.exists() {
active_path = Some(expected_active);
}
} else {
// Input is likely an active config (e.g., .env)
active_path = Some(input_path.clone());
// Try to find a template
let possible_templates = [
format!("{}.example", input_name),
format!("{}.template", input_name),
];
for t in possible_templates {
let p = input_path.with_file_name(t);
if p.exists() {
template_path = Some(p);
break;
}
}
}
let output_path = args let output_path = args
.output .output
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| determine_output_path(&input_path))); .unwrap_or_else(|| determine_output_path(&input_path));
info!("Output: {}", output_path.display()); let mut vars = handler.parse(&input_path).unwrap_or_else(|err| {
println!("Error parsing input file: {}", err);
// 1. Load active config if it exists vec![]
let mut vars = if let Some(active) = &active_path { });
handler.parse(active).unwrap_or_default()
} else {
Vec::new()
};
// 2. Load template config and merge
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 vars.is_empty() { if vars.is_empty() {
warn!("No variables found."); println!(
"No variables found in {} or file could not be parsed.",
input_path.display()
);
return Ok(());
}
if let Err(e) = handler.merge(&output_path, &mut vars) {
println!("Warning: Could not merge existing output file: {}", e);
} }
let config = load_config(); let config = load_config();
let mut app = App::new(vars); let mut app = App::new(vars);
// Terminal lifecycle enable_raw_mode()?;
enable_raw_mode()
.map_err(|e| MouldError::Terminal(format!("Failed to enable raw mode: {}", e)))?;
let mut stdout = io::stdout(); let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture) execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
.map_err(|e| MouldError::Terminal(format!("Failed to enter alternate screen: {}", e)))?;
let backend = CrosstermBackend::new(stdout); let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend) let mut terminal = Terminal::new(backend)?;
.map_err(|e| MouldError::Terminal(format!("Failed to create terminal backend: {}", e)))?;
let mut runner = AppRunner::new( let mut runner = AppRunner::new(&mut terminal, &mut app, &config, &output_path, handler.as_ref());
&mut terminal,
&mut app,
&config,
&output_path,
handler.as_ref(),
);
let res = runner.run(); let res = runner.run();
// Restoration disable_raw_mode()?;
disable_raw_mode().ok();
execute!( execute!(
terminal.backend_mut(), terminal.backend_mut(),
LeaveAlternateScreen, LeaveAlternateScreen,
DisableMouseCapture DisableMouseCapture
) )?;
.ok(); terminal.show_cursor()?;
terminal.show_cursor().ok();
if let Err(err) = res {
println!("{:?}", err);
}
match res {
Ok(_) => {
info!("Successfully finished mould session.");
Ok(()) Ok(())
} }
Err(e) => {
error!("Application error during run: {}", e);
Err(e.into())
}
}
}

View File

@@ -2,35 +2,25 @@ use crate::app::{App, Mode};
use crate::config::Config; use crate::config::Config;
use crate::format::FormatHandler; use crate::format::FormatHandler;
use crossterm::event::{self, Event, KeyCode, KeyEvent}; use crossterm::event::{self, Event, KeyCode, KeyEvent};
use ratatui::Terminal;
use ratatui::backend::Backend; use ratatui::backend::Backend;
use ratatui::Terminal;
use std::io; use std::io;
use std::path::Path; use std::path::Path;
use tui_input::backend::crossterm::EventHandler; use tui_input::backend::crossterm::EventHandler;
/// Manages the main application execution loop, event handling, and terminal interaction.
pub struct AppRunner<'a, B: Backend> { pub struct AppRunner<'a, B: Backend> {
/// Reference to the terminal instance.
terminal: &'a mut Terminal<B>, terminal: &'a mut Terminal<B>,
/// Mutable reference to the application state.
app: &'a mut App, app: &'a mut App,
/// Loaded user configuration.
config: &'a Config, config: &'a Config,
/// Path where the final configuration will be saved.
output_path: &'a Path, output_path: &'a Path,
/// Handler for the specific file format (env, json, yaml, toml).
handler: &'a dyn FormatHandler, handler: &'a dyn FormatHandler,
/// 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>
where where
io::Error: From<B::Error>, io::Error: From<B::Error>,
{ {
/// Creates a new runner instance.
pub fn new( pub fn new(
terminal: &'a mut Terminal<B>, terminal: &'a mut Terminal<B>,
app: &'a mut App, app: &'a mut App,
@@ -45,15 +35,12 @@ where
output_path, output_path,
handler, handler,
command_buffer: String::new(), command_buffer: String::new(),
key_sequence: String::new(),
} }
} }
/// Starts the main application loop.
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.draw(|f| crate::ui::draw(f, self.app, self.config))?;
.draw(|f| crate::ui::draw(f, self.app, self.config))?;
if let Event::Key(key) = event::read()? { if let Event::Key(key) = event::read()? {
self.handle_key_event(key)?; self.handle_key_event(key)?;
@@ -62,16 +49,13 @@ where
Ok(()) Ok(())
} }
/// Primary dispatcher for all keyboard events.
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::Search => self.handle_search_mode(key),
} }
} }
/// Handles keys in Normal mode, separating navigation from command entry.
fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> { fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> {
if !self.command_buffer.is_empty() { if !self.command_buffer.is_empty() {
self.handle_command_mode(key) self.handle_command_mode(key)
@@ -80,7 +64,6 @@ where
} }
} }
/// Logic for entering and executing ":" style commands.
fn handle_command_mode(&mut self, key: KeyEvent) -> io::Result<()> { fn handle_command_mode(&mut self, key: KeyEvent) -> io::Result<()> {
match key.code { match key.code {
KeyCode::Enter => { KeyCode::Enter => {
@@ -107,94 +90,32 @@ where
} }
} }
/// 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 {
self.key_sequence.push(c); let c_str = c.to_string();
if c_str == self.config.keybinds.down {
// Collect all configured keybinds self.app.next();
let binds = [ } else if c_str == self.config.keybinds.up {
(&self.config.keybinds.down, "down"), self.app.previous();
(&self.config.keybinds.up, "up"), } else if c_str == self.config.keybinds.edit {
(&self.config.keybinds.edit, "edit"), self.app.enter_insert();
(&self.config.keybinds.search, "search"), } else if c_str == ":" {
(&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"),
(&"a".to_string(), "add_missing"),
(&":".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(),
"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(),
"add_missing" => self.add_missing_item(),
"command" => {
self.command_buffer.push(':'); self.command_buffer.push(':');
self.sync_command_status(); self.sync_command_status();
} } else if c_str == "q" {
"quit" => self.app.running = false, 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.
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 | KeyCode::Enter => {
@@ -207,29 +128,6 @@ where
Ok(()) Ok(())
} }
/// Handles search mode key events.
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
match key.code {
KeyCode::Enter | KeyCode::Esc => {
self.app.mode = Mode::Normal;
self.app.status_message = None;
}
KeyCode::Backspace => {
self.app.search_query.pop();
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
self.app.jump_next_match();
}
KeyCode::Char(c) => {
self.app.search_query.push(c);
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
self.app.jump_next_match();
}
_ => {}
}
Ok(())
}
/// Logic to map command strings (like ":w") to internal application actions.
fn execute_command(&mut self, cmd: &str) -> io::Result<()> { fn execute_command(&mut self, cmd: &str) -> io::Result<()> {
if cmd == self.config.keybinds.save { if cmd == self.config.keybinds.save {
self.save_file() self.save_file()
@@ -246,7 +144,6 @@ where
} }
} }
/// Attempts to write the current app state to the specified output file.
fn save_file(&mut self) -> io::Result<()> { fn save_file(&mut self) -> io::Result<()> {
if self.handler.write(self.output_path, &self.app.vars).is_ok() { if self.handler.write(self.output_path, &self.app.vars).is_ok() {
self.app.status_message = Some(format!("Saved to {}", self.output_path.display())); self.app.status_message = Some(format!("Saved to {}", self.output_path.display()));
@@ -256,7 +153,6 @@ where
Ok(()) Ok(())
} }
/// Synchronizes the status bar display with the active command buffer.
fn sync_command_status(&mut self) { fn sync_command_status(&mut self) {
if self.command_buffer.is_empty() { if self.command_buffer.is_empty() {
self.app.status_message = None; self.app.status_message = None;

247
src/ui.rs
View File

@@ -1,242 +1,139 @@
use crate::app::{App, Mode}; use crate::app::{App, Mode};
use crate::config::Config; use crate::config::Config;
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Direction, Layout}, layout::{Constraint, Direction, Layout},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph}, widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
Frame,
}; };
/// Renders the main application interface using ratatui.
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). // Background
if !theme.transparent { if !theme.transparent {
f.render_widget( f.render_widget(Block::default().style(Style::default().bg(theme.crust())), size);
Block::default().style(Style::default().bg(theme.bg_normal())),
size,
);
} }
// Horizontal layout with 1-character side margins. // Main layout with horizontal padding
let outer_layout = Layout::default() let outer_layout = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([ .constraints([
Constraint::Length(1), Constraint::Length(1), // Left padding
Constraint::Min(0), Constraint::Min(0), // Content
Constraint::Length(1), Constraint::Length(1), // Right padding
]) ])
.split(size); .split(size);
// Vertical layout for the main UI components.
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 padding
Constraint::Min(3), // Main list Constraint::Min(3), // List
Constraint::Length(3), // Focused input field Constraint::Length(3), // Input area
Constraint::Length(1), // Spacer Constraint::Length(1), // Bottom padding
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. let max_key_len = app
let matching_indices = app.matching_indices(); .vars
.iter()
.map(|v| v.key.len())
.max()
.unwrap_or(20)
.min(40);
// List
let items: Vec<ListItem> = app let items: Vec<ListItem> = app
.vars .vars
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, var)| { .map(|(i, var)| {
let is_selected = i == app.selected; let is_selected = i == app.selected;
let is_match = matching_indices.contains(&i);
// Indentation based on depth
let indent = " ".repeat(var.depth);
let prefix = if var.is_group { "+ " } else { " " };
// Determine colors based on depth
let depth_color = if is_selected {
theme.bg_normal()
} else {
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 {
Style::default()
.fg(theme.fg_highlight())
.add_modifier(Modifier::BOLD)
} else if is_match {
Style::default()
.fg(theme.bg_search())
.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 {
Style::default().fg(depth_color)
};
let mut key_spans = vec![
Span::raw(indent),
Span::styled(prefix, Style::default().fg(theme.border_normal())),
Span::styled(&var.key, key_style),
];
// Add status indicator if not present (only for leaf variables)
if !var.is_group {
match var.status {
crate::format::ItemStatus::MissingFromActive => {
let missing_style = if is_selected {
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD)
};
key_spans.push(Span::styled(" (missing)", missing_style));
}
crate::format::ItemStatus::Modified => {
if !is_selected {
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
}
}
_ => {}
}
}
let item_style = if is_selected {
Style::default().bg(theme.bg_highlight())
} else {
Style::default().fg(text_color)
};
if var.is_group {
ListItem::new(Line::from(key_spans)).style(item_style)
} else {
// Show live input text for the selected item if in Insert mode.
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 {
var.value.as_deref().unwrap_or("") &var.value
};
let key_style = if is_selected {
Style::default().fg(theme.crust()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.lavender())
}; };
let value_style = if is_selected { let value_style = if is_selected {
Style::default().fg(theme.fg_highlight()) Style::default().fg(theme.crust())
} else { } else {
Style::default().fg(theme.fg_normal()) Style::default().fg(theme.text())
}; };
let mut val_spans = vec![ let line = Line::from(vec![
Span::raw(format!("{} └─ ", " ".repeat(var.depth))), Span::styled(format!(" {:<width$} ", var.key, width = max_key_len), key_style),
Span::styled(val, value_style), Span::styled("", Style::default().fg(theme.surface1())),
]; Span::styled(format!(" {} ", val), value_style),
]);
if let Some(t_val) = &var.template_value { let item_style = if is_selected {
if Some(t_val) != var.value.as_ref() { Style::default().bg(theme.blue())
let t_style = if is_selected {
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
} else { } else {
Style::default().fg(theme.fg_dimmed()).add_modifier(Modifier::ITALIC) Style::default().fg(theme.text())
}; };
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(line).style(item_style)
}
}) })
.collect(); .collect();
let list = List::new(items).block( let list = List::new(items)
.block(
Block::default() Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.title(" Config Variables ") .title(" Config Variables ")
.title_style( .title_style(Style::default().fg(theme.mauve()).add_modifier(Modifier::BOLD))
Style::default() .border_style(Style::default().fg(theme.surface1())),
.fg(theme.fg_accent())
.add_modifier(Modifier::BOLD),
)
.border_style(Style::default().fg(theme.border_normal())),
); );
let mut state = ListState::default(); let mut state = ListState::default();
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. // Input Area
let current_var = app.vars.get(app.selected); let current_var = app.vars.get(app.selected);
let mut input_title = " Input ".to_string(); let input_title = if let Some(var) = current_var {
let mut extra_info = String::new(); if var.default_value.is_empty() {
format!(" Editing: {} ", var.key)
if let Some(var) = current_var {
if var.is_group {
input_title = format!(" Group: {} ", var.path);
} else { } else {
input_title = format!(" Editing: {} ", var.path); format!(" Editing: {} (Default: {}) ", var.key, var.default_value)
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.border_active(), Mode::Insert => theme.green(),
Mode::Normal | Mode::Search => theme.border_normal(), Mode::Normal => theme.surface1(),
}; };
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 input = Paragraph::new(input_text)
let display_text = if let Some(var) = current_var { .style(Style::default().fg(theme.text()))
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)
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.title(input_title) .title(input_title)
.title_style( .title_style(Style::default().fg(theme.peach()).add_modifier(Modifier::BOLD))
Style::default()
.fg(theme.fg_accent()) // Make title pop
.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.
if let Mode::Insert = app.mode { if let Mode::Insert = app.mode {
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,
@@ -244,48 +141,36 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
)); ));
} }
// Render the modern pill-style status bar. // Status bar
let (mode_str, mode_style) = match app.mode { let (mode_str, mode_style) = match app.mode {
Mode::Normal => ( Mode::Normal => (
" NORMAL ", " NORMAL ",
Style::default() Style::default()
.bg(theme.bg_highlight()) .bg(theme.blue())
.fg(theme.bg_normal()) .fg(theme.crust())
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
), ),
Mode::Insert => ( Mode::Insert => (
" INSERT ", " INSERT ",
Style::default() Style::default()
.bg(theme.bg_active()) .bg(theme.green())
.fg(theme.bg_normal()) .fg(theme.crust())
.add_modifier(Modifier::BOLD),
),
Mode::Search => (
" SEARCH ",
Style::default()
.bg(theme.bg_search())
.fg(theme.bg_normal())
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
), ),
}; };
let status_msg = app let status_msg = app.status_message.as_deref().unwrap_or_else(|| {
.status_message match app.mode {
.as_deref() Mode::Normal => " navigation | i: edit | :w: save | :q: quit ",
.unwrap_or_else(|| match app.mode {
Mode::Normal => " navigation | i: edit | /: search | :w: save | :q: quit ",
Mode::Insert => " Esc: back to normal | Enter: commit ", Mode::Insert => " Esc: back to normal | Enter: commit ",
Mode::Search => " Esc: back to normal | type to filter ", }
}); });
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), Style::default().bg(theme.surface0()).fg(theme.text())),
format!(" {} ", status_msg),
Style::default().bg(theme.border_normal()).fg(theme.fg_normal()),
),
]); ]);
let status = Paragraph::new(status_line).style(Style::default().bg(theme.border_normal())); let status = Paragraph::new(status_line).style(Style::default().bg(theme.surface0()));
f.render_widget(status, chunks[4]); f.render_widget(status, chunks[4]);
} }