mogh_config 2.0.2

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
// Integration test binaries only use a subset
// of the library dependencies.
#![allow(unused_crate_dependencies)]

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

use mogh_config::ConfigLoader;

/// Creates a unique, empty directory for a test
/// and cleans it up on drop.
struct TestDir(PathBuf);

impl TestDir {
  fn new(name: &str) -> TestDir {
    let path = std::env::temp_dir().join(format!(
      "mogh_config_test_{}_{name}",
      std::process::id()
    ));
    // Ensure a clean folder
    let _ = std::fs::remove_dir_all(&path);
    std::fs::create_dir_all(&path).unwrap();
    TestDir(path)
  }

  fn write(&self, file: &str, contents: &str) -> PathBuf {
    let path = self.0.join(file);
    std::fs::write(&path, contents).unwrap();
    path
  }
}

impl Drop for TestDir {
  fn drop(&mut self) {
    let _ = std::fs::remove_dir_all(&self.0);
  }
}

fn load(
  paths: &[&Path],
  match_wildcards: &[&str],
  merge_nested: bool,
  extend_array: bool,
) -> serde_json::Value {
  ConfigLoader {
    paths,
    match_wildcards,
    include_file_name: ".include",
    merge_nested,
    extend_array,
    debug_print: false,
  }
  .load()
  .unwrap()
}

#[test]
fn loads_toml_yaml_and_json_files() {
  let dir = TestDir::new("formats");
  let toml = dir.write("config.toml", "a = 1");
  let yaml = dir.write("config.yaml", "b: 2");
  let yml = dir.write("config.yml", "c: 3");
  let json = dir.write("config.json", r#"{ "d": 4 }"#);

  let config = load(&[&toml, &yaml, &yml, &json], &[], false, false);
  assert_eq!(
    config,
    serde_json::json!({ "a": 1, "b": 2, "c": 3, "d": 4 })
  );
}

#[test]
fn extension_matching_is_case_insensitive() {
  let dir = TestDir::new("upper_ext");
  let toml = dir.write("config.TOML", "a = 1");
  let config = load(&[&toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "a": 1 }));
}

#[test]
fn unsupported_extension_is_skipped_with_warning() {
  let dir = TestDir::new("unsupported_ext");
  let txt = dir.write("config.txt", "a = 1");
  let toml = dir.write("config.toml", "b = 2");
  // The .txt file fails to parse and is skipped, rest still loads.
  let config = load(&[&txt, &toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "b": 2 }));
}

#[test]
fn missing_paths_are_skipped() {
  let dir = TestDir::new("missing_path");
  let toml = dir.write("config.toml", "a = 1");
  let missing = dir.0.join("does_not_exist.toml");
  let config = load(&[&missing, &toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "a": 1 }));
}

#[test]
fn later_paths_override_earlier_paths() {
  let dir = TestDir::new("precedence");
  let base = dir.write(
    "base.toml",
    "a = 1\nb = \"base\"\narr = [1]\n[nested]\nx = 1\ny = 1",
  );
  let override_ = dir.write(
    "override.json",
    r#"{ "b": "override", "arr": [2], "nested": { "y": 2 } }"#,
  );

  // merge_nested + extend_array
  let config = load(&[&base, &override_], &[], true, true);
  assert_eq!(
    config,
    serde_json::json!({
      "a": 1,
      "b": "override",
      "arr": [1, 2],
      "nested": { "x": 1, "y": 2 }
    })
  );

  // replace nested / arrays
  let config = load(&[&base, &override_], &[], false, false);
  assert_eq!(
    config,
    serde_json::json!({
      "a": 1,
      "b": "override",
      "arr": [2],
      "nested": { "y": 2 }
    })
  );
}

#[test]
fn repeated_path_moves_to_highest_priority() {
  let dir = TestDir::new("repeat_path");
  let first = dir.write("first.toml", "a = \"first\"");
  let second = dir.write("second.toml", "a = \"second\"");
  // `first` is repeated after `second`, so it should win.
  let config = load(&[&first, &second, &first], &[], false, false);
  assert_eq!(config, serde_json::json!({ "a": "first" }));
}

#[test]
fn directory_loading_respects_wildcard_order() {
  let dir = TestDir::new("wildcards");
  dir.write("01_a.toml", "key = \"a\"\nonly_a = 1");
  dir.write("02_b.toml", "key = \"b\"\nonly_b = 1");
  dir.write("ignored.toml", "ignored = 1");

  // Later wildcards have higher priority, so 01_a wins.
  let config =
    load(&[&dir.0], &["02_*.toml", "01_*.toml"], false, false);
  assert_eq!(
    config,
    serde_json::json!({ "key": "a", "only_a": 1, "only_b": 1 })
  );

  // With a single wildcard, files apply in path order (02_b last).
  let config = load(&[&dir.0], &["0*.toml"], false, false);
  assert_eq!(
    config,
    serde_json::json!({ "key": "b", "only_a": 1, "only_b": 1 })
  );

  // Files not matching any wildcard are excluded entirely.
  let config = load(&[&dir.0], &["0*.toml"], false, false);
  assert_eq!(config.get("ignored"), None);
}

#[test]
fn file_paths_override_directory_paths() {
  let dir = TestDir::new("file_over_dir");
  dir.write("config.toml", "a = \"dir\"");
  let standalone = TestDir::new("file_over_dir_standalone");
  let file = standalone.write("override.toml", "a = \"file\"");

  let config = load(&[&dir.0, &file], &["*.toml"], false, false);
  assert_eq!(config, serde_json::json!({ "a": "file" }));
}

#[test]
fn include_file_pulls_in_other_directories() {
  let included = TestDir::new("included_dir");
  included.write("extra.toml", "extra = 1\nkey = \"included\"");
  let dir = TestDir::new("includes");
  dir.write("main.toml", "key = \"main\"\nmain = 1");
  dir.write(
    ".include",
    &format!(
      "# comment line\n\n{} # end of line comment\n",
      included.0.display()
    ),
  );

  let config = load(&[&dir.0], &["*.toml"], false, false);
  assert_eq!(config.get("extra"), Some(&serde_json::json!(1)));
  assert_eq!(config.get("main"), Some(&serde_json::json!(1)));
  // Includes override the directory's own files.
  assert_eq!(config.get("key"), Some(&serde_json::json!("included")));
}

#[test]
fn includes_apply_in_include_order() {
  // Directory names are chosen so that path order (zz < ...)
  // disagrees with include order, proving include order wins.
  let main = TestDir::new("zz_order_main");
  let first = TestDir::new("yy_order_first");
  let second = TestDir::new("aa_order_second");
  let nested = TestDir::new("bb_order_nested");
  main.write("main.toml", "key = \"main\"\nmain = 1");
  first.write("first.toml", "key = \"first\"\nfirst = 1");
  second.write("second.toml", "key = \"second\"\nsecond = 1");
  nested.write("nested.toml", "key = \"nested\"\nnested = 1");
  // first includes nested, so nested is applied right after
  // first, before second.
  first.write(
    ".include",
    &format!(
      "{}
",
      nested.0.display()
    ),
  );
  main.write(
    ".include",
    &format!(
      "{}
{}
",
      first.0.display(),
      second.0.display()
    ),
  );

  let config = load(&[&main.0], &["*.toml"], false, false);
  assert_eq!(
    config,
    serde_json::json!({
      "key": "second",
      "main": 1,
      "first": 1,
      "nested": 1,
      "second": 1,
    })
  );

  // Reversing the include order reverses the priority.
  main.write(
    ".include",
    &format!(
      "{}
{}
",
      second.0.display(),
      first.0.display()
    ),
  );
  let config = load(&[&main.0], &["*.toml"], false, false);
  assert_eq!(config.get("key"), Some(&serde_json::json!("nested")));
}

#[test]
fn wildcard_priority_is_per_directory() {
  let main = TestDir::new("wc_per_dir_main");
  let included = TestDir::new("wc_per_dir_included");
  main.write("02_high.toml", "key = \"main-high\"");
  included.write("01_low.toml", "key = \"included-low\"");
  main.write(
    ".include",
    &format!(
      "{}
",
      included.0.display()
    ),
  );
  // 02_* is the higher priority wildcard, but only within a
  // directory: the include still overrides the main directory.
  let config =
    load(&[&main.0], &["01_*.toml", "02_*.toml"], false, false);
  assert_eq!(config, serde_json::json!({ "key": "included-low" }));
}

#[test]
fn interpolates_env_vars_into_config() {
  let var = "MOGH_CONFIG_TEST_INTERPOLATION_VAR";
  unsafe { std::env::set_var(var, "interpolated") };
  let dir = TestDir::new("interpolation");
  let toml =
    dir.write("config.toml", &format!("value = \"${{{var}}}\""));
  let config = load(&[&toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "value": "interpolated" }));
}

#[test]
fn interpolates_unset_env_vars_to_empty_string() {
  let dir = TestDir::new("interpolation_unset");
  let toml = dir.write(
    "config.toml",
    "value = \"${MOGH_CONFIG_TEST_DEFINITELY_UNSET_VAR}\"",
  );
  let config = load(&[&toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "value": "" }));
}

#[test]
fn include_cycles_do_not_recurse_forever() {
  let a = TestDir::new("cycle_a");
  // b is nested in a, so `..` from b is a.
  let b = a.0.join("b");
  std::fs::create_dir(&b).unwrap();
  a.write("a.toml", "a = 1");
  std::fs::write(b.join("b.toml"), "b = 2").unwrap();
  // a includes b and itself, b includes a (absolute and relative).
  a.write(".include", &format!("{}\n.\n", b.display()));
  std::fs::write(
    b.join(".include"),
    format!("{}\n..\n", a.0.display()),
  )
  .unwrap();
  let config = load(&[&a.0], &["*.toml"], false, false);
  assert_eq!(config.get("a"), Some(&serde_json::json!(1)));
  assert_eq!(config.get("b"), Some(&serde_json::json!(2)));
}

#[test]
fn diamond_includes_keep_last_occurrence_priority() {
  // main includes first then second, both include shared.
  // shared is applied under second as well, so it overrides
  // second, as the include order rule promises.
  let main = TestDir::new("diamond_main");
  let first = TestDir::new("diamond_first");
  let second = TestDir::new("diamond_second");
  let shared = TestDir::new("diamond_shared");
  main.write("main.toml", "key = \"main\"");
  first.write("first.toml", "key = \"first\"");
  second.write("second.toml", "key = \"second\"");
  shared.write("shared.toml", "key = \"shared\"\nshared = 1");
  first.write(".include", &format!("{}\n", shared.0.display()));
  second.write(".include", &format!("{}\n", shared.0.display()));
  main.write(
    ".include",
    &format!("{}\n{}\n", first.0.display(), second.0.display()),
  );
  let config = load(&[&main.0], &["*.toml"], false, false);
  assert_eq!(
    config,
    serde_json::json!({ "key": "shared", "shared": 1 })
  );
}

#[test]
fn include_file_is_not_loaded_as_config() {
  let dir = TestDir::new("include_not_config");
  dir.write("config.toml", "a = 1");
  dir.write(".include", "# nothing\n");
  // No wildcards: every file would otherwise be attempted.
  let config = load(&[&dir.0], &[], false, false);
  assert_eq!(config, serde_json::json!({ "a": 1 }));
}

#[test]
fn include_paths_may_contain_hash() {
  let included = TestDir::new("hash#dir");
  included.write("extra.toml", "extra = 1");
  let dir = TestDir::new("hash_include");
  dir.write("main.toml", "main = 1");
  dir.write(
    ".include",
    &format!("{} # trailing comment\n", included.0.display()),
  );
  let config = load(&[&dir.0], &["*.toml"], false, false);
  assert_eq!(config.get("extra"), Some(&serde_json::json!(1)));
}

#[cfg(unix)]
#[test]
fn symlinked_files_in_directories_are_loaded() {
  let real = TestDir::new("symlink_real");
  let target = real.write("real.toml", "linked = 1");
  let dir = TestDir::new("symlink_dir");
  std::os::unix::fs::symlink(&target, dir.0.join("config.toml"))
    .unwrap();
  let config = load(&[&dir.0], &["*.toml"], false, false);
  assert_eq!(config, serde_json::json!({ "linked": 1 }));
}

#[test]
fn interpolated_values_cannot_inject_or_break_json() {
  let var = "MOGH_CONFIG_TEST_INJECTION_VAR";
  let value = "x\",\"admin\":true,\"y\":\"z\\\nline2 $(whoami)";
  unsafe { std::env::set_var(var, value) };
  let dir = TestDir::new("interpolation_injection");
  let toml = dir.write(
    "config.toml",
    &format!("value = \"${{{var}}}\"\n[nested]\ninner = \"${{{var}}}\"\nlist = [\"${{{var}}}\"]"),
  );
  let config = load(&[&toml], &[], false, false);
  assert_eq!(
    config,
    serde_json::json!({
      "value": value,
      "nested": { "inner": value, "list": [value] }
    })
  );
}

#[test]
fn shell_output_and_env_values_are_not_reinterpolated() {
  // The output of $(env) contains this literal `${...}` text,
  // which must be kept verbatim rather than expanded.
  let literal_var = "MOGH_CONFIG_TEST_LITERAL_VAR";
  unsafe {
    std::env::set_var(
      literal_var,
      "keep ${MOGH_CONFIG_TEST_UNSET} literal",
    )
  };
  // An env var whose value references another env var expands
  // one level, but `$(...)` in either value is never executed.
  let outer = "MOGH_CONFIG_TEST_OUTER_VAR";
  let inner = "MOGH_CONFIG_TEST_INNER_VAR";
  unsafe {
    std::env::set_var(outer, format!("outer ${{{inner}}} $(whoami)"));
    std::env::set_var(inner, "inner $(whoami)");
  }
  let dir = TestDir::new("interpolation_no_reinterpolation");
  let toml = dir.write(
    "config.toml",
    &format!("from_shell = \"$(env)\"\nfrom_env = \"${{{outer}}}\""),
  );
  let config = load(&[&toml], &[], false, false);
  let from_shell = config["from_shell"].as_str().unwrap();
  assert!(
    from_shell.contains("keep ${MOGH_CONFIG_TEST_UNSET} literal"),
    "{from_shell}"
  );
  assert_eq!(
    config["from_env"],
    serde_json::json!("outer inner $(whoami) $(whoami)")
  );
}

#[test]
fn interpolates_shell_commands_and_keys() {
  let dir = TestDir::new("interpolation_shell");
  let toml = dir.write(
    "config.toml",
    "value = \"$(true)\"\n\"${MOGH_CONFIG_TEST_DEFINITELY_UNSET_VAR}key\" = 1",
  );
  let config = load(&[&toml], &[], false, false);
  assert_eq!(config, serde_json::json!({ "value": "", "key": 1 }));
}

#[test]
fn errors_do_not_leak_config_values() {
  #[derive(serde::Deserialize, Debug)]
  #[allow(dead_code)]
  struct Typed {
    port: u16,
  }
  let dir = TestDir::new("error_redaction");
  let toml = dir.write("config.toml", "port = \"hunter2secret\"");
  let err = ConfigLoader {
    paths: &[&toml],
    match_wildcards: &[],
    include_file_name: ".include",
    merge_nested: false,
    extend_array: false,
    debug_print: false,
  }
  .load::<Typed>()
  .unwrap_err();
  let message = err.to_string();
  assert!(!message.contains("hunter2secret"), "{message}");
  assert!(message.contains("expected u16"), "{message}");
}