c4-config 0.6.0

Load a folder of config files (jsonc/yaml/json/toml/ini/cnf/env/csv/xlsx/ods) into one deep-merged value
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
//! c4 CLI — flags in `USAGE` below, output rules in CLAUDE.md. Built
//! only with `--features cli`.
//!
//! Loads config sources (default: ./config) and writes the merged result
//! as a single document: `[sources...] [-f fmt] [-o path] [--trace]`.

use std::path::PathBuf;
use std::process::ExitCode;

use c4::{Loader, Options, Order, Source};

const USAGE: &str = "\
usage: c4 [sources...] [options]

Load config sources (default: ./config) and write the merged result as
one document. Sources are folders and/or files given positionally; later
sources override earlier ones.

Output:
  -f, --format <fmt>    json|jsonc|yaml|toml|ini|env|csv|debug
                        (default: the -o extension, else debug)
  -o, --output <path>   write to a file instead of stdout (format from ext)
  --trace               annotate every value with its source + format

Options (mirror Options; each boolean also has a --no-<name> form and
takes no =value):
  --dir-depth <n>       subdirectory levels to scan: 1 (default) = the
                        folder + one level, 0 = the folder only, -1 = all
  --filename-as-key     make each file a key named after it (default off)
  --dirname-as-key      make each subfolder a key (default off)
  --sheetname-as-key    spreadsheets: make each sheet a key (default off;
                        off merges every sheet like several files)
  --tree                preset: --filename-as-key --dirname-as-key
                        --sheetname-as-key --dir-depth -1
  --dot-key             expand dotted keys a.b.c -> {a:{b:{c}}} (default on)
  --case-sensitive      case-sensitive key merge (default on)
  --order <id>          folders_first_alphabetic (default) | alphabetic |
                        reverse_alphabetic  (also: folders_first, reverse)
  --auto-no-ext-files  keyed files: auto-detect extension-less files (on)
  --ignore-unknown-ext  keyed files: skip unknown-extension files (on)
  --ignore-commented-data-keys
                        drop parsed data keys named #*/_* (default on)
  --ignore-commented-filenames
                        skip scanned files named #*/_* (default on)
  --ignore-commented-dirnames
                        skip scanned folders named #*/_* (default on)
  --ignore-commented-sheetnames
                        spreadsheets: skip sheets named #*/_* (default on)
  --ignore-hidden-sheets
                        spreadsheets: skip hidden sheets (default on)
  -h, --help            show this help

Examples:
  c4                                    # read ./config, print the debug form
  c4 ./config ./local.toml -f yaml      # merge sources, print yaml
  c4 -o merged.json                     # write json (format from extension)
  c4 --trace -f json                    # provenance tree as json
  c4 --tree ./config                    # tree preset: folders/files become keys
  c4 --dirname-as-key                   # nest each subfolder as a key
  c4 --dir-depth -1                     # merge every subdirectory level
  c4 --order alphabetic                 # folders and files interleaved
  c4 --no-dot-key --no-case-sensitive   # flat keys, case-insensitive merge

Notes:
  csv is positional key,value[,format]; for a header row or renamed/
  reordered columns, use a CustomFormat (see the csv-header example).
  Spreadsheets (xlsx/xlsm/xlsb/xls/ods) parse each sheet as a db record
  grid (keys row, types row, data rows); every sheet is read and merged
  like a file (with --sheetname-as-key, each becomes a key instead).
  They are input-only formats (-f excel is not valid output).
  env and ini output reads back with c4: env quotes and escapes the dotenv
  way; ini writes one [section] level and errors on what ini cannot hold
  (nested sections, newlines, edge whitespace, '=' in keys).
";

/// Output serializer. Jsonc collapses into Json; env and ini share the
/// flat `key=value` emitter; Debug prints the Rust `{:#?}` form of the
/// loaded `Value` / `TracedValue`.
#[derive(Clone, Copy, PartialEq)]
enum OutFormat {
    Json,
    Yaml,
    Toml,
    Ini,
    Env,
    Csv,
    Debug,
}

impl OutFormat {
    fn from_id(id: &str) -> Option<Self> {
        Some(match id {
            "json" | "jsonc" => OutFormat::Json,
            "yaml" => OutFormat::Yaml,
            "toml" => OutFormat::Toml,
            "ini" => OutFormat::Ini,
            "env" => OutFormat::Env,
            "csv" => OutFormat::Csv,
            "debug" => OutFormat::Debug,
            _ => return None,
        })
    }

    fn from_extension(ext: &str) -> Option<Self> {
        Some(match ext {
            "json" | "jsonc" => OutFormat::Json,
            "yml" | "yaml" => OutFormat::Yaml,
            "toml" => OutFormat::Toml,
            "ini" => OutFormat::Ini,
            "env" => OutFormat::Env,
            "csv" => OutFormat::Csv,
            "debug" => OutFormat::Debug,
            _ => return None,
        })
    }
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(message) => {
            eprintln!("c4: {message}");
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<(), String> {
    let mut sources: Vec<PathBuf> = Vec::new();
    let mut format_flag: Option<String> = None;
    let mut out_path: Option<PathBuf> = None;
    let mut trace = false;
    // the CLI is always flat-by-default and opts into keying via flags
    // (`--tree`, `--filename-as-key`, …). `Options::default()` would flip
    // to tree-shaped loading when the binary is built with the `tree`
    // feature, so pin an explicit flat baseline regardless of build.
    let mut opts = Options {
        filename_as_key: false,
        dirname_as_key: false,
        sheetname_as_key: false,
        dir_depth: 1,
        ..Options::default()
    };

    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        // support both `--flag value` and `--flag=value` for value flags
        let (name, inline) = match arg.split_once('=') {
            Some((n, v)) => (n, Some(v.to_owned())),
            None => (arg.as_str(), None),
        };
        // a value flag's argument comes from `--flag=v` or the next token
        let mut value = |err: &str| inline.clone().or_else(|| args.next()).ok_or(err.to_owned());
        match name {
            "-f" | "--format" => format_flag = Some(value("-f needs a format id")?),
            "-o" | "--output" => out_path = Some(PathBuf::from(value("-o needs a path")?)),
            "--trace" => trace = true,
            "--order" => {
                let id = value("--order needs an id")?;
                opts.order =
                    Order::from_id(&id).ok_or_else(|| format!("unknown order id '{id}'"))?;
            }
            "--dir-depth" => {
                let v = value("--dir-depth needs an integer")?;
                opts.dir_depth = v
                    .parse()
                    .map_err(|_| format!("--dir-depth needs an integer (got '{v}')"))?;
            }
            "--filename-as-key" => opts.filename_as_key = true,
            "--no-filename-as-key" => opts.filename_as_key = false,
            "--dirname-as-key" => opts.dirname_as_key = true,
            "--no-dirname-as-key" => opts.dirname_as_key = false,
            "--sheetname-as-key" => opts.sheetname_as_key = true,
            "--no-sheetname-as-key" => opts.sheetname_as_key = false,
            "--dot-key" => opts.dot_key = true,
            "--no-dot-key" => opts.dot_key = false,
            "--case-sensitive" => opts.case_sensitive = true,
            "--no-case-sensitive" => opts.case_sensitive = false,
            // the tree preset: folders, files and sheets all become keys,
            // and the whole tree is scanned
            "--tree" => {
                opts.filename_as_key = true;
                opts.dirname_as_key = true;
                opts.sheetname_as_key = true;
                opts.dir_depth = -1;
            }
            "--no-tree" => {
                opts.filename_as_key = false;
                opts.dirname_as_key = false;
                opts.sheetname_as_key = false;
                opts.dir_depth = 1;
            }
            "--auto-no-ext-files" => opts.auto_no_ext_files = true,
            "--no-auto-no-ext-files" => opts.auto_no_ext_files = false,
            "--ignore-unknown-ext" => opts.ignore_unknown_ext = true,
            "--no-ignore-unknown-ext" => opts.ignore_unknown_ext = false,
            "--ignore-commented-data-keys" => opts.ignore_commented_data_keys = true,
            "--no-ignore-commented-data-keys" => opts.ignore_commented_data_keys = false,
            "--ignore-commented-filenames" => opts.ignore_commented_filenames = true,
            "--no-ignore-commented-filenames" => opts.ignore_commented_filenames = false,
            "--ignore-commented-dirnames" => opts.ignore_commented_dirnames = true,
            "--no-ignore-commented-dirnames" => opts.ignore_commented_dirnames = false,
            "--ignore-commented-sheetnames" => opts.ignore_commented_sheetnames = true,
            "--no-ignore-commented-sheetnames" => opts.ignore_commented_sheetnames = false,
            "--ignore-hidden-sheets" => opts.ignore_hidden_sheets = true,
            "--no-ignore-hidden-sheets" => opts.ignore_hidden_sheets = false,
            "-h" | "--help" => {
                print!("{USAGE}");
                return Ok(());
            }
            flag if flag.starts_with('-') => {
                return Err(format!("unknown flag '{flag}'\n{USAGE}"));
            }
            _ => {
                sources.push(PathBuf::from(arg));
                continue;
            }
        }
        // a boolean flag must not take a value: `--dot-key=false` would
        // otherwise turn the option on
        let value_flag = matches!(
            name,
            "-f" | "--format" | "-o" | "--output" | "--order" | "--dir-depth"
        );
        if inline.is_some() && !value_flag {
            let hint = match name.strip_prefix("--no-") {
                Some(on) => format!(" (use --{on} to turn it on)"),
                None if matches!(name, "--trace" | "-h" | "--help") => String::new(),
                None => format!(" (use --no-{} to turn it off)", &name[2..]),
            };
            return Err(format!("flag '{name}' takes no value{hint}"));
        }
    }

    let format = resolve_format(format_flag.as_deref(), out_path.as_deref())?;

    // a path source auto-detects folder vs file at load time (a missing
    // path gets the loader's NotFound error); default source is ./config
    opts.sources = if sources.is_empty() {
        vec![Source::Path(PathBuf::from("config"))]
    } else {
        sources.into_iter().map(Source::Path).collect()
    };

    let loader = Loader::new(opts);
    // debug prints the typed result directly, every other format goes
    // through one serde_json tree
    let traced = loader.trace().map_err(|e| e.to_string())?;
    for warning in &traced.warnings {
        eprintln!("c4: warning: {warning}");
    }
    let text = if trace {
        match format {
            OutFormat::Debug => format!("{traced:#?}\n"),
            _ => emit(
                &serde_json::to_value(&traced).map_err(|e| e.to_string())?,
                format,
            )?,
        }
    } else {
        let value: c4::Value = traced.value.into();
        match format {
            OutFormat::Debug => format!("{value:#?}\n"),
            _ => emit(
                &serde_json::to_value(&value).map_err(|e| e.to_string())?,
                format,
            )?,
        }
    };
    match out_path {
        Some(path) => {
            std::fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display()))
        }
        None => {
            print!("{text}");
            Ok(())
        }
    }
}

/// The default is auto: `-f` wins, else the `-o` extension decides, and
/// when neither names a format (no `-o`, or an extension no output
/// format matches) the fallback is the Rust Debug form.
fn resolve_format(
    flag: Option<&str>,
    out_path: Option<&std::path::Path>,
) -> Result<OutFormat, String> {
    if let Some(id) = flag {
        return OutFormat::from_id(id).ok_or_else(|| format!("unknown output format '{id}'"));
    }
    if let Some(ext) = out_path
        .and_then(|p| p.extension())
        .and_then(|e| e.to_str())
        && let Some(format) = OutFormat::from_extension(&ext.to_lowercase())
    {
        return Ok(format);
    }
    Ok(OutFormat::Debug)
}

fn emit(tree: &serde_json::Value, format: OutFormat) -> Result<String, String> {
    match format {
        OutFormat::Debug => unreachable!("debug is handled before serialization"),
        OutFormat::Json => serde_json::to_string_pretty(tree)
            .map(|s| s + "\n")
            .map_err(|e| e.to_string()),
        OutFormat::Yaml => yaml_serde::to_string(tree).map_err(|e| e.to_string()),
        OutFormat::Toml => {
            toml::to_string_pretty(&without_nulls(tree, "")?).map_err(|e| e.to_string())
        }
        OutFormat::Env => {
            let mut out = String::new();
            for (key, value) in flatten(tree) {
                if key.is_empty()
                    || key.starts_with('#')
                    || key.chars().any(|c| c == '=' || c.is_whitespace())
                {
                    return Err(format!("key '{key}' cannot be written as env"));
                }
                out.push_str(&format!("{key}={}\n", env_value(value)?));
            }
            Ok(out)
        }
        OutFormat::Ini => ini(tree),
        OutFormat::Csv => {
            let mut out = String::new();
            for (key, value) in flatten(tree) {
                let (cell, ty) = csv_cell(value)?;
                out.push_str(&format!(
                    "{},{},{ty}\n",
                    csv_escape(&key),
                    csv_escape(&cell)
                ));
            }
            Ok(out)
        }
    }
}

/// toml has no null: drop null keys (an absent key is toml's null) and
/// refuse a null inside an array, which has no position to drop.
fn without_nulls(value: &serde_json::Value, path: &str) -> Result<serde_json::Value, String> {
    let join = |key: &str| {
        if path.is_empty() {
            key.to_owned()
        } else {
            format!("{path}.{key}")
        }
    };
    Ok(match value {
        serde_json::Value::Object(map) => serde_json::Value::Object(
            map.iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| Ok((k.clone(), without_nulls(v, &join(k))?)))
                .collect::<Result<_, String>>()?,
        ),
        serde_json::Value::Array(items) => {
            if items.iter().any(serde_json::Value::is_null) {
                return Err(format!(
                    "'{path}' holds a null inside an array, which toml cannot hold"
                ));
            }
            serde_json::Value::Array(
                items
                    .iter()
                    .enumerate()
                    .map(|(i, v)| without_nulls(v, &format!("{path}[{i}]")))
                    .collect::<Result<_, String>>()?,
            )
        }
        other => other.clone(),
    })
}

/// Depth-first flatten of nested objects into dotted keys (the reverse of
/// `dot_key`); keys come out sorted because objects are sorted maps.
fn flatten(tree: &serde_json::Value) -> Vec<(String, &serde_json::Value)> {
    fn walk<'a>(
        prefix: &str,
        v: &'a serde_json::Value,
        out: &mut Vec<(String, &'a serde_json::Value)>,
    ) {
        match v {
            serde_json::Value::Object(map) => {
                for (key, value) in map {
                    let key = if prefix.is_empty() {
                        key.clone()
                    } else {
                        format!("{prefix}.{key}")
                    };
                    walk(&key, value, out);
                }
            }
            leaf => out.push((prefix.to_owned(), leaf)),
        }
    }
    let mut out = Vec::new();
    walk("", tree, &mut out);
    out
}

/// env value text: scalars raw, arrays embedded as JSON strings, quoted
/// and escaped the dotenv way when needed so the env parser reads it back.
fn env_value(value: &serde_json::Value) -> Result<String, String> {
    let text = scalar_text(value)?;
    let plain = !text.is_empty()
        && !text.starts_with(['"', '\''])
        && !text
            .chars()
            .any(|c| c.is_whitespace() || matches!(c, '#' | '"'));
    if plain {
        return Ok(text);
    }
    let mut quoted = String::from('"');
    for c in text.chars() {
        match c {
            '\n' => quoted.push_str("\\n"),
            '\r' => quoted.push_str("\\r"),
            '\t' => quoted.push_str("\\t"),
            '"' => quoted.push_str("\\\""),
            '\\' => quoted.push_str("\\\\"),
            c => quoted.push(c),
        }
    }
    quoted.push('"');
    Ok(quoted)
}

/// Scalars as text, arrays embedded as JSON strings.
fn scalar_text(value: &serde_json::Value) -> Result<String, String> {
    Ok(match value {
        serde_json::Value::Null => String::new(),
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Bool(_) | serde_json::Value::Number(_) => value.to_string(),
        serde_json::Value::Array(_) => serde_json::to_string(value).map_err(|e| e.to_string())?,
        serde_json::Value::Object(_) => unreachable!("objects are flattened"),
    })
}

/// ini output — the subset c4's ini parser reads: root keys first, then
/// one `[section]` per top-level object; no quoting or escapes, so what
/// that cannot hold is an error instead of a file that reads back wrong.
fn ini(tree: &serde_json::Value) -> Result<String, String> {
    let serde_json::Value::Object(root) = tree else {
        return Err("ini output needs an object at the root".into());
    };
    let line = |key: &str, value: &serde_json::Value| -> Result<String, String> {
        if key.is_empty()
            || key.starts_with(['[', ';', '#'])
            || key.contains(['=', '\n'])
            || key.trim() != key
        {
            return Err(format!("key '{key}' cannot be written as ini"));
        }
        let text = scalar_text(value)?;
        if text.contains(['\n', '\r']) {
            return Err(format!(
                "value of '{key}' has a newline, which ini cannot hold"
            ));
        }
        if text.trim() != text {
            return Err(format!(
                "value of '{key}' has leading or trailing whitespace, which ini cannot hold"
            ));
        }
        Ok(format!("{key}={text}\n"))
    };
    let mut out = String::new();
    for (key, value) in root {
        if !value.is_object() {
            out.push_str(&line(key, value)?);
        }
    }
    for (section, value) in root {
        let serde_json::Value::Object(entries) = value else {
            continue;
        };
        if section.is_empty() || section.contains([']', '\n']) || section.trim() != section {
            return Err(format!("section '{section}' cannot be written as ini"));
        }
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&format!("[{section}]\n"));
        for (key, value) in entries {
            if value.is_object() {
                return Err(format!(
                    "'{section}.{key}' nests below a section, which ini cannot hold"
                ));
            }
            out.push_str(&line(key, value)?);
        }
    }
    Ok(out)
}

/// csv value cell + explicit format column.
fn csv_cell(value: &serde_json::Value) -> Result<(String, String), String> {
    Ok(match value {
        // read back as a `json` cell, like arrays
        serde_json::Value::Null => ("null".into(), "json".into()),
        serde_json::Value::Bool(b) => (b.to_string(), "bool".into()),
        serde_json::Value::Number(n) => (n.to_string(), csv_number_type(n).into()),
        serde_json::Value::String(s) => (s.clone(), "str".into()),
        // arrays emit as a single json cell (the table stage reads them
        // back with the `json` type); objects are flattened away upstream
        serde_json::Value::Array(_) => (
            serde_json::to_string(value).map_err(|e| e.to_string())?,
            "json".into(),
        ),
        serde_json::Value::Object(_) => unreachable!("objects are flattened"),
    })
}

fn csv_number_type(n: &serde_json::Number) -> &'static str {
    if n.is_i64() {
        "i64"
    } else if n.is_u64() {
        "u64"
    } else {
        "f64"
    }
}

fn csv_escape(cell: &str) -> String {
    if cell.contains(',') || cell.contains('"') || cell.contains('\n') {
        format!("\"{}\"", cell.replace('"', "\"\""))
    } else {
        cell.to_owned()
    }
}