rtb-cli 0.6.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
//! `config` CLI subtree — `show / get / set / schema / validate`.
//!
//! Operates on the canonical user-file path
//! `<ProjectDirs::config_dir()>/<tool>/config.yaml` (overridable via
//! `--config-file PATH`). Format is determined by the file's
//! extension on read and kept consistent on write:
//!
//! | Extension | Format |
//! |---|---|
//! | `.yml`, `.yaml` (or no extension) | YAML |
//! | `.toml` | TOML |
//! | `.json` | JSON |
//!
//! # Design note (v0.4)
//!
//! The framework's `App` currently carries `Arc<Config<()>>` — the
//! typed-config generic `App<C>` is post-v0.1 work. So the v0.4
//! subtree operates on the file directly rather than the typed
//! `Config<C>`. `get` / `set` walk the parsed value as a
//! `serde_yaml::Value`; `schema` errors with a helpful message
//! pointing at the typed-config integration gap. The behaviour
//! upgrades non-disruptively when `App<C>` lands.
//!
//! # Lint exception
//!
//! `linkme::distributed_slice` emits `#[link_section]` which Rust
//! 1.95+ flags under `unsafe_code`. Allowed at module level — no
//! hand-rolled `unsafe` blocks anywhere in the module.

#![allow(unsafe_code)]

use std::ffi::OsString;
use std::path::{Path, PathBuf};

use async_trait::async_trait;
use clap::{Parser, Subcommand};
use directories::ProjectDirs;
use linkme::distributed_slice;
use miette::miette;
use rtb_app::app::App;
use rtb_app::command::{Command, CommandSpec, BUILTIN_COMMANDS};
use rtb_app::features::Feature;

use crate::render::{strip_global_output, OutputMode};

/// The `config` subcommand.
pub struct ConfigCmd;

#[async_trait]
impl Command for ConfigCmd {
    fn spec(&self) -> &CommandSpec {
        static SPEC: CommandSpec = CommandSpec {
            name: "config",
            about: "Show, query, mutate, and validate the user config (show / get / set / schema / validate)",
            aliases: &[],
            feature: Some(Feature::Config),
        };
        &SPEC
    }

    fn subcommand_passthrough(&self) -> bool {
        true
    }

    async fn run(&self, app: App) -> miette::Result<()> {
        let mut args: Vec<OsString> = std::env::args_os().collect();
        if args.len() >= 2 {
            args.drain(..2);
        }
        args.insert(0, OsString::from("config"));
        args = strip_global_output(args);

        let cli = match ConfigCli::try_parse_from(args) {
            Ok(c) => c,
            Err(e) => {
                use clap::error::ErrorKind;
                if matches!(e.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion) {
                    print!("{e}");
                    return Ok(());
                }
                return Err(miette!("{e}"));
            }
        };

        let mode = OutputMode::from_args_os();
        let sub = cli.command.unwrap_or(ConfigSub::Show(ShowOpts {}));
        match sub {
            ConfigSub::Show(_) => run_show(&app),
            ConfigSub::Get { path } => run_get(&app, &path, mode),
            ConfigSub::Set { path, value, config_file } => {
                run_set(&app, &path, &value, config_file.as_deref())
            }
            ConfigSub::Schema => run_schema(&app),
            ConfigSub::Validate { config_file } => run_validate(&app, config_file.as_deref()),
        }
    }
}

#[distributed_slice(BUILTIN_COMMANDS)]
fn __register_config() -> Box<dyn Command> {
    Box::new(ConfigCmd)
}

// ---------------------------------------------------------------------
// clap surface
// ---------------------------------------------------------------------

#[derive(Debug, Parser)]
#[command(name = "config", about = "Inspect, mutate, and validate config")]
struct ConfigCli {
    #[command(subcommand)]
    command: Option<ConfigSub>,
}

#[derive(Debug, Subcommand)]
enum ConfigSub {
    /// Print the currently-resolved configuration. Default subcommand.
    Show(ShowOpts),
    /// Read a JSON-pointer path against the user config file.
    Get {
        /// JSON-pointer path (`/foo/bar` style). Leading `/` optional.
        path: String,
    },
    /// Write a value to a JSON-pointer path in the user config file.
    Set {
        /// JSON-pointer path to write to.
        path: String,
        /// Value to write. Parsed as JSON; falls back to a string.
        value: String,
        /// Override the canonical user-file path.
        #[arg(long, value_name = "PATH")]
        config_file: Option<PathBuf>,
    },
    /// Print the JSON Schema for the tool's typed config.
    Schema,
    /// Validate a candidate config file. Defaults to the merged result.
    Validate {
        /// Validate this file instead of the merged config.
        #[arg(long, value_name = "PATH")]
        config_file: Option<PathBuf>,
    },
}

#[derive(Debug, clap::Args)]
struct ShowOpts {}

// ---------------------------------------------------------------------
// `show`
// ---------------------------------------------------------------------

fn run_show(app: &App) -> miette::Result<()> {
    if let Some(value) = app.config_value() {
        // Typed config wired — render as YAML for human reading.
        let yaml = serde_yaml::to_string(&value).map_err(|e| miette!("yaml: {e}"))?;
        print!("{yaml}");
        return Ok(());
    }
    // No typed config wired — keep the v0.4 placeholder text.
    // Downstream tools that don't call
    // `Application::builder().config(...)` see this; tools that do
    // hit the typed path above.
    println!("# no typed configuration is installed on this App");
    println!("# (call `Application::builder().config(C)` to wire it)");
    Ok(())
}

// ---------------------------------------------------------------------
// `get`
// ---------------------------------------------------------------------

fn run_get(app: &App, path: &str, mode: OutputMode) -> miette::Result<()> {
    // Prefer the typed-config-rendered value when wired — it
    // reflects the merged Config<C> that the tool actually sees,
    // including embedded defaults and env-var overlays. Fall back
    // to the v0.4 user-file walk for tools without typed wiring.
    let (value, source) = if let Some(value) = app.config_value() {
        (value, "merged config".to_string())
    } else {
        let file = canonical_path(app)?;
        let value = read_value(&file)?;
        (value, format!("`{}`", file.display()))
    };
    let pointer = json_pointer(path);
    let resolved =
        value.pointer(&pointer).ok_or_else(|| miette!("path `{path}` not found in {source}"))?;
    match mode {
        OutputMode::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(resolved).map_err(|e| miette!("serialise: {e}"))?,
            );
        }
        OutputMode::Text => match resolved {
            serde_json::Value::String(s) => println!("{s}"),
            other => println!("{other}"),
        },
    }
    Ok(())
}

// ---------------------------------------------------------------------
// `set`
// ---------------------------------------------------------------------

fn run_set(app: &App, path: &str, value: &str, override_path: Option<&Path>) -> miette::Result<()> {
    let file = match override_path {
        Some(p) => p.to_path_buf(),
        None => canonical_path(app)?,
    };
    // Parse `<value>` as JSON; fall back to a string literal so the
    // common case of a bare scalar (`config set .timeout 30`,
    // `config set .name alice`) does not require quoting.
    let parsed: serde_json::Value = serde_json::from_str(value)
        .unwrap_or_else(|_| serde_json::Value::String(value.to_string()));

    let mut current = if file.exists() {
        read_value(&file)?
    } else {
        serde_json::Value::Object(serde_json::Map::new())
    };
    let pointer = json_pointer(path);
    set_pointer(&mut current, &pointer, parsed).map_err(|msg| miette!("{msg}"))?;

    // Schema-aware write: when typed config is wired, refuse to
    // persist a candidate the schema rejects. The check runs
    // against the merged value rather than the user-file alone so
    // a bad set against env-driven defaults still gets caught.
    if let Some(schema) = app.config_schema() {
        let validator =
            jsonschema::validator_for(schema).map_err(|e| miette!("compile schema: {e}"))?;
        if let Err(error) = validator.validate(&current) {
            return Err(miette!(
                "config set rejected: candidate value at `{path}` fails the wired schema: {error}",
            ));
        }
    }

    write_value(&file, &current)?;
    println!("set `{path}` in `{}`", file.display());
    Ok(())
}

// ---------------------------------------------------------------------
// `schema`
// ---------------------------------------------------------------------

fn run_schema(app: &App) -> miette::Result<()> {
    if let Some(schema) = app.config_schema() {
        let json = serde_json::to_string_pretty(schema).map_err(|e| miette!("json: {e}"))?;
        println!("{json}");
        return Ok(());
    }
    // No typed config wired — same fallback as v0.4.
    Err(miette!(
        help = "wire your typed config via Application::builder().config(...). \
                Without typed-config wiring there is no schema to emit; \
                downstream tools that override the `config` command can call \
                rtb_config::Config::schema()",
        "config schema is not available without a typed-config integration"
    ))
}

// ---------------------------------------------------------------------
// `validate`
// ---------------------------------------------------------------------

fn run_validate(app: &App, override_path: Option<&Path>) -> miette::Result<()> {
    // Three sources for the candidate value, in order of preference:
    //
    // 1. `--config-file <PATH>` — explicit override always wins; an
    //    absent file is an error.
    // 2. No override + typed config wired — validate the in-memory
    //    merged value (matches the spec "Defaults to the merged
    //    result" wording).
    // 3. No override + no typed config — fall back to the canonical
    //    user file; absent file is an error (the v0.4 untyped path).
    let (value, label): (serde_json::Value, String) = if let Some(p) = override_path {
        if !p.exists() {
            return Err(miette!("config file `{}` does not exist", p.display()));
        }
        (read_value(p)?, format!("`{}`", p.display()))
    } else if let Some(merged) = app.config_value() {
        (merged, "merged config".to_string())
    } else {
        let p = canonical_path(app)?;
        if !p.exists() {
            return Err(miette!("config file `{}` does not exist", p.display()));
        }
        let label = format!("`{}`", p.display());
        (read_value(&p)?, label)
    };

    if let Some(schema) = app.config_schema() {
        let validator =
            jsonschema::validator_for(schema).map_err(|e| miette!("compile schema: {e}"))?;
        if let Err(error) = validator.validate(&value) {
            return Err(miette!("config validation failed at {label}: {error}"));
        }
        println!("ok: {label} validates against the wired schema");
    } else {
        println!("ok: {label} parses cleanly (no schema wired — format check only)");
    }
    Ok(())
}

// ---------------------------------------------------------------------
// shared
// ---------------------------------------------------------------------

fn canonical_path(app: &App) -> miette::Result<PathBuf> {
    let dirs = ProjectDirs::from("dev", "", &app.metadata.name).ok_or_else(|| {
        miette!(
            help = "rtb-cli could not derive a config directory; HOME may be unset",
            "no config directory available for tool `{}`",
            app.metadata.name
        )
    })?;
    Ok(dirs.config_dir().join("config.yaml"))
}

fn read_value(path: &Path) -> miette::Result<serde_json::Value> {
    let body =
        std::fs::read_to_string(path).map_err(|e| miette!("read {}: {e}", path.display()))?;
    let format = file_format(path);
    match format {
        Format::Yaml => {
            let yaml: serde_yaml::Value = serde_yaml::from_str(&body)
                .map_err(|e| miette!("parse yaml `{}`: {e}", path.display()))?;
            // YAML → JSON Value: serde-cross-format. `serde_json::to_value`
            // works for any `Serialize` source.
            serde_json::to_value(yaml).map_err(|e| miette!("yaml→json: {e}"))
        }
        Format::Json => {
            serde_json::from_str(&body).map_err(|e| miette!("parse json `{}`: {e}", path.display()))
        }
        Format::Toml => {
            let raw: toml::Value = toml::from_str(&body)
                .map_err(|e| miette!("parse toml `{}`: {e}", path.display()))?;
            serde_json::to_value(raw).map_err(|e| miette!("toml→json: {e}"))
        }
    }
}

fn write_value(path: &Path, value: &serde_json::Value) -> miette::Result<()> {
    let format = file_format(path);
    let serialised = match format {
        Format::Yaml => serde_yaml::to_string(value).map_err(|e| miette!("yaml: {e}"))?,
        Format::Json => serde_json::to_string_pretty(value).map_err(|e| miette!("json: {e}"))?,
        Format::Toml => {
            // Round-trip through `toml::Value` so non-table tops get a
            // proper error rather than a panic.
            let toml_value: toml::Value =
                toml::Value::try_from(value).map_err(|e| miette!("json→toml: {e}"))?;
            toml::to_string_pretty(&toml_value).map_err(|e| miette!("toml: {e}"))?
        }
    };
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)
                .map_err(|e| miette!("create parent {}: {e}", parent.display()))?;
        }
    }
    std::fs::write(path, serialised).map_err(|e| miette!("write {}: {e}", path.display()))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Format {
    Yaml,
    Toml,
    Json,
}

fn file_format(path: &Path) -> Format {
    match path.extension().and_then(|e| e.to_str()) {
        Some("toml") => Format::Toml,
        Some("json") => Format::Json,
        _ => Format::Yaml,
    }
}

/// Convert a user-supplied path into a `serde_json` JSON-pointer
/// string. Accepts both `/foo/bar` (canonical) and `.foo.bar`
/// (UX-friendly) forms; the canonical form is what
/// `serde_json::Value::pointer` expects.
fn json_pointer(path: &str) -> String {
    if path.starts_with('/') {
        path.to_string()
    } else if let Some(rest) = path.strip_prefix('.') {
        format!("/{}", rest.replace('.', "/"))
    } else {
        format!("/{}", path.replace('.', "/"))
    }
}

/// Write `value` at the given JSON pointer. Creates intermediate
/// `Object` containers as needed. Returns an error string when an
/// intermediate is a non-object (`/foo/bar` against a value where
/// `foo` is a number).
fn set_pointer(
    target: &mut serde_json::Value,
    pointer: &str,
    value: serde_json::Value,
) -> Result<(), String> {
    if pointer.is_empty() || pointer == "/" {
        *target = value;
        return Ok(());
    }
    let segments: Vec<&str> = pointer.trim_start_matches('/').split('/').collect();
    let mut cursor = target;
    for (i, segment) in segments.iter().enumerate() {
        let last = i == segments.len() - 1;
        if last {
            if let serde_json::Value::Object(map) = cursor {
                map.insert((*segment).to_string(), value);
                return Ok(());
            }
            return Err(format!("cannot set `{segment}` on a non-object value"));
        }
        if !cursor.is_object() {
            *cursor = serde_json::Value::Object(serde_json::Map::new());
        }
        let map = cursor.as_object_mut().expect("just-set object");
        cursor = map
            .entry((*segment).to_string())
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    }
    Ok(())
}