rtb-cli 0.7.0

Rust Tool Base — CLI application scaffolding, clap integration, and built-in commands.
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
//! The [`Application`] entry-point type and its hand-rolled typestate
//! builder.

use std::ffi::OsString;
use std::sync::Arc;

use clap::Command as ClapCommand;
use rtb_app::app::App;
use rtb_app::command::{Command as RtbCommand, BUILTIN_COMMANDS};
use rtb_app::features::Features;
use rtb_app::metadata::ToolMetadata;
use rtb_app::version::VersionInfo;
use rtb_assets::Assets;
use rtb_config::Config;

use crate::runtime::{self, LogFormat};

/// A fully-configured application ready to dispatch.
pub struct Application {
    app: App,
    commands: Vec<Box<dyn RtbCommand>>,
    install_hooks: bool,
}

impl Application {
    /// Start building a new application. `metadata` and `version`
    /// must be provided before [`ApplicationBuilder::build`] will
    /// compile — enforced by the phantom-typed typestate below.
    pub fn builder() -> ApplicationBuilder<NoMetadata, NoVersion> {
        ApplicationBuilder::new()
    }

    /// Parse CLI arguments from `std::env::args_os()`, dispatch,
    /// return.
    pub async fn run(self) -> miette::Result<()> {
        // Collect eagerly — `std::env::ArgsOs` is not `Send`, which
        // would poison the returned Future for multi-thread runtimes.
        let args: Vec<OsString> = std::env::args_os().collect();
        self.run_with_args(args).await
    }

    /// Programmatic dispatch. Useful in tests.
    pub async fn run_with_args<I, S>(self, args: I) -> miette::Result<()>
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString> + Clone,
    {
        if self.install_hooks {
            rtb_error::hook::install_report_handler();
            rtb_error::hook::install_panic_hook();
            if let Some(footer) = self.app.metadata.help.footer() {
                rtb_error::hook::install_with_footer(move || footer.clone());
            }
        }

        runtime::install_tracing(LogFormat::auto());
        runtime::bind_shutdown_signals(self.app.shutdown.clone());

        let clap_cmd = build_clap_tree(&self.app.metadata, &self.commands);
        let matches = match clap_cmd.try_get_matches_from(args) {
            Ok(m) => m,
            Err(e) if is_help_or_version(&e) => {
                // clap already printed help/version to stdout; exit
                // successfully rather than bubble a neutral error up
                // through the diagnostic pipeline.
                print!("{e}");
                return Ok(());
            }
            Err(e) => return Err(map_clap_error(&e)),
        };

        let Some((sub, sub_matches)) = matches.subcommand() else {
            // No subcommand — clap's `arg_required_else_help` makes
            // the parser itself error in this case, but guard
            // defensively in case a downstream override disables it.
            return Err(rtb_error::Error::CommandNotFound("<none>".into()).into());
        };

        let cmd = self
            .commands
            .iter()
            .find(|c| c.spec().name == sub)
            .ok_or_else(|| rtb_error::Error::CommandNotFound(sub.to_string()))?;

        // For a passthrough command, hand its captured trailing tokens to
        // the dispatched `App` so it re-parses them via
        // `crate::parse_passthrough` instead of re-reading global argv.
        // `try_get_many` is panic-safe when the subcommand has no `rest`
        // arg (i.e. non-passthrough commands) — it yields an empty slice.
        let trailing: Vec<std::ffi::OsString> = sub_matches
            .try_get_many::<std::ffi::OsString>("rest")
            .ok()
            .flatten()
            .map(|vals| vals.cloned().collect())
            .unwrap_or_default();
        let app = self.app.clone().with_trailing_args(trailing);

        // Run registered pre-run hooks (e.g. the self-update policy check)
        // before dispatching the matched command. Leaf crates register
        // these via `BUILTIN_PRERUN_HOOKS`; a hook returning `Err` aborts
        // the run. Help/version already short-circuited above, so hooks do
        // not fire for `--help`/`--version`.
        for hook in rtb_app::command::BUILTIN_PRERUN_HOOKS {
            hook(app.clone()).await?;
        }

        cmd.run(app).await
    }

    /// Run, render any error through the installed diagnostic handler, and
    /// return the process exit code.
    ///
    /// Honours a code attached via [`rtb_error::WithExitCode`] (read once,
    /// at this boundary — not an error funnel); defaults to `1` on error and
    /// `0` on success. This is the boundary a binary's `main` should use:
    ///
    /// ```no_run
    /// # async fn wrap(app: rtb_cli::Application) -> std::process::ExitCode {
    /// app.run_and_exit().await
    /// # }
    /// ```
    pub async fn run_and_exit(self) -> std::process::ExitCode {
        match self.run().await {
            Ok(()) => std::process::ExitCode::SUCCESS,
            Err(report) => report_to_exit_code(&report),
        }
    }
}

/// Render `report` and map it to a process exit code.
///
/// Prints the diagnostic through the installed handler (matching what
/// `Termination` for `Result<(), Report>` does) and honours a code attached
/// via [`rtb_error::WithExitCode`] (default `1`).
///
/// Exposed so a binary's `main` can map a *builder* error — raised before
/// [`Application::run_and_exit`] is reachable — to the same exit path.
#[must_use]
pub fn report_to_exit_code(report: &miette::Report) -> std::process::ExitCode {
    eprintln!("{report:?}");
    std::process::ExitCode::from(rtb_error::exit_code_of(report).unwrap_or(1))
}

// -----------------------------------------------------------------
// Typestate builder
// -----------------------------------------------------------------

/// Phantom marker: metadata has not been set.
pub struct NoMetadata;
/// Phantom marker: metadata has been set.
pub struct HasMetadata(ToolMetadata);
/// Phantom marker: version has not been set.
pub struct NoVersion;
/// Phantom marker: version has been set.
pub struct HasVersion(VersionInfo);

/// Typestate-guarded builder. `metadata` and `version` are required;
/// omitting either is a compile error (the `build()` method is only
/// implemented on `ApplicationBuilder<HasMetadata, HasVersion>`).
#[must_use]
pub struct ApplicationBuilder<M, V> {
    metadata: M,
    version: V,
    assets: Option<Assets>,
    features: Option<Features>,
    install_hooks: bool,
    credentials_provider: Option<Arc<dyn rtb_app::credentials::CredentialProvider>>,
    /// Captured at builder time when `config<C>` is called: the
    /// erased `Config<C>` storage and the closure-based ops bundle
    /// that drives schema-aware `config_cmd` paths.
    typed_config: Option<rtb_app::typed_config::ErasedConfig>,
    typed_config_ops: Option<Arc<rtb_app::typed_config::TypedConfigOps>>,
}

impl ApplicationBuilder<NoMetadata, NoVersion> {
    /// Construct an empty builder.
    pub fn new() -> Self {
        Self {
            metadata: NoMetadata,
            version: NoVersion,
            assets: None,
            features: None,
            install_hooks: true,
            credentials_provider: None,
            typed_config: None,
            typed_config_ops: None,
        }
    }
}

impl Default for ApplicationBuilder<NoMetadata, NoVersion> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V> ApplicationBuilder<NoMetadata, V> {
    /// Set the static tool metadata. Required.
    pub fn metadata(self, m: ToolMetadata) -> ApplicationBuilder<HasMetadata, V> {
        ApplicationBuilder {
            metadata: HasMetadata(m),
            version: self.version,
            assets: self.assets,
            features: self.features,
            install_hooks: self.install_hooks,
            credentials_provider: self.credentials_provider,
            typed_config: self.typed_config,
            typed_config_ops: self.typed_config_ops,
        }
    }
}

impl<M> ApplicationBuilder<M, NoVersion> {
    /// Set the build-time version info. Required.
    pub fn version(self, v: VersionInfo) -> ApplicationBuilder<M, HasVersion> {
        ApplicationBuilder {
            metadata: self.metadata,
            version: HasVersion(v),
            assets: self.assets,
            features: self.features,
            install_hooks: self.install_hooks,
            credentials_provider: self.credentials_provider,
            typed_config: self.typed_config,
            typed_config_ops: self.typed_config_ops,
        }
    }
}

impl<M, V> ApplicationBuilder<M, V> {
    /// Override the embedded-assets overlay. Defaults to an empty
    /// [`Assets`].
    pub fn assets(mut self, a: Assets) -> Self {
        self.assets = Some(a);
        self
    }

    /// Override the runtime feature set. Defaults to
    /// [`Features::default`].
    pub fn features(mut self, f: Features) -> Self {
        self.features = Some(f);
        self
    }

    /// Control installation of the `miette` report/panic hooks.
    /// `true` by default. Pass `false` from tests that want to
    /// manage hooks themselves.
    pub const fn install_hooks(mut self, yes: bool) -> Self {
        self.install_hooks = yes;
        self
    }

    /// Wire a credential provider so the v0.4 `credentials list /
    /// test / doctor` subcommands can enumerate the tool's
    /// `CredentialRef`s. The argument is anything that implements
    /// [`rtb_credentials::CredentialBearing`] — typically the tool's
    /// typed config struct passed as `Arc::new(my_config.clone())`.
    ///
    /// Tools that don't wire a provider see `credentials list` print
    /// an empty table — the subtree degrades gracefully rather than
    /// erroring out at startup.
    pub fn credentials_from<T>(mut self, provider: Arc<T>) -> Self
    where
        T: rtb_credentials::CredentialBearing + Send + Sync + 'static,
    {
        self.credentials_provider =
            Some(provider as Arc<dyn rtb_app::credentials::CredentialProvider>);
        self
    }

    /// Wire a typed config so command handlers can reach it via
    /// `app.typed_config::<C>()` and the framework-supplied
    /// `config show / get / set / schema / validate` subcommands
    /// drive their schema-aware paths.
    ///
    /// The `JsonSchema` bound is required (per v0.4.1 scope A3
    /// resolution) so the schema-aware leaves work for everyone
    /// who opts in. Tools with non-`JsonSchema`-able config shapes
    /// can keep the v0.4 raw-YAML fallback by *not* calling this
    /// step; the rest of the framework continues to work
    /// unchanged.
    pub fn config<C>(mut self, config: rtb_config::Config<C>) -> Self
    where
        C: serde::Serialize
            + serde::de::DeserializeOwned
            + schemars::JsonSchema
            + Send
            + Sync
            + 'static,
    {
        let ops = rtb_app::typed_config::TypedConfigOps::new::<C>();
        self.typed_config = Some(rtb_app::typed_config::erase(config));
        self.typed_config_ops = Some(Arc::new(ops));
        self
    }
}

impl ApplicationBuilder<HasMetadata, HasVersion> {
    /// Finalise the builder. Only compiles when both
    /// [`ApplicationBuilder::metadata`] and
    /// [`ApplicationBuilder::version`] have been supplied.
    pub fn build(self) -> miette::Result<Application> {
        let HasMetadata(metadata) = self.metadata;
        let HasVersion(version) = self.version;

        let features = self.features.unwrap_or_default();
        let assets = self.assets.unwrap_or_default();

        // Build a basic App via the public constructor; if
        // `.config(...)` was called the typed-config bundle gets
        // attached afterwards (replacing the placeholder
        // `Config<()>` storage with the same allocation
        // `ApplicationBuilder::config<C>` set up).
        let app =
            App::new(metadata, version, Config::<()>::default(), assets, self.credentials_provider);
        let app = match (self.typed_config, self.typed_config_ops) {
            (Some(erased), Some(ops)) => app.with_typed_config(erased, ops),
            _ => app,
        };

        // Materialise BUILTIN_COMMANDS filtered by the runtime
        // Features set.
        let mut commands: Vec<Box<dyn RtbCommand>> = Vec::new();
        for factory in BUILTIN_COMMANDS {
            let cmd = factory();
            let enabled_here = cmd.spec().feature.is_none_or(|f| features.is_enabled(f));
            if enabled_here {
                commands.push(cmd);
            }
        }

        // Deduplicate by command name. `linkme`'s slice order is
        // link-time-determined and not stable across compiler
        // versions or dep graph changes, so we cannot rely on
        // "last-registered wins". Instead, the LAST entry in slice
        // order for each name wins — which matches the intuition
        // that a downstream crate's real command overrides the
        // rtb-cli stub of the same name.
        let mut seen: std::collections::HashMap<&'static str, usize> =
            std::collections::HashMap::new();
        for (idx, cmd) in commands.iter().enumerate() {
            seen.insert(cmd.spec().name, idx);
        }
        let keep: std::collections::HashSet<usize> = seen.values().copied().collect();
        let mut i = 0usize;
        commands.retain(|_| {
            let keep_this = keep.contains(&i);
            i += 1;
            keep_this
        });

        // Stable order by command name keeps `--help` output
        // deterministic regardless of link-time slice ordering.
        commands.sort_by(|a, b| a.spec().name.cmp(b.spec().name));

        Ok(Application { app, commands, install_hooks: self.install_hooks })
    }
}

// -----------------------------------------------------------------
// clap glue
// -----------------------------------------------------------------

fn build_clap_tree(metadata: &ToolMetadata, commands: &[Box<dyn RtbCommand>]) -> ClapCommand {
    let mut root = ClapCommand::new(metadata.name.clone())
        .about(metadata.summary.clone())
        .arg_required_else_help(true)
        .subcommand_required(true)
        // Global `--output text|json` flag. Declared once at the
        // root with `global = true`; clap propagates it onto every
        // subcommand automatically. Subcommands that print
        // structured data honour it via [`crate::render::output`];
        // interactive ones (init, mcp serve, update run) ignore it.
        // See v0.4 scope addendum §2.5 / O5.
        .arg(
            clap::Arg::new("output")
                .long("output")
                .global(true)
                .value_parser(clap::value_parser!(crate::render::OutputMode))
                .default_value("text")
                .help("Output rendering mode for structured-output subcommands"),
        );

    if !metadata.description.is_empty() {
        root = root.long_about(metadata.description.clone());
    }

    for cmd in commands {
        let spec = cmd.spec();
        let mut sub = ClapCommand::new(spec.name).about(spec.about);
        for alias in spec.aliases {
            sub = sub.alias(*alias);
        }
        if let Some(short) = spec.short {
            sub = sub.short_flag(short);
        }
        if let Some(long) = spec.long_about {
            sub = sub.long_about(long);
        }
        if cmd.subcommand_passthrough() {
            // Let the command own its inner clap subtree. The
            // `trailing_var_arg` arg captures every token after
            // `<name>` (including `--help`, `--flag value`, sub-sub-
            // commands) without further validation — the command
            // re-parses `std::env::args_os()` itself.
            sub = sub.arg(
                clap::Arg::new("rest")
                    .num_args(0..)
                    // `OsString` (not the default `String`) so non-UTF-8
                    // arguments survive to the command's own parser.
                    .value_parser(clap::value_parser!(std::ffi::OsString))
                    .trailing_var_arg(true)
                    .allow_hyphen_values(true),
            );
            // Drop the auto-injected `--help` so it reaches the inner
            // parser instead of clap's default help screen at the
            // outer layer.
            sub = sub.disable_help_flag(true);
        }
        root = root.subcommand(sub);
    }

    root
}

/// `true` when the clap error is a "successful" user-facing output
/// (help or version) that should return `Ok(())` rather than bubble
/// up through the diagnostic pipeline.
fn is_help_or_version(err: &clap::Error) -> bool {
    use clap::error::ErrorKind;
    matches!(err.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion)
}

fn map_clap_error(err: &clap::Error) -> miette::Report {
    use clap::error::ErrorKind;
    match err.kind() {
        ErrorKind::InvalidSubcommand | ErrorKind::UnknownArgument => {
            let name = err
                .get(clap::error::ContextKind::InvalidSubcommand)
                .or_else(|| err.get(clap::error::ContextKind::InvalidArg))
                .map_or_else(|| err.to_string(), |v| format!("{v}"));
            rtb_error::Error::CommandNotFound(name).into()
        }
        _ => miette::miette!("{}", err),
    }
}