reinhardt-admin-cli 0.1.3

Command-line tool for Reinhardt project management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
#![warn(missing_docs)]

//! Reinhardt Admin CLI
//!
//! Global command-line tool for Reinhardt project management.
//! This is the equivalent of Django's `django-admin` command.
//!
//! ## Installation
//!
//! While Reinhardt is on a pre-release (`-rc.*` / `-alpha.*`),
//! `cargo install` requires an explicit `--version` because pre-releases
//! are not selected by default. Once `0.1.0` stable ships, `--version`
//! becomes optional. The literal below is auto-bumped by release-plz on
//! each release.
//!
//! <!-- reinhardt-version-sync -->
//! ```bash
//! cargo install reinhardt-admin-cli --version "0.1.3"
//! ```
//!
//! ## Usage
//!
//! ```bash
//! reinhardt-admin startproject myproject --with-rest
//! reinhardt-admin startproject myproject --with-pages
//! reinhardt-admin startapp myapp --with-rest
//! reinhardt-formatter fmt src/
//! reinhardt-admin --help
//! ```

use reinhardt_admin_cli::migrate_v2;

use std::path::PathBuf;

use clap::{Parser, Subcommand, ValueEnum};
use colored::Colorize;
use reinhardt_commands::{
	BaseCommand, CommandContext, CommandResult, PluginDisableCommand, PluginEnableCommand,
	PluginInfoCommand, PluginInstallCommand, PluginListCommand, PluginRemoveCommand,
	PluginSearchCommand, PluginUpdateCommand, StartAppCommand, StartProjectCommand,
};
use std::process;

/// Project/app architecture type used with `--template`.
#[derive(Clone, Debug, ValueEnum)]
enum TemplateType {
	/// RESTful API project/app structure
	Rest,
	/// Pages (WASM + SSR) project/app structure
	Pages,
}

/// The resolved project architecture, after alias expansion.
enum ResolvedProjectType {
	Pages,
	Rest,
}

/// Resolves the mutually-exclusive `--template`/`--with-pages`/`--with-rest` group
/// into a single `ResolvedProjectType`.
///
/// # Panics
///
/// Unreachable in practice — clap's `ArgGroup` with `required = true` guarantees
/// that exactly one of the three args is set.
fn resolve_project_type(
	template: Option<TemplateType>,
	with_pages: bool,
	with_rest: bool,
) -> ResolvedProjectType {
	match (template, with_pages, with_rest) {
		(Some(TemplateType::Pages), _, _) | (_, true, _) => ResolvedProjectType::Pages,
		(Some(TemplateType::Rest), _, _) | (_, _, true) => ResolvedProjectType::Rest,
		// ArgGroup required=true guarantees one branch above is taken (#3842)
		_ => unreachable!(),
	}
}

#[derive(Parser)]
#[command(name = "reinhardt-admin")]
#[command(about = "Reinhardt project administration utility", long_about = None)]
#[command(version)]
struct Cli {
	#[command(subcommand)]
	command: Commands,

	/// Verbosity level (can be repeated)
	#[arg(short, long, action = clap::ArgAction::Count)]
	verbosity: u8,
}

#[derive(Subcommand)]
enum Commands {
	/// Create a new Reinhardt project
	#[command(group(
		clap::ArgGroup::new("project_type")
			.required(true)
			.args(["template", "with_pages", "with_rest"])
	))]
	Startproject {
		/// Name of the project
		#[arg(value_name = "PROJECT_NAME")]
		name: String,

		/// Directory to create the project in (defaults to current directory)
		#[arg(value_name = "DIRECTORY")]
		directory: Option<String>,

		/// Project architecture type: rest (RESTful API) or pages (WASM + SSR)
		#[arg(long, value_name = "TYPE", value_enum, group = "project_type")]
		template: Option<TemplateType>,

		/// Create a project with reinhardt-pages (WASM + SSR). Alias for --template pages.
		#[arg(long, group = "project_type")]
		with_pages: bool,

		/// Create a RESTful API project. Alias for --template rest.
		#[arg(long, group = "project_type")]
		with_rest: bool,

		/// Root directory whose sub-templates override embedded defaults.
		/// Also reads the REINHARDT_TEMPLATE_DIR environment variable.
		#[arg(long, value_name = "DIR")]
		template_dir: Option<String>,
	},

	/// Create a new Reinhardt app
	#[command(group(
		clap::ArgGroup::new("app_type")
			.required(true)
			.args(["template", "with_pages", "with_rest"])
	))]
	Startapp {
		/// Name of the app
		#[arg(value_name = "APP_NAME")]
		name: String,

		/// Directory to create the app in (defaults to current directory)
		#[arg(value_name = "DIRECTORY")]
		directory: Option<String>,

		/// App architecture type: rest (RESTful API) or pages (WASM + SSR)
		#[arg(long, value_name = "TYPE", value_enum, group = "app_type")]
		template: Option<TemplateType>,

		/// Create an app with reinhardt-pages (WASM + SSR). Alias for --template pages.
		#[arg(long, group = "app_type")]
		with_pages: bool,

		/// Create a RESTful API app. Alias for --template rest.
		#[arg(long, group = "app_type")]
		with_rest: bool,

		/// Root directory whose sub-templates override embedded defaults.
		/// Also reads the REINHARDT_TEMPLATE_DIR environment variable.
		#[arg(long, value_name = "DIR")]
		template_dir: Option<String>,
	},

	/// Manage Reinhardt plugins (Dentdelion)
	Plugin {
		#[command(subcommand)]
		subcommand: PluginCommands,
	},

	/// Format Rust code and page!/form!/head! macro DSL in source files
	///
	/// By default, formats page!/form!/head! DSL macros with Topiary and then runs rustfmt.
	/// Use --with-rustfmt=false to only format Reinhardt DSL macros.
	Fmt {
		/// Path to file or directory to format
		#[arg(value_name = "PATH")]
		path: PathBuf,

		/// Check if files are formatted without modifying them
		#[arg(long)]
		check: bool,

		/// Also run rustfmt after DSL formatting
		#[arg(long, default_value = "true", action = clap::ArgAction::Set)]
		with_rustfmt: bool,

		/// Path to rustfmt.toml configuration file
		#[arg(long, value_name = "PATH")]
		config_path: Option<PathBuf>,

		/// Rust edition to use (overrides rustfmt.toml)
		#[arg(long, value_name = "EDITION")]
		edition: Option<String>,

		/// Style edition to use (overrides rustfmt.toml)
		#[arg(long, value_name = "EDITION")]
		style_edition: Option<String>,

		/// Set options from command line (overrides rustfmt.toml)
		/// Format: key1=val1,key2=val2
		#[arg(long, value_name = "OPTIONS")]
		config: Option<String>,

		/// Use colored output
		#[arg(long, value_name = "WHEN", default_value = "auto")]
		color: String,

		/// Backup any modified files
		#[arg(long)]
		backup: bool,
	},

	/// Format all code: Reinhardt DSL macros via Topiary + Rust via rustfmt
	///
	/// This command formats page!/form!/head! macros first, then runs
	/// `cargo fmt --all` on the root workspace.
	///
	/// Files that belong to a separate (nested) cargo workspace, such as
	/// `examples/` or the trybuild fixture crates, are skipped. `cargo fmt
	/// --all` only formats the root workspace, so formatting their DSL macros
	/// without the rustfmt pass would leave them inconsistent. Format those
	/// sub-workspaces with their own task (e.g. `cargo make fmt-check-examples`).
	FmtAll {
		/// Check if files are formatted without modifying them
		#[arg(long)]
		check: bool,

		/// Path to rustfmt.toml configuration file
		/// If not specified, searches upward from current directory for rustfmt.toml
		#[arg(long, value_name = "PATH")]
		config_path: Option<PathBuf>,

		/// Rust edition to use (overrides rustfmt.toml)
		#[arg(long, value_name = "EDITION")]
		edition: Option<String>,

		/// Style edition to use (overrides rustfmt.toml)
		#[arg(long, value_name = "EDITION")]
		style_edition: Option<String>,

		/// Set options from command line (overrides rustfmt.toml)
		/// Format: key1=val1,key2=val2
		#[arg(long, value_name = "OPTIONS")]
		config: Option<String>,

		/// Use colored output
		#[arg(long, value_name = "WHEN", default_value = "auto")]
		color: String,

		/// Backup any modified files
		#[arg(long)]
		backup: bool,
	},

	/// Migrate Manouche v1 source files to v2 grammar (spec §6.1 + §6.2).
	MigrateManoucheV2(migrate_v2::MigrateV2Args),
}

/// Plugin management subcommands
#[derive(Subcommand)]
enum PluginCommands {
	/// List installed plugins
	List {
		/// Show detailed information
		#[arg(short, long)]
		verbose: bool,

		/// Show only enabled plugins
		#[arg(long)]
		enabled: bool,

		/// Show only disabled plugins
		#[arg(long)]
		disabled: bool,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Show plugin information
	Info {
		/// Plugin name (e.g., auth-delion)
		#[arg(value_name = "NAME")]
		name: String,

		/// Fetch info from crates.io instead of local
		#[arg(long)]
		remote: bool,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Install a plugin from crates.io
	Install {
		/// Plugin name (e.g., auth-delion)
		#[arg(value_name = "NAME")]
		name: String,

		/// Specific version to install
		#[arg(long)]
		version: Option<String>,

		/// Skip confirmation prompt
		#[arg(short, long)]
		yes: bool,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Remove a plugin
	Remove {
		/// Plugin name to remove
		#[arg(value_name = "NAME")]
		name: String,

		/// Also remove plugin configuration
		#[arg(long)]
		purge: bool,

		/// Skip confirmation prompt
		#[arg(short, long)]
		yes: bool,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Enable a disabled plugin
	Enable {
		/// Plugin name to enable
		#[arg(value_name = "NAME")]
		name: String,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Disable an enabled plugin
	Disable {
		/// Plugin name to disable
		#[arg(value_name = "NAME")]
		name: String,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},

	/// Search for plugins on crates.io
	Search {
		/// Search query
		#[arg(value_name = "QUERY")]
		query: String,

		/// Maximum number of results
		#[arg(long, default_value = "10")]
		limit: u64,
	},

	/// Update plugin(s) to latest version
	Update {
		/// Plugin name (omit for --all)
		#[arg(value_name = "NAME")]
		name: Option<String>,

		/// Update all plugins
		#[arg(long)]
		all: bool,

		/// Skip confirmation prompt
		#[arg(short, long)]
		yes: bool,

		/// Project root directory
		#[arg(long)]
		project_root: Option<String>,
	},
}

#[tokio::main]
async fn main() {
	let cli = Cli::parse();

	let result = match cli.command {
		Commands::Startproject {
			name,
			directory,
			template,
			with_pages,
			with_rest,
			template_dir,
		} => {
			run_startproject(
				name,
				directory,
				template,
				with_pages,
				with_rest,
				template_dir,
				cli.verbosity,
			)
			.await
		}
		Commands::Startapp {
			name,
			directory,
			template,
			with_pages,
			with_rest,
			template_dir,
		} => {
			run_startapp(
				name,
				directory,
				template,
				with_pages,
				with_rest,
				template_dir,
				cli.verbosity,
			)
			.await
		}
		Commands::Plugin { subcommand } => run_plugin(subcommand, cli.verbosity).await,
		Commands::Fmt {
			path,
			check,
			with_rustfmt,
			config_path,
			edition,
			style_edition,
			config,
			color,
			backup,
		} => run_fmt(
			path,
			check,
			with_rustfmt,
			config_path,
			edition,
			style_edition,
			config,
			color,
			backup,
			cli.verbosity,
		),
		Commands::FmtAll {
			check,
			config_path,
			edition,
			style_edition,
			config,
			color,
			backup,
		} => run_fmt_all(
			check,
			config_path,
			edition,
			style_edition,
			config,
			color,
			backup,
			cli.verbosity,
		),
		Commands::MigrateManoucheV2(args) => {
			if let Err(e) = migrate_v2::run(args) {
				eprintln!("{}", format!("error: {e}").red());
				process::exit(1);
			}
			Ok(())
		}
	};

	if let Err(e) = result {
		eprintln!("Error: {}", e);
		process::exit(1);
	}
}

async fn run_startproject(
	name: String,
	directory: Option<String>,
	template: Option<TemplateType>,
	with_pages: bool,
	with_rest: bool,
	template_dir: Option<String>,
	verbosity: u8,
) -> CommandResult<()> {
	let mut ctx = CommandContext::default();
	ctx.set_verbosity(verbosity);
	ctx.add_arg(name);
	if let Some(dir) = directory {
		ctx.add_arg(dir);
	}
	match resolve_project_type(template, with_pages, with_rest) {
		ResolvedProjectType::Pages => ctx.set_option("with-pages".to_string(), "true".to_string()),
		ResolvedProjectType::Rest => ctx.set_option("restful".to_string(), "true".to_string()),
	}
	if let Some(td) = template_dir {
		ctx.set_option("template-dir".to_string(), td);
	}

	let cmd = StartProjectCommand;
	cmd.execute(&ctx).await
}

async fn run_startapp(
	name: String,
	directory: Option<String>,
	template: Option<TemplateType>,
	with_pages: bool,
	with_rest: bool,
	template_dir: Option<String>,
	verbosity: u8,
) -> CommandResult<()> {
	let mut ctx = CommandContext::default();
	ctx.set_verbosity(verbosity);
	ctx.add_arg(name);
	if let Some(dir) = directory {
		ctx.add_arg(dir);
	}
	match resolve_project_type(template, with_pages, with_rest) {
		ResolvedProjectType::Pages => ctx.set_option("with-pages".to_string(), "true".to_string()),
		ResolvedProjectType::Rest => ctx.set_option("restful".to_string(), "true".to_string()),
	}
	if let Some(td) = template_dir {
		ctx.set_option("template-dir".to_string(), td);
	}

	let cmd = StartAppCommand;
	cmd.execute(&ctx).await
}

async fn run_plugin(subcommand: PluginCommands, verbosity: u8) -> CommandResult<()> {
	match subcommand {
		PluginCommands::List {
			verbose,
			enabled,
			disabled,
			project_root,
		} => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			if verbose {
				ctx.set_option("verbose".to_string(), "true".to_string());
			}
			if enabled {
				ctx.set_option("enabled".to_string(), "true".to_string());
			}
			if disabled {
				ctx.set_option("disabled".to_string(), "true".to_string());
			}
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginListCommand.execute(&ctx).await
		}
		PluginCommands::Info {
			name,
			remote,
			project_root,
		} => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(name);
			if remote {
				ctx.set_option("remote".to_string(), "true".to_string());
			}
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginInfoCommand.execute(&ctx).await
		}
		PluginCommands::Install {
			name,
			version,
			yes,
			project_root,
		} => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(name);
			if let Some(v) = version {
				ctx.set_option("version".to_string(), v);
			}
			if yes {
				ctx.set_option("yes".to_string(), "true".to_string());
			}
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginInstallCommand.execute(&ctx).await
		}
		PluginCommands::Remove {
			name,
			purge,
			yes,
			project_root,
		} => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(name);
			if purge {
				ctx.set_option("purge".to_string(), "true".to_string());
			}
			if yes {
				ctx.set_option("yes".to_string(), "true".to_string());
			}
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginRemoveCommand.execute(&ctx).await
		}
		PluginCommands::Enable { name, project_root } => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(name);
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginEnableCommand.execute(&ctx).await
		}
		PluginCommands::Disable { name, project_root } => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(name);
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginDisableCommand.execute(&ctx).await
		}
		PluginCommands::Search { query, limit } => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			ctx.add_arg(query);
			ctx.set_option("limit".to_string(), limit.to_string());
			PluginSearchCommand.execute(&ctx).await
		}
		PluginCommands::Update {
			name,
			all,
			yes,
			project_root,
		} => {
			let mut ctx = CommandContext::default();
			ctx.set_verbosity(verbosity);
			if let Some(n) = name {
				ctx.add_arg(n);
			}
			if all {
				ctx.set_option("all".to_string(), "true".to_string());
			}
			if yes {
				ctx.set_option("yes".to_string(), "true".to_string());
			}
			if let Some(root) = project_root {
				ctx.set_option("project-root".to_string(), root);
			}
			PluginUpdateCommand.execute(&ctx).await
		}
	}
}

#[allow(clippy::too_many_arguments)] // CLI command handler with many options
fn run_fmt(
	path: PathBuf,
	check: bool,
	with_rustfmt: bool,
	config_path: Option<PathBuf>,
	edition: Option<String>,
	style_edition: Option<String>,
	config: Option<String>,
	color: String,
	backup: bool,
	verbosity: u8,
) -> CommandResult<()> {
	let mut command = formatter_delegate_command(verbosity);
	command.arg("fmt").arg(path);
	push_flag(&mut command, "--check", check);
	if !with_rustfmt {
		command.arg("--with-rustfmt=false");
	}
	push_optional_path(&mut command, "--config-path", config_path.as_ref());
	push_optional_str(&mut command, "--edition", edition.as_deref());
	push_optional_str(&mut command, "--style-edition", style_edition.as_deref());
	push_optional_str(&mut command, "--config", config.as_deref());
	push_optional_str(&mut command, "--color", Some(&color));
	push_flag(&mut command, "--backup", backup);
	run_formatter_delegate(command)
}

/// Format all code: DSL macros via Topiary, then Rust via `cargo fmt --all`.
#[allow(clippy::too_many_arguments)] // CLI command handler with many options
fn run_fmt_all(
	check: bool,
	config_path: Option<PathBuf>,
	edition: Option<String>,
	style_edition: Option<String>,
	config: Option<String>,
	color: String,
	backup: bool,
	verbosity: u8,
) -> CommandResult<()> {
	let mut command = formatter_delegate_command(verbosity);
	command.arg("fmt-all");
	push_flag(&mut command, "--check", check);
	push_optional_path(&mut command, "--config-path", config_path.as_ref());
	push_optional_str(&mut command, "--edition", edition.as_deref());
	push_optional_str(&mut command, "--style-edition", style_edition.as_deref());
	push_optional_str(&mut command, "--config", config.as_deref());
	push_optional_str(&mut command, "--color", Some(&color));
	push_flag(&mut command, "--backup", backup);
	run_formatter_delegate(command)
}

fn formatter_delegate_command(verbosity: u8) -> process::Command {
	let mut command = process::Command::new("reinhardt-formatter");
	for _ in 0..verbosity {
		command.arg("-v");
	}
	command
}

fn push_flag(command: &mut process::Command, flag: &str, enabled: bool) {
	if enabled {
		command.arg(flag);
	}
}

fn push_optional_path(command: &mut process::Command, flag: &str, value: Option<&PathBuf>) {
	if let Some(value) = value {
		command.arg(flag).arg(value);
	}
}

fn push_optional_str(command: &mut process::Command, flag: &str, value: Option<&str>) {
	if let Some(value) = value {
		command.arg(flag).arg(value);
	}
}

fn run_formatter_delegate(mut command: process::Command) -> CommandResult<()> {
	let status = command.status().map_err(|err| {
		reinhardt_commands::CommandError::ExecutionError(format!(
			"failed to run reinhardt-formatter: {err}. Install or build the formatter binary to use fmt commands."
		))
	})?;

	if status.success() {
		Ok(())
	} else {
		Err(reinhardt_commands::CommandError::ExecutionError(format!(
			"reinhardt-formatter exited with status {status}"
		)))
	}
}

#[cfg(test)]
mod resolve_project_type_tests {
	use super::*;

	#[test]
	fn with_pages_bool_resolves_to_pages() {
		assert!(matches!(
			resolve_project_type(None, true, false),
			ResolvedProjectType::Pages
		));
	}

	#[test]
	fn with_rest_bool_resolves_to_rest() {
		assert!(matches!(
			resolve_project_type(None, false, true),
			ResolvedProjectType::Rest
		));
	}

	#[test]
	fn template_pages_resolves_to_pages() {
		assert!(matches!(
			resolve_project_type(Some(TemplateType::Pages), false, false),
			ResolvedProjectType::Pages
		));
	}

	#[test]
	fn template_rest_resolves_to_rest() {
		assert!(matches!(
			resolve_project_type(Some(TemplateType::Rest), false, false),
			ResolvedProjectType::Rest
		));
	}

	#[test]
	fn template_pages_with_bool_false_resolves_to_pages() {
		// --template pages takes precedence, both bools false
		assert!(matches!(
			resolve_project_type(Some(TemplateType::Pages), false, false),
			ResolvedProjectType::Pages
		));
	}

	#[test]
	fn template_rest_with_bool_false_resolves_to_rest() {
		// --template rest takes precedence, both bools false
		assert!(matches!(
			resolve_project_type(Some(TemplateType::Rest), false, false),
			ResolvedProjectType::Rest
		));
	}
}

#[cfg(test)]
mod arg_group_tests {
	use super::*;
	use clap::error::ErrorKind;

	fn try_parse(args: &[&str]) -> Result<Cli, clap::Error> {
		Cli::try_parse_from(args)
	}

	#[test]
	fn startproject_with_pages_flag_accepted() {
		assert!(
			try_parse(&["reinhardt-admin", "startproject", "myproj", "--with-pages"]).is_ok(),
			"--with-pages should be accepted"
		);
	}

	#[test]
	fn startproject_with_rest_flag_accepted() {
		assert!(
			try_parse(&["reinhardt-admin", "startproject", "myproj", "--with-rest"]).is_ok(),
			"--with-rest should be accepted"
		);
	}

	#[test]
	fn startproject_template_pages_accepted() {
		assert!(
			try_parse(&[
				"reinhardt-admin",
				"startproject",
				"myproj",
				"--template",
				"pages"
			])
			.is_ok(),
			"--template pages should be accepted"
		);
	}

	#[test]
	fn startproject_template_rest_accepted() {
		assert!(
			try_parse(&[
				"reinhardt-admin",
				"startproject",
				"myproj",
				"--template",
				"rest"
			])
			.is_ok(),
			"--template rest should be accepted"
		);
	}

	#[test]
	fn startproject_missing_type_is_error() {
		let result = try_parse(&["reinhardt-admin", "startproject", "myproj"]);
		assert!(result.is_err(), "expected Err when type flag omitted");
		assert_eq!(
			result.err().unwrap().kind(),
			ErrorKind::MissingRequiredArgument
		);
	}

	#[test]
	fn startproject_duplicate_flags_are_error() {
		assert!(
			try_parse(&[
				"reinhardt-admin",
				"startproject",
				"myproj",
				"--with-pages",
				"--with-rest",
			])
			.is_err(),
			"duplicate type flags should be rejected"
		);
	}

	#[test]
	fn startproject_template_and_alias_together_are_error() {
		assert!(
			try_parse(&[
				"reinhardt-admin",
				"startproject",
				"myproj",
				"--template",
				"pages",
				"--with-pages",
			])
			.is_err(),
			"--template + --with-pages should be rejected"
		);
	}

	#[test]
	fn startapp_with_pages_flag_accepted() {
		assert!(
			try_parse(&["reinhardt-admin", "startapp", "myapp", "--with-pages"]).is_ok(),
			"--with-pages should be accepted for startapp"
		);
	}

	#[test]
	fn startapp_missing_type_is_error() {
		let result = try_parse(&["reinhardt-admin", "startapp", "myapp"]);
		assert!(result.is_err(), "expected Err when type flag omitted");
		assert_eq!(
			result.err().unwrap().kind(),
			ErrorKind::MissingRequiredArgument
		);
	}
}