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
11 changed files with 78 additions and 276 deletions

88
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"
@@ -855,18 +784,14 @@ dependencies = [
name = "mould" name = "mould"
version = "0.2.0" 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,6 +1,6 @@
[package] [package]
name = "mould" name = "mould"
version = "0.2.1" version = "0.2.0"
edition = "2024" edition = "2024"
authors = ["Nils Pukropp <nils@narl.io>"] authors = ["Nils Pukropp <nils@narl.io>"]
@@ -9,17 +9,13 @@ name = "mould"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
anyhow = "1.0.102"
clap = { version = "4.6.0", features = ["derive"] } 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 = { 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"

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

@@ -1,32 +1,21 @@
use crate::format::EnvVar; 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,
} }
/// 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<EnvVar>,
/// 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,
} }
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<EnvVar>) -> Self {
let initial_input = vars.get(0).map(|v| v.value.clone()).unwrap_or_default(); let initial_input = vars.get(0).map(|v| v.value.clone()).unwrap_or_default();
Self { Self {
@@ -39,7 +28,6 @@ impl App {
} }
} }
/// 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();
@@ -47,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 {
@@ -59,29 +46,30 @@ impl App {
} }
} }
/// 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()); self.input = Input::new(var.value.clone());
} }
} }
/// 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(); var.value = self.input.value().to_string();
} }
} }
/// Transitions the application into Insert Mode.
pub fn enter_insert(&mut self) { pub fn enter_insert(&mut self) {
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 = true, value_name = "INPUT_FILE")]
pub input: PathBuf, pub input: 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

@@ -2,34 +2,22 @@ use serde::{Deserialize, Serialize};
use std::fs; use std::fs;
use ratatui::style::Color; use ratatui::style::Color;
/// Configuration for the application's appearance.
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ThemeConfig { pub struct ThemeConfig {
/// If true, skip rendering the background block to let the terminal's transparency show.
#[serde(default)] #[serde(default)]
pub transparent: bool, pub transparent: bool,
/// Color for standard background areas (when not transparent).
pub crust: String, pub crust: String,
/// Dark surface color for UI elements like the status bar.
pub surface0: String, pub surface0: String,
/// Light surface color for borders and dividers.
pub surface1: String, pub surface1: String,
/// Default text color.
pub text: String, pub text: String,
/// Color for selection highlighting and normal mode tag.
pub blue: String, pub blue: String,
/// Color for insert mode highlighting and success status.
pub green: String, pub green: String,
/// Accent color for configuration keys.
pub lavender: String, pub lavender: String,
/// Accent color for primary section titles.
pub mauve: String, pub mauve: String,
/// Accent color for input field titles.
pub peach: String, pub peach: 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 {
@@ -54,7 +42,6 @@ impl ThemeConfig {
} }
impl Default for ThemeConfig { impl Default for ThemeConfig {
/// Default theme: Catppuccin Mocha.
fn default() -> Self { fn default() -> Self {
Self { Self {
transparent: false, transparent: false,
@@ -71,7 +58,6 @@ impl Default for ThemeConfig {
} }
} }
/// Custom keybindings for navigation and application control.
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
pub struct KeybindsConfig { pub struct KeybindsConfig {
pub down: String, pub down: String,
@@ -95,7 +81,6 @@ impl Default for KeybindsConfig {
} }
} }
/// 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)]
@@ -104,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 thiserror::Error;
use std::io;
/// 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

@@ -121,6 +121,14 @@ impl FormatHandler for HierarchicalHandler {
} }
fn write(&self, path: &Path, vars: &[EnvVar]) -> 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 {
insert_into_value(&mut root, &var.key, &var.value); insert_into_value(&mut root, &var.key, &var.value);

View File

@@ -1,17 +1,15 @@
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};
@@ -22,56 +20,38 @@ use crossterm::{
}; };
use ratatui::{backend::CrosstermBackend, Terminal}; 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" { if file_name == ".env.example" {
return input.with_file_name(".env"); return input.with_file_name(".env");
} }
if file_name == "docker-compose.yml" { if file_name == "docker-compose.yml" {
return input.with_file_name("docker-compose.override.yml"); return input.with_file_name("docker-compose.override.yml");
} }
if file_name == "docker-compose.yaml" { if file_name == "docker-compose.yaml" {
return input.with_file_name("docker-compose.override.yaml"); return input.with_file_name("docker-compose.override.yaml");
} }
if file_name.ends_with(".example.json") { if file_name.ends_with(".example.json") {
return input.with_file_name(file_name.replace(".example.json", ".json")); return input.with_file_name(file_name.replace(".example.json", ".json"));
} }
if file_name.ends_with(".template.json") { if file_name.ends_with(".template.json") {
return input.with_file_name(file_name.replace(".template.json", ".json")); return input.with_file_name(file_name.replace(".template.json", ".json"));
} }
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()
)) ))
} }
fn main() -> anyhow::Result<()> { fn main() -> Result<(), Box<dyn Error>> {
let args = cli::parse(); let args = cli::parse();
// Initialize logger with verbosity from CLI
let log_level = match args.verbose {
0 => log::LevelFilter::Warn,
1 => log::LevelFilter::Info,
_ => log::LevelFilter::Debug,
};
env_logger::Builder::new()
.filter_level(log_level)
.format_timestamp(None)
.init();
let input_path = args.input; let input_path = args.input;
if !input_path.exists() { if !input_path.exists() {
error!("Input file not found: {}", input_path.display()); println!("Input file does not exist: {}", input_path.display());
return Err(MouldError::FileNotFound(input_path.display().to_string()).into()); return Ok(());
} }
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);
@@ -79,53 +59,46 @@ fn main() -> anyhow::Result<()> {
.output .output
.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);
let mut vars = handler.parse(&input_path).map_err(|e| { vec![]
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 in {}", input_path.display()); 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) { if let Err(e) = handler.merge(&output_path, &mut vars) {
warn!("Could not merge existing output file: {}", e); 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(&mut terminal, &mut app, &config, &output_path, handler.as_ref()); let mut runner = AppRunner::new(&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().ok(); terminal.show_cursor()?;
match res { if let Err(err) = res {
Ok(_) => { println!("{:?}", err);
info!("Successfully finished mould session.");
Ok(())
},
Err(e) => {
error!("Application error during run: {}", e);
Err(e.into())
}
} }
Ok(())
} }

View File

@@ -8,19 +8,12 @@ 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,
} }
@@ -28,7 +21,6 @@ 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,
@@ -46,11 +38,9 @@ where
} }
} }
/// 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)?;
@@ -59,7 +49,6 @@ 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),
@@ -67,7 +56,6 @@ where
} }
} }
/// 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)
@@ -76,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 => {
@@ -103,7 +90,6 @@ 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 {
let c_str = c.to_string(); let c_str = c.to_string();
@@ -130,7 +116,6 @@ where
Ok(()) Ok(())
} }
/// 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 => {
@@ -143,7 +128,6 @@ where
Ok(()) 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()
@@ -160,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()));
@@ -170,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;

View File

@@ -8,42 +8,36 @@ use ratatui::{
Frame, 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.crust())),
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]);
// Calculate alignment for the key-value separator based on the longest key.
let max_key_len = app let max_key_len = app
.vars .vars
.iter() .iter()
@@ -52,7 +46,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
.unwrap_or(20) .unwrap_or(20)
.min(40); .min(40);
// Build the interactive list of configuration variables. // List
let items: Vec<ListItem> = app let items: Vec<ListItem> = app
.vars .vars
.iter() .iter()
@@ -60,7 +54,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
.map(|(i, var)| { .map(|(i, var)| {
let is_selected = i == app.selected; let is_selected = i == app.selected;
// 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 {
@@ -68,9 +61,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
}; };
let key_style = if is_selected { let key_style = if is_selected {
Style::default() Style::default().fg(theme.crust()).add_modifier(Modifier::BOLD)
.fg(theme.crust())
.add_modifier(Modifier::BOLD)
} else { } else {
Style::default().fg(theme.lavender()) Style::default().fg(theme.lavender())
}; };
@@ -82,10 +73,7 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
}; };
let line = Line::from(vec![ let line = Line::from(vec![
Span::styled( Span::styled(format!(" {:<width$} ", var.key, width = max_key_len), key_style),
format!(" {:<width$} ", var.key, width = max_key_len),
key_style,
),
Span::styled("", Style::default().fg(theme.surface1())), Span::styled("", Style::default().fg(theme.surface1())),
Span::styled(format!(" {} ", val), value_style), Span::styled(format!(" {} ", val), value_style),
]); ]);
@@ -100,20 +88,21 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
}) })
.collect(); .collect();
let list = List::new(items).block( let list = List::new(items)
Block::default() .block(
.borders(Borders::ALL) Block::default()
.border_type(BorderType::Rounded) .borders(Borders::ALL)
.title(" Config Variables ") .border_type(BorderType::Rounded)
.title_style(Style::default().fg(theme.mauve()).add_modifier(Modifier::BOLD)) .title(" Config Variables ")
.border_style(Style::default().fg(theme.surface1())), .title_style(Style::default().fg(theme.mauve()).add_modifier(Modifier::BOLD))
); .border_style(Style::default().fg(theme.surface1())),
);
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 input_title = if let Some(var) = current_var { let input_title = if let Some(var) = current_var {
if var.default_value.is_empty() { if var.default_value.is_empty() {
@@ -145,7 +134,6 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
); );
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,
@@ -153,7 +141,7 @@ 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 ",
@@ -171,17 +159,16 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
), ),
}; };
let status_msg = app.status_message.as_deref().unwrap_or_else(|| match app.mode { let status_msg = app.status_message.as_deref().unwrap_or_else(|| {
Mode::Normal => " navigation | i: edit | :w: save | :q: quit ", match app.mode {
Mode::Insert => " Esc: back to normal | Enter: commit ", Mode::Normal => " navigation | i: edit | :w: save | :q: quit ",
Mode::Insert => " Esc: back to normal | Enter: commit ",
}
}); });
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.surface0()).fg(theme.text()),
),
]); ]);
let status = Paragraph::new(status_line).style(Style::default().bg(theme.surface0())); let status = Paragraph::new(status_line).style(Style::default().bg(theme.surface0()));