forgeFRENParcourir les dépôts

roneocratesroneo-clisrcmain.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

882 lines · 30.1 KiBRustRaw
  1. mod prompter;
  2. mod reporter;
  3. mod style;
  4. use std::env;
  5. use std::fs;
  6. use std::io::{self, Write};
  7. use std::path::{Path, PathBuf};
  8. use std::process::ExitCode;
  9. use crate::prompter::TerminalPrompter;
  10. use crate::reporter::ConsoleReporter;
  11. use clap::{Args, Parser, Subcommand, ValueEnum};
  12. use indexmap::IndexMap;
  13. use roneo_core::config::{json_display, parse_yaml_cli_value, parse_yaml_mapping};
  14. use roneo_core::{
  15. ConflictMode, CopyOptions, ExtensionRegistry, NonInteractivePrompter, OperationReport,
  16. Prompter, ResolvedTemplate, RoneoError, WasmExtension, check_update, copy, diff_update, recopy,
  17. update,
  18. };
  19. #[derive(Debug, Parser)]
  20. #[command(
  21. name = "roneo",
  22. version,
  23. about = "Fast, nimble Rust port of Copier for scaffolding and updating project templates",
  24. propagate_version = true
  25. )]
  26. struct Cli {
  27. #[command(subcommand)]
  28. command: Commands,
  29. }
  30. #[derive(Debug, Subcommand)]
  31. enum Commands {
  32. /// Copy a template into a destination directory
  33. Copy {
  34. /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`)
  35. template: String,
  36. /// Destination directory (defaults to current directory)
  37. #[arg(default_value = ".")]
  38. destination: PathBuf,
  39. /// On error, do not delete the destination directory if it was created by Roneo (Copier `-C`)
  40. #[arg(short = 'C', long)]
  41. no_cleanup: bool,
  42. #[command(flatten)]
  43. opts: SharedOpts,
  44. },
  45. /// Smart-update a git-tracked project from its template via 3-way merge
  46. Update {
  47. /// Destination project directory (defaults to current directory)
  48. #[arg(default_value = ".")]
  49. destination: PathBuf,
  50. /// How to record merge conflicts (`inline` markers or `.rej` files)
  51. #[arg(short = 'o', long, value_enum, default_value_t = CliConflictMode::Inline)]
  52. conflict: CliConflictMode,
  53. /// Lines of context to use for detecting conflicts (Copier `-c`, default 3)
  54. #[arg(short = 'c', long, default_value_t = 3)]
  55. context_lines: usize,
  56. /// Skip clean-working-tree git check (advanced)
  57. #[arg(long)]
  58. skip_git_check: bool,
  59. #[command(flatten)]
  60. opts: SharedOpts,
  61. },
  62. /// Re-apply a template onto an existing project using saved answers (no 3-way merge)
  63. Recopy {
  64. /// Destination project directory (defaults to current directory)
  65. #[arg(default_value = ".")]
  66. destination: PathBuf,
  67. /// Optional template source override (defaults to `_src_path` in answers file)
  68. #[arg(long)]
  69. src: Option<String>,
  70. #[command(flatten)]
  71. opts: SharedOpts,
  72. },
  73. /// Preview the 3-way unified diff that `roneo update` would apply without modifying files
  74. Diff {
  75. /// Destination project directory (defaults to current directory)
  76. #[arg(default_value = ".")]
  77. destination: PathBuf,
  78. /// Lines of context to include in the unified diff (default 3)
  79. #[arg(short = 'c', long, default_value_t = 3)]
  80. context_lines: usize,
  81. #[command(flatten)]
  82. opts: SharedOpts,
  83. },
  84. /// Check if a project is using the latest version of its template (Copier `check-update`)
  85. CheckUpdate {
  86. /// Destination project directory (defaults to current directory)
  87. #[arg(default_value = ".")]
  88. destination: PathBuf,
  89. /// Custom answers file path relative to destination
  90. #[arg(short = 'a', long)]
  91. answers_file: Option<PathBuf>,
  92. /// Allow pre-release VCS tags (PEP 440) when comparing versions
  93. #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")]
  94. prereleases: bool,
  95. /// Output format (`plain` or `json`)
  96. #[arg(long = "output-format", value_enum, default_value_t = CheckUpdateFormat::Plain)]
  97. output_format: CheckUpdateFormat,
  98. /// Suppress status output; exit with code 2 when a new template version is available
  99. #[arg(short = 'q', long)]
  100. quiet: bool,
  101. },
  102. /// Inspect a template's configuration, questions, settings, and tasks without copying
  103. Inspect {
  104. /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`)
  105. template: String,
  106. /// Git ref (branch, tag, or commit) to inspect
  107. #[arg(short = 'r', long)]
  108. vcs_ref: Option<String>,
  109. /// Output machine-readable JSON
  110. #[arg(long)]
  111. json: bool,
  112. },
  113. /// Manage standalone sandboxed WebAssembly (`.wasm`) plugins
  114. Plugin {
  115. #[command(subcommand)]
  116. action: PluginCommands,
  117. },
  118. /// Print shell completion script (`bash`, `zsh`, or `fish`)
  119. Completions {
  120. /// Target shell
  121. #[arg(value_enum)]
  122. shell: CompletionShell,
  123. },
  124. }
  125. #[derive(Debug, Subcommand)]
  126. enum PluginCommands {
  127. /// Install a `.wasm` plugin into the local Roneo plugin directory (`~/.config/roneo/plugins`)
  128. Install {
  129. /// Path to the `.wasm` file
  130. path: PathBuf,
  131. /// Optional short alias name (defaults to the plugin's manifest `name`)
  132. #[arg(long)]
  133. name: Option<String>,
  134. },
  135. /// List installed `.wasm` plugins
  136. List,
  137. /// Inspect a `.wasm` plugin's manifest (by path or installed name)
  138. Inspect {
  139. /// Path to `.wasm` file or installed plugin name
  140. plugin: String,
  141. },
  142. /// Remove an installed plugin by name
  143. Remove {
  144. /// Installed plugin name
  145. name: String,
  146. },
  147. }
  148. #[derive(Debug, Clone, Copy, ValueEnum)]
  149. enum CheckUpdateFormat {
  150. Plain,
  151. Json,
  152. }
  153. #[derive(Debug, Clone, Copy, ValueEnum)]
  154. enum CompletionShell {
  155. Bash,
  156. Zsh,
  157. Fish,
  158. }
  159. #[derive(Debug, Clone, Copy, ValueEnum)]
  160. enum CliConflictMode {
  161. Inline,
  162. Rej,
  163. }
  164. impl From<CliConflictMode> for ConflictMode {
  165. fn from(value: CliConflictMode) -> Self {
  166. match value {
  167. CliConflictMode::Inline => Self::Inline,
  168. CliConflictMode::Rej => Self::Rej,
  169. }
  170. }
  171. }
  172. #[derive(Debug, Args)]
  173. struct SharedOpts {
  174. /// Git branch, tag, or commit to use from the template repository
  175. #[arg(short = 'r', long)]
  176. vcs_ref: Option<String>,
  177. /// Provide an answer directly (`key=value`); repeatable
  178. #[arg(short = 'd', long = "data", value_name = "KEY=VALUE")]
  179. data: Vec<String>,
  180. /// Load answers from a YAML or JSON file
  181. #[arg(long = "data-file", value_name = "PATH")]
  182. data_file: Option<PathBuf>,
  183. /// Custom answers file path relative to destination
  184. #[arg(short = 'a', long)]
  185. answers_file: Option<PathBuf>,
  186. /// Additional gitignore-style path patterns to exclude; repeatable
  187. #[arg(short = 'x', long = "exclude")]
  188. exclude: Vec<String>,
  189. /// Skip existing destination files matching this pattern (Copier `-s` / `--skip-if-exists`); repeatable
  190. #[arg(short = 's', long = "skip", alias = "skip-if-exists")]
  191. skip_if_exists: Vec<String>,
  192. /// Disable Copier's built-in default exclude rules
  193. #[arg(long)]
  194. no_default_excludes: bool,
  195. /// Allow selecting pre-release VCS tags (PEP 440) when `--vcs-ref` is omitted
  196. #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")]
  197. prereleases: bool,
  198. /// Overwrite existing files without skipping
  199. #[arg(short = 'w', long)]
  200. overwrite: bool,
  201. /// Shorthand for `--defaults --overwrite` (Copier `-f` / `--force`)
  202. #[arg(short = 'f', long)]
  203. force: bool,
  204. /// Dry-run: show planned operations without writing any files or running tasks
  205. #[arg(short = 'n', long)]
  206. pretend: bool,
  207. /// Use default values for all questions without prompting interactively
  208. #[arg(short = 'l', long)]
  209. defaults: bool,
  210. /// Skip questions that already have saved answers during update/recopy
  211. #[arg(short = 'A', long)]
  212. skip_answered: bool,
  213. /// Force prompting for specific question(s), even with `--defaults`, `--skip-answered`, or `ask: false`; repeatable
  214. #[arg(long = "ask", value_name = "QUESTION")]
  215. ask: Vec<String>,
  216. /// Skip running `_tasks` and `_migrations`
  217. #[arg(short = 'T', long)]
  218. skip_tasks: bool,
  219. /// Allow running `_tasks` and `_migrations` defined by the template (alias: `--UNSAFE`)
  220. #[arg(long, alias = "UNSAFE")]
  221. trust: bool,
  222. /// Load a sandboxed WebAssembly plugin (`.wasm` file path or installed plugin name); repeatable
  223. #[arg(long = "plugin", value_name = "PATH_OR_NAME")]
  224. plugins: Vec<String>,
  225. /// Suppress non-error output
  226. #[arg(short = 'q', long)]
  227. quiet: bool,
  228. }
  229. fn main() -> ExitCode {
  230. let cli = Cli::parse();
  231. match run(cli) {
  232. Ok(had_conflicts) => {
  233. if had_conflicts {
  234. ExitCode::from(2)
  235. } else {
  236. ExitCode::SUCCESS
  237. }
  238. }
  239. Err(RoneoError::UserAborted) => {
  240. eprintln!("{}", style::yellow("Aborted."));
  241. ExitCode::from(130)
  242. }
  243. Err(err) => {
  244. eprintln!("{} {err}", style::red_bold("error:"));
  245. ExitCode::FAILURE
  246. }
  247. }
  248. }
  249. fn run(cli: Cli) -> roneo_core::Result<bool> {
  250. match cli.command {
  251. Commands::Copy {
  252. template,
  253. destination,
  254. no_cleanup,
  255. opts,
  256. } => {
  257. let mut copy_opts = build_options(&opts, ConflictMode::Inline, false)?;
  258. copy_opts.cleanup_on_error = !no_cleanup;
  259. let reporter = ConsoleReporter {
  260. quiet: opts.quiet,
  261. pretend: opts.pretend,
  262. };
  263. let prompter =
  264. select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty());
  265. let report = copy(
  266. &template,
  267. &destination,
  268. &copy_opts,
  269. prompter.as_ref(),
  270. &reporter,
  271. )?;
  272. if !opts.quiet {
  273. print_summary("Copied", &report, opts.pretend);
  274. }
  275. Ok(false)
  276. }
  277. Commands::Update {
  278. destination,
  279. conflict,
  280. context_lines,
  281. skip_git_check,
  282. opts,
  283. } => {
  284. let mut copy_opts = build_options(&opts, conflict.into(), skip_git_check)?;
  285. copy_opts.context_lines = context_lines;
  286. let reporter = ConsoleReporter {
  287. quiet: opts.quiet,
  288. pretend: opts.pretend,
  289. };
  290. let prompter =
  291. select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty());
  292. let report = update(&destination, &copy_opts, prompter.as_ref(), &reporter)?;
  293. if !opts.quiet {
  294. print_summary("Updated", &report, opts.pretend);
  295. }
  296. if !report.conflicts.is_empty() {
  297. eprintln!(
  298. "\n{} {} conflicted file(s) need manual resolution.",
  299. style::yellow_bold("warning:"),
  300. report.conflicts.len()
  301. );
  302. return Ok(true);
  303. }
  304. Ok(false)
  305. }
  306. Commands::Recopy {
  307. destination,
  308. src,
  309. opts,
  310. } => {
  311. let copy_opts = build_options(&opts, ConflictMode::Inline, false)?;
  312. let reporter = ConsoleReporter {
  313. quiet: opts.quiet,
  314. pretend: opts.pretend,
  315. };
  316. let prompter =
  317. select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty());
  318. let report = recopy(
  319. &destination,
  320. src.as_deref(),
  321. &copy_opts,
  322. prompter.as_ref(),
  323. &reporter,
  324. )?;
  325. if !opts.quiet {
  326. print_summary("Recopied", &report, opts.pretend);
  327. }
  328. Ok(false)
  329. }
  330. Commands::Diff {
  331. destination,
  332. context_lines,
  333. opts,
  334. } => {
  335. let mut copy_opts = build_options(&opts, ConflictMode::Inline, true)?;
  336. copy_opts.context_lines = context_lines;
  337. let prompter =
  338. select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty());
  339. let diff = diff_update(&destination, &copy_opts, prompter.as_ref())?;
  340. if diff.patch.trim().is_empty() {
  341. if !opts.quiet {
  342. println!("{}", style::dim("No template changes to apply."));
  343. }
  344. } else {
  345. let mut stdout = io::stdout().lock();
  346. if !opts.quiet {
  347. let to = diff.to_commit.as_deref().unwrap_or("HEAD");
  348. if writeln!(
  349. stdout,
  350. "{} {} ({} -> {})\n",
  351. style::bold("Diff:"),
  352. diff.src_path,
  353. style::yellow(&diff.from_commit),
  354. style::green(to),
  355. )
  356. .is_err()
  357. {
  358. return Ok(false);
  359. }
  360. }
  361. for line in diff.patch.lines() {
  362. let res = if line.starts_with("diff --git") {
  363. writeln!(stdout, "{}", style::bold(line))
  364. } else if line.starts_with("@@") {
  365. writeln!(stdout, "{}", style::cyan(line))
  366. } else if line.starts_with('+') && !line.starts_with("+++") {
  367. writeln!(stdout, "{}", style::green(line))
  368. } else if line.starts_with('-') && !line.starts_with("---") {
  369. writeln!(stdout, "{}", style::red(line))
  370. } else {
  371. writeln!(stdout, "{line}")
  372. };
  373. if res.is_err() {
  374. break;
  375. }
  376. }
  377. }
  378. Ok(false)
  379. }
  380. Commands::CheckUpdate {
  381. destination,
  382. answers_file,
  383. prereleases,
  384. output_format,
  385. quiet,
  386. } => {
  387. let copy_opts = CopyOptions {
  388. answers_file,
  389. use_prereleases: prereleases,
  390. quiet,
  391. ..CopyOptions::default()
  392. };
  393. let rep = check_update(&destination, &copy_opts)?;
  394. if rep.update_available {
  395. if quiet {
  396. return Ok(true);
  397. }
  398. match output_format {
  399. CheckUpdateFormat::Json => {
  400. let payload = serde_json::json!({
  401. "update_available": rep.update_available,
  402. "current_version": rep.current_version,
  403. "latest_version": rep.latest_version,
  404. });
  405. println!("{payload}");
  406. }
  407. CheckUpdateFormat::Plain => {
  408. println!(
  409. "New template version available.\nCurrent version is {}, latest version is {}.",
  410. rep.current_version, rep.latest_version
  411. );
  412. }
  413. }
  414. } else if !quiet {
  415. match output_format {
  416. CheckUpdateFormat::Json => {
  417. let payload = serde_json::json!({
  418. "update_available": rep.update_available,
  419. "current_version": rep.current_version,
  420. "latest_version": rep.latest_version,
  421. });
  422. println!("{payload}");
  423. }
  424. CheckUpdateFormat::Plain => {
  425. println!("Project is up-to-date!");
  426. }
  427. }
  428. }
  429. Ok(false)
  430. }
  431. Commands::Inspect {
  432. template,
  433. vcs_ref,
  434. json,
  435. } => {
  436. let resolved = ResolvedTemplate::resolve(&template, vcs_ref.as_deref())?;
  437. if json {
  438. let payload = serde_json::json!({
  439. "src_path": resolved.original_src,
  440. "resolved_src": resolved.resolved_src,
  441. "commit": resolved.commit,
  442. "commit_hash": resolved.commit_hash,
  443. "requires_trust": resolved.config.requires_trust(),
  444. "settings": resolved.config.settings,
  445. "questions": resolved.config.questions,
  446. });
  447. let _ = writeln!(io::stdout(), "{}", serde_json::to_string_pretty(&payload)?);
  448. } else {
  449. print_inspect(&resolved);
  450. }
  451. Ok(false)
  452. }
  453. Commands::Plugin { action } => {
  454. handle_plugin_command(action)?;
  455. Ok(false)
  456. }
  457. Commands::Completions { shell } => {
  458. print_completions(shell);
  459. Ok(false)
  460. }
  461. }
  462. }
  463. fn plugin_dir() -> PathBuf {
  464. if let Ok(custom) = env::var("RONEO_PLUGIN_DIR")
  465. && !custom.trim().is_empty()
  466. {
  467. return PathBuf::from(custom);
  468. }
  469. let home = env::var("HOME")
  470. .or_else(|_| env::var("USERPROFILE"))
  471. .unwrap_or_else(|_| ".".into());
  472. PathBuf::from(home).join(".config/roneo/plugins")
  473. }
  474. fn validate_plugin_alias(name: &str) -> roneo_core::Result<()> {
  475. let valid = !name.is_empty()
  476. && !name.starts_with('.')
  477. && !name.contains("..")
  478. && name
  479. .bytes()
  480. .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
  481. if !valid {
  482. return Err(RoneoError::Plugin(format!(
  483. "Invalid plugin alias '{name}': must contain only ASCII letters, digits, '.', '-', or '_' and must not traverse paths"
  484. )));
  485. }
  486. Ok(())
  487. }
  488. fn resolve_plugin_spec(spec: &str) -> roneo_core::Result<PathBuf> {
  489. let direct = Path::new(spec);
  490. if direct.is_file() {
  491. return Ok(direct.to_path_buf());
  492. }
  493. validate_plugin_alias(spec)?;
  494. let dir = plugin_dir();
  495. let candidate = if spec
  496. .rsplit('.')
  497. .next()
  498. .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm"))
  499. {
  500. dir.join(spec)
  501. } else {
  502. dir.join(format!("{spec}.wasm"))
  503. };
  504. if candidate.is_file() {
  505. return Ok(candidate);
  506. }
  507. Err(RoneoError::Plugin(format!(
  508. "Plugin '{spec}' not found as a file or in '{}'",
  509. dir.display()
  510. )))
  511. }
  512. fn handle_plugin_command(action: PluginCommands) -> roneo_core::Result<()> {
  513. match action {
  514. PluginCommands::Install { path, name } => {
  515. let ext = WasmExtension::from_file(&path)?;
  516. let plugin_name = name.unwrap_or_else(|| ext.manifest().name.clone());
  517. if plugin_name.is_empty() {
  518. return Err(RoneoError::Plugin(
  519. "Plugin manifest has an empty name; pass `--name <alias>`".into(),
  520. ));
  521. }
  522. validate_plugin_alias(&plugin_name)?;
  523. let dir = plugin_dir();
  524. fs::create_dir_all(&dir).map_err(|e| RoneoError::io(&dir, e))?;
  525. let dst = dir.join(format!("{plugin_name}.wasm"));
  526. fs::copy(&path, &dst).map_err(|e| RoneoError::io(&dst, e))?;
  527. println!(
  528. "{} '{}' -> {}",
  529. style::green_bold("Installed plugin"),
  530. style::bold(&plugin_name),
  531. dst.display()
  532. );
  533. }
  534. PluginCommands::List => {
  535. let dir = plugin_dir();
  536. println!("{} {}", style::bold("Plugin directory:"), dir.display());
  537. if !dir.is_dir() {
  538. println!(" (no plugins installed)");
  539. return Ok(());
  540. }
  541. let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
  542. .map_err(|e| RoneoError::io(&dir, e))?
  543. .filter_map(Result::ok)
  544. .map(|e| e.path())
  545. .filter(|p| {
  546. p.extension()
  547. .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm"))
  548. })
  549. .collect();
  550. entries.sort();
  551. if entries.is_empty() {
  552. println!(" (no plugins installed)");
  553. return Ok(());
  554. }
  555. for path in entries {
  556. let alias = path
  557. .file_stem()
  558. .map_or_default(|s| s.to_string_lossy().into_owned());
  559. match WasmExtension::from_file(&path) {
  560. Ok(ext) => {
  561. let m = ext.manifest();
  562. println!(
  563. " {} {} (filters: {}, functions: {}, tests: {}, context_hook: {})",
  564. style::cyan("•"),
  565. style::bold(&alias),
  566. m.filters.len(),
  567. m.functions.len(),
  568. m.tests.len(),
  569. m.has_context_hook
  570. );
  571. }
  572. Err(e) => {
  573. let msg = e.to_string();
  574. println!(
  575. " {} {} ({})",
  576. style::red("✗"),
  577. style::bold(&alias),
  578. style::red(&msg)
  579. );
  580. }
  581. }
  582. }
  583. }
  584. PluginCommands::Inspect { plugin } => {
  585. let path = resolve_plugin_spec(&plugin)?;
  586. let ext = WasmExtension::from_file(&path)?;
  587. let m = ext.manifest();
  588. println!("{} {}", style::bold("Plugin: "), m.name);
  589. println!("{} {}", style::bold("File: "), path.display());
  590. println!("{} {}", style::bold("Strict: "), m.strict_undefined);
  591. println!("{} {}", style::bold("Hook: "), m.has_context_hook);
  592. println!("{} {:?}", style::bold("Filters: "), m.filters);
  593. println!("{} {:?}", style::bold("Funcs: "), m.functions);
  594. println!("{} {:?}", style::bold("Tests: "), m.tests);
  595. if !m.template_files.is_empty() {
  596. println!("{} {:?}", style::bold("Files: "), m.template_files);
  597. }
  598. }
  599. PluginCommands::Remove { name } => {
  600. validate_plugin_alias(&name)?;
  601. let path = plugin_dir().join(format!("{name}.wasm"));
  602. if !path.is_file() {
  603. return Err(RoneoError::Plugin(format!(
  604. "Installed plugin '{name}' not found at '{}'",
  605. path.display()
  606. )));
  607. }
  608. fs::remove_file(&path).map_err(|e| RoneoError::io(&path, e))?;
  609. println!(
  610. "{} '{}'",
  611. style::yellow_bold("Removed plugin"),
  612. style::bold(&name)
  613. );
  614. }
  615. }
  616. Ok(())
  617. }
  618. fn select_prompter(use_defaults: bool) -> Box<dyn Prompter> {
  619. if use_defaults {
  620. Box::new(NonInteractivePrompter)
  621. } else {
  622. Box::new(TerminalPrompter)
  623. }
  624. }
  625. fn build_options(
  626. opts: &SharedOpts,
  627. conflict_mode: ConflictMode,
  628. skip_git_check: bool,
  629. ) -> roneo_core::Result<CopyOptions> {
  630. let mut data = IndexMap::new();
  631. if let Some(path) = &opts.data_file {
  632. let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?;
  633. data.extend(parse_yaml_mapping(&raw)?);
  634. }
  635. for pair in &opts.data {
  636. let (k, raw_v) = pair.split_once('=').ok_or_else(|| {
  637. RoneoError::InvalidConfig(format!(
  638. "Invalid `--data` entry '{pair}'; expected KEY=VALUE"
  639. ))
  640. })?;
  641. data.insert(k.trim().to_string(), parse_yaml_cli_value(raw_v));
  642. }
  643. let mut extensions = ExtensionRegistry::new();
  644. for spec in &opts.plugins {
  645. let wasm_path = resolve_plugin_spec(spec)?;
  646. extensions.add_wasm_file(&wasm_path)?;
  647. }
  648. Ok(CopyOptions {
  649. vcs_ref: opts.vcs_ref.clone(),
  650. data,
  651. answers_file: opts.answers_file.clone(),
  652. exclude: opts.exclude.clone(),
  653. skip_if_exists: opts.skip_if_exists.clone(),
  654. use_default_excludes: !opts.no_default_excludes,
  655. use_prereleases: opts.prereleases,
  656. overwrite: opts.overwrite || opts.force,
  657. pretend: opts.pretend,
  658. defaults: opts.defaults || opts.force,
  659. skip_answered: opts.skip_answered,
  660. ask_questions: opts.ask.clone(),
  661. skip_tasks: opts.skip_tasks,
  662. trust: opts.trust,
  663. conflict_mode,
  664. context_lines: 3,
  665. cleanup_on_error: true,
  666. skip_git_check,
  667. quiet: opts.quiet,
  668. user_settings: None,
  669. extensions,
  670. })
  671. }
  672. fn print_completions(shell: CompletionShell) {
  673. match shell {
  674. CompletionShell::Bash => print!(
  675. r#"# bash completion for roneo
  676. _roneo_completions() {{
  677. local cur prev
  678. COMPREPLY=()
  679. cur="${{COMP_WORDS[COMP_CWORD]}}"
  680. prev="${{COMP_WORDS[COMP_CWORD-1]}}"
  681. if [[ ${{COMP_CWORD}} -eq 1 ]]; then
  682. COMPREPLY=( $(compgen -W "copy update diff recopy check-update inspect plugin completions help" -- "${{cur}}") )
  683. return 0
  684. fi
  685. if [[ "${{COMP_WORDS[1]}}" == "plugin" && ${{COMP_CWORD}} -eq 2 ]]; then
  686. COMPREPLY=( $(compgen -W "install list inspect remove" -- "${{cur}}") )
  687. return 0
  688. fi
  689. if [[ "${{cur}}" == -* ]]; then
  690. 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}}") )
  691. return 0
  692. fi
  693. }}
  694. complete -o default -F _roneo_completions roneo
  695. "#
  696. ),
  697. CompletionShell::Zsh => print!(
  698. r"#compdef roneo
  699. _roneo() {{
  700. local -a commands
  701. commands=(
  702. 'copy:Copy a template into a destination directory'
  703. 'update:Smart-update a git-tracked project via 3-way merge'
  704. 'diff:Preview the 3-way unified diff for an update'
  705. 'recopy:Re-apply a template using saved answers'
  706. 'check-update:Check if a newer template version is available'
  707. 'inspect:Inspect template configuration and questions'
  708. 'plugin:Manage sandboxed WebAssembly (.wasm) plugins'
  709. 'completions:Print shell completion script'
  710. )
  711. _arguments -C \
  712. '1:command:->cmd' \
  713. '*::arg:->args'
  714. case $state in
  715. cmd) _describe 'command' commands ;;
  716. args) _files ;;
  717. esac
  718. }}
  719. compdef _roneo roneo
  720. "
  721. ),
  722. CompletionShell::Fish => print!(
  723. r"# fish completion for roneo
  724. complete -c roneo -f -n '__fish_use_subcommand' -a copy -d 'Copy a template into a destination directory'
  725. complete -c roneo -f -n '__fish_use_subcommand' -a update -d 'Smart-update a git-tracked project via 3-way merge'
  726. complete -c roneo -f -n '__fish_use_subcommand' -a diff -d 'Preview the 3-way unified diff for an update'
  727. complete -c roneo -f -n '__fish_use_subcommand' -a recopy -d 'Re-apply a template using saved answers'
  728. complete -c roneo -f -n '__fish_use_subcommand' -a check-update -d 'Check if a newer template version is available'
  729. complete -c roneo -f -n '__fish_use_subcommand' -a inspect -d 'Inspect template configuration and questions'
  730. complete -c roneo -f -n '__fish_use_subcommand' -a plugin -d 'Manage sandboxed WebAssembly plugins'
  731. complete -c roneo -f -n '__fish_use_subcommand' -a completions -d 'Print shell completion script'
  732. "
  733. ),
  734. }
  735. }
  736. fn print_summary(verb: &str, report: &OperationReport, pretend: bool) {
  737. let commit_note = report
  738. .commit
  739. .as_deref()
  740. .map_or_default(|c| format!(" ({c})"));
  741. let mode = if pretend { " [dry-run]" } else { "" };
  742. println!(
  743. "\n{} {}{} -> {} ({} created, {} updated, {} skipped){}",
  744. style::green_bold(verb),
  745. style::bold(&report.src_path),
  746. style::dim(&commit_note),
  747. report.dst_path.display(),
  748. report.created,
  749. report.updated,
  750. report.skipped,
  751. style::dim(mode),
  752. );
  753. }
  754. fn print_inspect(resolved: &ResolvedTemplate) {
  755. let cfg = &resolved.config;
  756. println!("{} {}", style::bold("Template:"), resolved.original_src);
  757. if let Some(commit) = &resolved.commit {
  758. println!("{} {commit}", style::bold("Version: "));
  759. }
  760. if let Some(sub) = &cfg.settings.subdirectory {
  761. println!("{} {sub}", style::bold("Subdir: "));
  762. }
  763. println!("{} {}", style::bold("Answers: "), cfg.settings.answers_file);
  764. println!(
  765. "{} {}",
  766. style::bold("Suffix: "),
  767. if cfg.settings.templates_suffix.is_empty() {
  768. "(none)"
  769. } else {
  770. &cfg.settings.templates_suffix
  771. }
  772. );
  773. if !cfg.settings.roneo_plugins.is_empty() {
  774. println!(
  775. "{} {}",
  776. style::bold("Plugins: "),
  777. cfg.settings.roneo_plugins.join(", ")
  778. );
  779. }
  780. if cfg.requires_trust() {
  781. println!(
  782. "{} {} ({} task(s), {} migration(s))",
  783. style::bold("Trust: "),
  784. style::yellow_bold("required (--trust)"),
  785. cfg.settings.tasks.len(),
  786. cfg.settings.migrations.len()
  787. );
  788. }
  789. println!(
  790. "\n{} ({})",
  791. style::bold_underlined("Questions"),
  792. cfg.questions.len()
  793. );
  794. if cfg.questions.is_empty() {
  795. println!(" (none)");
  796. } else {
  797. for (name, q) in &cfg.questions {
  798. let def = q
  799. .default
  800. .as_ref()
  801. .map_or_default(|d| format!(" [default: {}]", json_display(d)));
  802. let secret = if q.secret { " [secret]" } else { "" };
  803. let cond = q
  804. .when
  805. .as_ref()
  806. .map_or_default(|w| format!(" [when: {}]", json_display(w)));
  807. println!(
  808. " {} {} ({:?}){}{}{}",
  809. style::cyan("•"),
  810. style::bold(name),
  811. q.kind,
  812. style::dim(&def),
  813. style::yellow(secret),
  814. style::dim(&cond),
  815. );
  816. if let Some(help) = &q.help {
  817. println!(" {}", style::dim(help));
  818. }
  819. if let Some(choices) = &q.choices {
  820. let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect();
  821. println!(" choices: {}", labels.join(", "));
  822. }
  823. }
  824. }
  825. }