mod prompter; mod reporter; mod style; use std::env; use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use crate::prompter::TerminalPrompter; use crate::reporter::ConsoleReporter; use clap::{Args, Parser, Subcommand, ValueEnum}; use indexmap::IndexMap; use roneo_core::config::{json_display, parse_yaml_cli_value, parse_yaml_mapping}; use roneo_core::{ ConflictMode, CopyOptions, ExtensionRegistry, NonInteractivePrompter, OperationReport, Prompter, ResolvedTemplate, RoneoError, WasmExtension, check_update, copy, diff_update, recopy, update, }; #[derive(Debug, Parser)] #[command( name = "roneo", version, about = "Fast, nimble Rust port of Copier for scaffolding and updating project templates", propagate_version = true )] struct Cli { #[command(subcommand)] command: Commands, } #[derive(Debug, Subcommand)] enum Commands { /// Copy a template into a destination directory Copy { /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`) template: String, /// Destination directory (defaults to current directory) #[arg(default_value = ".")] destination: PathBuf, /// On error, do not delete the destination directory if it was created by Roneo (Copier `-C`) #[arg(short = 'C', long)] no_cleanup: bool, #[command(flatten)] opts: SharedOpts, }, /// Smart-update a git-tracked project from its template via 3-way merge Update { /// Destination project directory (defaults to current directory) #[arg(default_value = ".")] destination: PathBuf, /// How to record merge conflicts (`inline` markers or `.rej` files) #[arg(short = 'o', long, value_enum, default_value_t = CliConflictMode::Inline)] conflict: CliConflictMode, /// Lines of context to use for detecting conflicts (Copier `-c`, default 3) #[arg(short = 'c', long, default_value_t = 3)] context_lines: usize, /// Skip clean-working-tree git check (advanced) #[arg(long)] skip_git_check: bool, #[command(flatten)] opts: SharedOpts, }, /// Re-apply a template onto an existing project using saved answers (no 3-way merge) Recopy { /// Destination project directory (defaults to current directory) #[arg(default_value = ".")] destination: PathBuf, /// Optional template source override (defaults to `_src_path` in answers file) #[arg(long)] src: Option, #[command(flatten)] opts: SharedOpts, }, /// Preview the 3-way unified diff that `roneo update` would apply without modifying files Diff { /// Destination project directory (defaults to current directory) #[arg(default_value = ".")] destination: PathBuf, /// Lines of context to include in the unified diff (default 3) #[arg(short = 'c', long, default_value_t = 3)] context_lines: usize, #[command(flatten)] opts: SharedOpts, }, /// Check if a project is using the latest version of its template (Copier `check-update`) CheckUpdate { /// Destination project directory (defaults to current directory) #[arg(default_value = ".")] destination: PathBuf, /// Custom answers file path relative to destination #[arg(short = 'a', long)] answers_file: Option, /// Allow pre-release VCS tags (PEP 440) when comparing versions #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")] prereleases: bool, /// Output format (`plain` or `json`) #[arg(long = "output-format", value_enum, default_value_t = CheckUpdateFormat::Plain)] output_format: CheckUpdateFormat, /// Suppress status output; exit with code 2 when a new template version is available #[arg(short = 'q', long)] quiet: bool, }, /// Inspect a template's configuration, questions, settings, and tasks without copying Inspect { /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`) template: String, /// Git ref (branch, tag, or commit) to inspect #[arg(short = 'r', long)] vcs_ref: Option, /// Output machine-readable JSON #[arg(long)] json: bool, }, /// Manage standalone sandboxed WebAssembly (`.wasm`) plugins Plugin { #[command(subcommand)] action: PluginCommands, }, /// Print shell completion script (`bash`, `zsh`, or `fish`) Completions { /// Target shell #[arg(value_enum)] shell: CompletionShell, }, } #[derive(Debug, Subcommand)] enum PluginCommands { /// Install a `.wasm` plugin into the local Roneo plugin directory (`~/.config/roneo/plugins`) Install { /// Path to the `.wasm` file path: PathBuf, /// Optional short alias name (defaults to the plugin's manifest `name`) #[arg(long)] name: Option, }, /// List installed `.wasm` plugins List, /// Inspect a `.wasm` plugin's manifest (by path or installed name) Inspect { /// Path to `.wasm` file or installed plugin name plugin: String, }, /// Remove an installed plugin by name Remove { /// Installed plugin name name: String, }, } #[derive(Debug, Clone, Copy, ValueEnum)] enum CheckUpdateFormat { Plain, Json, } #[derive(Debug, Clone, Copy, ValueEnum)] enum CompletionShell { Bash, Zsh, Fish, } #[derive(Debug, Clone, Copy, ValueEnum)] enum CliConflictMode { Inline, Rej, } impl From for ConflictMode { fn from(value: CliConflictMode) -> Self { match value { CliConflictMode::Inline => Self::Inline, CliConflictMode::Rej => Self::Rej, } } } #[derive(Debug, Args)] struct SharedOpts { /// Git branch, tag, or commit to use from the template repository #[arg(short = 'r', long)] vcs_ref: Option, /// Provide an answer directly (`key=value`); repeatable #[arg(short = 'd', long = "data", value_name = "KEY=VALUE")] data: Vec, /// Load answers from a YAML or JSON file #[arg(long = "data-file", value_name = "PATH")] data_file: Option, /// Custom answers file path relative to destination #[arg(short = 'a', long)] answers_file: Option, /// Additional gitignore-style path patterns to exclude; repeatable #[arg(short = 'x', long = "exclude")] exclude: Vec, /// Skip existing destination files matching this pattern (Copier `-s` / `--skip-if-exists`); repeatable #[arg(short = 's', long = "skip", alias = "skip-if-exists")] skip_if_exists: Vec, /// Disable Copier's built-in default exclude rules #[arg(long)] no_default_excludes: bool, /// Allow selecting pre-release VCS tags (PEP 440) when `--vcs-ref` is omitted #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")] prereleases: bool, /// Overwrite existing files without skipping #[arg(short = 'w', long)] overwrite: bool, /// Shorthand for `--defaults --overwrite` (Copier `-f` / `--force`) #[arg(short = 'f', long)] force: bool, /// Dry-run: show planned operations without writing any files or running tasks #[arg(short = 'n', long)] pretend: bool, /// Use default values for all questions without prompting interactively #[arg(short = 'l', long)] defaults: bool, /// Skip questions that already have saved answers during update/recopy #[arg(short = 'A', long)] skip_answered: bool, /// Force prompting for specific question(s), even with `--defaults`, `--skip-answered`, or `ask: false`; repeatable #[arg(long = "ask", value_name = "QUESTION")] ask: Vec, /// Skip running `_tasks` and `_migrations` #[arg(short = 'T', long)] skip_tasks: bool, /// Allow running `_tasks` and `_migrations` defined by the template (alias: `--UNSAFE`) #[arg(long, alias = "UNSAFE")] trust: bool, /// Load a sandboxed WebAssembly plugin (`.wasm` file path or installed plugin name); repeatable #[arg(long = "plugin", value_name = "PATH_OR_NAME")] plugins: Vec, /// Suppress non-error output #[arg(short = 'q', long)] quiet: bool, } fn main() -> ExitCode { let cli = Cli::parse(); match run(cli) { Ok(had_conflicts) => { if had_conflicts { ExitCode::from(2) } else { ExitCode::SUCCESS } } Err(RoneoError::UserAborted) => { eprintln!("{}", style::yellow("Aborted.")); ExitCode::from(130) } Err(err) => { eprintln!("{} {err}", style::red_bold("error:")); ExitCode::FAILURE } } } fn run(cli: Cli) -> roneo_core::Result { match cli.command { Commands::Copy { template, destination, no_cleanup, opts, } => { let mut copy_opts = build_options(&opts, ConflictMode::Inline, false)?; copy_opts.cleanup_on_error = !no_cleanup; let reporter = ConsoleReporter { quiet: opts.quiet, pretend: opts.pretend, }; let prompter = select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); let report = copy( &template, &destination, ©_opts, prompter.as_ref(), &reporter, )?; if !opts.quiet { print_summary("Copied", &report, opts.pretend); } Ok(false) } Commands::Update { destination, conflict, context_lines, skip_git_check, opts, } => { let mut copy_opts = build_options(&opts, conflict.into(), skip_git_check)?; copy_opts.context_lines = context_lines; let reporter = ConsoleReporter { quiet: opts.quiet, pretend: opts.pretend, }; let prompter = select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); let report = update(&destination, ©_opts, prompter.as_ref(), &reporter)?; if !opts.quiet { print_summary("Updated", &report, opts.pretend); } if !report.conflicts.is_empty() { eprintln!( "\n{} {} conflicted file(s) need manual resolution.", style::yellow_bold("warning:"), report.conflicts.len() ); return Ok(true); } Ok(false) } Commands::Recopy { destination, src, opts, } => { let copy_opts = build_options(&opts, ConflictMode::Inline, false)?; let reporter = ConsoleReporter { quiet: opts.quiet, pretend: opts.pretend, }; let prompter = select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); let report = recopy( &destination, src.as_deref(), ©_opts, prompter.as_ref(), &reporter, )?; if !opts.quiet { print_summary("Recopied", &report, opts.pretend); } Ok(false) } Commands::Diff { destination, context_lines, opts, } => { let mut copy_opts = build_options(&opts, ConflictMode::Inline, true)?; copy_opts.context_lines = context_lines; let prompter = select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); let diff = diff_update(&destination, ©_opts, prompter.as_ref())?; if diff.patch.trim().is_empty() { if !opts.quiet { println!("{}", style::dim("No template changes to apply.")); } } else { let mut stdout = io::stdout().lock(); if !opts.quiet { let to = diff.to_commit.as_deref().unwrap_or("HEAD"); if writeln!( stdout, "{} {} ({} -> {})\n", style::bold("Diff:"), diff.src_path, style::yellow(&diff.from_commit), style::green(to), ) .is_err() { return Ok(false); } } for line in diff.patch.lines() { let res = if line.starts_with("diff --git") { writeln!(stdout, "{}", style::bold(line)) } else if line.starts_with("@@") { writeln!(stdout, "{}", style::cyan(line)) } else if line.starts_with('+') && !line.starts_with("+++") { writeln!(stdout, "{}", style::green(line)) } else if line.starts_with('-') && !line.starts_with("---") { writeln!(stdout, "{}", style::red(line)) } else { writeln!(stdout, "{line}") }; if res.is_err() { break; } } } Ok(false) } Commands::CheckUpdate { destination, answers_file, prereleases, output_format, quiet, } => { let copy_opts = CopyOptions { answers_file, use_prereleases: prereleases, quiet, ..CopyOptions::default() }; let rep = check_update(&destination, ©_opts)?; if rep.update_available { if quiet { return Ok(true); } match output_format { CheckUpdateFormat::Json => { let payload = serde_json::json!({ "update_available": rep.update_available, "current_version": rep.current_version, "latest_version": rep.latest_version, }); println!("{payload}"); } CheckUpdateFormat::Plain => { println!( "New template version available.\nCurrent version is {}, latest version is {}.", rep.current_version, rep.latest_version ); } } } else if !quiet { match output_format { CheckUpdateFormat::Json => { let payload = serde_json::json!({ "update_available": rep.update_available, "current_version": rep.current_version, "latest_version": rep.latest_version, }); println!("{payload}"); } CheckUpdateFormat::Plain => { println!("Project is up-to-date!"); } } } Ok(false) } Commands::Inspect { template, vcs_ref, json, } => { let resolved = ResolvedTemplate::resolve(&template, vcs_ref.as_deref())?; if json { let payload = serde_json::json!({ "src_path": resolved.original_src, "resolved_src": resolved.resolved_src, "commit": resolved.commit, "commit_hash": resolved.commit_hash, "requires_trust": resolved.config.requires_trust(), "settings": resolved.config.settings, "questions": resolved.config.questions, }); let _ = writeln!(io::stdout(), "{}", serde_json::to_string_pretty(&payload)?); } else { print_inspect(&resolved); } Ok(false) } Commands::Plugin { action } => { handle_plugin_command(action)?; Ok(false) } Commands::Completions { shell } => { print_completions(shell); Ok(false) } } } fn plugin_dir() -> PathBuf { if let Ok(custom) = env::var("RONEO_PLUGIN_DIR") && !custom.trim().is_empty() { return PathBuf::from(custom); } let home = env::var("HOME") .or_else(|_| env::var("USERPROFILE")) .unwrap_or_else(|_| ".".into()); PathBuf::from(home).join(".config/roneo/plugins") } fn validate_plugin_alias(name: &str) -> roneo_core::Result<()> { let valid = !name.is_empty() && !name.starts_with('.') && !name.contains("..") && name .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')); if !valid { return Err(RoneoError::Plugin(format!( "Invalid plugin alias '{name}': must contain only ASCII letters, digits, '.', '-', or '_' and must not traverse paths" ))); } Ok(()) } fn resolve_plugin_spec(spec: &str) -> roneo_core::Result { let direct = Path::new(spec); if direct.is_file() { return Ok(direct.to_path_buf()); } validate_plugin_alias(spec)?; let dir = plugin_dir(); let candidate = if spec .rsplit('.') .next() .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm")) { dir.join(spec) } else { dir.join(format!("{spec}.wasm")) }; if candidate.is_file() { return Ok(candidate); } Err(RoneoError::Plugin(format!( "Plugin '{spec}' not found as a file or in '{}'", dir.display() ))) } fn handle_plugin_command(action: PluginCommands) -> roneo_core::Result<()> { match action { PluginCommands::Install { path, name } => { let ext = WasmExtension::from_file(&path)?; let plugin_name = name.unwrap_or_else(|| ext.manifest().name.clone()); if plugin_name.is_empty() { return Err(RoneoError::Plugin( "Plugin manifest has an empty name; pass `--name `".into(), )); } validate_plugin_alias(&plugin_name)?; let dir = plugin_dir(); fs::create_dir_all(&dir).map_err(|e| RoneoError::io(&dir, e))?; let dst = dir.join(format!("{plugin_name}.wasm")); fs::copy(&path, &dst).map_err(|e| RoneoError::io(&dst, e))?; println!( "{} '{}' -> {}", style::green_bold("Installed plugin"), style::bold(&plugin_name), dst.display() ); } PluginCommands::List => { let dir = plugin_dir(); println!("{} {}", style::bold("Plugin directory:"), dir.display()); if !dir.is_dir() { println!(" (no plugins installed)"); return Ok(()); } let mut entries: Vec = fs::read_dir(&dir) .map_err(|e| RoneoError::io(&dir, e))? .filter_map(Result::ok) .map(|e| e.path()) .filter(|p| { p.extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm")) }) .collect(); entries.sort(); if entries.is_empty() { println!(" (no plugins installed)"); return Ok(()); } for path in entries { let alias = path .file_stem() .map_or_default(|s| s.to_string_lossy().into_owned()); match WasmExtension::from_file(&path) { Ok(ext) => { let m = ext.manifest(); println!( " {} {} (filters: {}, functions: {}, tests: {}, context_hook: {})", style::cyan("•"), style::bold(&alias), m.filters.len(), m.functions.len(), m.tests.len(), m.has_context_hook ); } Err(e) => { let msg = e.to_string(); println!( " {} {} ({})", style::red("✗"), style::bold(&alias), style::red(&msg) ); } } } } PluginCommands::Inspect { plugin } => { let path = resolve_plugin_spec(&plugin)?; let ext = WasmExtension::from_file(&path)?; let m = ext.manifest(); println!("{} {}", style::bold("Plugin: "), m.name); println!("{} {}", style::bold("File: "), path.display()); println!("{} {}", style::bold("Strict: "), m.strict_undefined); println!("{} {}", style::bold("Hook: "), m.has_context_hook); println!("{} {:?}", style::bold("Filters: "), m.filters); println!("{} {:?}", style::bold("Funcs: "), m.functions); println!("{} {:?}", style::bold("Tests: "), m.tests); if !m.template_files.is_empty() { println!("{} {:?}", style::bold("Files: "), m.template_files); } } PluginCommands::Remove { name } => { validate_plugin_alias(&name)?; let path = plugin_dir().join(format!("{name}.wasm")); if !path.is_file() { return Err(RoneoError::Plugin(format!( "Installed plugin '{name}' not found at '{}'", path.display() ))); } fs::remove_file(&path).map_err(|e| RoneoError::io(&path, e))?; println!( "{} '{}'", style::yellow_bold("Removed plugin"), style::bold(&name) ); } } Ok(()) } fn select_prompter(use_defaults: bool) -> Box { if use_defaults { Box::new(NonInteractivePrompter) } else { Box::new(TerminalPrompter) } } fn build_options( opts: &SharedOpts, conflict_mode: ConflictMode, skip_git_check: bool, ) -> roneo_core::Result { let mut data = IndexMap::new(); if let Some(path) = &opts.data_file { let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?; data.extend(parse_yaml_mapping(&raw)?); } for pair in &opts.data { let (k, raw_v) = pair.split_once('=').ok_or_else(|| { RoneoError::InvalidConfig(format!( "Invalid `--data` entry '{pair}'; expected KEY=VALUE" )) })?; data.insert(k.trim().to_string(), parse_yaml_cli_value(raw_v)); } let mut extensions = ExtensionRegistry::new(); for spec in &opts.plugins { let wasm_path = resolve_plugin_spec(spec)?; extensions.add_wasm_file(&wasm_path)?; } Ok(CopyOptions { vcs_ref: opts.vcs_ref.clone(), data, answers_file: opts.answers_file.clone(), exclude: opts.exclude.clone(), skip_if_exists: opts.skip_if_exists.clone(), use_default_excludes: !opts.no_default_excludes, use_prereleases: opts.prereleases, overwrite: opts.overwrite || opts.force, pretend: opts.pretend, defaults: opts.defaults || opts.force, skip_answered: opts.skip_answered, ask_questions: opts.ask.clone(), skip_tasks: opts.skip_tasks, trust: opts.trust, conflict_mode, context_lines: 3, cleanup_on_error: true, skip_git_check, quiet: opts.quiet, user_settings: None, extensions, }) } fn print_completions(shell: CompletionShell) { match shell { CompletionShell::Bash => print!( r#"# bash completion for roneo _roneo_completions() {{ local cur prev COMPREPLY=() cur="${{COMP_WORDS[COMP_CWORD]}}" prev="${{COMP_WORDS[COMP_CWORD-1]}}" if [[ ${{COMP_CWORD}} -eq 1 ]]; then COMPREPLY=( $(compgen -W "copy update diff recopy check-update inspect plugin completions help" -- "${{cur}}") ) return 0 fi if [[ "${{COMP_WORDS[1]}}" == "plugin" && ${{COMP_CWORD}} -eq 2 ]]; then COMPREPLY=( $(compgen -W "install list inspect remove" -- "${{cur}}") ) return 0 fi if [[ "${{cur}}" == -* ]]; then COMPREPLY=( $(compgen -W "-r --vcs-ref -d --data --data-file -a --answers-file -x --exclude -s --skip -g --prereleases -w --overwrite -f --force -n --pretend -l --defaults -A --skip-answered --ask -T --skip-tasks --trust --UNSAFE -C --no-cleanup -c --context-lines -o --conflict --output-format --plugin -q --quiet -h --help" -- "${{cur}}") ) return 0 fi }} complete -o default -F _roneo_completions roneo "# ), CompletionShell::Zsh => print!( r"#compdef roneo _roneo() {{ local -a commands commands=( 'copy:Copy a template into a destination directory' 'update:Smart-update a git-tracked project via 3-way merge' 'diff:Preview the 3-way unified diff for an update' 'recopy:Re-apply a template using saved answers' 'check-update:Check if a newer template version is available' 'inspect:Inspect template configuration and questions' 'plugin:Manage sandboxed WebAssembly (.wasm) plugins' 'completions:Print shell completion script' ) _arguments -C \ '1:command:->cmd' \ '*::arg:->args' case $state in cmd) _describe 'command' commands ;; args) _files ;; esac }} compdef _roneo roneo " ), CompletionShell::Fish => print!( r"# fish completion for roneo complete -c roneo -f -n '__fish_use_subcommand' -a copy -d 'Copy a template into a destination directory' complete -c roneo -f -n '__fish_use_subcommand' -a update -d 'Smart-update a git-tracked project via 3-way merge' complete -c roneo -f -n '__fish_use_subcommand' -a diff -d 'Preview the 3-way unified diff for an update' complete -c roneo -f -n '__fish_use_subcommand' -a recopy -d 'Re-apply a template using saved answers' complete -c roneo -f -n '__fish_use_subcommand' -a check-update -d 'Check if a newer template version is available' complete -c roneo -f -n '__fish_use_subcommand' -a inspect -d 'Inspect template configuration and questions' complete -c roneo -f -n '__fish_use_subcommand' -a plugin -d 'Manage sandboxed WebAssembly plugins' complete -c roneo -f -n '__fish_use_subcommand' -a completions -d 'Print shell completion script' " ), } } fn print_summary(verb: &str, report: &OperationReport, pretend: bool) { let commit_note = report .commit .as_deref() .map_or_default(|c| format!(" ({c})")); let mode = if pretend { " [dry-run]" } else { "" }; println!( "\n{} {}{} -> {} ({} created, {} updated, {} skipped){}", style::green_bold(verb), style::bold(&report.src_path), style::dim(&commit_note), report.dst_path.display(), report.created, report.updated, report.skipped, style::dim(mode), ); } fn print_inspect(resolved: &ResolvedTemplate) { let cfg = &resolved.config; println!("{} {}", style::bold("Template:"), resolved.original_src); if let Some(commit) = &resolved.commit { println!("{} {commit}", style::bold("Version: ")); } if let Some(sub) = &cfg.settings.subdirectory { println!("{} {sub}", style::bold("Subdir: ")); } println!("{} {}", style::bold("Answers: "), cfg.settings.answers_file); println!( "{} {}", style::bold("Suffix: "), if cfg.settings.templates_suffix.is_empty() { "(none)" } else { &cfg.settings.templates_suffix } ); if !cfg.settings.roneo_plugins.is_empty() { println!( "{} {}", style::bold("Plugins: "), cfg.settings.roneo_plugins.join(", ") ); } if cfg.requires_trust() { println!( "{} {} ({} task(s), {} migration(s))", style::bold("Trust: "), style::yellow_bold("required (--trust)"), cfg.settings.tasks.len(), cfg.settings.migrations.len() ); } println!( "\n{} ({})", style::bold_underlined("Questions"), cfg.questions.len() ); if cfg.questions.is_empty() { println!(" (none)"); } else { for (name, q) in &cfg.questions { let def = q .default .as_ref() .map_or_default(|d| format!(" [default: {}]", json_display(d))); let secret = if q.secret { " [secret]" } else { "" }; let cond = q .when .as_ref() .map_or_default(|w| format!(" [when: {}]", json_display(w))); println!( " {} {} ({:?}){}{}{}", style::cyan("•"), style::bold(name), q.kind, style::dim(&def), style::yellow(secret), style::dim(&cond), ); if let Some(help) = &q.help { println!(" {}", style::dim(help)); } if let Some(choices) = &q.choices { let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect(); println!(" choices: {}", labels.join(", ")); } } } }