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
//! Command registration methods for AppBuilder.
//!
//! This module contains methods for registering commands and handlers:
//! - Simple command registration with closures
//! - Struct-based handler registration
//! - Command groups for nested hierarchies
//! - Hook registration
use clap::ArgMatches;
use serde::Serialize;
use super::{AppBuilder, PendingCommand};
use crate::cli::group::{
ClosureRecipe, CommandConfig, ErasedConfigRecipe, GroupBuilder, GroupEntry, PassthroughRecipe,
StructRecipe,
};
use crate::cli::handler::{CommandContext, FnHandler, Handler, HandlerResult};
use crate::cli::hooks::Hooks;
use crate::setup::SetupError;
impl AppBuilder {
/// Creates a command group for organizing related commands.
///
/// Groups allow nested command hierarchies with a fluent API:
///
/// ```rust,ignore
/// App::builder()
/// .template_dir("templates")
/// .group("db", |g| g
/// .command("migrate", db::migrate)
/// .command("backup", db::backup))
/// .group("app", |g| g
/// .command("start", app::start)
/// .group("config", |g| g
/// .command("get", app::config_get)
/// .command("set", app::config_set)))
/// .build()
/// ```
///
/// Commands within groups use dot notation for paths:
/// - `db.migrate`, `db.backup`
/// - `app.start`, `app.config.get`, `app.config.set`
pub fn group<F>(mut self, name: &str, configure: F) -> Result<Self, SetupError>
where
F: FnOnce(GroupBuilder) -> GroupBuilder,
{
let builder = configure(GroupBuilder::new());
self.register_group(name, builder)?;
Ok(self)
}
/// Registers a command handler with inline configuration.
///
/// Use this to set explicit template or hooks without using `.hooks()` separately:
///
/// ```rust,ignore
/// App::builder()
/// .command_with("list", handler, |cfg| cfg
/// .template("custom/list.j2")
/// .pre_dispatch(validate_auth)
/// .post_output(copy_to_clipboard))
/// .build()
/// ```
pub fn command_with<F, T, C>(
mut self,
path: &str,
handler: F,
configure: C,
) -> Result<Self, SetupError>
where
F: FnMut(&ArgMatches, &CommandContext) -> HandlerResult<T> + 'static,
T: Serialize + 'static,
C: FnOnce(CommandConfig<FnHandler<F, T>>) -> CommandConfig<FnHandler<F, T>>,
{
let config = CommandConfig::new(FnHandler::new(handler));
let mut config = configure(config);
// Resolve template
let template = config
.template
.clone()
.unwrap_or_else(|| self.resolve_template(path));
// Register hooks if present
if let Some(hooks) = config.hooks.take() {
self.command_hooks.insert(path.to_string(), hooks);
}
// Create a recipe for deferred closure creation using the handler
let recipe = ClosureRecipe::new(config.handler);
// Store pending command - check for duplicates
if self.pending_commands.borrow().contains_key(path) {
return Err(SetupError::DuplicateCommand(path.to_string()));
}
self.pending_commands.borrow_mut().insert(
path.to_string(),
PendingCommand {
recipe: Box::new(recipe),
template,
},
);
Ok(self)
}
/// Helper to register a group's commands recursively.
pub(crate) fn register_group(
&mut self,
prefix: &str,
builder: GroupBuilder,
) -> Result<(), SetupError> {
for (name, entry) in builder.entries {
let path = format!("{}.{}", prefix, name);
match entry {
GroupEntry::Command { mut handler } => {
// Resolve template
let template = handler
.template()
.map(String::from)
.unwrap_or_else(|| self.resolve_template(&path));
// Extract and register hooks
if let Some(hooks) = handler.take_hooks() {
self.command_hooks.insert(path.clone(), hooks);
}
// Create a recipe for deferred closure creation
let recipe = ErasedConfigRecipe::from_handler(handler);
// Check for duplicates
if self.pending_commands.borrow().contains_key(&path) {
return Err(SetupError::DuplicateCommand(path.clone()));
}
// Store pending command
self.pending_commands.borrow_mut().insert(
path,
PendingCommand {
recipe: Box::new(recipe),
template,
},
);
}
GroupEntry::Group { builder: nested } => {
self.register_group(&path, nested)?;
}
}
}
Ok(())
}
/// Resolves a template from a command path using conventions.
///
/// Resolution order:
/// 1. If template_registry is set, look up by command path (e.g., "db/migrate.j2")
/// 2. If template_dir is set, return the file path for runtime loading
/// 3. Otherwise return empty string (JSON serialization fallback)
pub(crate) fn resolve_template(&self, command_path: &str) -> String {
let file_path = command_path.replace('.', "/");
let template_name = format!("{}{}", file_path, self.template_ext);
// First, try to get content from embedded templates
if let Some(ref registry) = self.template_registry {
if let Ok(content) = registry.get_content(&template_name) {
return content;
}
}
// Fall back to file path if template_dir is configured
if let Some(ref dir) = self.template_dir {
return format!("{}/{}", dir.display(), template_name);
}
// No template found - will use JSON serialization in structured modes
String::new()
}
/// Registers a command handler (closure) with a template.
///
/// The handler will be invoked when the command path matches. The path uses
/// dot notation for nested commands (e.g., "config.get" matches `app config get`).
///
/// # Arguments
///
/// * `path` - Command path using dot notation (e.g., "list" or "config.get")
/// * `handler` - The handler closure
/// * `template` - MiniJinja template for rendering output
///
/// # Example
///
/// ```rust,ignore
/// use standout::cli::{App, Output, HandlerResult};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct ListOutput { items: Vec<String> }
///
/// App::builder()
/// .command("list", |_m, _ctx| -> HandlerResult<ListOutput> {
/// Ok(Output::Render(ListOutput { items: vec!["one".into()] }))
/// }, "{% for item in items %}{{ item }}\n{% endfor %}")
/// .parse(cmd);
/// ```
pub fn command<F, T>(self, path: &str, handler: F, template: &str) -> Result<Self, SetupError>
where
F: FnMut(&ArgMatches, &CommandContext) -> HandlerResult<T> + 'static,
T: Serialize + 'static,
{
self.command_handler(path, FnHandler::new(handler), template)
}
/// Registers a struct handler with a template.
///
/// Use this when your handler needs to carry state (like database connections).
///
/// # Arguments
///
/// * `path` - Command path using dot notation (e.g., "list" or "config.get")
/// * `handler` - A struct implementing the `Handler` trait
/// * `template` - MiniJinja template for rendering output
///
/// # Example
///
/// ```rust,ignore
/// use standout::cli::{App, Handler, HandlerResult, Output, CommandContext};
/// use clap::ArgMatches;
/// use serde::Serialize;
///
/// struct ListHandler { db: Database }
///
/// impl Handler for ListHandler {
/// type Output = Vec<Item>;
/// fn handle(&self, _m: &ArgMatches, _ctx: &CommandContext) -> HandlerResult<Self::Output> {
/// Ok(Output::Render(self.db.list()?))
/// }
/// }
///
/// App::builder()
/// .command_handler("list", ListHandler { db }, "{% for item in items %}...")
/// .parse(cmd);
/// ```
pub fn command_handler<H, T>(
self,
path: &str,
handler: H,
template: &str,
) -> Result<Self, SetupError>
where
H: Handler<Output = T> + 'static,
T: Serialize + 'static,
{
let template = template.to_string();
// Create a recipe for deferred closure creation
let recipe = StructRecipe::new(handler);
// Check for duplicates
if self.pending_commands.borrow().contains_key(path) {
return Err(SetupError::DuplicateCommand(path.to_string()));
}
// Store pending command - closure will be created at dispatch time
self.pending_commands.borrow_mut().insert(
path.to_string(),
PendingCommand {
recipe: Box::new(recipe),
template,
},
);
Ok(self)
}
/// Registers a passthrough command that bypasses the rendering pipeline.
///
/// The handler receives `&ArgMatches` and `&CommandContext`, writes directly to
/// stdout (or does whatever it needs), and the framework marks the command as
/// handled with no rendered output. The command still participates in
/// help/completions and dispatch.
///
/// Use this for commands that manage their own output (e.g., shell init scripts
/// that output `eval`-able code, or commands that delegate to another tool).
///
/// # Example
///
/// ```rust,ignore
/// use standout::cli::App;
///
/// App::builder()
/// .command_passthrough("init-sh", |_m, _ctx| {
/// print!("export PATH=\"$HOME/.myapp/bin:$PATH\"");
/// Ok(())
/// })
/// .build()?
/// .run(cmd, args);
/// ```
pub fn command_passthrough<F>(self, path: &str, handler: F) -> Result<Self, SetupError>
where
F: FnMut(&ArgMatches, &CommandContext) -> Result<(), anyhow::Error> + 'static,
{
let recipe = PassthroughRecipe::new(handler);
if self.pending_commands.borrow().contains_key(path) {
return Err(SetupError::DuplicateCommand(path.to_string()));
}
self.pending_commands.borrow_mut().insert(
path.to_string(),
PendingCommand {
recipe: Box::new(recipe),
template: String::new(),
},
);
Ok(self)
}
/// Registers hooks for a specific command path.
///
/// Hooks are executed around the command handler:
/// - Pre-dispatch hooks run before the handler
/// - Post-dispatch hooks run after the handler, before rendering (receives raw data)
/// - Post-output hooks run after rendering, can transform output
///
/// Multiple hooks at the same phase are chained in registration order.
/// Hooks abort on first error.
///
/// # Arguments
///
/// * `path` - Command path using dot notation (e.g., "list" or "config.get")
/// * `hooks` - The hooks configuration
///
/// # Example
///
/// ```rust,ignore
/// use standout::cli::{App, Hooks, Output, HookError};
/// use serde_json::json;
///
/// App::builder()
/// .command("list", handler, template)
/// .hooks("list", Hooks::new()
/// .pre_dispatch(|_m, ctx| {
/// println!("Running: {:?}", ctx.command_path);
/// Ok(())
/// })
/// .post_dispatch(|_m, _ctx, mut data| {
/// // Modify raw data before rendering
/// if let Some(obj) = data.as_object_mut() {
/// obj.insert("processed".into(), json!(true));
/// }
/// Ok(data)
/// })
/// .post_output(|_m, _ctx, output| {
/// if let RenderedOutput::Text(ref text) = output {
/// // Copy to clipboard, log, etc.
/// }
/// Ok(output)
/// }))
/// .build()?
/// .run(cmd, args);
/// ```
pub fn hooks(mut self, path: &str, hooks: Hooks) -> Self {
self.command_hooks.insert(path.to_string(), hooks);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::handler::Output as HandlerOutput;
use crate::OutputMode;
use clap::Command;
#[test]
fn test_command_registration() {
use serde_json::json;
let builder = AppBuilder::new()
.command(
"list",
|_m, _ctx| Ok(HandlerOutput::Render(json!({"items": ["a", "b"]}))),
"Items: {{ items }}",
)
.unwrap();
assert!(builder.has_command("list"));
}
#[test]
fn test_hooks_registration() {
use crate::cli::hooks::Hooks;
let builder = AppBuilder::new().hooks("list", Hooks::new().pre_dispatch(|_, _| Ok(())));
assert!(builder.command_hooks.contains_key("list"));
}
#[test]
fn test_command_with_inline_config() {
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let builder = AppBuilder::new()
.command_with(
"list",
|_m, _ctx| Ok(HandlerOutput::Render(json!({"items": ["a", "b"]}))),
move |cfg| {
cfg.template("Items: {{ items | length }}")
.pre_dispatch(move |_, _| {
counter_clone.fetch_add(1, Ordering::SeqCst);
Ok(())
})
},
)
.unwrap();
let cmd = Command::new("app").subcommand(Command::new("list"));
let matches = cmd.try_get_matches_from(["app", "list"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Text);
assert!(result.is_handled());
assert_eq!(result.output(), Some("Items: 2"));
assert_eq!(counter.load(Ordering::SeqCst), 1);
}
// ============================================================================
// Group Tests
// ============================================================================
#[test]
fn test_group_basic() {
use serde_json::json;
let builder = AppBuilder::new()
.group("db", |g| {
g.command("migrate", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"status": "migrated"})))
})
.command("backup", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"status": "backed_up"})))
})
})
.unwrap();
let cmd =
Command::new("app").subcommand(Command::new("db").subcommand(Command::new("migrate")));
let matches = cmd.try_get_matches_from(["app", "db", "migrate"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Json);
assert!(result.is_handled());
let output = result.output().unwrap();
assert!(output.contains("migrated"));
}
#[test]
fn test_group_nested() {
use serde_json::json;
let builder = AppBuilder::new()
.group("app", |g| {
g.command("start", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"action": "start"})))
})
.group("config", |g| {
g.command("get", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"value": "test_value"})))
})
.command("set", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"ok": true})))
})
})
})
.unwrap();
// Test nested command: app.config.get
let cmd = Command::new("cli").subcommand(
Command::new("app")
.subcommand(Command::new("start"))
.subcommand(
Command::new("config")
.subcommand(Command::new("get"))
.subcommand(Command::new("set")),
),
);
let matches = cmd
.try_get_matches_from(["cli", "app", "config", "get"])
.unwrap();
let result = builder.dispatch(matches, OutputMode::Json);
assert!(result.is_handled());
let output = result.output().unwrap();
assert!(output.contains("test_value"));
}
#[test]
fn test_group_with_template() {
use serde_json::json;
let builder = AppBuilder::new()
.group("db", |g| {
g.command_with(
"migrate",
|_m, _ctx| Ok(HandlerOutput::Render(json!({"count": 5}))),
|cfg| cfg.template("Migrated {{ count }} tables"),
)
})
.unwrap();
let cmd =
Command::new("app").subcommand(Command::new("db").subcommand(Command::new("migrate")));
let matches = cmd.try_get_matches_from(["app", "db", "migrate"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Text);
assert!(result.is_handled());
assert_eq!(result.output(), Some("Migrated 5 tables"));
}
#[test]
fn test_group_with_hooks() {
use serde_json::json;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let hook_called = Arc::new(AtomicBool::new(false));
let hook_called_clone = hook_called.clone();
let builder = AppBuilder::new()
.group("db", |g| {
g.command_with(
"migrate",
|_m, _ctx| Ok(HandlerOutput::Render(json!({"done": true}))),
move |cfg| {
cfg.template("{{ done }}").pre_dispatch(move |_, _| {
hook_called_clone.store(true, Ordering::SeqCst);
Ok(())
})
},
)
})
.unwrap();
let cmd =
Command::new("app").subcommand(Command::new("db").subcommand(Command::new("migrate")));
let matches = cmd.try_get_matches_from(["app", "db", "migrate"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Text);
assert!(result.is_handled());
assert!(hook_called.load(Ordering::SeqCst));
}
#[test]
fn test_multiple_groups() {
use serde_json::json;
let builder = AppBuilder::new()
.group("db", |g| {
g.command("migrate", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"type": "db"})))
})
})
.unwrap()
.group("cache", |g| {
g.command("clear", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"type": "cache"})))
})
})
.unwrap();
assert!(builder.has_command("db.migrate"));
assert!(builder.has_command("cache.clear"));
}
#[test]
fn test_group_mixed_with_regular_commands() {
use serde_json::json;
let builder = AppBuilder::new()
.command(
"version",
|_m, _ctx| Ok(HandlerOutput::Render(json!({"v": "1.0.0"}))),
"{{ v }}",
)
.unwrap()
.group("db", |g| {
g.command("migrate", |_m, _ctx| {
Ok(HandlerOutput::Render(json!({"ok": true})))
})
})
.unwrap();
assert!(builder.has_command("version"));
assert!(builder.has_command("db.migrate"));
}
#[test]
fn test_command_passthrough() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let called = Arc::new(AtomicBool::new(false));
let called_clone = called.clone();
let builder = AppBuilder::new()
.command_passthrough("init-sh", move |_m, _ctx| {
called_clone.store(true, Ordering::SeqCst);
Ok(())
})
.unwrap();
assert!(builder.has_command("init-sh"));
let cmd = Command::new("app").subcommand(Command::new("init-sh"));
let matches = cmd.try_get_matches_from(["app", "init-sh"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Text);
assert!(called.load(Ordering::SeqCst));
// Passthrough commands produce empty handled output (silent)
assert!(result.is_handled());
assert_eq!(result.output(), Some(""));
}
#[test]
fn test_group_passthrough() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let called = Arc::new(AtomicBool::new(false));
let called_clone = called.clone();
let builder = AppBuilder::new()
.group("shell", |g| {
g.passthrough("init", move |_m, _ctx| {
called_clone.store(true, Ordering::SeqCst);
Ok(())
})
})
.unwrap();
assert!(builder.has_command("shell.init"));
let cmd =
Command::new("app").subcommand(Command::new("shell").subcommand(Command::new("init")));
let matches = cmd.try_get_matches_from(["app", "shell", "init"]).unwrap();
let result = builder.dispatch(matches, OutputMode::Text);
assert!(called.load(Ordering::SeqCst));
assert!(result.is_handled());
}
}