argot-cmd 0.2.0

An agent-first command interface framework for Rust
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
use std::sync::Arc;

use argot_cmd::{
    render::{render_help, render_markdown},
    Argument, Command, Example, Flag, Parser, Registry,
};

fn build_registry() -> Registry {
    let list = Command::builder("list")
        .alias("ls")
        .summary("List all items")
        .description("Lists items, optionally filtered.")
        .argument(
            Argument::builder("filter")
                .description("optional filter string")
                .build()
                .unwrap(),
        )
        .flag(
            Flag::builder("verbose")
                .short('v')
                .description("verbose output")
                .build()
                .unwrap(),
        )
        .example(Example::new("list everything", "myapp list"))
        .best_practice("pipe output through less for large lists")
        .anti_pattern("list without a filter on huge datasets")
        .build()
        .unwrap();

    let remote_add = Command::builder("add")
        .summary("Add a remote")
        .argument(
            Argument::builder("name")
                .description("remote name")
                .required()
                .build()
                .unwrap(),
        )
        .argument(
            Argument::builder("url")
                .description("remote URL")
                .required()
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    let remote_remove = Command::builder("remove")
        .alias("rm")
        .summary("Remove a remote")
        .argument(
            Argument::builder("name")
                .description("remote name")
                .required()
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();

    let remote = Command::builder("remote")
        .summary("Manage remotes")
        .subcommand(remote_add)
        .subcommand(remote_remove)
        .build()
        .unwrap();

    let run = Command::builder("run")
        .summary("Run a script")
        .handler(Arc::new(|_parsed| {
            println!("run handler called");
            Ok(())
        }))
        .build()
        .unwrap();

    Registry::new(vec![list, remote, run])
}

#[test]
fn test_registry_list_and_get() {
    let r = build_registry();
    assert_eq!(r.list_commands().len(), 3);
    assert!(r.get_command("list").is_some());
    assert!(r.get_command("missing").is_none());
}

#[test]
fn test_registry_get_subcommand() {
    let r = build_registry();
    assert_eq!(
        r.get_subcommand(&["remote", "add"]).unwrap().canonical,
        "add"
    );
    assert_eq!(
        r.get_subcommand(&["remote", "remove"]).unwrap().canonical,
        "remove"
    );
    assert!(r.get_subcommand(&["remote", "nope"]).is_none());
}

#[test]
fn test_registry_search() {
    let r = build_registry();
    let results = r.search("remote");
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].canonical, "remote");

    assert!(r.search("zzz").is_empty());
}

#[test]
fn test_registry_to_json() {
    let r = build_registry();
    let json = r.to_json().unwrap();
    let v: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert!(v.is_array());
    // handler field should be absent (serde skip)
    assert!(json.contains("\"canonical\""));
    assert!(!json.contains("\"handler\""));
}

#[test]
fn test_parse_flat_command_with_alias() {
    let r = build_registry();
    let parser = Parser::new(r.commands());

    let parsed = parser.parse(&["ls"]).unwrap();
    assert_eq!(parsed.command.canonical, "list");
}

#[test]
fn test_parse_flag_boolean() {
    let r = build_registry();
    let parser = Parser::new(r.commands());

    let parsed = parser.parse(&["list", "-v"]).unwrap();
    assert_eq!(parsed.flags["verbose"], "true");
}

#[test]
fn test_parse_subcommand_two_levels() {
    let r = build_registry();
    let parser = Parser::new(r.commands());

    let parsed = parser
        .parse(&["remote", "add", "origin", "https://example.com"])
        .unwrap();
    assert_eq!(parsed.command.canonical, "add");
    assert_eq!(parsed.args["name"], "origin");
    assert_eq!(parsed.args["url"], "https://example.com");
}

#[test]
fn test_parse_subcommand_alias() {
    let r = build_registry();
    let parser = Parser::new(r.commands());

    let parsed = parser.parse(&["remote", "rm", "origin"]).unwrap();
    assert_eq!(parsed.command.canonical, "remove");
    assert_eq!(parsed.args["name"], "origin");
}

#[test]
fn test_parse_missing_required_arg() {
    let r = build_registry();
    let parser = Parser::new(r.commands());

    // "remote add" requires both name and url
    let err = parser.parse(&["remote", "add"]).unwrap_err();
    assert!(
        matches!(err, argot_cmd::ParseError::MissingArgument(_)),
        "expected MissingArgument, got {:?}",
        err
    );
}

#[test]
fn test_render_help_pipeline() {
    let r = build_registry();
    let cmd = r.get_command("list").unwrap();
    let help = render_help(cmd);

    assert!(help.contains("NAME"));
    assert!(help.contains("list"));
    assert!(help.contains("SUMMARY"));
    assert!(help.contains("EXAMPLES"));
    assert!(help.contains("BEST PRACTICES"));
    assert!(help.contains("ANTI-PATTERNS"));
}

#[test]
fn test_render_markdown_pipeline() {
    let r = build_registry();
    let cmd = r.get_command("list").unwrap();
    let md = render_markdown(cmd);
    assert!(md.starts_with("# list"));
}

#[test]
fn test_handler_is_callable() {
    let r = build_registry();
    let cmd = r.get_command("run").unwrap();
    assert!(cmd.handler.is_some());
    // Invoke the handler with a minimal ParsedCommand
    use argot_cmd::ParsedCommand;
    use std::collections::HashMap;
    let parsed = ParsedCommand {
        command: cmd,
        args: HashMap::new(),
        flags: HashMap::new(),
    };
    let result = (cmd.handler.as_ref().unwrap())(&parsed);
    assert!(result.is_ok());
}

#[test]
fn test_full_pipeline() {
    // Build → Register → Parse → Render
    let r = build_registry();
    let parser = Parser::new(r.commands());

    let parsed = parser.parse(&["list", "needle"]).unwrap();
    assert_eq!(parsed.command.canonical, "list");
    assert_eq!(
        parsed.args.get("filter").map(String::as_str),
        Some("needle")
    );

    let help = render_help(parsed.command);
    assert!(!help.is_empty());

    let md = render_markdown(parsed.command);
    assert!(md.starts_with("# list"));
}

#[test]
fn test_serde_round_trip_with_subcommands() {
    let r = build_registry(); // uses the existing helper
    let json = r.to_json().unwrap();

    // Re-parse the JSON into a Vec<Command>
    let commands: Vec<argot_cmd::Command> = serde_json::from_str(&json).unwrap();

    // Verify structure survived round-trip
    let remote = commands
        .iter()
        .find(|c| c.canonical == "remote")
        .expect("remote not found");
    assert!(
        !remote.subcommands.is_empty(),
        "subcommands should survive serde"
    );

    let add_sub = remote.subcommands.iter().find(|c| c.canonical == "add");
    assert!(
        add_sub.is_some(),
        "remote.add subcommand should survive serde"
    );

    // Handlers are skipped — verify they are None after deserialization
    let run = commands
        .iter()
        .find(|c| c.canonical == "run")
        .expect("run not found");
    assert!(
        run.handler.is_none(),
        "handler must be None after deserialization"
    );

    // Re-build a registry from the deserialized commands and verify parsing still works
    let new_registry = argot_cmd::Registry::new(commands);
    let parser = argot_cmd::Parser::new(new_registry.commands());
    let parsed = parser.parse(&["list"]).unwrap();
    assert_eq!(parsed.command.canonical, "list");
}

#[test]
fn test_command_named_help_parses_correctly() {
    // A user-defined "help" command should be parseable; it only conflicts
    // with Cli's --help flag, not with direct Parser use.
    let help_cmd = argot_cmd::Command::builder("help")
        .summary("Show help information")
        .build()
        .unwrap();
    let registry = argot_cmd::Registry::new(vec![help_cmd]);
    let parser = argot_cmd::Parser::new(registry.commands());
    let parsed = parser.parse(&["help"]).unwrap();
    assert_eq!(parsed.command.canonical, "help");
}

#[test]
fn test_command_named_version_parses_correctly() {
    let version_cmd = argot_cmd::Command::builder("version")
        .summary("Print version information")
        .build()
        .unwrap();
    let registry = argot_cmd::Registry::new(vec![version_cmd]);
    let parser = argot_cmd::Parser::new(registry.commands());
    let parsed = parser.parse(&["version"]).unwrap();
    assert_eq!(parsed.command.canonical, "version");
}

// ================================================================
// ParseError variant coverage
// ================================================================

#[test]
fn test_parse_error_no_command() {
    let cmds = vec![Command::builder("run").build().unwrap()];
    assert!(matches!(
        Parser::new(&cmds).parse(&[]),
        Err(argot_cmd::ParseError::NoCommand)
    ));
}

#[test]
fn test_parse_error_unknown_command() {
    let cmds = vec![Command::builder("run").build().unwrap()];
    assert!(matches!(
        Parser::new(&cmds).parse(&["nope"]),
        Err(argot_cmd::ParseError::Resolve(
            argot_cmd::ResolveError::Unknown { .. }
        ))
    ));
}

#[test]
fn test_parse_error_ambiguous_command() {
    let cmds = vec![
        Command::builder("fetch").build().unwrap(),
        Command::builder("format").build().unwrap(),
    ];
    assert!(matches!(
        Parser::new(&cmds).parse(&["f"]),
        Err(argot_cmd::ParseError::Resolve(
            argot_cmd::ResolveError::Ambiguous { .. }
        ))
    ));
}

#[test]
fn test_parse_error_missing_argument() {
    let cmds = vec![Command::builder("get")
        .argument(Argument::builder("id").required().build().unwrap())
        .build()
        .unwrap()];
    match Parser::new(&cmds).parse(&["get"]) {
        Err(argot_cmd::ParseError::MissingArgument(n)) => assert_eq!(n, "id"),
        other => panic!("expected MissingArgument(id), got {:?}", other),
    }
}

#[test]
fn test_parse_error_unexpected_argument() {
    let cmds = vec![Command::builder("run").build().unwrap()];
    match Parser::new(&cmds).parse(&["run", "extra"]) {
        Err(argot_cmd::ParseError::UnexpectedArgument(v)) => assert_eq!(v, "extra"),
        other => panic!("expected UnexpectedArgument, got {:?}", other),
    }
}

#[test]
fn test_parse_error_missing_required_flag() {
    let cmds = vec![Command::builder("deploy")
        .flag(
            Flag::builder("env")
                .takes_value()
                .required()
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    match Parser::new(&cmds).parse(&["deploy"]) {
        Err(argot_cmd::ParseError::MissingFlag(n)) => assert_eq!(n, "env"),
        other => panic!("expected MissingFlag(env), got {:?}", other),
    }
}

#[test]
fn test_parse_error_flag_missing_value() {
    let cmds = vec![Command::builder("build")
        .flag(Flag::builder("target").takes_value().build().unwrap())
        .build()
        .unwrap()];
    match Parser::new(&cmds).parse(&["build", "--target"]) {
        Err(argot_cmd::ParseError::FlagMissingValue { name }) => assert_eq!(name, "target"),
        other => panic!("expected FlagMissingValue, got {:?}", other),
    }
}

#[test]
fn test_parse_error_unknown_flag() {
    let cmds = vec![Command::builder("run").build().unwrap()];
    match Parser::new(&cmds).parse(&["run", "--ghost"]) {
        Err(argot_cmd::ParseError::UnknownFlag(n)) => assert!(n.contains("ghost")),
        other => panic!("expected UnknownFlag, got {:?}", other),
    }
}

#[test]
fn test_parse_error_unknown_subcommand() {
    let cmds = vec![Command::builder("remote")
        .subcommand(Command::builder("add").build().unwrap())
        .build()
        .unwrap()];
    match Parser::new(&cmds).parse(&["remote", "bogus"]) {
        Err(argot_cmd::ParseError::UnknownSubcommand { parent, got }) => {
            assert_eq!(parent, "remote");
            assert_eq!(got, "bogus");
        }
        other => panic!("expected UnknownSubcommand, got {:?}", other),
    }
}

#[test]
fn test_parse_error_invalid_choice() {
    let cmds = vec![Command::builder("build")
        .flag(
            Flag::builder("format")
                .takes_value()
                .choices(["json", "yaml"])
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    match Parser::new(&cmds).parse(&["build", "--format=xml"]) {
        Err(argot_cmd::ParseError::InvalidChoice {
            flag,
            value,
            choices,
        }) => {
            assert_eq!(flag, "format");
            assert_eq!(value, "xml");
            assert!(choices.contains(&"json".to_string()));
        }
        other => panic!("expected InvalidChoice, got {:?}", other),
    }
}

// ================================================================
// Positive paths for recently added features
// ================================================================

#[test]
fn test_choices_valid_value_accepted() {
    let cmds = vec![Command::builder("build")
        .flag(
            Flag::builder("fmt")
                .takes_value()
                .choices(["json", "yaml"])
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    let parsed = Parser::new(&cmds).parse(&["build", "--fmt=yaml"]).unwrap();
    assert_eq!(parsed.flags["fmt"], "yaml");
}

#[test]
fn test_repeatable_boolean_flag_count() {
    let cmds = vec![Command::builder("run")
        .flag(
            Flag::builder("verbose")
                .short('v')
                .repeatable()
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    let parsed = Parser::new(&cmds)
        .parse(&["run", "-v", "-v", "-v"])
        .unwrap();
    assert_eq!(parsed.flags["verbose"], "3");
    assert_eq!(parsed.flag_count("verbose"), 3);
}

#[test]
fn test_repeatable_value_flag_collects() {
    let cmds = vec![Command::builder("run")
        .flag(
            Flag::builder("tag")
                .takes_value()
                .repeatable()
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    let parsed = Parser::new(&cmds)
        .parse(&["run", "--tag=alpha", "--tag=beta"])
        .unwrap();
    let tags: Vec<String> = serde_json::from_str(&parsed.flags["tag"]).unwrap();
    assert_eq!(tags, ["alpha", "beta"]);
}

#[test]
fn test_flag_present_and_absent() {
    let cmds = vec![Command::builder("x")
        .flag(Flag::builder("v").build().unwrap())
        .flag(
            Flag::builder("out")
                .takes_value()
                .default_value("text")
                .build()
                .unwrap(),
        )
        .build()
        .unwrap()];
    let parsed = Parser::new(&cmds).parse(&["x", "--v"]).unwrap();
    assert!(parsed.flag("v").is_some());
    assert!(parsed.flag("out").is_some()); // default applied
    assert!(parsed.flag("other").is_none());
}

// ================================================================
// Async integration tests (require `async` feature + tokio runtime)
// ================================================================

#[cfg(feature = "async")]
mod async_tests {
    use argot_cmd::{Cli, CliError, Command};
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    fn make_async_cli_no_handler() -> Cli {
        let cmd = Command::builder("greet")
            .summary("Say hello")
            .build()
            .unwrap();
        Cli::new(vec![cmd]).app_name("testapp").version("1.2.3")
    }

    #[tokio::test]
    async fn test_async_run_empty_args() {
        let cli = make_async_cli_no_handler();
        let result = cli.run_async(std::iter::empty::<&str>()).await;
        assert!(
            result.is_ok(),
            "empty args should return Ok, got {:?}",
            result
        );
    }

    #[tokio::test]
    async fn test_async_run_help_flag() {
        let cli = make_async_cli_no_handler();
        let result = cli.run_async(["--help"]).await;
        assert!(result.is_ok(), "--help should return Ok, got {:?}", result);
    }

    #[tokio::test]
    async fn test_async_run_version_flag() {
        let cli = make_async_cli_no_handler();
        let result = cli.run_async(["--version"]).await;
        assert!(
            result.is_ok(),
            "--version should return Ok, got {:?}",
            result
        );
    }

    #[tokio::test]
    async fn test_async_run_with_async_handler() {
        let called = Arc::new(AtomicBool::new(false));
        let called2 = called.clone();

        let cmd = Command::builder("deploy")
            .summary("Deploy the app")
            .async_handler(Arc::new(move |_parsed| {
                let called3 = called2.clone();
                Box::pin(async move {
                    called3.store(true, Ordering::SeqCst);
                    Ok(())
                })
            }))
            .build()
            .unwrap();

        let cli = Cli::new(vec![cmd]).app_name("testapp").version("1.0.0");
        let result = cli.run_async(["deploy"]).await;
        assert!(
            result.is_ok(),
            "async handler should succeed, got {:?}",
            result
        );
        assert!(
            called.load(Ordering::SeqCst),
            "async handler should have been called"
        );
    }

    #[tokio::test]
    async fn test_async_run_with_sync_handler_fallback() {
        let called = Arc::new(AtomicBool::new(false));
        let called2 = called.clone();

        let cmd = Command::builder("build")
            .summary("Build the project")
            .handler(Arc::new(move |_parsed| {
                called2.store(true, Ordering::SeqCst);
                Ok(())
            }))
            .build()
            .unwrap();

        let cli = Cli::new(vec![cmd]).app_name("testapp").version("1.0.0");
        let result = cli.run_async(["build"]).await;
        assert!(
            result.is_ok(),
            "sync handler fallback should succeed, got {:?}",
            result
        );
        assert!(
            called.load(Ordering::SeqCst),
            "sync handler should have been called via run_async"
        );
    }

    #[tokio::test]
    async fn test_async_run_unknown_command() {
        let cli = make_async_cli_no_handler();
        let result = cli.run_async(["unknowncmd"]).await;
        assert!(
            matches!(result, Err(CliError::Parse(_))),
            "unknown command should yield Parse error, got {:?}",
            result
        );
    }

    #[tokio::test]
    async fn test_async_run_no_handler() {
        let cli = make_async_cli_no_handler();
        let result = cli.run_async(["greet"]).await;
        assert!(
            matches!(result, Err(CliError::NoHandler(ref name)) if name == "greet"),
            "expected NoHandler(\"greet\"), got {:?}",
            result
        );
    }
}