1use std::{
2 collections::{BTreeMap, BTreeSet},
3 future::Future,
4 io::Write,
5 process::ExitCode,
6 sync::{Arc, Mutex},
7 time::Duration,
8};
9
10mod builtins;
11mod help;
12mod tree_render;
13
14use clap::{ArgMatches, Command};
15
16use crate::{
17 ActivityEmitter, Auditor, AuthProvider, Authorizer, CliCoreError, CommandMeta, CommandSpec,
18 GroupSpec, GuideEntry, Middleware, MiddlewareRequest, Result, RuntimeCommandSpec,
19 RuntimeGroupSpec,
20 auth::commands::auth_command_group,
21 command::{
22 CommandContext, StreamSender, command_args_from_matches, command_path_from_matches,
23 leaf_matches,
24 },
25 error::exit_code_for_error,
26 flags::{
27 GlobalFlags, default_output_format, derive_bool_flags, derive_value_flags,
28 extract_command_path, extract_output_format, extract_search_query,
29 global_flags_from_matches, has_true_schema_flag, register_global_flags,
30 },
31 guide::guide_content,
32 module::{Module, ModuleContext},
33 output::{
34 HumanViewDef, NextAction, SchemaRegistry, format_help_section,
35 global_human_view_registry_snapshot, global_schema_registry_snapshot,
36 },
37 search::{SearchDocument, SearchIndex},
38};
39
40use builtins::{guide_args, guide_command, help_args, help_command};
41use help::{GROUP_HELP_TEMPLATE, ROOT_HELP_TEMPLATE};
42pub use help::{ModuleHelpEntry, build_root_long, render_next_actions_human};
43
44#[derive(Clone, Debug, Default, Eq, PartialEq)]
46pub struct BuildInfo {
47 pub version: String,
49 pub commit: Option<String>,
51 pub date: Option<String>,
53}
54
55impl BuildInfo {
56 #[must_use]
58 pub fn new(version: impl Into<String>) -> Self {
59 Self {
60 version: version.into(),
61 commit: None,
62 date: None,
63 }
64 }
65
66 #[must_use]
68 pub fn with_commit(mut self, commit: impl Into<String>) -> Self {
69 self.commit = Some(commit.into());
70 self
71 }
72
73 #[must_use]
75 pub fn with_date(mut self, date: impl Into<String>) -> Self {
76 self.date = Some(date.into());
77 self
78 }
79
80 #[must_use]
82 pub fn version_string(&self) -> String {
83 let commit = self.commit.as_deref().unwrap_or_default();
84 let date = self.date.as_deref().unwrap_or_default();
85
86 if commit.is_empty() && date.is_empty() {
87 self.version.clone()
88 } else {
89 format!("{} (commit {commit}, built {date})", self.version)
90 }
91 }
92}
93
94pub type InitDeps = Arc<dyn Fn(&mut Middleware) -> Result<()> + Send + Sync>;
96pub type RegisterFlags = Arc<dyn Fn(Command) -> Command + Send + Sync>;
98pub type ApplyFlags = Arc<dyn Fn(&ArgMatches, &mut Middleware) -> Result<()> + Send + Sync>;
100pub type PreRun =
102 Arc<dyn Fn(&mut Middleware, &str, &crate::middleware::ValueMap) -> Result<()> + Send + Sync>;
103pub type ResolveMeta = Arc<dyn Fn(&str, CommandMeta) -> CommandMeta + Send + Sync>;
105pub type OnShutdown = Arc<dyn Fn() + Send + Sync>;
107pub type ExtraSearchDocs = Arc<dyn Fn() -> Vec<SearchDocument> + Send + Sync>;
109pub type RootNextActions = Arc<dyn Fn() -> Vec<NextAction> + Send + Sync>;
113
114const DEFAULT_ADMIN_CATEGORY: &str = "Admin";
118
119#[derive(Clone, Default)]
125pub struct CliConfig {
126 pub name: String,
128 pub short: String,
130 pub long: Option<String>,
132 pub build: BuildInfo,
134 pub app_id: String,
136 pub default_auth_provider: Option<String>,
138 pub modules: Vec<Module>,
140 pub commands: Vec<RuntimeCommandSpec>,
142 pub guides: Vec<GuideEntry>,
144 pub views: Vec<HumanViewDef>,
146 pub auth_providers: Vec<Arc<dyn AuthProvider>>,
148 pub authz: Option<Arc<dyn Authorizer>>,
150 pub auditor: Option<Arc<dyn Auditor>>,
152 pub activity: Option<Arc<dyn ActivityEmitter>>,
154 pub init_deps: Option<InitDeps>,
156 pub register_flags: Option<RegisterFlags>,
158 pub apply_flags: Option<ApplyFlags>,
160 pub pre_run: Option<PreRun>,
162 pub meta_resolver: Option<ResolveMeta>,
164 pub on_shutdown: Option<OnShutdown>,
166 pub extra_search_docs: Option<ExtraSearchDocs>,
168 pub root_next_actions: Option<RootNextActions>,
170 pub admin_category: Option<String>,
175}
176
177impl CliConfig {
178 #[must_use]
180 pub fn new(
181 name: impl Into<String>,
182 short: impl Into<String>,
183 app_id: impl Into<String>,
184 ) -> Self {
185 Self {
186 name: name.into(),
187 short: short.into(),
188 app_id: app_id.into(),
189 ..Self::default()
190 }
191 }
192
193 #[must_use]
195 pub fn with_long(mut self, long: impl Into<String>) -> Self {
196 self.long = Some(long.into());
197 self
198 }
199
200 #[must_use]
202 pub fn with_build(mut self, build: BuildInfo) -> Self {
203 self.build = build;
204 self
205 }
206
207 #[must_use]
209 pub fn with_default_auth_provider(mut self, provider: impl Into<String>) -> Self {
210 self.default_auth_provider = Some(provider.into());
211 self
212 }
213
214 #[must_use]
216 pub fn with_module(mut self, module: Module) -> Self {
217 self.modules.push(module);
218 self
219 }
220
221 #[must_use]
223 pub fn with_modules(mut self, modules: impl IntoIterator<Item = Module>) -> Self {
224 self.modules.extend(modules);
225 self
226 }
227
228 #[must_use]
230 pub fn with_command(mut self, command: RuntimeCommandSpec) -> Self {
231 self.commands.push(command);
232 self
233 }
234
235 #[must_use]
237 pub fn with_guide(mut self, guide: GuideEntry) -> Self {
238 self.guides.push(guide);
239 self
240 }
241
242 #[must_use]
244 pub fn with_guides(mut self, guides: impl IntoIterator<Item = GuideEntry>) -> Self {
245 self.guides.extend(guides);
246 self
247 }
248
249 #[must_use]
251 pub fn with_view(mut self, view: HumanViewDef) -> Self {
252 self.views.push(view);
253 self
254 }
255
256 #[must_use]
258 pub fn with_auth_provider(mut self, provider: Arc<dyn AuthProvider>) -> Self {
259 self.auth_providers.push(provider);
260 self
261 }
262
263 #[must_use]
265 pub fn with_authz(mut self, authz: Arc<dyn Authorizer>) -> Self {
266 self.authz = Some(authz);
267 self
268 }
269
270 #[must_use]
272 pub fn with_auditor(mut self, auditor: Arc<dyn Auditor>) -> Self {
273 self.auditor = Some(auditor);
274 self
275 }
276
277 #[must_use]
279 pub fn with_activity(mut self, activity: Arc<dyn ActivityEmitter>) -> Self {
280 self.activity = Some(activity);
281 self
282 }
283
284 #[must_use]
286 pub fn with_init_deps(mut self, init_deps: InitDeps) -> Self {
287 self.init_deps = Some(init_deps);
288 self
289 }
290
291 #[must_use]
293 pub fn with_register_flags(mut self, register_flags: RegisterFlags) -> Self {
294 self.register_flags = Some(register_flags);
295 self
296 }
297
298 #[must_use]
300 pub fn with_apply_flags(mut self, apply_flags: ApplyFlags) -> Self {
301 self.apply_flags = Some(apply_flags);
302 self
303 }
304
305 #[must_use]
307 pub fn with_pre_run(mut self, pre_run: PreRun) -> Self {
308 self.pre_run = Some(pre_run);
309 self
310 }
311
312 #[must_use]
314 pub fn with_meta_resolver(mut self, meta_resolver: ResolveMeta) -> Self {
315 self.meta_resolver = Some(meta_resolver);
316 self
317 }
318
319 #[must_use]
321 pub fn with_on_shutdown(mut self, on_shutdown: OnShutdown) -> Self {
322 self.on_shutdown = Some(on_shutdown);
323 self
324 }
325
326 #[must_use]
328 pub fn with_extra_search_docs(mut self, extra_search_docs: ExtraSearchDocs) -> Self {
329 self.extra_search_docs = Some(extra_search_docs);
330 self
331 }
332
333 #[must_use]
335 pub fn with_root_next_actions(mut self, root_next_actions: RootNextActions) -> Self {
336 self.root_next_actions = Some(root_next_actions);
337 self
338 }
339
340 #[must_use]
344 pub fn with_admin_category(mut self, category: impl Into<String>) -> Self {
345 self.admin_category = Some(category.into());
346 self
347 }
348}
349
350impl std::fmt::Debug for CliConfig {
351 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 formatter
353 .debug_struct("CliConfig")
354 .field("name", &self.name)
355 .field("short", &self.short)
356 .field("long", &self.long)
357 .field("build", &self.build)
358 .field("app_id", &self.app_id)
359 .field("default_auth_provider", &self.default_auth_provider)
360 .field("modules", &self.modules)
361 .field("commands", &self.commands)
362 .field("guides", &self.guides)
363 .field("views", &self.views)
364 .field("auth_providers_len", &self.auth_providers.len())
365 .field("has_authz", &self.authz.is_some())
366 .field("has_auditor", &self.auditor.is_some())
367 .field("has_activity", &self.activity.is_some())
368 .field("has_init_deps", &self.init_deps.is_some())
369 .field("has_register_flags", &self.register_flags.is_some())
370 .field("has_apply_flags", &self.apply_flags.is_some())
371 .field("has_pre_run", &self.pre_run.is_some())
372 .field("has_meta_resolver", &self.meta_resolver.is_some())
373 .field("has_on_shutdown", &self.on_shutdown.is_some())
374 .field("has_extra_search_docs", &self.extra_search_docs.is_some())
375 .field("has_root_next_actions", &self.root_next_actions.is_some())
376 .field("admin_category", &self.admin_category)
377 .finish()
378 }
379}
380
381#[derive(Clone, Debug, PartialEq)]
383pub struct CliRunOutput {
384 pub exit_code: i32,
386 pub rendered: String,
388}
389
390impl From<crate::middleware::MiddlewareOutput> for CliRunOutput {
391 fn from(o: crate::middleware::MiddlewareOutput) -> Self {
392 Self {
393 exit_code: o.exit_code,
394 rendered: o.rendered,
395 }
396 }
397}
398
399#[derive(Clone)]
405pub struct Cli {
406 config: CliConfig,
407 middleware: Middleware,
408 root: Command,
409 commands: BTreeMap<String, RuntimeCommandSpec>,
410 module_entries: Vec<ModuleHelpEntry>,
411 guide_entries: Vec<GuideEntry>,
412 init_deps: Option<InitDeps>,
413 apply_flags: Option<ApplyFlags>,
414 pre_run: Option<PreRun>,
415 meta_resolver: Option<ResolveMeta>,
416 on_shutdown: Option<OnShutdown>,
417 extra_search_docs: Option<ExtraSearchDocs>,
418 root_next_actions: Option<RootNextActions>,
419 init_state: Arc<Mutex<Option<std::result::Result<Middleware, InitFailure>>>>,
420}
421
422#[derive(Clone, Debug, Eq, PartialEq)]
423struct InitFailure {
424 message: String,
425 code: String,
426 system: String,
427 request_id: String,
428 exit_code: i32,
429}
430
431impl InitFailure {
432 fn capture(err: &CliCoreError) -> Self {
433 let envelope = crate::output::build_error_envelope(err, "");
434 let (code, system, request_id) = envelope.error.map_or_else(
435 || ("ERROR".to_owned(), String::new(), String::new()),
436 |error| (error.code, error.system, error.request_id),
437 );
438 Self {
439 message: err.to_string(),
440 code,
441 system,
442 request_id,
443 exit_code: exit_code_for_error(err),
444 }
445 }
446
447 fn into_error(self) -> CliCoreError {
448 CliCoreError::with_exit_code(
449 self.exit_code,
450 CliCoreError::SystemMessage {
451 message: self.message,
452 system: self.system,
453 code: self.code,
454 request_id: self.request_id,
455 },
456 )
457 }
458}
459
460impl std::fmt::Debug for Cli {
461 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462 formatter
463 .debug_struct("Cli")
464 .field("config", &self.config)
465 .field("middleware", &self.middleware)
466 .field("root", &self.root)
467 .field("commands", &self.commands)
468 .field("module_entries", &self.module_entries)
469 .field("guide_entries", &self.guide_entries)
470 .field("has_init_deps", &self.init_deps.is_some())
471 .field("has_apply_flags", &self.apply_flags.is_some())
472 .field("has_pre_run", &self.pre_run.is_some())
473 .field("has_meta_resolver", &self.meta_resolver.is_some())
474 .field("has_on_shutdown", &self.on_shutdown.is_some())
475 .field("has_extra_search_docs", &self.extra_search_docs.is_some())
476 .field("has_root_next_actions", &self.root_next_actions.is_some())
477 .finish()
478 }
479}
480
481impl Cli {
482 #[must_use]
484 pub fn new(config: CliConfig) -> Self {
485 let auth_providers = config.auth_providers.clone();
486 let guides = config.guides.clone();
487 let views = config.views.clone();
488 let modules = config.modules.clone();
489 let commands = config.commands.clone();
490 let init_deps = config.init_deps.clone();
491 let apply_flags = config.apply_flags.clone();
492 let pre_run = config.pre_run.clone();
493 let meta_resolver = config.meta_resolver.clone();
494 let on_shutdown = config.on_shutdown.clone();
495 let extra_search_docs = config.extra_search_docs.clone();
496 let root_next_actions = config.root_next_actions.clone();
497 let mut root = Command::new(config.name.clone())
498 .about(config.short.clone())
499 .disable_help_subcommand(true)
500 .version(config.build.version_string());
501 if let Some(long) = &config.long
502 && !long.is_empty()
503 {
504 root = root.long_about(long.clone());
505 }
506 root = register_global_flags(root)
507 .subcommand(help_command())
508 .subcommand(guide_command())
509 .subcommand(Command::new("tree").about("Display full command tree"));
510 if let Some(register_flags) = &config.register_flags {
511 root = register_flags(root);
512 }
513 let intro = config
514 .long
515 .as_deref()
516 .filter(|long| !long.is_empty())
517 .unwrap_or(config.short.as_str());
518 root = root
519 .long_about(build_root_long(intro, &[], false))
520 .help_template(ROOT_HELP_TEMPLATE);
521
522 let mut middleware = Middleware::new();
523 middleware.app_id = config.app_id.clone();
524 middleware.default_auth_provider = config.default_auth_provider.clone().unwrap_or_default();
525 middleware.authz = config.authz.clone();
526 middleware.auditor = config.auditor.clone();
527 middleware.activity = config.activity.clone();
528 middleware
529 .schema_registry
530 .merge(&global_schema_registry_snapshot());
531 middleware
532 .human_views
533 .merge(&global_human_view_registry_snapshot());
534
535 let mut cli = Self {
536 config,
537 middleware,
538 root,
539 commands: BTreeMap::new(),
540 module_entries: Vec::new(),
541 guide_entries: Vec::new(),
542 init_deps,
543 apply_flags,
544 pre_run,
545 meta_resolver,
546 on_shutdown,
547 extra_search_docs,
548 root_next_actions,
549 init_state: Arc::new(Mutex::new(None)),
550 };
551 for provider in auth_providers {
552 cli.register_auth_provider(provider);
553 }
554 if cli.middleware.default_auth_provider.is_empty()
555 && let Some(provider) = cli.middleware.auth.registered_names().first()
556 {
557 cli.middleware.default_auth_provider = provider.clone();
558 }
559 if !cli.middleware.default_auth_provider.is_empty() {
560 cli.ensure_auth_command();
561 }
562 for view in views {
563 cli.middleware.human_views.register(view);
564 }
565 cli.add_guides(guides);
566 for module in modules {
567 cli.add_module(module);
568 }
569 for command in commands {
570 cli.add_command(command);
571 }
572 cli
573 }
574
575 fn register_auth_help_entry(&mut self) {
580 let category = self
581 .config
582 .admin_category
583 .clone()
584 .unwrap_or_else(|| DEFAULT_ADMIN_CATEGORY.to_owned());
585 let already_listed = self.module_entries.iter().any(|entry| entry.name == "auth");
586 let short = self
587 .root
588 .find_subcommand("auth")
589 .filter(|auth| !auth.is_hide_set())
590 .map(|auth| {
591 auth.get_about()
592 .map(ToString::to_string)
593 .unwrap_or_default()
594 });
595 if !already_listed && let Some(short) = short {
596 self.module_entries.push(ModuleHelpEntry {
597 category,
598 name: "auth".to_owned(),
599 short,
600 });
601 }
602 self.refresh_root_long();
603 }
604
605 #[must_use]
607 pub fn middleware(&self) -> &Middleware {
608 &self.middleware
609 }
610
611 pub fn middleware_mut(&mut self) -> &mut Middleware {
613 &mut self.middleware
614 }
615
616 pub async fn execute(&self) -> ExitCode {
618 let mut stdout = std::io::stdout().lock();
619 let mut stderr = std::io::stderr().lock();
620 match self
621 .execute_from(std::env::args_os(), &mut stdout, &mut stderr)
622 .await
623 {
624 Ok(code) => code,
625 Err(err) => {
626 drop(writeln!(stderr, "{err}"));
627 ExitCode::from(1)
628 }
629 }
630 }
631
632 pub async fn execute_from<I, S, O, E>(
634 &self,
635 args: I,
636 stdout: &mut O,
637 stderr: &mut E,
638 ) -> std::io::Result<ExitCode>
639 where
640 I: IntoIterator<Item = S>,
641 S: Into<std::ffi::OsString> + Clone,
642 O: Write,
643 E: Write,
644 {
645 self.execute_from_until_signal(args, stdout, stderr, shutdown_signal())
646 .await
647 }
648
649 pub async fn execute_from_until_signal<I, S, O, E, Shutdown>(
651 &self,
652 args: I,
653 stdout: &mut O,
654 stderr: &mut E,
655 shutdown: Shutdown,
656 ) -> std::io::Result<ExitCode>
657 where
658 I: IntoIterator<Item = S>,
659 S: Into<std::ffi::OsString> + Clone,
660 O: Write,
661 E: Write,
662 Shutdown: Future<Output = ()>,
663 {
664 let output = run_until_signal(self.run(args), shutdown).await;
665 if output.exit_code == 130
666 && output.rendered == "command interrupted\n"
667 && let Some(on_shutdown) = &self.on_shutdown
668 {
669 on_shutdown();
670 }
671 if output.exit_code == 0 {
672 stdout.write_all(output.rendered.as_bytes())?;
673 } else {
674 stderr.write_all(output.rendered.as_bytes())?;
675 }
676 Ok(process_exit_code(output.exit_code))
677 }
678
679 pub fn register_auth_provider(&mut self, provider: Arc<dyn AuthProvider>) -> &mut Self {
681 self.middleware.auth.register(provider);
682 self.ensure_auth_command();
683 self.refresh_root_long();
684 self
685 }
686
687 #[must_use]
689 pub fn root_command(&self) -> &Command {
690 &self.root
691 }
692
693 pub fn add_module_group(
695 &mut self,
696 category: impl Into<String>,
697 group: RuntimeGroupSpec,
698 ) -> &mut Self {
699 let category = category.into();
700 if !group.group.hidden {
701 self.module_entries.push(ModuleHelpEntry {
702 category,
703 name: group.group.name.clone(),
704 short: group.group.short.clone(),
705 });
706 }
707
708 let mut prefix = Vec::new();
709 register_runtime_group_schemas(&group, &mut prefix, &mut self.middleware.schema_registry);
710 let mut prefix = Vec::new();
711 group.register_commands(&mut prefix, &mut self.commands);
712 let mut prefix = Vec::new();
713 let clap_group = runtime_group_clap_command_with_schema_help(
714 &group,
715 &mut prefix,
716 &self.middleware.schema_registry,
717 );
718 self.root = self.root.clone().subcommand(clap_group);
719 self.refresh_root_long();
720 self
721 }
722
723 pub fn add_module(&mut self, module: Module) -> &mut Self {
725 for view in module.views.clone() {
726 self.middleware.human_views.register(view);
727 }
728 self.add_guides(module.guides.clone());
729 let mut context = ModuleContext::new(&mut self.middleware);
730 let group = (module.register)(&mut context);
731 let (guides, views) = context.into_parts();
732 for view in views {
733 self.middleware.human_views.register(view);
734 }
735 self.add_guides(guides);
736 self.add_module_group(module.category, group)
737 }
738
739 pub fn add_command(&mut self, command: RuntimeCommandSpec) -> &mut Self {
741 let name = command.spec.name.clone();
742 register_command_schema(&command.spec, &name, &mut self.middleware.schema_registry);
743 self.commands.insert(name, command.clone());
744 self.root = self
745 .root
746 .clone()
747 .subcommand(command_clap_command_with_schema_help(
748 &command.spec,
749 &command.spec.name,
750 &self.middleware.schema_registry,
751 ));
752 self
753 }
754
755 pub fn set_has_guide(&mut self, has_guide: bool) -> &mut Self {
757 if has_guide && self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
758 self.root = self.root.clone().subcommand(guide_command());
759 }
760 self.refresh_root_long();
761 self
762 }
763
764 pub fn add_guides(&mut self, entries: impl IntoIterator<Item = GuideEntry>) -> &mut Self {
766 let mut seen = self
767 .guide_entries
768 .iter()
769 .map(|entry| entry.name.clone())
770 .collect::<BTreeSet<_>>();
771 for entry in entries {
772 if seen.insert(entry.name.clone()) {
773 self.guide_entries.push(entry);
774 }
775 }
776 if !self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
777 self.root = self.root.clone().subcommand(guide_command());
778 }
779 self.refresh_root_long();
780 self
781 }
782
783 pub async fn run<I, S>(&self, args: I) -> CliRunOutput
785 where
786 I: IntoIterator<Item = S>,
787 S: Into<std::ffi::OsString> + Clone,
788 {
789 let raw_args = args
790 .into_iter()
791 .map(Into::into)
792 .collect::<Vec<std::ffi::OsString>>();
793 let text_args = raw_args
794 .iter()
795 .map(|arg| arg.to_string_lossy().into_owned())
796 .collect::<Vec<_>>();
797 let clap_args = normalize_optional_global_flags_before_command(&self.root, &text_args);
798 if has_root_version_flag(&text_args, &self.root, &self.config.name) {
799 return self.finish_run(CliRunOutput {
800 exit_code: 0,
801 rendered: format!(
802 "{} version {}\n",
803 self.config.name,
804 self.config.build.version_string()
805 ),
806 });
807 }
808 if let Some(output) = self.try_run_schema_bypass(&text_args) {
809 return output;
810 }
811 if let Some(output) = self.try_run_search_bypass(&text_args) {
812 return output;
813 }
814 if let Some(message) =
815 unknown_group_command_message(&self.root, &text_args, &self.config.name)
816 {
817 return self.finish_run(CliRunOutput {
818 exit_code: 1,
819 rendered: message,
820 });
821 }
822
823 let matches = match self.root.clone().try_get_matches_from(clap_args) {
824 Ok(matches) => matches,
825 Err(err) => {
826 return self.finish_run(CliRunOutput {
827 exit_code: err.exit_code(),
828 rendered: err.to_string(),
829 });
830 }
831 };
832
833 let default_format = default_output_format(&self.config.app_id);
834 let flags = global_flags_from_matches(&matches, &default_format);
835 let command_timeout = match parse_command_timeout(&flags.timeout) {
836 Ok(timeout) => timeout,
837 Err(err) => {
838 return self.finish_run(render_cli_error(
839 &self.middleware,
840 &err,
841 &self.config.app_id,
842 ));
843 }
844 };
845 let mut middleware = self.middleware.clone();
846 apply_global_flags(&mut middleware, &flags, command_timeout);
847 if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
848 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
849 }
850
851 let command_path = command_path_from_matches(&self.config.name, &matches);
852 if command_path == "help" {
853 if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &help_args(&matches))
854 {
855 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
856 }
857 return self.finish_run(self.render_help_command(&matches));
858 }
859 if command_path == "tree" {
860 if let Err(err) = self.run_pre_run(
861 &mut middleware,
862 &command_path,
863 &crate::middleware::ValueMap::new(),
864 ) {
865 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
866 }
867 return self.finish_run(tree_render::render_tree(
868 &self.root,
869 &self.config.app_id,
870 &middleware,
871 ));
872 }
873 if command_path == "guide" {
874 if let Err(err) =
875 self.run_pre_run(&mut middleware, &command_path, &guide_args(&matches))
876 {
877 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
878 }
879 return self.finish_run(self.render_guide(&matches));
880 }
881 let Some(command) = self.commands.get(&command_path) else {
882 if !command_path.is_empty()
883 && let Some(group) = find_command_by_colon_path(&self.root, &command_path)
884 && group.get_subcommands().next().is_some()
885 {
886 if let Err(err) = self.run_pre_run(
887 &mut middleware,
888 &command_path,
889 &crate::middleware::ValueMap::new(),
890 ) {
891 return self.finish_run(render_cli_error(
892 &middleware,
893 &err,
894 &self.config.app_id,
895 ));
896 }
897 return self.finish_run(CliRunOutput {
898 exit_code: 0,
899 rendered: group.clone().render_long_help().to_string(),
900 });
901 }
902 if command_path.is_empty()
903 && let Some(root_next_actions) = &self.root_next_actions
904 {
905 let actions = root_next_actions();
910 return self.finish_run(self.render_root(&middleware, actions));
911 }
912 return self.finish_run(CliRunOutput {
913 exit_code: if command_path.is_empty() { 0 } else { 1 },
914 rendered: if command_path.is_empty() {
915 self.root.clone().render_long_help().to_string()
916 } else {
917 format!("unknown command {command_path:?}")
918 },
919 });
920 };
921
922 let mut middleware = match self.initialized_middleware() {
923 Ok(middleware) => middleware,
924 Err(err) => {
925 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
926 }
927 };
928 apply_global_flags(&mut middleware, &flags, command_timeout);
929 if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
930 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
931 }
932
933 let leaf = leaf_matches(&matches);
934 let args = command_args_from_matches(leaf, &command.spec, false);
935 let user_args = command_args_from_matches(leaf, &command.spec, true);
936 if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &args) {
937 return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
938 }
939 let meta = self.resolve_meta(&command_path, command.spec.metadata());
940 let default_fields = command.spec.default_fields.clone().unwrap_or_default();
941 let system = command.spec.system.clone().unwrap_or_default();
942
943 if let Some(streaming_handler) = command.streaming_handler.clone() {
944 let result = run_with_timeout(
945 command_timeout,
946 &flags.timeout,
947 run_streaming_command(
948 &middleware,
949 MiddlewareRequest {
950 meta,
951 command_path: &command_path,
952 system: &system,
953 user_args,
954 args,
955 default_fields: &default_fields,
956 no_auth: command.spec.no_auth,
957 },
958 Arc::new(leaf.clone()),
959 streaming_handler,
960 ),
961 )
962 .await;
963 return self.finish_run(match result {
964 Ok(output) => output,
965 Err(err) => render_cli_error(&middleware, &err, &self.config.app_id),
966 });
967 }
968
969 let handler = command.handler.clone();
970 let args_for_handler = args.clone();
971 let user_args_for_handler = user_args.clone();
972 let handler_path = command_path.clone();
973 let middleware_for_handler = middleware.clone();
974 let raw_matches_for_handler = Arc::new(leaf.clone());
975 let result = run_with_timeout(
976 command_timeout,
977 &flags.timeout,
978 middleware.run(
979 MiddlewareRequest {
980 meta,
981 command_path: &command_path,
982 system: &system,
983 user_args,
984 args,
985 default_fields: &default_fields,
986 no_auth: command.spec.no_auth,
987 },
988 async move |credential| {
989 handler(CommandContext {
990 credential,
991 args: args_for_handler,
992 user_args: user_args_for_handler,
993 command_path: handler_path,
994 middleware: middleware_for_handler,
995 raw_matches: raw_matches_for_handler,
996 })
997 .await
998 },
999 ),
1000 )
1001 .await;
1002
1003 match result {
1004 Ok(output) => self.finish_run(output.into()),
1005 Err(err) => self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id)),
1006 }
1007 }
1008
1009 fn try_run_search_bypass(&self, args: &[String]) -> Option<CliRunOutput> {
1010 let query = extract_search_query(args);
1011 if query.is_empty() {
1012 return None;
1013 }
1014 let scope = self.search_scope(args);
1015 let output_format =
1016 extract_output_format(args, &default_output_format(&self.config.app_id));
1017 Some(self.render_search(&query, &scope, &output_format))
1018 }
1019
1020 fn try_run_schema_bypass(&self, args: &[String]) -> Option<CliRunOutput> {
1021 if !has_true_schema_flag(args) {
1022 return None;
1023 }
1024 let bool_flags = derive_bool_flags(&self.root);
1025 let value_flags = derive_value_flags(&self.root);
1026 let command_path =
1027 self.canonical_command_path(&extract_command_path(args, &bool_flags, &value_flags));
1028 let schema = self.middleware.schema_registry.get_by_path(&command_path)?;
1029 let output_format =
1030 extract_output_format(args, &default_output_format(&self.config.app_id));
1031 Some(self.render_schema(schema, &output_format))
1032 }
1033
1034 fn render_schema(
1035 &self,
1036 schema: crate::output::SchemaInfo,
1037 output_format: &str,
1038 ) -> CliRunOutput {
1039 let format: crate::output::OutputFormat = match output_format.parse() {
1040 Ok(format) => format,
1041 Err(err) => {
1042 return CliRunOutput {
1043 exit_code: exit_code_for_error(&err),
1044 rendered: err.to_string(),
1045 };
1046 }
1047 };
1048 let envelope =
1049 crate::Envelope::success(schema, self.config.app_id.clone()).prepare_for_render("");
1050 match crate::output::render(format, &envelope) {
1051 Ok(rendered) => CliRunOutput {
1052 exit_code: 0,
1053 rendered,
1054 },
1055 Err(err) => CliRunOutput {
1056 exit_code: exit_code_for_error(&err),
1057 rendered: err.to_string(),
1058 },
1059 }
1060 }
1061
1062 fn render_search(&self, query: &str, scope: &str, output_format: &str) -> CliRunOutput {
1063 let format: crate::output::OutputFormat = match output_format.parse() {
1064 Ok(format) => format,
1065 Err(err) => {
1066 return CliRunOutput {
1067 exit_code: exit_code_for_error(&err),
1068 rendered: err.to_string(),
1069 };
1070 }
1071 };
1072 let docs = self.search_documents(scope);
1073 let results = SearchIndex::new(docs).search(query, 10);
1074 let envelope =
1075 crate::Envelope::success(results, self.config.app_id.clone()).prepare_for_render("");
1076 match crate::output::render(format, &envelope) {
1077 Ok(rendered) => CliRunOutput {
1078 exit_code: 0,
1079 rendered,
1080 },
1081 Err(err) => CliRunOutput {
1082 exit_code: exit_code_for_error(&err),
1083 rendered: err.to_string(),
1084 },
1085 }
1086 }
1087
1088 fn render_root(&self, middleware: &Middleware, actions: Vec<NextAction>) -> CliRunOutput {
1094 if !crate::output::is_valid_output_format(&middleware.output_format) {
1099 let err = CliCoreError::InvalidOutputFormat(middleware.output_format.clone());
1100 return CliRunOutput {
1101 exit_code: exit_code_for_error(&err),
1102 rendered: err.to_string(),
1103 };
1104 }
1105 let format = middleware
1106 .output_format
1107 .parse()
1108 .unwrap_or(crate::output::OutputFormat::Json);
1109 if format == crate::output::OutputFormat::Human {
1110 let base_long = self
1114 .root
1115 .get_long_about()
1116 .map(ToString::to_string)
1117 .unwrap_or_default();
1118 let long = format!("{base_long}{}", render_next_actions_human(&actions));
1119 let rendered = self
1120 .root
1121 .clone()
1122 .long_about(long)
1123 .render_long_help()
1124 .to_string();
1125 return CliRunOutput {
1126 exit_code: 0,
1127 rendered,
1128 };
1129 }
1130 let description = self
1131 .config
1132 .long
1133 .as_deref()
1134 .filter(|long| !long.is_empty())
1135 .unwrap_or(self.config.short.as_str());
1136 let data = serde_json::json!({
1137 "description": description,
1138 "version": self.config.build.version,
1139 });
1140 let envelope = crate::Envelope::success(data, self.config.app_id.clone())
1141 .with_next_actions(actions)
1142 .prepare_for_render(&middleware.verbose);
1143 match crate::output::render(format, &envelope) {
1144 Ok(rendered) => CliRunOutput {
1145 exit_code: 0,
1146 rendered,
1147 },
1148 Err(err) => CliRunOutput {
1149 exit_code: exit_code_for_error(&err),
1150 rendered: err.to_string(),
1151 },
1152 }
1153 }
1154
1155 fn search_documents(&self, scope: &str) -> Vec<SearchDocument> {
1156 let (scoped, mut prefix) = find_command_and_canonical_path_by_colon_path(&self.root, scope)
1157 .unwrap_or((&self.root, Vec::new()));
1158 let mut docs = Vec::new();
1159 let mut aliases = Vec::new();
1160 append_command_alias_terms(scoped, &mut aliases);
1161 collect_command_search_documents(scoped, &mut prefix, &mut aliases, &mut docs);
1162 if scope.is_empty() {
1163 for entry in &self.guide_entries {
1164 docs.push(SearchDocument {
1165 id: format!("guide:{}", entry.name),
1166 kind: "guide".to_owned(),
1167 title: format!("guide {}", entry.name),
1168 summary: entry.summary.clone(),
1169 content: format!("{} {}", entry.summary, entry.content),
1170 });
1171 }
1172 if let Some(extra_search_docs) = &self.extra_search_docs {
1173 docs.extend(extra_search_docs());
1174 }
1175 }
1176 docs
1177 }
1178
1179 fn search_scope(&self, args: &[String]) -> String {
1180 let parts = extract_search_scope_parts(args);
1181 canonical_path_from_parts(&self.root, &parts).unwrap_or_default()
1182 }
1183
1184 fn canonical_command_path(&self, command_path: &str) -> String {
1185 find_command_and_canonical_path_by_colon_path(&self.root, command_path).map_or_else(
1186 || command_path.to_owned(),
1187 |(_, canonical)| canonical.join(":"),
1188 )
1189 }
1190
1191 fn render_guide(&self, matches: &ArgMatches) -> CliRunOutput {
1192 let leaf = leaf_matches(matches);
1193 let topic = leaf.get_one::<String>("topic").map(String::as_str);
1194 match guide_content(&self.guide_entries, topic) {
1195 Ok(rendered) => CliRunOutput {
1196 exit_code: 0,
1197 rendered,
1198 },
1199 Err(err) => CliRunOutput {
1200 exit_code: 1,
1201 rendered: err,
1202 },
1203 }
1204 }
1205
1206 fn render_help_command(&self, matches: &ArgMatches) -> CliRunOutput {
1207 let leaf = leaf_matches(matches);
1208 let parts = leaf
1209 .get_many::<String>("command")
1210 .map(|values| values.map(String::as_str).collect::<Vec<_>>())
1211 .unwrap_or_default();
1212 if parts.is_empty() {
1213 return CliRunOutput {
1214 exit_code: 0,
1215 rendered: self.root.clone().render_long_help().to_string(),
1216 };
1217 }
1218 let Some(command) = find_help_target(&self.root, &parts) else {
1219 return CliRunOutput {
1220 exit_code: 1,
1221 rendered: format!(
1222 "unknown command {:?} — run '{} help' for available commands",
1223 parts.join(" "),
1224 self.config.name
1225 ),
1226 };
1227 };
1228 CliRunOutput {
1229 exit_code: 0,
1230 rendered: command.clone().render_long_help().to_string(),
1231 }
1232 }
1233
1234 fn refresh_root_long(&mut self) {
1235 const BUILTINS: [&str; 4] = ["help", "guide", "tree", "completion"];
1240 let categorized: BTreeSet<&str> = self
1241 .module_entries
1242 .iter()
1243 .map(|entry| entry.name.as_str())
1244 .collect();
1245 let mut generic: Vec<ModuleHelpEntry> = self
1246 .root
1247 .get_subcommands()
1248 .filter(|command| !command.is_hide_set())
1249 .filter(|command| !BUILTINS.contains(&command.get_name()))
1250 .filter(|command| !categorized.contains(command.get_name()))
1251 .map(|command| ModuleHelpEntry {
1252 category: "Commands".to_owned(),
1253 name: command.get_name().to_owned(),
1254 short: command
1255 .get_about()
1256 .map(ToString::to_string)
1257 .unwrap_or_default(),
1258 })
1259 .collect();
1260 generic.sort_by(|left, right| left.name.cmp(&right.name));
1261
1262 let mut entries = self.module_entries.clone();
1263 entries.extend(generic);
1264 let has_guide = !self.guide_entries.is_empty() || has_subcommand(&self.root, "guide");
1265 let intro = self
1266 .config
1267 .long
1268 .as_deref()
1269 .filter(|long| !long.is_empty())
1270 .unwrap_or(self.config.short.as_str());
1271 self.root = self
1272 .root
1273 .clone()
1274 .long_about(build_root_long(intro, &entries, has_guide));
1275 }
1276
1277 fn ensure_auth_command(&mut self) {
1278 let default_provider = self.default_auth_provider();
1279 let registered_names = self.middleware.auth.registered_names();
1280 if default_provider.is_empty() && registered_names.is_empty() {
1281 return;
1282 }
1283 let replacing_builtin = self.commands.contains_key("auth:login");
1284 if has_subcommand(&self.root, "auth") && !replacing_builtin {
1285 return;
1286 }
1287 let group = auth_command_group(&default_provider, ®istered_names);
1288 let mut prefix = Vec::new();
1289 group.register_commands(&mut prefix, &mut self.commands);
1290 let mut prefix = Vec::new();
1291 let clap_group = runtime_group_clap_command_with_schema_help(
1292 &group,
1293 &mut prefix,
1294 &self.middleware.schema_registry,
1295 );
1296 self.root = if replacing_builtin {
1297 self.root.clone().mut_subcommand("auth", |_| clap_group)
1298 } else {
1299 self.root.clone().subcommand(clap_group)
1300 };
1301 self.register_auth_help_entry();
1305 }
1306
1307 fn default_auth_provider(&self) -> String {
1308 if !self.middleware.default_auth_provider.is_empty() {
1309 return self.middleware.default_auth_provider.clone();
1310 }
1311 self.middleware
1312 .auth
1313 .registered_names()
1314 .into_iter()
1315 .next()
1316 .unwrap_or_default()
1317 }
1318
1319 fn initialized_middleware(&self) -> Result<Middleware> {
1320 let Some(init_deps) = &self.init_deps else {
1321 return Ok(self.middleware.clone());
1322 };
1323 let mut guard = self
1324 .init_state
1325 .lock()
1326 .map_err(|_| CliCoreError::message("init deps lock poisoned"))?;
1327 if let Some(result) = guard.as_ref() {
1328 return result.clone().map_err(InitFailure::into_error);
1329 }
1330 let mut middleware = self.middleware.clone();
1331 let result = init_deps(&mut middleware)
1332 .map(|()| middleware)
1333 .map_err(|err| InitFailure::capture(&err));
1334 *guard = Some(result.clone());
1335 result.map_err(InitFailure::into_error)
1336 }
1337
1338 fn apply_config_flags(&self, matches: &ArgMatches, middleware: &mut Middleware) -> Result<()> {
1339 if let Some(apply_flags) = &self.apply_flags {
1340 apply_flags(matches, middleware)?;
1341 }
1342 Ok(())
1343 }
1344
1345 fn run_pre_run(
1346 &self,
1347 middleware: &mut Middleware,
1348 command_path: &str,
1349 args: &crate::middleware::ValueMap,
1350 ) -> Result<()> {
1351 if let Some(pre_run) = &self.pre_run {
1352 pre_run(middleware, command_path, args)?;
1353 }
1354 Ok(())
1355 }
1356
1357 fn resolve_meta(&self, command_path: &str, meta: CommandMeta) -> CommandMeta {
1358 if let Some(resolver) = &self.meta_resolver {
1359 resolver(command_path, meta)
1360 } else {
1361 meta
1362 }
1363 }
1364
1365 fn finish_run(&self, output: CliRunOutput) -> CliRunOutput {
1366 if let Some(on_shutdown) = &self.on_shutdown {
1367 on_shutdown();
1368 }
1369 output
1370 }
1371}
1372
1373fn apply_global_flags(middleware: &mut Middleware, flags: &GlobalFlags, timeout: Option<Duration>) {
1374 middleware.output_format = flags.output_format.clone();
1375 middleware.verbose = flags.verbose.clone();
1376 middleware.dry_run = flags.dry_run;
1377 middleware.fields = flags.fields.clone();
1378 middleware.filter = flags.filter.clone();
1379 middleware.expr = flags.expr.clone();
1380 middleware.limit = flags.limit;
1381 middleware.offset = flags.offset;
1382 middleware.reason = flags.reason.clone();
1383 middleware.schema = flags.schema;
1384 middleware.timeout = timeout;
1385 middleware.debug = flags.debug.clone();
1386 middleware.search = flags.search.clone();
1387}
1388
1389async fn run_with_timeout<F, T>(
1390 timeout: Option<Duration>,
1391 timeout_label: &str,
1392 future: F,
1393) -> Result<T>
1394where
1395 F: Future<Output = Result<T>>,
1396{
1397 let Some(timeout) = timeout else {
1398 return future.await;
1399 };
1400 match tokio::time::timeout(timeout, future).await {
1401 Ok(result) => result,
1402 Err(_) => Err(CliCoreError::message(format!(
1403 "command timed out after {timeout_label}"
1404 ))),
1405 }
1406}
1407
1408async fn run_until_signal<Run, Shutdown>(run: Run, shutdown: Shutdown) -> CliRunOutput
1409where
1410 Run: Future<Output = CliRunOutput>,
1411 Shutdown: Future<Output = ()>,
1412{
1413 tokio::pin!(run);
1414 tokio::pin!(shutdown);
1415 tokio::select! {
1416 output = &mut run => output,
1417 () = &mut shutdown => CliRunOutput {
1418 exit_code: 130,
1419 rendered: "command interrupted\n".to_owned(),
1420 },
1421 }
1422}
1423
1424#[cfg(unix)]
1425async fn shutdown_signal() {
1426 let ctrl_c = tokio::signal::ctrl_c();
1427 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
1428 Ok(mut sigterm) => {
1429 tokio::select! {
1430 _ = ctrl_c => {},
1431 _ = sigterm.recv() => {},
1432 }
1433 }
1434 Err(_) => {
1435 drop(ctrl_c.await);
1436 }
1437 }
1438}
1439
1440#[cfg(not(unix))]
1441async fn shutdown_signal() {
1442 drop(tokio::signal::ctrl_c().await);
1443}
1444
1445fn parse_command_timeout(raw: &str) -> Result<Option<Duration>> {
1446 let raw = raw.trim();
1447 if raw.is_empty() {
1448 return Ok(Some(Duration::from_secs(60)));
1449 }
1450 let Some(seconds) = parse_duration_seconds(raw) else {
1451 return Err(CliCoreError::message(format!(
1452 "invalid timeout {raw:?}: expected duration like 60s, 5m, or 0s"
1453 )));
1454 };
1455 if seconds <= 0.0 {
1456 Ok(None)
1457 } else {
1458 Ok(Some(Duration::from_secs_f64(seconds)))
1459 }
1460}
1461
1462fn parse_duration_seconds(raw: &str) -> Option<f64> {
1463 for (suffix, seconds) in [
1464 ("ns", 0.000_000_001_f64),
1465 ("us", 0.000_001_f64),
1466 ("µs", 0.000_001_f64),
1467 ("ms", 0.001_f64),
1468 ("s", 1.0_f64),
1469 ("m", 60.0_f64),
1470 ("h", 3600.0_f64),
1471 ] {
1472 if let Some(number) = raw.strip_suffix(suffix) {
1473 let value = number.parse::<f64>().ok()?;
1474 if !value.is_finite() {
1475 return None;
1476 }
1477 return Some(value * seconds);
1478 }
1479 }
1480 None
1481}
1482
1483fn render_cli_error(
1484 middleware: &Middleware,
1485 err: &(dyn std::error::Error + 'static),
1486 system: &str,
1487) -> CliRunOutput {
1488 let format = middleware
1489 .output_format
1490 .parse::<crate::output::OutputFormat>()
1491 .unwrap_or(crate::output::OutputFormat::Json);
1492 let envelope =
1493 crate::output::build_error_envelope(err, system).prepare_for_render(&middleware.verbose);
1494 match crate::output::render(format, &envelope) {
1495 Ok(rendered) => CliRunOutput {
1496 exit_code: exit_code_for_error(err),
1497 rendered,
1498 },
1499 Err(render_err) => CliRunOutput {
1500 exit_code: exit_code_for_error(err),
1501 rendered: render_err.to_string(),
1502 },
1503 }
1504}
1505
1506fn find_command_by_colon_path<'command>(
1507 root: &'command Command,
1508 path: &str,
1509) -> Option<&'command Command> {
1510 find_command_and_canonical_path_by_colon_path(root, path).map(|(command, _)| command)
1511}
1512
1513fn find_help_target<'command>(
1514 root: &'command Command,
1515 parts: &[&str],
1516) -> Option<&'command Command> {
1517 let mut current = root;
1518 let mut matched_any = false;
1519 for part in parts {
1520 let Some(next) = current.find_subcommand(part) else {
1521 break;
1522 };
1523 current = next;
1524 matched_any = true;
1525 }
1526 matched_any.then_some(current)
1527}
1528
1529fn find_command_and_canonical_path_by_colon_path<'command>(
1530 root: &'command Command,
1531 path: &str,
1532) -> Option<(&'command Command, Vec<String>)> {
1533 if path.is_empty() {
1534 return Some((root, Vec::new()));
1535 }
1536 let mut current = root;
1537 let mut canonical = Vec::new();
1538 for part in path.split(':') {
1539 current = current.find_subcommand(part)?;
1540 canonical.push(current.get_name().to_owned());
1541 }
1542 Some((current, canonical))
1543}
1544
1545fn canonical_path_from_parts(root: &Command, parts: &[String]) -> Option<String> {
1546 if parts.is_empty() {
1547 return Some(String::new());
1548 }
1549 let mut current = root;
1550 let mut canonical = Vec::new();
1551 for part in parts {
1552 current = current.find_subcommand(part)?;
1553 canonical.push(current.get_name().to_owned());
1554 }
1555 Some(canonical.join(":"))
1556}
1557
1558fn extract_search_scope_parts(args: &[String]) -> Vec<String> {
1559 let mut parts = Vec::new();
1560 let mut index = 1;
1561 while index < args.len() {
1562 let arg = &args[index];
1563 if arg == "--search" || arg.starts_with("--search=") {
1564 break;
1565 }
1566 if arg.starts_with('-') {
1567 if !arg.contains('=') && index + 1 < args.len() && !args[index + 1].starts_with('-') {
1568 index += 2;
1569 } else {
1570 index += 1;
1571 }
1572 continue;
1573 }
1574 parts.push(arg.clone());
1575 index += 1;
1576 }
1577 parts
1578}
1579
1580fn collect_command_search_documents(
1581 command: &Command,
1582 prefix: &mut Vec<String>,
1583 aliases: &mut Vec<String>,
1584 docs: &mut Vec<SearchDocument>,
1585) {
1586 if command.is_hide_set() || command.get_name() == "completion" {
1587 return;
1588 }
1589 if command.get_subcommands().next().is_some() {
1590 for child in command.get_subcommands() {
1591 prefix.push(child.get_name().to_owned());
1592 let alias_len = aliases.len();
1593 append_command_alias_terms(child, aliases);
1594 collect_command_search_documents(child, prefix, aliases, docs);
1595 aliases.truncate(alias_len);
1596 prefix.pop();
1597 }
1598 return;
1599 }
1600 if prefix.is_empty() {
1601 prefix.push(command.get_name().to_owned());
1602 append_command_alias_terms(command, aliases);
1603 }
1604 let path = prefix.join(" ");
1605 let alias_text = aliases.join(" ");
1606 docs.push(SearchDocument {
1607 id: format!("cmd:{path}"),
1608 kind: "command".to_owned(),
1609 title: path,
1610 summary: command
1611 .get_about()
1612 .map(ToString::to_string)
1613 .unwrap_or_default(),
1614 content: format!(
1615 "{} {} {} {}",
1616 command
1617 .get_about()
1618 .map(ToString::to_string)
1619 .unwrap_or_default(),
1620 command
1621 .get_long_about()
1622 .map(ToString::to_string)
1623 .unwrap_or_default(),
1624 command_flag_text(command),
1625 alias_text
1626 ),
1627 });
1628 if prefix.len() == 1 && prefix[0] == command.get_name() {
1629 prefix.pop();
1630 }
1631}
1632
1633fn append_command_alias_terms(command: &Command, aliases: &mut Vec<String>) {
1634 aliases.extend(command.get_all_aliases().map(str::to_owned));
1635 aliases.extend(
1636 command
1637 .get_all_short_flag_aliases()
1638 .map(|alias| alias.to_string()),
1639 );
1640 aliases.extend(command.get_all_long_flag_aliases().map(str::to_owned));
1641}
1642
1643fn command_flag_text(command: &Command) -> String {
1644 command
1645 .get_arguments()
1646 .filter_map(|arg| {
1647 let mut names = Vec::new();
1648 if let Some(short) = arg.get_short() {
1649 names.push(format!("-{short}"));
1650 }
1651 if let Some(long) = arg.get_long() {
1652 names.push(format!("--{long}"));
1653 }
1654 if let Some(short_aliases) = arg.get_all_short_aliases() {
1655 names.extend(
1656 short_aliases
1657 .into_iter()
1658 .map(|short_alias| format!("-{short_alias}")),
1659 );
1660 }
1661 if let Some(aliases) = arg.get_all_aliases() {
1662 names.extend(aliases.into_iter().map(|alias| format!("--{alias}")));
1663 }
1664 (!names.is_empty()).then(|| names.join(" "))
1665 })
1666 .collect::<Vec<_>>()
1667 .join(" ")
1668}
1669
1670fn has_subcommand(command: &Command, name: &str) -> bool {
1671 command
1672 .get_subcommands()
1673 .any(|child| child.get_name() == name)
1674}
1675
1676fn has_root_version_flag(args: &[String], root: &Command, root_name: &str) -> bool {
1677 let bool_flags = derive_bool_flags(root);
1678 let value_flags = derive_value_flags(root);
1679 let mut iter = args.iter().peekable();
1680 if iter
1681 .peek()
1682 .is_some_and(|arg| arg_matches_root_name(arg, root_name))
1683 {
1684 iter.next();
1685 }
1686
1687 while let Some(arg) = iter.next() {
1688 match arg.as_str() {
1689 "--version" | "-v" => return true,
1690 "--" => return false,
1691 value if value.contains('=') || bool_flags.contains(value) => continue,
1692 value
1693 if value_flags.contains(value)
1694 || unknown_flag_consumes_value(value, iter.peek()) =>
1695 {
1696 iter.next();
1697 }
1698 value if value.starts_with('-') => {}
1699 _ => return false,
1700 }
1701 }
1702 false
1703}
1704
1705fn normalize_optional_global_flags_before_command(root: &Command, args: &[String]) -> Vec<String> {
1706 let optional_string_defaults = BTreeMap::from([("--verbose", "all"), ("--debug", "*")]);
1707 let optional_bool_defaults = BTreeMap::from([("--dry-run", "true"), ("--schema", "true")]);
1708 let mut normalized = Vec::with_capacity(args.len());
1709 let mut index = 0;
1710 let mut current = root;
1711 while index < args.len() {
1712 let arg = &args[index];
1713 if index == 0 && arg_matches_root_name(arg, root.get_name()) {
1714 normalized.push(arg.clone());
1715 index += 1;
1716 continue;
1717 }
1718
1719 if let Some(default) = optional_bool_defaults.get(arg.as_str()) {
1720 normalized.push(format!("{arg}={default}"));
1721 index += 1;
1722 continue;
1723 }
1724
1725 if let Some(default) = optional_string_defaults.get(arg.as_str()) {
1726 match args.get(index + 1) {
1727 None => {
1728 normalized.push(format!("{arg}={default}"));
1729 index += 1;
1730 continue;
1731 }
1732 Some(next)
1733 if current.get_name() == root.get_name()
1734 || next.starts_with('-')
1735 || direct_subcommand(current, next).is_some() =>
1736 {
1737 normalized.push(format!("{arg}={default}"));
1738 index += 1;
1739 continue;
1740 }
1741 Some(next) => {
1742 normalized.push(arg.clone());
1743 normalized.push(next.clone());
1744 index += 2;
1745 continue;
1746 }
1747 }
1748 }
1749
1750 normalized.push(arg.clone());
1751 if !arg.starts_with('-')
1752 && let Some(next_command) = direct_subcommand(current, arg)
1753 {
1754 current = next_command;
1755 }
1756 index += 1;
1757 }
1758 normalized
1759}
1760
1761fn direct_subcommand<'command>(
1762 command: &'command Command,
1763 token: &str,
1764) -> Option<&'command Command> {
1765 command.get_subcommands().find(|child| {
1766 child.get_name() == token || child.get_all_aliases().any(|alias| alias == token)
1767 })
1768}
1769
1770fn unknown_group_command_message(
1771 root: &Command,
1772 args: &[String],
1773 root_name: &str,
1774) -> Option<String> {
1775 let bool_flags = derive_bool_flags(root);
1776 let value_flags = derive_value_flags(root);
1777 let positionals = positional_command_tokens(args, root_name, &bool_flags, &value_flags);
1778 if positionals.is_empty() {
1779 return None;
1780 }
1781
1782 let mut current = root;
1783 let mut path = vec![root.get_name().to_owned()];
1784 for token in positionals {
1785 if let Some(next) = current.find_subcommand(&token) {
1786 current = next;
1787 path.push(next.get_name().to_owned());
1788 continue;
1789 }
1790 if current.get_subcommands().next().is_some() {
1791 return Some(format!(
1792 "unknown command {token:?} for {:?}",
1793 path.join(" ")
1794 ));
1795 }
1796 return None;
1797 }
1798 None
1799}
1800
1801fn positional_command_tokens(
1802 args: &[String],
1803 root_name: &str,
1804 bool_flags: &BTreeSet<String>,
1805 value_flags: &BTreeSet<String>,
1806) -> Vec<String> {
1807 let mut tokens = Vec::new();
1808 let mut iter = args.iter().peekable();
1809 if iter
1810 .peek()
1811 .is_some_and(|arg| arg_matches_root_name(arg, root_name))
1812 {
1813 iter.next();
1814 }
1815
1816 while let Some(arg) = iter.next() {
1817 if arg == "--" {
1818 tokens.extend(iter.cloned());
1819 break;
1820 }
1821 if arg.contains('=') {
1822 continue;
1823 }
1824 if bool_flags.contains(arg) {
1825 continue;
1826 }
1827 if value_flags.contains(arg) || unknown_flag_consumes_value(arg, iter.peek()) {
1828 iter.next();
1829 continue;
1830 }
1831 if arg.starts_with('-') {
1832 continue;
1833 }
1834 tokens.push(arg.clone());
1835 }
1836 tokens
1837}
1838
1839fn unknown_flag_consumes_value(arg: &str, next: Option<&&String>) -> bool {
1840 arg.starts_with('-') && next.is_some_and(|value| !value.starts_with('-'))
1841}
1842
1843fn arg_matches_root_name(arg: &str, root_name: &str) -> bool {
1844 arg == root_name
1845 || std::path::Path::new(arg)
1846 .file_stem()
1847 .and_then(|n| n.to_str())
1848 .is_some_and(|n| n == root_name)
1849}
1850
1851fn register_runtime_group_schemas(
1852 group: &RuntimeGroupSpec,
1853 prefix: &mut Vec<String>,
1854 schemas: &mut SchemaRegistry,
1855) {
1856 prefix.push(group.group.name.clone());
1857 for child_group in &group.groups {
1858 register_runtime_group_schemas(child_group, prefix, schemas);
1859 }
1860 for child in &group.commands {
1861 prefix.push(child.spec.name.clone());
1862 register_command_schema(&child.spec, &prefix.join(":"), schemas);
1863 prefix.pop();
1864 }
1865 prefix.pop();
1866}
1867
1868fn register_command_schema(spec: &CommandSpec, command_path: &str, schemas: &mut SchemaRegistry) {
1869 if let Some(schema) = &spec.output_schema {
1870 schemas.register_info(command_path.to_owned(), schema.clone());
1871 }
1872}
1873
1874fn runtime_group_clap_command_with_schema_help(
1875 group: &RuntimeGroupSpec,
1876 prefix: &mut Vec<String>,
1877 schemas: &SchemaRegistry,
1878) -> Command {
1879 let mut command = group_clap_command_without_children(&group.group);
1880 prefix.push(group.group.name.clone());
1881 for child_group in &group.groups {
1882 command = command.subcommand(runtime_group_clap_command_with_schema_help(
1883 child_group,
1884 prefix,
1885 schemas,
1886 ));
1887 }
1888 for child in &group.commands {
1889 prefix.push(child.spec.name.clone());
1890 let command_path = prefix.join(":");
1891 command = command.subcommand(command_clap_command_with_schema_help(
1892 &child.spec,
1893 &command_path,
1894 schemas,
1895 ));
1896 prefix.pop();
1897 }
1898 prefix.pop();
1899 command
1900}
1901
1902fn group_clap_command_without_children(group: &GroupSpec) -> Command {
1903 let mut command = Command::new(group.name.clone())
1904 .about(group.short.clone())
1905 .help_template(GROUP_HELP_TEMPLATE);
1906 if let Some(long) = &group.long
1907 && !long.is_empty()
1908 {
1909 command = command.long_about(long.clone());
1910 }
1911 for alias in &group.aliases {
1912 command = command.alias(alias.clone());
1913 }
1914 if group.hidden {
1915 command = command.hide(true);
1916 }
1917 command
1918}
1919
1920fn command_clap_command_with_schema_help(
1921 spec: &CommandSpec,
1922 command_path: &str,
1923 schemas: &SchemaRegistry,
1924) -> Command {
1925 let mut command = spec.clap_command();
1926 let Some(schema) = schemas.get_by_path(command_path) else {
1927 return command;
1928 };
1929 let schema_help = format_help_section(&schema.fields);
1930 if schema_help.is_empty() {
1931 return command;
1932 }
1933 let base = spec
1934 .long
1935 .as_ref()
1936 .filter(|long| !long.is_empty())
1937 .cloned()
1938 .unwrap_or_else(|| spec.short.clone());
1939 let long = if base.is_empty() {
1940 schema_help
1941 } else {
1942 format!("{base}\n\n{schema_help}")
1943 };
1944 command = command.long_about(long);
1945 command
1946}
1947
1948fn process_exit_code(code: i32) -> ExitCode {
1949 if code == 0 {
1950 return ExitCode::SUCCESS;
1951 }
1952 match u8::try_from(code) {
1953 Ok(code) if code != 0 => ExitCode::from(code),
1954 Ok(_) | Err(_) => ExitCode::from(1),
1955 }
1956}
1957
1958async fn run_streaming_command(
1959 middleware: &Middleware,
1960 request: MiddlewareRequest<'_>,
1961 raw_matches: Arc<ArgMatches>,
1962 streaming_handler: crate::command::StreamingCommandHandler,
1963) -> Result<CliRunOutput> {
1964 use tokio::{io::AsyncWriteExt, sync::mpsc};
1965
1966 let args_for_handler = request.args.clone();
1967 let user_args_for_handler = request.user_args.clone();
1968 let handler_path = request.command_path.to_owned();
1969 let middleware_for_handler = middleware.clone();
1970 let raw_matches_for_handler = raw_matches;
1971
1972 let (tx, mut rx) = mpsc::channel::<serde_json::Value>(64);
1973 let sender = StreamSender(tx);
1974
1975 let writer = tokio::spawn(async move {
1979 let mut stdout = tokio::io::stdout();
1980 while let Some(event) = rx.recv().await {
1981 let Ok(line) = serde_json::to_string(&event) else {
1982 continue;
1983 };
1984 if stdout.write_all(line.as_bytes()).await.is_err()
1985 || stdout.write_all(b"\n").await.is_err()
1986 || stdout.flush().await.is_err()
1987 {
1988 break;
1989 }
1990 }
1991 });
1992
1993 let output = middleware
1994 .run(request, async move |credential| {
1995 streaming_handler(
1996 CommandContext {
1997 credential,
1998 args: args_for_handler,
1999 user_args: user_args_for_handler,
2000 command_path: handler_path,
2001 middleware: middleware_for_handler,
2002 raw_matches: raw_matches_for_handler,
2003 },
2004 sender,
2005 )
2006 .await?;
2007 Ok(crate::CommandResult::new(serde_json::Value::Null))
2008 })
2009 .await;
2010
2011 let _write_result = writer.await;
2014
2015 match output {
2016 Ok(out) if out.exit_code == 0 => Ok(CliRunOutput {
2017 exit_code: 0,
2018 rendered: String::new(),
2019 }),
2020 Ok(out) => Ok(out.into()),
2021 Err(err) => Ok(CliRunOutput {
2022 exit_code: exit_code_for_error(&err),
2023 rendered: render_cli_error(middleware, &err, middleware.app_id.as_str()).rendered,
2024 }),
2025 }
2026}