-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.rs
More file actions
1840 lines (1714 loc) · 60.7 KB
/
cli.rs
File metadata and controls
1840 lines (1714 loc) · 60.7 KB
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::{BTreeMap, BTreeSet},
future::Future,
io::Write,
process::ExitCode,
sync::{Arc, Mutex},
time::Duration,
};
mod builtins;
mod help;
mod tree_render;
use clap::{ArgMatches, Command};
use crate::{
ActivityEmitter, Auditor, AuthProvider, Authorizer, CliCoreError, CommandMeta, CommandSpec,
GroupSpec, GuideEntry, Middleware, MiddlewareRequest, Result, RuntimeCommandSpec,
RuntimeGroupSpec,
auth::commands::auth_command_group,
command::{
CommandContext, StreamSender, command_args_from_matches, command_path_from_matches,
leaf_matches,
},
error::exit_code_for_error,
flags::{
GlobalFlags, derive_bool_flags, derive_value_flags, extract_command_path,
extract_output_format, extract_search_query, global_flags_from_matches,
has_true_schema_flag, register_global_flags,
},
guide::guide_content,
module::{Module, ModuleContext},
output::{
HumanViewDef, SchemaRegistry, format_help_section, global_human_view_registry_snapshot,
global_schema_registry_snapshot,
},
search::{SearchDocument, SearchIndex},
};
use builtins::{guide_args, guide_command, help_args, help_command};
pub use help::{ModuleHelpEntry, build_root_long};
/// Build metadata shown by the root `--version` flag.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BuildInfo {
/// Semantic version or other release label.
pub version: String,
/// Optional source control commit identifier.
pub commit: Option<String>,
/// Optional build date string.
pub date: Option<String>,
}
impl BuildInfo {
/// Creates build metadata with only a version string.
#[must_use]
pub fn new(version: impl Into<String>) -> Self {
Self {
version: version.into(),
commit: None,
date: None,
}
}
/// Adds a commit identifier to the version string shown by `--version`.
#[must_use]
pub fn with_commit(mut self, commit: impl Into<String>) -> Self {
self.commit = Some(commit.into());
self
}
/// Adds a build date to the version string shown by `--version`.
#[must_use]
pub fn with_date(mut self, date: impl Into<String>) -> Self {
self.date = Some(date.into());
self
}
/// Returns the rendered version string used by the root `--version` flag.
#[must_use]
pub fn version_string(&self) -> String {
let commit = self.commit.as_deref().unwrap_or_default();
let date = self.date.as_deref().unwrap_or_default();
if commit.is_empty() && date.is_empty() {
self.version.clone()
} else {
format!("{} (commit {commit}, built {date})", self.version)
}
}
}
/// Late dependency initializer run once before real command execution.
pub type InitDeps = Arc<dyn Fn(&mut Middleware) -> Result<()> + Send + Sync>;
/// Hook used to add application-specific global flags to the root `clap` command.
pub type RegisterFlags = Arc<dyn Fn(Command) -> Command + Send + Sync>;
/// Hook used to copy parsed application-specific flags into middleware.
pub type ApplyFlags = Arc<dyn Fn(&ArgMatches, &mut Middleware) -> Result<()> + Send + Sync>;
/// Hook run immediately before executable commands and built-ins.
pub type PreRun =
Arc<dyn Fn(&mut Middleware, &str, &crate::middleware::ValueMap) -> Result<()> + Send + Sync>;
/// Hook used to adjust command metadata globally before middleware executes.
pub type ResolveMeta = Arc<dyn Fn(&str, CommandMeta) -> CommandMeta + Send + Sync>;
/// Hook called after a CLI run completes.
pub type OnShutdown = Arc<dyn Fn() + Send + Sync>;
/// Hook that contributes extra root-scope `--search` documents.
pub type ExtraSearchDocs = Arc<dyn Fn() -> Vec<SearchDocument> + Send + Sync>;
/// Declarative configuration for a CLI application.
///
/// Use [`CliConfig::new`] for the common path and chain `with_*` methods for
/// modules, auth providers, guides, views, and lifecycle hooks. Direct struct
/// literals remain available for advanced setup and tests.
#[derive(Clone, Default)]
pub struct CliConfig {
/// Root command name shown in usage output.
pub name: String,
/// One-line root command description.
pub short: String,
/// Optional longer root command description. Defaults to `short`.
pub long: Option<String>,
/// Version/build metadata for `--version`.
pub build: BuildInfo,
/// Application id stored in middleware and output metadata.
pub app_id: String,
/// Fallback auth provider when a command does not select one explicitly.
pub default_auth_provider: Option<String>,
/// Domain modules mounted under the root command.
pub modules: Vec<Module>,
/// Additional top-level runtime commands.
pub commands: Vec<RuntimeCommandSpec>,
/// Global guide entries mounted under `guide`.
pub guides: Vec<GuideEntry>,
/// Global human output views.
pub views: Vec<HumanViewDef>,
/// Providers registered before command execution starts.
pub auth_providers: Vec<Arc<dyn AuthProvider>>,
/// Optional authorization gatekeeper injected into middleware.
pub authz: Option<Arc<dyn Authorizer>>,
/// Optional audit recorder injected into middleware.
pub auditor: Option<Arc<dyn Auditor>>,
/// Optional activity event sink injected into middleware.
pub activity: Option<Arc<dyn ActivityEmitter>>,
/// Optional late initializer for runtime dependencies.
pub init_deps: Option<InitDeps>,
/// Optional hook for adding application-specific global flags.
pub register_flags: Option<RegisterFlags>,
/// Optional hook for applying parsed application-specific flags.
pub apply_flags: Option<ApplyFlags>,
/// Optional hook run before executable commands and built-ins.
pub pre_run: Option<PreRun>,
/// Optional hook for global command metadata adjustments.
pub meta_resolver: Option<ResolveMeta>,
/// Optional hook called after each run.
pub on_shutdown: Option<OnShutdown>,
/// Optional root-scope search document provider.
pub extra_search_docs: Option<ExtraSearchDocs>,
}
impl CliConfig {
/// Creates the minimum useful CLI configuration.
#[must_use]
pub fn new(
name: impl Into<String>,
short: impl Into<String>,
app_id: impl Into<String>,
) -> Self {
Self {
name: name.into(),
short: short.into(),
app_id: app_id.into(),
..Self::default()
}
}
/// Sets root long help text.
#[must_use]
pub fn with_long(mut self, long: impl Into<String>) -> Self {
self.long = Some(long.into());
self
}
/// Sets build metadata used by `--version`.
#[must_use]
pub fn with_build(mut self, build: BuildInfo) -> Self {
self.build = build;
self
}
/// Sets the fallback auth provider for commands that do not name one.
#[must_use]
pub fn with_default_auth_provider(mut self, provider: impl Into<String>) -> Self {
self.default_auth_provider = Some(provider.into());
self
}
/// Adds one domain module.
#[must_use]
pub fn with_module(mut self, module: Module) -> Self {
self.modules.push(module);
self
}
/// Adds several domain modules.
#[must_use]
pub fn with_modules(mut self, modules: impl IntoIterator<Item = Module>) -> Self {
self.modules.extend(modules);
self
}
/// Adds a top-level runtime command outside a module.
#[must_use]
pub fn with_command(mut self, command: RuntimeCommandSpec) -> Self {
self.commands.push(command);
self
}
/// Adds one global guide.
#[must_use]
pub fn with_guide(mut self, guide: GuideEntry) -> Self {
self.guides.push(guide);
self
}
/// Adds several global guides.
#[must_use]
pub fn with_guides(mut self, guides: impl IntoIterator<Item = GuideEntry>) -> Self {
self.guides.extend(guides);
self
}
/// Adds one global human view.
#[must_use]
pub fn with_view(mut self, view: HumanViewDef) -> Self {
self.views.push(view);
self
}
/// Registers one auth provider.
#[must_use]
pub fn with_auth_provider(mut self, provider: Arc<dyn AuthProvider>) -> Self {
self.auth_providers.push(provider);
self
}
/// Sets the authorization gatekeeper.
#[must_use]
pub fn with_authz(mut self, authz: Arc<dyn Authorizer>) -> Self {
self.authz = Some(authz);
self
}
/// Sets the audit recorder.
#[must_use]
pub fn with_auditor(mut self, auditor: Arc<dyn Auditor>) -> Self {
self.auditor = Some(auditor);
self
}
/// Sets the activity event sink.
#[must_use]
pub fn with_activity(mut self, activity: Arc<dyn ActivityEmitter>) -> Self {
self.activity = Some(activity);
self
}
/// Sets the late dependency initializer.
#[must_use]
pub fn with_init_deps(mut self, init_deps: InitDeps) -> Self {
self.init_deps = Some(init_deps);
self
}
/// Sets the application-specific global flag registration hook.
#[must_use]
pub fn with_register_flags(mut self, register_flags: RegisterFlags) -> Self {
self.register_flags = Some(register_flags);
self
}
/// Sets the application-specific parsed flag application hook.
#[must_use]
pub fn with_apply_flags(mut self, apply_flags: ApplyFlags) -> Self {
self.apply_flags = Some(apply_flags);
self
}
/// Sets the pre-run hook.
#[must_use]
pub fn with_pre_run(mut self, pre_run: PreRun) -> Self {
self.pre_run = Some(pre_run);
self
}
/// Sets the command metadata resolver hook.
#[must_use]
pub fn with_meta_resolver(mut self, meta_resolver: ResolveMeta) -> Self {
self.meta_resolver = Some(meta_resolver);
self
}
/// Sets the shutdown hook.
#[must_use]
pub fn with_on_shutdown(mut self, on_shutdown: OnShutdown) -> Self {
self.on_shutdown = Some(on_shutdown);
self
}
/// Sets the provider for additional root-scope search documents.
#[must_use]
pub fn with_extra_search_docs(mut self, extra_search_docs: ExtraSearchDocs) -> Self {
self.extra_search_docs = Some(extra_search_docs);
self
}
}
impl std::fmt::Debug for CliConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CliConfig")
.field("name", &self.name)
.field("short", &self.short)
.field("long", &self.long)
.field("build", &self.build)
.field("app_id", &self.app_id)
.field("default_auth_provider", &self.default_auth_provider)
.field("modules", &self.modules)
.field("commands", &self.commands)
.field("guides", &self.guides)
.field("views", &self.views)
.field("auth_providers_len", &self.auth_providers.len())
.field("has_authz", &self.authz.is_some())
.field("has_auditor", &self.auditor.is_some())
.field("has_activity", &self.activity.is_some())
.field("has_init_deps", &self.init_deps.is_some())
.field("has_register_flags", &self.register_flags.is_some())
.field("has_apply_flags", &self.apply_flags.is_some())
.field("has_pre_run", &self.pre_run.is_some())
.field("has_meta_resolver", &self.meta_resolver.is_some())
.field("has_on_shutdown", &self.on_shutdown.is_some())
.field("has_extra_search_docs", &self.extra_search_docs.is_some())
.finish()
}
}
/// Captured result of running a CLI in tests or embedding contexts.
#[derive(Clone, Debug, PartialEq)]
pub struct CliRunOutput {
/// Process-style exit code.
pub exit_code: i32,
/// Rendered stdout or stderr payload.
pub rendered: String,
}
impl From<crate::middleware::MiddlewareOutput> for CliRunOutput {
fn from(o: crate::middleware::MiddlewareOutput) -> Self {
Self {
exit_code: o.exit_code,
rendered: o.rendered,
}
}
}
/// Configured CLI application.
///
/// A `Cli` owns the `clap` command tree, middleware, registered runtime
/// commands, guides, schemas, and built-ins. Consumer binaries normally create
/// one `Cli` and call [`Cli::execute`].
#[derive(Clone)]
pub struct Cli {
config: CliConfig,
middleware: Middleware,
root: Command,
commands: BTreeMap<String, RuntimeCommandSpec>,
module_entries: Vec<ModuleHelpEntry>,
guide_entries: Vec<GuideEntry>,
init_deps: Option<InitDeps>,
apply_flags: Option<ApplyFlags>,
pre_run: Option<PreRun>,
meta_resolver: Option<ResolveMeta>,
on_shutdown: Option<OnShutdown>,
extra_search_docs: Option<ExtraSearchDocs>,
init_state: Arc<Mutex<Option<std::result::Result<Middleware, InitFailure>>>>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct InitFailure {
message: String,
code: String,
system: String,
request_id: String,
exit_code: i32,
}
impl InitFailure {
fn capture(err: &CliCoreError) -> Self {
let envelope = crate::output::build_error_envelope(err, "");
let (code, system, request_id) = envelope.error.map_or_else(
|| ("ERROR".to_owned(), String::new(), String::new()),
|error| (error.code, error.system, error.request_id),
);
Self {
message: err.to_string(),
code,
system,
request_id,
exit_code: exit_code_for_error(err),
}
}
fn into_error(self) -> CliCoreError {
CliCoreError::with_exit_code(
self.exit_code,
CliCoreError::SystemMessage {
message: self.message,
system: self.system,
code: self.code,
request_id: self.request_id,
},
)
}
}
impl std::fmt::Debug for Cli {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Cli")
.field("config", &self.config)
.field("middleware", &self.middleware)
.field("root", &self.root)
.field("commands", &self.commands)
.field("module_entries", &self.module_entries)
.field("guide_entries", &self.guide_entries)
.field("has_init_deps", &self.init_deps.is_some())
.field("has_apply_flags", &self.apply_flags.is_some())
.field("has_pre_run", &self.pre_run.is_some())
.field("has_meta_resolver", &self.meta_resolver.is_some())
.field("has_on_shutdown", &self.on_shutdown.is_some())
.field("has_extra_search_docs", &self.extra_search_docs.is_some())
.finish()
}
}
impl Cli {
/// Builds a CLI application from declarative configuration.
#[must_use]
pub fn new(config: CliConfig) -> Self {
let auth_providers = config.auth_providers.clone();
let guides = config.guides.clone();
let views = config.views.clone();
let modules = config.modules.clone();
let commands = config.commands.clone();
let init_deps = config.init_deps.clone();
let apply_flags = config.apply_flags.clone();
let pre_run = config.pre_run.clone();
let meta_resolver = config.meta_resolver.clone();
let on_shutdown = config.on_shutdown.clone();
let extra_search_docs = config.extra_search_docs.clone();
let mut root = Command::new(config.name.clone())
.about(config.short.clone())
.disable_help_subcommand(true)
.version(config.build.version_string());
if let Some(long) = &config.long
&& !long.is_empty()
{
root = root.long_about(long.clone());
}
root = register_global_flags(root)
.subcommand(help_command())
.subcommand(guide_command())
.subcommand(Command::new("tree").about("Display full command tree"));
if let Some(register_flags) = &config.register_flags {
root = register_flags(root);
}
let intro = config
.long
.as_deref()
.filter(|long| !long.is_empty())
.unwrap_or(config.short.as_str());
root = root.long_about(build_root_long(intro, &[], false));
let mut middleware = Middleware::new();
middleware.app_id = config.app_id.clone();
middleware.default_auth_provider = config.default_auth_provider.clone().unwrap_or_default();
middleware.authz = config.authz.clone();
middleware.auditor = config.auditor.clone();
middleware.activity = config.activity.clone();
middleware
.schema_registry
.merge(&global_schema_registry_snapshot());
middleware
.human_views
.merge(&global_human_view_registry_snapshot());
let mut cli = Self {
config,
middleware,
root,
commands: BTreeMap::new(),
module_entries: Vec::new(),
guide_entries: Vec::new(),
init_deps,
apply_flags,
pre_run,
meta_resolver,
on_shutdown,
extra_search_docs,
init_state: Arc::new(Mutex::new(None)),
};
for provider in auth_providers {
cli.register_auth_provider(provider);
}
if cli.middleware.default_auth_provider.is_empty()
&& let Some(provider) = cli.middleware.auth.registered_names().first()
{
cli.middleware.default_auth_provider = provider.clone();
}
if !cli.middleware.default_auth_provider.is_empty() {
cli.ensure_auth_command();
}
for view in views {
cli.middleware.human_views.register(view);
}
cli.add_guides(guides);
for module in modules {
cli.add_module(module);
}
for command in commands {
cli.add_command(command);
}
cli
}
/// Returns the shared middleware template.
#[must_use]
pub fn middleware(&self) -> &Middleware {
&self.middleware
}
/// Returns mutable middleware for advanced application setup.
pub fn middleware_mut(&mut self) -> &mut Middleware {
&mut self.middleware
}
/// Executes the CLI with process arguments and process stdout/stderr.
pub async fn execute(&self) -> ExitCode {
let mut stdout = std::io::stdout().lock();
let mut stderr = std::io::stderr().lock();
match self
.execute_from(std::env::args_os(), &mut stdout, &mut stderr)
.await
{
Ok(code) => code,
Err(err) => {
drop(writeln!(stderr, "{err}"));
ExitCode::from(1)
}
}
}
/// Executes the CLI with caller-provided args and output writers.
pub async fn execute_from<I, S, O, E>(
&self,
args: I,
stdout: &mut O,
stderr: &mut E,
) -> std::io::Result<ExitCode>
where
I: IntoIterator<Item = S>,
S: Into<std::ffi::OsString> + Clone,
O: Write,
E: Write,
{
self.execute_from_until_signal(args, stdout, stderr, shutdown_signal())
.await
}
/// Executes the CLI until either command completion or a shutdown signal future resolves.
pub async fn execute_from_until_signal<I, S, O, E, Shutdown>(
&self,
args: I,
stdout: &mut O,
stderr: &mut E,
shutdown: Shutdown,
) -> std::io::Result<ExitCode>
where
I: IntoIterator<Item = S>,
S: Into<std::ffi::OsString> + Clone,
O: Write,
E: Write,
Shutdown: Future<Output = ()>,
{
let output = run_until_signal(self.run(args), shutdown).await;
if output.exit_code == 130
&& output.rendered == "command interrupted\n"
&& let Some(on_shutdown) = &self.on_shutdown
{
on_shutdown();
}
if output.exit_code == 0 {
stdout.write_all(output.rendered.as_bytes())?;
} else {
stderr.write_all(output.rendered.as_bytes())?;
}
Ok(process_exit_code(output.exit_code))
}
/// Registers an auth provider after construction.
pub fn register_auth_provider(&mut self, provider: Arc<dyn AuthProvider>) -> &mut Self {
self.middleware.auth.register(provider);
self.ensure_auth_command();
self.refresh_root_long();
self
}
/// Returns the built `clap` root command.
#[must_use]
pub fn root_command(&self) -> &Command {
&self.root
}
/// Adds one runtime module group after construction.
pub fn add_module_group(
&mut self,
category: impl Into<String>,
group: RuntimeGroupSpec,
) -> &mut Self {
let category = category.into();
if !group.group.hidden {
self.module_entries.push(ModuleHelpEntry {
category,
name: group.group.name.clone(),
short: group.group.short.clone(),
});
}
let mut prefix = Vec::new();
register_runtime_group_schemas(&group, &mut prefix, &mut self.middleware.schema_registry);
let mut prefix = Vec::new();
group.register_commands(&mut prefix, &mut self.commands);
let mut prefix = Vec::new();
let clap_group = runtime_group_clap_command_with_schema_help(
&group,
&mut prefix,
&self.middleware.schema_registry,
);
self.root = self.root.clone().subcommand(clap_group);
self.refresh_root_long();
self
}
/// Adds one module after construction.
pub fn add_module(&mut self, module: Module) -> &mut Self {
for view in module.views.clone() {
self.middleware.human_views.register(view);
}
self.add_guides(module.guides.clone());
let mut context = ModuleContext::new(&mut self.middleware);
let group = (module.register)(&mut context);
let (guides, views) = context.into_parts();
for view in views {
self.middleware.human_views.register(view);
}
self.add_guides(guides);
self.add_module_group(module.category, group)
}
/// Adds one top-level runtime command after construction.
pub fn add_command(&mut self, command: RuntimeCommandSpec) -> &mut Self {
let name = command.spec.name.clone();
register_command_schema(&command.spec, &name, &mut self.middleware.schema_registry);
self.commands.insert(name, command.clone());
self.root = self
.root
.clone()
.subcommand(command_clap_command_with_schema_help(
&command.spec,
&command.spec.name,
&self.middleware.schema_registry,
));
self
}
/// Controls whether the built-in `guide` command is advertised.
pub fn set_has_guide(&mut self, has_guide: bool) -> &mut Self {
if has_guide && self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
self.root = self.root.clone().subcommand(guide_command());
}
self.refresh_root_long();
self
}
/// Adds guide entries after construction.
pub fn add_guides(&mut self, entries: impl IntoIterator<Item = GuideEntry>) -> &mut Self {
let mut seen = self
.guide_entries
.iter()
.map(|entry| entry.name.clone())
.collect::<BTreeSet<_>>();
for entry in entries {
if seen.insert(entry.name.clone()) {
self.guide_entries.push(entry);
}
}
if !self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
self.root = self.root.clone().subcommand(guide_command());
}
self.refresh_root_long();
self
}
/// Runs the CLI with provided args and captures the rendered result.
pub async fn run<I, S>(&self, args: I) -> CliRunOutput
where
I: IntoIterator<Item = S>,
S: Into<std::ffi::OsString> + Clone,
{
let raw_args = args
.into_iter()
.map(Into::into)
.collect::<Vec<std::ffi::OsString>>();
let text_args = raw_args
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>();
let clap_args = normalize_optional_global_flags_before_command(&self.root, &text_args);
if has_root_version_flag(&text_args, &self.root, &self.config.name) {
return self.finish_run(CliRunOutput {
exit_code: 0,
rendered: format!(
"{} version {}\n",
self.config.name,
self.config.build.version_string()
),
});
}
if let Some(output) = self.try_run_schema_bypass(&text_args) {
return output;
}
if let Some(output) = self.try_run_search_bypass(&text_args) {
return output;
}
if let Some(message) =
unknown_group_command_message(&self.root, &text_args, &self.config.name)
{
return self.finish_run(CliRunOutput {
exit_code: 1,
rendered: message,
});
}
let matches = match self.root.clone().try_get_matches_from(clap_args) {
Ok(matches) => matches,
Err(err) => {
return self.finish_run(CliRunOutput {
exit_code: err.exit_code(),
rendered: err.to_string(),
});
}
};
let flags = global_flags_from_matches(&matches);
let command_timeout = match parse_command_timeout(&flags.timeout) {
Ok(timeout) => timeout,
Err(err) => {
return self.finish_run(render_cli_error(
&self.middleware,
&err,
&self.config.app_id,
));
}
};
let mut middleware = self.middleware.clone();
apply_global_flags(&mut middleware, &flags, command_timeout);
if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
let command_path = command_path_from_matches(&self.config.name, &matches);
if command_path == "help" {
if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &help_args(&matches))
{
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
return self.finish_run(self.render_help_command(&matches));
}
if command_path == "tree" {
if let Err(err) = self.run_pre_run(
&mut middleware,
&command_path,
&crate::middleware::ValueMap::new(),
) {
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
return self.finish_run(tree_render::render_tree(
&self.root,
&self.config.app_id,
&middleware,
));
}
if command_path == "guide" {
if let Err(err) =
self.run_pre_run(&mut middleware, &command_path, &guide_args(&matches))
{
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
return self.finish_run(self.render_guide(&matches));
}
let Some(command) = self.commands.get(&command_path) else {
if !command_path.is_empty()
&& let Some(group) = find_command_by_colon_path(&self.root, &command_path)
&& group.get_subcommands().next().is_some()
{
if let Err(err) = self.run_pre_run(
&mut middleware,
&command_path,
&crate::middleware::ValueMap::new(),
) {
return self.finish_run(render_cli_error(
&middleware,
&err,
&self.config.app_id,
));
}
return self.finish_run(CliRunOutput {
exit_code: 0,
rendered: group.clone().render_long_help().to_string(),
});
}
return self.finish_run(CliRunOutput {
exit_code: if command_path.is_empty() { 0 } else { 1 },
rendered: if command_path.is_empty() {
self.root.clone().render_long_help().to_string()
} else {
format!("unknown command {command_path:?}")
},
});
};
let mut middleware = match self.initialized_middleware() {
Ok(middleware) => middleware,
Err(err) => {
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
};
apply_global_flags(&mut middleware, &flags, command_timeout);
if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
let leaf = leaf_matches(&matches);
let args = command_args_from_matches(leaf, &command.spec, false);
let user_args = command_args_from_matches(leaf, &command.spec, true);
if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &args) {
return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
}
let meta = self.resolve_meta(&command_path, command.spec.metadata());
let default_fields = command.spec.default_fields.clone().unwrap_or_default();
let system = command.spec.system.clone().unwrap_or_default();
if let Some(streaming_handler) = command.streaming_handler.clone() {
let result = run_with_timeout(
command_timeout,
&flags.timeout,
run_streaming_command(
&middleware,
MiddlewareRequest {
meta,
command_path: &command_path,
system: &system,
user_args,
args,
default_fields: &default_fields,
no_auth: command.spec.no_auth,
},
Arc::new(leaf.clone()),
streaming_handler,
),
)
.await;
return self.finish_run(match result {
Ok(output) => output,
Err(err) => render_cli_error(&middleware, &err, &self.config.app_id),
});
}
let handler = command.handler.clone();
let args_for_handler = args.clone();
let user_args_for_handler = user_args.clone();
let handler_path = command_path.clone();
let middleware_for_handler = middleware.clone();
let raw_matches_for_handler = Arc::new(leaf.clone());
let result = run_with_timeout(
command_timeout,
&flags.timeout,
middleware.run(
MiddlewareRequest {
meta,
command_path: &command_path,
system: &system,
user_args,
args,
default_fields: &default_fields,
no_auth: command.spec.no_auth,
},
async move |credential| {
handler(CommandContext {
credential,
args: args_for_handler,
user_args: user_args_for_handler,
command_path: handler_path,
middleware: middleware_for_handler,
raw_matches: raw_matches_for_handler,
})
.await
},
),
)
.await;
match result {
Ok(output) => self.finish_run(output.into()),
Err(err) => self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id)),
}
}
fn try_run_search_bypass(&self, args: &[String]) -> Option<CliRunOutput> {
let query = extract_search_query(args);
if query.is_empty() {
return None;
}
let scope = self.search_scope(args);
let output_format = extract_output_format(args);
Some(self.render_search(&query, &scope, &output_format))
}
fn try_run_schema_bypass(&self, args: &[String]) -> Option<CliRunOutput> {
if !has_true_schema_flag(args) {
return None;
}
let bool_flags = derive_bool_flags(&self.root);
let value_flags = derive_value_flags(&self.root);
let command_path =
self.canonical_command_path(&extract_command_path(args, &bool_flags, &value_flags));
let schema = self.middleware.schema_registry.get_by_path(&command_path)?;
let output_format = extract_output_format(args);
Some(self.render_schema(schema, &output_format))
}
fn render_schema(
&self,
schema: crate::output::SchemaInfo,
output_format: &str,
) -> CliRunOutput {
let format: crate::output::OutputFormat = match output_format.parse() {
Ok(format) => format,
Err(err) => {
return CliRunOutput {
exit_code: exit_code_for_error(&err),
rendered: err.to_string(),
};
}
};
let envelope =
crate::Envelope::success(schema, self.config.app_id.clone()).prepare_for_render("");
match crate::output::render(format, &envelope) {
Ok(rendered) => CliRunOutput {
exit_code: 0,
rendered,
},
Err(err) => CliRunOutput {
exit_code: exit_code_for_error(&err),
rendered: err.to_string(),
},
}
}
fn render_search(&self, query: &str, scope: &str, output_format: &str) -> CliRunOutput {
let format: crate::output::OutputFormat = match output_format.parse() {
Ok(format) => format,
Err(err) => {
return CliRunOutput {
exit_code: exit_code_for_error(&err),
rendered: err.to_string(),
};
}
};
let docs = self.search_documents(scope);
let results = SearchIndex::new(docs).search(query, 10);
let envelope =
crate::Envelope::success(results, self.config.app_id.clone()).prepare_for_render("");
match crate::output::render(format, &envelope) {
Ok(rendered) => CliRunOutput {
exit_code: 0,
rendered,
},
Err(err) => CliRunOutput {
exit_code: exit_code_for_error(&err),
rendered: err.to_string(),
},