mogh_config 5.0.3

Utilities to merge config from multiple files / directories.
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
use std::{
  collections::HashSet,
  fs::File,
  io::Read,
  path::{Path, PathBuf},
};

use colored::Colorize;
use mogh_env_parser::{is_env_file, parse_env_file_object};
use serde::de::DeserializeOwned;

use crate::{
  Error, Result,
  error::{redact_serde_error, redact_toml_error, redact_yaml_error},
  flat::FlatPrefixes,
  includes::read_includes,
  interpolate::{interpolate_value, unsupported_interpolations},
  merge::merge_source,
  unknown::CheckedSource,
};

/// Whether a config path is a cicada source: it starts with
/// `cicada:` (`cicada://...`, `cicada:/...` or `cicada:...`, leading
/// whitespace aside), the scheme of `cicada_loader`'s paths
/// (`cicada_loader::is_cicada_path` tells one the same way). Told
/// apart here, with or without the feature, so a build without it
/// refuses the path ([Error::CicadaFeatureDisabled]) rather than
/// skipping it as a missing local path.
///
/// Note. Must compare against the path as a string,
/// Path::starts_with compares whole components and misses
/// the `cicada:some/path` (no slash) form.
pub(crate) fn is_cicada_path(path: &Path) -> bool {
  path.to_string_lossy().trim_start().starts_with("cicada:")
}

/// A config file found by [load_config_files].
pub(crate) struct FoundFile {
  /// As listed, as an include line names it, or as a directory scan
  /// found it (under the canonical directory). Not canonicalized: a
  /// symlink keeps the name its type is detected from.
  pub(crate) path: PathBuf,
  /// Named as a path or by an include line, rather than found by a
  /// directory scan. A named file is loaded or an error, whatever
  /// its name. A scan skips a file it finds which is no config file
  /// type (a `config.toml.bak` matching `*config.*`), as nobody
  /// asked for that file in particular.
  pub(crate) named: bool,
}

/// Whether an io error means the path doesn't exist (also through a
/// file: `app.toml/x`, or a dangling symlink).
pub(crate) fn is_missing(e: &std::io::Error) -> bool {
  matches!(
    e.kind(),
    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
  )
}

/// The metadata of a path, following symlinks, or `None` when it
/// doesn't exist. A missing path is skipped (deliberate: an app may
/// list optional paths, eg. a mount which isn't always there). Any
/// other failure (permission denied on a parent directory) is an
/// error ([Error::ReadPathMetaData]): the path may well hold
/// configuration, and skipping it would start the app without it.
fn metadata_if_exists(
  path: &Path,
  debug_print: bool,
) -> Result<Option<std::fs::Metadata>> {
  match std::fs::metadata(path) {
    Ok(metadata) => Ok(Some(metadata)),
    Err(e) if is_missing(&e) => {
      if debug_print {
        println!(
          "{}: {}: {path:?} | {e:?}",
          "DEBUG".cyan(),
          "Skipping missing path".dimmed()
        );
      }
      Ok(None)
    }
    Err(e) => Err(Error::ReadPathMetaData {
      path: path.to_path_buf(),
      e,
    }),
  }
}

/// Collects the config files at `path` (a listed path, or an
/// include line) into `files` in priority order (later overrides
/// earlier):
///
/// - A `cicada:` path is a source of its own, an error
///   ([Error::CicadaFeatureDisabled]) without the feature.
/// - A missing path is skipped, see [metadata_if_exists], and so is
///   one which is no file or directory (`/dev/null`).
/// - A file is a file to load.
/// - A directory contributes, in this order:
///   1. Its own matching files, ordered by the matched wildcard
///      (later wildcards override earlier; a file matching several
///      takes the priority of the last one), then by name.
///   2. Each path listed in its include file, in the order listed,
///      recursively. Later includes override earlier ones, and
///      every include overrides the directory's own files.
///
/// A directory which exists but can't be read ([Error::ReadDir],
/// [Error::DirFile]), or a matching entry whose metadata can't be
/// read ([Error::ReadPathMetaData]), is an error rather than a
/// directory without config files.
///
/// A path included more than once (eg two includes sharing a
/// common include) is emitted each time, so its last occurrence
/// takes the highest priority. Only true recursion (a directory
/// including itself, directly or indirectly) is cut.
///
/// Files are emitted at the path they were found at (listed, by the
/// scan, or as an include line names them), not canonicalized, so a
/// symlink is loaded by its own name (which names its type).
/// [crate::ConfigLoader] dedupes them by their canonical path.
pub(crate) fn load_config_files(
  files: &mut Vec<FoundFile>,
  // canonical directories on the current include stack
  visiting: &mut HashSet<PathBuf>,
  path: &Path,
  keywords: &[wildcard::Wildcard],
  include_file_name: &'static str,
  debug_print: bool,
) -> Result<()> {
  // Cicada base case.
  if is_cicada_path(path) {
    #[cfg(not(feature = "cicada"))]
    return Err(Error::CicadaFeatureDisabled {
      path: path.to_path_buf(),
    });
    #[cfg(feature = "cicada")]
    {
      files.push(FoundFile {
        path: path.to_path_buf(),
        named: true,
      });
      return Ok(());
    }
  }

  let Some(metadata) = metadata_if_exists(path, debug_print)? else {
    return Ok(());
  };

  // File base case.
  if metadata.is_file() {
    files.push(FoundFile {
      path: path.to_path_buf(),
      named: true,
    });
    return Ok(());
  }

  // Neither a file nor a directory, eg. `/dev/null` listed to load
  // nothing: no config to load.
  if !metadata.is_dir() {
    if debug_print {
      println!(
        "{}: {}: {path:?}",
        "DEBUG".cyan(),
        "Skipping path which is no file or directory".dimmed()
      );
    }
    return Ok(());
  }

  let folder =
    path.canonicalize().map_err(|e| Error::ReadPathMetaData {
      path: path.to_path_buf(),
      e,
    })?;
  if !visiting.insert(folder.clone()) {
    if debug_print {
      println!(
        "{}: {}: {folder:?}",
        "DEBUG".cyan(),
        "Skipping include cycle".dimmed()
      );
    }
    return Ok(());
  }
  let read_dir =
    std::fs::read_dir(&folder).map_err(|e| Error::ReadDir {
      path: folder.clone(),
      e,
    })?;

  // Collect any config files in the current dir,
  // with the index of the matched wildcard.
  let mut dir_files = Vec::new();
  for dir_entry in read_dir {
    let dir_entry = dir_entry.map_err(|e| Error::DirFile {
      path: folder.clone(),
      e,
    })?;
    let path = dir_entry.path();
    let file_name = dir_entry.file_name();
    // The include file is never a config file.
    if file_name == include_file_name {
      continue;
    }
    // An env file next to the config (a compose `.env`) is only
    // a config source when a wildcard asks for it, or when it is
    // listed as a path itself.
    if keywords.is_empty() && is_env_file(&path) {
      if debug_print {
        println!(
          "{}: {}: {path:?} (match it with a wildcard to load it)",
          "DEBUG".cyan(),
          "Skipping env file".dimmed()
        );
      }
      continue;
    }
    // Ensure file name matches a wildcard keyword. A file
    // matching several takes the last (highest priority) one, so
    // `["*config.*", "*config.local.*"]` puts the local override
    // above the base file. Matched as bytes, so a name which isn't
    // utf-8 is matched (and loaded) like any other.
    let index = if keywords.is_empty() {
      0
    } else if let Some(index) = keywords
      .iter()
      .rposition(|wc| wc.is_match(file_name.as_encoded_bytes()))
    {
      index
    } else {
      continue;
    };
    // Follows symlinks (eg Kubernetes ConfigMap mounts), unlike
    // DirEntry::metadata. A dangling symlink is a missing file.
    let Some(metadata) = metadata_if_exists(&path, debug_print)?
    else {
      continue;
    };
    // Subdirectories are only loaded through an include file.
    if !metadata.is_file() {
      continue;
    }
    // As found (absolute, under the canonical folder), not the
    // canonical path: a symlink (`app.env` -> `secret`) keeps the
    // name its type is detected from.
    dir_files.push((index, path));
  }
  // Wildcard priority only applies within this directory.
  dir_files.sort();
  files.extend(
    dir_files
      .into_iter()
      .map(|(_, path)| FoundFile { path, named: false }),
  );

  // Collect any paths specified in 'includes'
  let includes = read_includes(&folder, include_file_name)?;
  if includes.is_empty() {
    visiting.remove(&folder);
    return Ok(());
  }

  if debug_print {
    println!(
      "{}: {}: {includes:?}",
      "DEBUG".cyan(),
      format_args!(
        "{} {path:?} {}",
        "Config Path".dimmed(),
        "Includes".dimmed()
      ),
    );
  }

  // Add these paths as well recursively.
  for path in includes {
    load_config_files(
      files,
      visiting,
      &path,
      keywords,
      include_file_name,
      debug_print,
    )?;
  }
  visiting.remove(&folder);
  Ok(())
}

/// loads multiple config files.
///
/// With the `cicada` feature, the files can be cicada paths
/// (`cicada://filesystem/config.yaml?env=prod+us-east`), provided the
/// user configures the `CICADA_...` env vars. The syntax is the
/// loader's (`cicada_loader::CicadaPath`: the filesystem first, then
/// the file inside it, the environments under `?env=` with `+`
/// layering several, `.env` for the environments themselves): each
/// such path is handed to it as written, and parsed, loaded and
/// typed by the name it holds (`config.yaml` as yaml, `.env` as an
/// env file).
///
/// A file which fails to open, read or parse is an error
/// ([Error::FileOpen], [Error::ReadFileContents], [Error::ParseToml]
/// and the other parse errors), named or found by a directory scan:
/// skipping it would start the app without the settings in it (a
/// `disable_user_registration`, the `trusted_proxies`). So is a
/// cicada source which fails to load ([Error::CicadaLoad]), eg.
/// Core briefly unreachable at an exit-on-change restart. A file
/// holding no settings (blank, comments only) is an empty source,
/// see [parse_config_contents]. The one file skipped (with a
/// warning) is one a directory scan finds which is no config file
/// type, such as a `config.toml.bak` matching `*config.*`; named
/// as a path or by an include line, it is an error
/// ([Error::UnsupportedFileType]).
///
/// A source which parsed is never skipped: it merges over the
/// sources before it key by key (see [crate::ConfigLoader]), and a
/// value of a type the config can't take fails the final
/// deserialization ([Error::ParseFinalJson]) instead.
///
/// Each local toml / yaml / json source is interpolated (`${VAR}`,
/// `$(cmd)`) as it is parsed. Env file sources and every cicada
/// source are not: their values are secrets taken verbatim, never
/// templates (Core interpolated a cicada file's `[[SECRET]]`
/// placeholders already), and a secret must not be able to run a
/// command in the process reading it.
///
/// Each source has its flat keys moved into their tables before it
/// merges (`flat`, see [crate::EnvSource::flat_prefix]), so the
/// sources may spell a field differently.
///
/// Returns the merged sources, for the final deserialization
/// ([crate::deserialize_final]), after the environment's values
/// when there is an [crate::EnvSource], and the keys of each local
/// toml / yaml / json source, to name the file of a key the config
/// type doesn't take ([crate::UnknownKey]). Env files and cicada
/// sources are left out of those: keys of other programs are normal
/// there (an env file shared with a compose project, the secrets of
/// an environment).
pub(crate) fn load_parse_config_files(
  files: &[FoundFile],
  merge_nested: bool,
  extend_array: bool,
  flat: &FlatPrefixes,
) -> Result<LoadedSources> {
  let mut target = serde_json::Map::new();
  let mut checked = Vec::new();

  for FoundFile { path: file, named } in files {
    // The source, whether to interpolate it, and whether it is an
    // env file (whose comma separated lists extend arrays).
    #[cfg(feature = "cicada")]
    if is_cicada_path(file) {
      // The loader's syntax: it parses the path (an error for one
      // which doesn't hold up, before anything is asked of Core)
      // and loads it. The path inside Cicada names the format.
      let cicada_path =
        cicada_loader::CicadaPath::parse(&file.to_string_lossy())
          .map_err(|e| cicada_load_error(file, &e))?;
      let node = cicada_path.path();
      // A file of no config type is told by its name, before the
      // device is initialized and the file read (an audited read).
      if !has_config_type(node) {
        return Err(Error::UnsupportedFileType {
          path: file.clone(),
        });
      }
      let contents = cicada_path
        .load()
        .map_err(|e| cicada_load_error(file, &e))?;
      let mut source: serde_json::Map<String, serde_json::Value> =
        parse_config_contents(node, &contents)?;
      flat.fold(file, &mut source)?;
      merge_source(
        &mut target,
        source,
        merge_nested,
        extend_array,
        is_env_file(node),
      );
      continue;
    }

    if !has_config_type(file) {
      if *named {
        return Err(Error::UnsupportedFileType {
          path: file.clone(),
        });
      }
      println!(
        "{}: {file:?} is not loaded: it is no config file type (toml, yaml, yml, json, or an env file). Narrow the config wildcards to leave it out.",
        "WARN".yellow(),
      );
      continue;
    }
    let env_file = is_env_file(file);
    let source: serde_json::Map<String, serde_json::Value> =
      load_parse_config_file(file)?;

    // Interpolate each string leaf (and key) individually, rather
    // than the serialized document, so values containing quotes,
    // backslashes or newlines cannot break or inject into the json.
    let mut source = if env_file {
      source
    } else {
      let mut source = serde_json::Value::Object(source);
      // Named by path, never by value.
      for path in unsupported_interpolations(&source) {
        println!(
          "{}: {file:?} | '{path}' has a '$(...)' or '${{...}}' which is kept as written: only '${{VAR}}' and '$(command)' with a single command word (letters, digits, '_') are interpolated",
          "WARN".yellow(),
        );
      }
      interpolate_value(&mut source);
      match source {
        serde_json::Value::Object(source) => source,
        _ => unreachable!("interpolation keeps the value an object"),
      }
    };
    flat.fold(file, &mut source)?;
    if !env_file {
      checked.push(CheckedSource::new(file.clone(), &source));
    }

    merge_source(
      &mut target,
      source,
      merge_nested,
      extend_array,
      env_file,
    );
  }

  Ok(LoadedSources {
    merged: target,
    checked,
  })
}

/// See [load_parse_config_files].
pub(crate) struct LoadedSources {
  /// The sources merged.
  pub(crate) merged: serde_json::Map<String, serde_json::Value>,
  /// The keys of the local toml / yaml / json sources.
  pub(crate) checked: Vec<CheckedSource>,
}

/// A `cicada:` source which didn't load ([Error::CicadaLoad]): the
/// path as listed, and the loader's error chain.
#[cfg(feature = "cicada")]
fn cicada_load_error(
  path: &Path,
  e: &dyn std::fmt::Display,
) -> Error {
  Error::CicadaLoad {
    path: path.to_path_buf(),
    message: format!("{e:#}"),
  }
}

/// Reads a file to a string: a failure to open it is
/// [Error::FileOpen], to read it (a directory, not utf-8)
/// [Error::ReadFileContents]. Neither carries the contents.
pub(crate) fn read_file(path: &Path) -> Result<String> {
  let mut file = File::open(path).map_err(|e| Error::FileOpen {
    e,
    path: path.to_path_buf(),
  })?;
  let mut contents = String::new();
  file.read_to_string(&mut contents).map_err(|e| {
    Error::ReadFileContents {
      e,
      path: path.to_path_buf(),
    }
  })?;
  Ok(contents)
}

/// Loads and parses a single config file
pub(crate) fn load_parse_config_file<T: DeserializeOwned>(
  file: &Path,
) -> Result<T> {
  parse_config_contents(file, &read_file(file)?)
}

/// Whether [parse_config_contents] can parse the file by its name:
/// an env file, or a toml / yaml / yml / json extension.
pub(crate) fn has_config_type(file: &Path) -> bool {
  is_env_file(file)
    || file.extension().and_then(|e| e.to_str()).is_some_and(|e| {
      matches!(
        e.to_ascii_lowercase().as_str(),
        "toml" | "yaml" | "yml" | "json"
      )
    })
}

/// Parses config contents by the file's name: toml, yaml / yml,
/// json, or an env file (`.env`, `*.env`, see
/// [parse_env_file_object]): a flat set of `NAME=value` entries
/// with names lowercased and dots nesting, so `DB_PASSWORD=x` fills
/// a `db_password` field and `DATABASE.ADDRESS=y` fills
/// `database.address`, the way `envy` would read the process
/// environment. A name with an empty segment (`.dockerconfigjson`)
/// stays one flat key.
///
/// Contents holding no settings are an empty config (`{}`), so a
/// placeholder doesn't stop the app: blank or comments only in any
/// format, and a yaml or json `null` document (`~`, a yaml file
/// whose every line is commented out). Anything else must parse
/// into an object.
pub(crate) fn parse_config_contents<T: DeserializeOwned>(
  file: &Path,
  contents: &str,
) -> Result<T> {
  if is_env_file(file) {
    let object = parse_env_file_object(contents).map_err(|e| {
      Error::ParseEnvFile {
        e,
        path: file.to_path_buf(),
      }
    })?;
    return serde_json::from_value(serde_json::Value::Object(object))
      .map_err(|e| Error::ParseJson {
        path: file.to_path_buf(),
        message: redact_serde_error(&e),
      });
  }
  let extension = file
    .extension()
    .and_then(|e| e.to_str())
    .map(str::to_ascii_lowercase);
  // `None` for a document holding no settings.
  let config: Option<T> = match extension.as_deref() {
    // Blank or comments only is an empty table already.
    Some("toml") => Some(toml::from_str(contents).map_err(|e| {
      Error::ParseToml {
        path: file.to_path_buf(),
        message: redact_toml_error(&e, contents),
      }
    })?),
    // Blank or comments only is an empty document already, `null`
    // (`~`, `--- ~`) is `None`.
    Some("yaml") | Some("yml") => serde_yaml_ng::from_str(contents)
      .map_err(|e| Error::ParseYaml {
      path: file.to_path_buf(),
      message: redact_yaml_error(&e),
    })?,
    // json has no comments: blank is no document at all.
    Some("json") if contents.trim().is_empty() => None,
    Some("json") => serde_json::from_str(contents).map_err(|e| {
      Error::ParseJson {
        path: file.to_path_buf(),
        message: redact_serde_error(&e),
      }
    })?,
    Some(_) | None => {
      return Err(Error::UnsupportedFileType {
        path: file.to_path_buf(),
      });
    }
  };
  match config {
    Some(config) => Ok(config),
    None => serde_json::from_value(serde_json::Value::Object(
      Default::default(),
    ))
    .map_err(|e| Error::ParseJson {
      path: file.to_path_buf(),
      message: redact_serde_error(&e),
    }),
  }
}