updated clap output
Some checks failed
Version Check / check-version (pull_request) Failing after 3s

This commit is contained in:
2026-03-16 17:57:44 +01:00
parent e72fdd9fcb
commit f413d5e2eb
5 changed files with 168 additions and 42 deletions

View File

@@ -3,18 +3,29 @@ use std::path::PathBuf;
/// mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)
#[derive(Parser, Debug)]
#[command(author, version, about)]
#[command(
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 {
/// The input template file (e.g., .env.example, config.json.template, docker-compose.yml)
#[arg(required = true, value_name = "INPUT_FILE")]
pub input: PathBuf,
/// Optional output file. If not provided, it will be inferred.
#[arg(short, long)]
#[arg(short, long, value_name = "OUTPUT_FILE")]
pub output: Option<PathBuf>,
/// Override the format detection (env, json, yaml, toml)
#[arg(short, long)]
#[arg(short, long, value_name = "FORMAT", value_parser = ["env", "json", "yaml", "toml"])]
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.

18
src/error.rs Normal file
View File

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

@@ -1,15 +1,17 @@
mod app;
mod cli;
mod config;
mod error;
mod format;
mod runner;
mod ui;
use app::App;
use config::load_config;
use error::MouldError;
use format::{detect_format, get_handler};
use log::{error, info, warn};
use runner::AppRunner;
use std::error::Error;
use std::io;
use std::path::{Path, PathBuf};
@@ -24,12 +26,10 @@ use ratatui::{backend::CrosstermBackend, Terminal};
fn determine_output_path(input: &Path) -> PathBuf {
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
// .env.example -> .env
if file_name == ".env.example" {
return input.with_file_name(".env");
}
// docker-compose.yml -> docker-compose.override.yml
if file_name == "docker-compose.yml" {
return input.with_file_name("docker-compose.override.yml");
}
@@ -37,7 +37,6 @@ fn determine_output_path(input: &Path) -> PathBuf {
return input.with_file_name("docker-compose.override.yaml");
}
// config.example.json -> config.json
if file_name.ends_with(".example.json") {
return input.with_file_name(file_name.replace(".example.json", ".json"));
}
@@ -45,78 +44,88 @@ fn determine_output_path(input: &Path) -> PathBuf {
return input.with_file_name(file_name.replace(".template.json", ".json"));
}
// Fallback: append .out to the extension
input.with_extension(format!(
"{}.out",
input.extension().unwrap_or_default().to_string_lossy()
))
}
fn main() -> Result<(), Box<dyn Error>> {
// Parse CLI arguments
fn main() -> anyhow::Result<()> {
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;
if !input_path.exists() {
println!("Input file does not exist: {}", input_path.display());
return Ok(());
error!("Input file not found: {}", input_path.display());
return Err(MouldError::FileNotFound(input_path.display().to_string()).into());
}
// Detect format and select appropriate handler
info!("Input: {}", input_path.display());
let format_type = detect_format(&input_path, args.format);
let handler = get_handler(format_type);
// Determine where to save the result
let output_path = args
.output
.unwrap_or_else(|| determine_output_path(&input_path));
// Initial parsing of the template file
let mut vars = handler.parse(&input_path).unwrap_or_else(|err| {
println!("Error parsing input file: {}", err);
vec![]
});
info!("Output: {}", output_path.display());
let mut 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() {
println!(
"No variables found in {} or file could not be parsed.",
input_path.display()
);
return Ok(());
warn!("No variables found in {}", input_path.display());
}
// Merge values from an existing output file if it exists
if let Err(e) = handler.merge(&output_path, &mut vars) {
println!("Warning: Could not merge existing output file: {}", e);
warn!("Could not merge existing output file: {}", e);
}
// Load user configuration and initialize application state
let config = load_config();
let mut app = App::new(vars);
// Initialize terminal into raw mode and enter alternate screen
enable_raw_mode()?;
// Terminal lifecycle
enable_raw_mode().map_err(|e| MouldError::Terminal(format!("Failed to enable raw mode: {}", e)))?;
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 mut terminal = Terminal::new(backend)?;
let mut terminal = Terminal::new(backend)
.map_err(|e| MouldError::Terminal(format!("Failed to create terminal backend: {}", e)))?;
// Instantiate the runner and start the application loop
let mut runner = AppRunner::new(&mut terminal, &mut app, &config, &output_path, handler.as_ref());
let res = runner.run();
// Clean up terminal state on exit
disable_raw_mode()?;
// Restoration
disable_raw_mode().ok();
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
).ok();
terminal.show_cursor().ok();
if let Err(err) = res {
println!("{:?}", err);
match res {
Ok(_) => {
info!("Successfully finished mould session.");
Ok(())
},
Err(e) => {
error!("Application error during run: {}", e);
Err(e.into())
}
}
Ok(())
}