cli-engine 0.1.0

Rust CLI framework for consistent command modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use std::{collections::BTreeMap, future::Future, pin::Pin, sync::Arc};

use clap::{Arg, ArgAction, ArgMatches, Command};
use schemars::JsonSchema;
use serde_json::{Number, Value};

use crate::{
    CommandMeta, Credential, Middleware, OutputSchema, Result, SchemaInfo, Tier,
    middleware::ValueMap,
};

/// Boxed future returned by runtime command handlers.
pub type CommandFuture = Pin<Box<dyn Future<Output = Result<CommandResult>> + Send>>;
/// Shared command handler used by [`RuntimeCommandSpec`].
pub type CommandHandler = Arc<dyn Fn(CommandContext) -> CommandFuture + Send + Sync>;

/// Data returned by a command handler.
///
/// Command handlers should return renderable data and keep output metadata on
/// [`CommandSpec`]. The metadata field is reserved for future command-result
/// extensions that are not known when the command is registered.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandResult {
    /// JSON data rendered by the configured output formatter.
    pub data: Value,
    /// Optional command-result extension metadata.
    pub metadata: CommandResultMetadata,
}

impl CommandResult {
    /// Creates a command result from renderable JSON data.
    #[must_use]
    pub fn new(data: Value) -> Self {
        Self {
            data,
            metadata: CommandResultMetadata::default(),
        }
    }
}

impl From<Value> for CommandResult {
    fn from(data: Value) -> Self {
        Self::new(data)
    }
}

/// Optional metadata a command can attach to its result.
#[non_exhaustive]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CommandResultMetadata {}

/// Runtime context passed to advanced command handlers.
///
/// Most commands can use [`RuntimeCommandSpec::new`] and receive just the
/// credential and effective args. Use this context when a command needs the
/// colon path, user-supplied args, or a snapshot of middleware state.
#[derive(Clone, Debug)]
pub struct CommandContext {
    /// Credential resolved by middleware. No-auth commands receive `None`.
    pub credential: Option<Credential>,
    /// Effective arguments, including defaults and framework-injected values.
    pub args: ValueMap,
    /// Arguments explicitly supplied by the user.
    pub user_args: ValueMap,
    /// Colon-separated command path such as `project:list`.
    pub command_path: String,
    /// Middleware snapshot for this invocation.
    pub middleware: Middleware,
}

/// Declarative leaf command metadata and parser arguments.
///
/// `CommandSpec` intentionally keeps command metadata next to the command's
/// handler. This is the primary copy/paste surface for teams adding commands.
#[derive(Clone, Debug, Default)]
pub struct CommandSpec {
    /// Leaf command name.
    pub name: String,
    /// One-line command description.
    pub short: String,
    /// Optional long help text.
    pub long: Option<String>,
    /// Alternate command names accepted by the parser.
    pub aliases: Vec<String>,
    /// Whether the command runs but is hidden from help, tree, and search.
    pub hidden: bool,
    /// Backend/system id used in output metadata and generic error envelopes.
    pub system: Option<String>,
    /// Default comma-separated field projection.
    pub default_fields: Option<String>,
    /// Whether the command bypasses credential resolution.
    pub no_auth: bool,
    /// Auth provider name for this command.
    pub auth_provider: Option<String>,
    /// Risk tier used by authentication, authorization, and dry-run.
    pub tier: Option<Tier>,
    /// Explicit dry-run prompt marker for commands without a tier.
    pub mutates: bool,
    /// Provider-specific auth metadata.
    pub auth_metadata: BTreeMap<String, String>,
    /// Command-specific `clap` arguments.
    pub args: Vec<Arg>,
    /// Optional output schema published through `--schema` and help.
    pub output_schema: Option<SchemaInfo>,
}

impl CommandSpec {
    /// Creates a command spec with the required name and one-line help.
    #[must_use]
    pub fn new(name: impl Into<String>, short: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            short: short.into(),
            ..Self::default()
        }
    }

    /// Sets expanded command help.
    #[must_use]
    pub fn with_long(mut self, long: impl Into<String>) -> Self {
        self.long = Some(long.into());
        self
    }

    /// Adds one command alias.
    #[must_use]
    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Hides or shows this command in discovery output.
    #[must_use]
    pub fn hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets the backend/system id for output metadata and error attribution.
    #[must_use]
    pub fn with_system(mut self, system: impl Into<String>) -> Self {
        self.system = Some(system.into());
        self
    }

    /// Sets the default field projection used when `--fields` is absent.
    #[must_use]
    pub fn with_default_fields(mut self, default_fields: impl Into<String>) -> Self {
        self.default_fields = Some(default_fields.into());
        self
    }

    /// Selects the auth provider for this command.
    #[must_use]
    pub fn with_auth_provider(mut self, provider: impl Into<String>) -> Self {
        self.auth_provider = Some(provider.into());
        self
    }

    /// Marks the command as no-auth.
    #[must_use]
    pub fn no_auth(mut self, no_auth: bool) -> Self {
        self.no_auth = no_auth;
        self
    }

    /// Sets the command risk tier.
    #[must_use]
    pub fn with_tier(mut self, tier: Tier) -> Self {
        self.tier = Some(tier);
        self
    }

    /// Adds provider-specific auth metadata.
    #[must_use]
    pub fn with_auth_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.auth_metadata.insert(key.into(), value.into());
        self
    }

    /// Adds a `clap` argument or option to this command.
    #[must_use]
    pub fn with_arg(mut self, arg: Arg) -> Self {
        self.args.push(arg);
        self
    }

    /// Adds a `clap` flag or option to this command.
    #[must_use]
    pub fn with_flag(self, flag: Arg) -> Self {
        self.with_arg(flag)
    }

    /// Registers a compact framework schema from an [`OutputSchema`] type.
    #[must_use]
    pub fn with_output_schema<T: OutputSchema>(mut self) -> Self {
        self.output_schema = Some(SchemaInfo {
            command: String::new(),
            fields: crate::output::fields_for::<T>(),
            schema: None,
        });
        self
    }

    /// Registers JSON Schema generated from a Rust type with `schemars`.
    #[must_use]
    pub fn with_json_schema<T: JsonSchema>(mut self) -> Self {
        self.output_schema = Some(crate::output::json_schema_info::<T>(""));
        self
    }

    /// Marks whether the command should short-circuit under `--dry-run`.
    #[must_use]
    pub fn mutates(mut self, mutates: bool) -> Self {
        self.mutates = mutates;
        self
    }

    /// Builds middleware metadata from the spec.
    #[must_use]
    pub fn metadata(&self) -> CommandMeta {
        let mut auth_metadata = self.auth_metadata.clone();
        if let Some(provider) = &self.auth_provider
            && !provider.is_empty()
        {
            auth_metadata.insert("provider".to_owned(), provider.clone());
        }
        if let Some(tier) = self.tier
            && !auth_metadata.contains_key("tier")
        {
            auth_metadata.insert("tier".to_owned(), tier.to_string());
        }
        let scopes = auth_metadata
            .get("scopes")
            .map(|scopes| {
                scopes
                    .split_whitespace()
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        CommandMeta {
            dry_run_prompt: self.mutates || self.tier.is_some_and(Tier::is_mutating),
            auth_metadata,
            scopes,
        }
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.name.clone()).about(self.short.clone());
        if let Some(long) = &self.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.aliases {
            command = command.alias(alias.clone());
        }
        if self.hidden {
            command = command.hide(true);
        }
        for arg in &self.args {
            command = command.arg(arg.clone());
        }
        command
    }
}

/// Declarative command group metadata.
///
/// Groups are noun-based containers. They do not run business logic directly;
/// when invoked bare, the CLI renders group help.
#[derive(Clone, Debug, Default)]
pub struct GroupSpec {
    /// Group command name.
    pub name: String,
    /// One-line group description.
    pub short: String,
    /// Optional long help text.
    pub long: Option<String>,
    /// Alternate group names accepted by the parser.
    pub aliases: Vec<String>,
    /// Whether the group runs but is hidden from discovery output.
    pub hidden: bool,
    /// Declarative child commands used for static tree construction.
    pub commands: Vec<CommandSpec>,
    /// Declarative nested groups used for static tree construction.
    pub groups: Vec<GroupSpec>,
}

impl GroupSpec {
    /// Creates a command group with the required name and one-line help.
    #[must_use]
    pub fn new(name: impl Into<String>, short: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            short: short.into(),
            ..Self::default()
        }
    }

    /// Sets expanded group help.
    #[must_use]
    pub fn with_long(mut self, long: impl Into<String>) -> Self {
        self.long = Some(long.into());
        self
    }

    /// Adds one group alias.
    #[must_use]
    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Hides or shows this group in discovery output.
    #[must_use]
    pub fn hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Adds one declarative child command.
    #[must_use]
    pub fn with_command(mut self, command: CommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Adds one declarative nested group.
    #[must_use]
    pub fn with_group(mut self, group: GroupSpec) -> Self {
        self.groups.push(group);
        self
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.name.clone()).about(self.short.clone());
        if let Some(long) = &self.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.aliases {
            command = command.alias(alias.clone());
        }
        if self.hidden {
            command = command.hide(true);
        }
        for group in &self.groups {
            command = command.subcommand(group.clap_command());
        }
        for child in &self.commands {
            command = command.subcommand(child.clap_command());
        }
        command
    }
}

/// Executable leaf command.
///
/// `RuntimeCommandSpec` pairs a [`CommandSpec`] with async business logic.
/// This split keeps metadata inspectable for help/search/schema generation
/// before the handler ever runs.
#[derive(Clone)]
pub struct RuntimeCommandSpec {
    /// Declarative command metadata.
    pub spec: CommandSpec,
    /// Async command implementation.
    pub handler: CommandHandler,
}

impl std::fmt::Debug for RuntimeCommandSpec {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RuntimeCommandSpec")
            .field("spec", &self.spec)
            .finish_non_exhaustive()
    }
}

impl RuntimeCommandSpec {
    /// Creates a runtime command with the common handler shape.
    ///
    /// The handler receives the optional credential and effective args. It
    /// returns [`CommandResult`], where `data` must be JSON-serializable.
    #[must_use]
    pub fn new<F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        F: Fn(Option<Credential>, ValueMap) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        Self {
            spec,
            handler: Arc::new(move |context| {
                let future = handler(context.credential, context.args);
                Box::pin(async move { future.await.map(Into::into) })
            }),
        }
    }

    /// Creates a runtime command with the full invocation context.
    #[must_use]
    pub fn new_with_context<F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        F: Fn(CommandContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        Self {
            spec,
            handler: Arc::new(move |context| {
                let future = handler(context);
                Box::pin(async move { future.await.map(Into::into) })
            }),
        }
    }
}

/// Executable command group with runtime children.
#[derive(Clone, Debug, Default)]
pub struct RuntimeGroupSpec {
    /// Declarative group metadata.
    pub group: GroupSpec,
    /// Executable leaf commands under this group.
    pub commands: Vec<RuntimeCommandSpec>,
    /// Executable nested groups under this group.
    pub groups: Vec<RuntimeGroupSpec>,
}

impl RuntimeGroupSpec {
    /// Creates a runtime group from declarative group metadata.
    #[must_use]
    pub fn new(group: GroupSpec) -> Self {
        Self {
            group,
            ..Self::default()
        }
    }

    /// Adds one executable leaf command.
    #[must_use]
    pub fn with_command(mut self, command: RuntimeCommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Adds one executable nested group.
    #[must_use]
    pub fn with_group(mut self, group: RuntimeGroupSpec) -> Self {
        self.groups.push(group);
        self
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.group.name.clone()).about(self.group.short.clone());
        if let Some(long) = &self.group.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.group.aliases {
            command = command.alias(alias.clone());
        }
        if self.group.hidden {
            command = command.hide(true);
        }
        for group in &self.groups {
            command = command.subcommand(group.clap_command());
        }
        for child in &self.commands {
            command = command.subcommand(child.spec.clap_command());
        }
        command
    }

    pub(crate) fn register_commands(
        &self,
        prefix: &mut Vec<String>,
        out: &mut BTreeMap<String, RuntimeCommandSpec>,
    ) {
        prefix.push(self.group.name.clone());
        for group in &self.groups {
            group.register_commands(prefix, out);
        }
        for command in &self.commands {
            prefix.push(command.spec.name.clone());
            out.insert(prefix.join(":"), command.clone());
            prefix.pop();
        }
        prefix.pop();
    }
}

/// Extracts the colon-separated command path from parsed `clap` matches.
#[must_use]
pub fn command_path_from_matches(root_name: &str, matches: &ArgMatches) -> String {
    let mut parts = Vec::new();
    let mut current = matches;
    while let Some((name, submatches)) = current.subcommand() {
        if name != root_name {
            parts.push(name.to_owned());
        }
        current = submatches;
    }
    parts.join(":")
}

/// Builds a colon-separated command path from path parts.
///
/// The optional annotation is used only for isolated single-command tests.
#[must_use]
pub fn command_path_from_parts(parts: &[impl AsRef<str>], path_annotation: Option<&str>) -> String {
    if parts.is_empty() {
        return String::new();
    }
    if parts.len() > 1 {
        return parts[1..]
            .iter()
            .map(AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(":");
    }
    path_annotation
        .filter(|annotation| !annotation.is_empty())
        .map_or_else(|| parts[0].as_ref().to_owned(), ToOwned::to_owned)
}

/// Returns the deepest subcommand matches.
#[must_use]
pub fn leaf_matches(matches: &ArgMatches) -> &ArgMatches {
    let mut current = matches;
    while let Some((_, submatches)) = current.subcommand() {
        current = submatches;
    }
    current
}

/// Converts parsed command arguments into the JSON-ish map consumed by middleware.
///
/// When `changed_only` is true, only arguments that came from the command line
/// are included. This is the user-args map used by authz and audit.
#[must_use]
pub fn command_args_from_matches(
    matches: &ArgMatches,
    spec: &CommandSpec,
    changed_only: bool,
) -> ValueMap {
    let mut args = ValueMap::new();
    for arg in &spec.args {
        let id = arg.get_id().to_string();
        let changed = matches
            .value_source(&id)
            .is_some_and(|source| source == clap::parser::ValueSource::CommandLine);
        if changed_only && !changed {
            continue;
        }
        if let Some(value) = arg_value_from_matches(matches, arg, &id) {
            args.insert(id, value);
        }
    }
    args
}

fn arg_value_from_matches(matches: &ArgMatches, flag: &Arg, id: &str) -> Option<Value> {
    matches.value_source(id)?;

    if matches!(flag.get_action(), ArgAction::SetTrue | ArgAction::SetFalse)
        && let Some(value) = matches.get_one::<bool>(id)
    {
        return Some(Value::Bool(*value));
    }

    if let Some(value) = typed_arg_value_from_matches(matches, id) {
        return Some(value);
    }

    if let Some(values) = matches.get_raw(id) {
        let rendered = values
            .map(|value| value.to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        return match rendered.as_slice() {
            [] => None,
            [single] => Some(Value::String(single.clone())),
            _ => Some(Value::Array(
                rendered.into_iter().map(Value::String).collect(),
            )),
        };
    }

    if let Some(value) = matches.get_one::<String>(id) {
        return Some(Value::String(value.clone()));
    }
    if let Some(value) = matches.get_one::<usize>(id) {
        return Some(serde_json::json!(value));
    }
    if let Some(value) = matches.get_one::<u64>(id) {
        return Some(serde_json::json!(value));
    }
    if let Some(value) = matches.get_one::<i64>(id) {
        return Some(serde_json::json!(value));
    }
    None
}

fn typed_arg_value_from_matches(matches: &ArgMatches, id: &str) -> Option<Value> {
    typed_values::<bool>(matches, id, Value::Bool)
        .or_else(|| typed_values::<i8>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i16>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i64>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i32>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u8>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u16>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u64>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u32>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| {
            typed_values::<usize>(matches, id, |value| {
                u64::try_from(value).map_or(Value::Null, |value| Value::Number(value.into()))
            })
        })
        .or_else(|| {
            typed_values::<f64>(matches, id, |value| {
                Number::from_f64(value).map_or(Value::Null, Value::Number)
            })
        })
        .or_else(|| {
            typed_values::<f32>(matches, id, |value| {
                Number::from_f64(f64::from(value)).map_or(Value::Null, Value::Number)
            })
        })
        .or_else(|| typed_values::<String>(matches, id, Value::String))
}

fn typed_values<T>(matches: &ArgMatches, id: &str, to_value: impl Fn(T) -> Value) -> Option<Value>
where
    T: Clone + Send + Sync + 'static,
{
    let Ok(Some(values)) = matches.try_get_many::<T>(id) else {
        return None;
    };
    let values = values.cloned().map(to_value).collect::<Vec<_>>();
    match values.as_slice() {
        [] => None,
        [single] => Some(single.clone()),
        _ => Some(Value::Array(values)),
    }
}