podup 1.7.1

Translate and run docker-compose files on rootless Podman
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! Docker Compose variable substitution.
//!
//! Applies `${VAR}` / `$VAR` substitution to individual scalar values of a
//! parsed compose document (compose-spec value-level interpolation).
//! Handles all compose-spec modifier forms: `:-`, `-`, `:+`, `+`, `:?`, `?`.

mod parse;

use std::collections::HashMap;
use std::path::Path;

use crate::error::{ComposeError, Result};

use parse::{collect_var_name, is_var_start, parse_braced_var, resolve_modifier};

/// Maximum nesting depth for interpolated default/alternate values
/// (`${A:-${A:-…}}`). Real compose files nest a handful of levels at most; this
/// cap turns a pathological chain into a clean error instead of a stack overflow.
const MAX_INTERP_DEPTH: usize = 64;

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Substitute all `$VAR` / `${VAR}` references in `input` using `vars`.
///
/// `vars` should contain both the process environment and the `.env` file
/// entries (process environment takes precedence).
pub fn substitute(input: &str, vars: &HashMap<String, String>) -> Result<String> {
	substitute_depth(input, vars, 0)
}

/// Inner substitution carrying the current nesting `depth` so recursive
/// interpolation of modifier defaults/alternates (`${A:-${B}}`) is bounded.
pub(super) fn substitute_depth(
	input: &str,
	vars: &HashMap<String, String>,
	depth: usize,
) -> Result<String> {
	if depth > MAX_INTERP_DEPTH {
		return Err(ComposeError::InvalidSubstitution(format!(
			"interpolation nesting too deep (more than {MAX_INTERP_DEPTH} levels)"
		)));
	}

	let mut out = String::with_capacity(input.len());
	let mut chars = input.chars().peekable();

	while let Some(ch) = chars.next() {
		if ch != '$' {
			out.push(ch);
			continue;
		}

		match chars.peek() {
			None => {
				out.push('$');
			}
			Some('$') => {
				chars.next();
				out.push('$');
			}
			Some('{') => {
				chars.next();
				let (var, modifier) = parse_braced_var(&mut chars)?;
				let value = resolve_modifier(var, modifier, vars, depth)?;
				out.push_str(&value);
			}
			Some(c) if is_var_start(*c) => {
				let var = collect_var_name(&mut chars);
				let value = match vars.get(&var) {
					Some(v) => v.clone(),
					None => {
						// Match docker compose v2: warn before defaulting to blank.
						tracing::warn!(
							"The {var} variable is not set. Defaulting to a blank string."
						);
						String::new()
					}
				};
				out.push_str(&value);
			}
			Some(_) => {
				out.push('$');
			}
		}
	}

	Ok(out)
}

/// Load a `.env` file from `dir`.
///
/// - Lines starting with `#` are comments and are skipped.
/// - Empty / whitespace-only lines are skipped.
/// - `KEY=VALUE` sets KEY to VALUE; surrounding quotes are stripped and
///   dotenv escapes/inline comments are handled.
/// - `KEY` without `=` sets KEY to empty string.
/// - Process environment variables take precedence: if a key already exists in
///   the current process env it will *not* be overridden by the `.env` file.
pub fn load_dotenv(dir: &Path) -> HashMap<String, String> {
	let path = dir.join(".env");
	let Ok(content) = crate::filesystem::read_to_string_capped(&path) else {
		return HashMap::new();
	};

	let mut map = HashMap::new();
	for (key, value) in crate::dotenv::parse(&content) {
		// Process environment variables take precedence over the `.env` file.
		if std::env::var(&key).is_ok() {
			continue;
		}
		map.insert(key, value);
	}

	map
}

/// Build the full variable map: process env + dotenv (process env wins).
pub fn build_vars(dir: &Path) -> HashMap<String, String> {
	let mut vars: HashMap<String, String> = std::env::vars().collect();
	for (k, v) in load_dotenv(dir) {
		vars.entry(k).or_insert(v);
	}
	vars
}

/// Build vars, layering explicit `--env-file` files over the process environment.
///
/// Compose v2 semantics: when one or more `--env-file` are given they *replace*
/// the default `.env` (which is therefore not loaded), and among several files
/// the **last** one wins. With no explicit files this is just [`build_vars`]
/// (process env + `.env`). Process env always takes precedence over file values.
///
/// A missing, unreadable, or malformed `--env-file` is silently skipped here
/// (legacy lenient behaviour). This signature is part of the published library
/// API and is kept for backward compatibility; the CLI drives
/// [`build_vars_with_env_files_strict`], which fails loudly on a bad file.
pub fn build_vars_with_env_files(dir: &Path, extra: &[String]) -> HashMap<String, String> {
	// `strict = false` can never produce an error.
	build_vars_with_env_files_inner(dir, extra, false).unwrap_or_default()
}

/// Like [`build_vars_with_env_files`] but rejects a bad `--env-file`.
///
/// An explicitly-passed `--env-file` that is missing, unreadable, or malformed
/// is a hard error (matching docker compose, which fails on a not-found env
/// file) rather than being silently skipped — a typo'd path must not fall back
/// to process-env/defaults and exit 0.
pub fn build_vars_with_env_files_strict(
	dir: &Path,
	extra: &[String],
) -> Result<HashMap<String, String>> {
	build_vars_with_env_files_inner(dir, extra, true)
}

/// The first control character in `value` that is never legitimate in an
/// env-file value, or `None` if there is none. Tab, newline and carriage return
/// are allowed — dotenv escapes (`\t`, `\n`, `\r`) and multi-line quoted values
/// produce them legitimately, and post-parse interpolation stores them verbatim
/// as scalar data. Everything else in the C0/C1 ranges (NUL, ESC, …) is
/// rejected. Pure so it is unit-tested.
fn first_disallowed_control_char(value: &str) -> Option<char> {
	value
		.chars()
		.find(|&c| c.is_control() && !matches!(c, '\t' | '\n' | '\r'))
}

fn build_vars_with_env_files_inner(
	dir: &Path,
	extra: &[String],
	strict: bool,
) -> Result<HashMap<String, String>> {
	if extra.is_empty() {
		return Ok(build_vars(dir));
	}

	// Explicit `--env-file`s replace `.env`; a later file overrides an earlier one.
	let mut file_vars: HashMap<String, String> = HashMap::new();
	for path in extra {
		let abs = if std::path::Path::new(path).is_absolute() {
			std::path::PathBuf::from(path)
		} else {
			dir.join(path)
		};
		let content = match crate::filesystem::read_to_string_capped(&abs) {
			Ok(content) => content,
			Err(e) => {
				if strict {
					return Err(crate::error::ComposeError::EnvFile(format!(
						"env file not found: {} ({e})",
						abs.display()
					)));
				}
				continue;
			}
		};
		let pairs = if strict {
			crate::dotenv::parse_strict(&content)?
		} else {
			crate::dotenv::parse(&content)
		};
		for (key, value) in pairs {
			// A disallowed control character (e.g. NUL) in a value would be
			// interpolated verbatim into a compose scalar, where it is meaningless
			// at best and corrupts the container's config at worst. Reject it here,
			// at load time, with an error that names the originating env file and
			// key — instead of letting it surface later as a compose-file parse
			// error at a meaningless post-substitution offset. Only the explicit
			// (strict) `--env-file`/`env_file:` path errors; the lenient `.env`
			// fallback keeps its historical pass-through behaviour.
			if strict {
				if let Some(bad) = first_disallowed_control_char(&value) {
					return Err(crate::error::ComposeError::EnvFile(format!(
						"env file {}: value of '{key}' contains a disallowed control \
						 character ({}); remove it before use",
						abs.display(),
						bad.escape_default(),
					)));
				}
			}
			file_vars.insert(key, value);
		}
	}

	// Process env wins over every file value.
	let mut vars: HashMap<String, String> = std::env::vars().collect();
	for (k, v) in file_vars {
		vars.entry(k).or_insert(v);
	}
	Ok(vars)
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
	use super::*;

	fn vars(pairs: &[(&str, &str)]) -> HashMap<String, String> {
		pairs
			.iter()
			.map(|(k, v)| (k.to_string(), v.to_string()))
			.collect()
	}

	// Plain passthrough

	#[test]
	fn plain_text_unchanged() {
		assert_eq!(
			substitute("hello world", &vars(&[])).unwrap(),
			"hello world"
		);
	}

	#[test]
	fn dollar_at_end_emitted_literally() {
		assert_eq!(substitute("price$", &vars(&[])).unwrap(), "price$");
	}

	#[test]
	fn double_dollar_becomes_single() {
		assert_eq!(substitute("$$", &vars(&[])).unwrap(), "$");
	}

	// $VAR (unbraced)

	#[test]
	fn unbraced_var_set_expands() {
		assert_eq!(substitute("$FOO", &vars(&[("FOO", "bar")])).unwrap(), "bar");
	}

	#[test]
	fn unbraced_var_unset_expands_to_empty() {
		assert_eq!(substitute("$MISSING", &vars(&[])).unwrap(), "");
	}

	#[test]
	fn unbraced_var_followed_by_non_ident() {
		assert_eq!(substitute("$FOO!", &vars(&[("FOO", "x")])).unwrap(), "x!");
	}

	// ${VAR} (braced, no modifier)

	#[test]
	fn braced_var_set_expands() {
		assert_eq!(
			substitute("${FOO}", &vars(&[("FOO", "val")])).unwrap(),
			"val"
		);
	}

	#[test]
	fn braced_var_unset_expands_to_empty() {
		assert_eq!(substitute("${MISSING}", &vars(&[])).unwrap(), "");
	}

	// ${VAR:-default}

	#[test]
	fn default_if_unset_or_empty_when_unset() {
		assert_eq!(
			substitute("${X:-fallback}", &vars(&[])).unwrap(),
			"fallback"
		);
	}

	#[test]
	fn default_if_unset_or_empty_when_empty() {
		assert_eq!(
			substitute("${X:-fallback}", &vars(&[("X", "")])).unwrap(),
			"fallback"
		);
	}

	#[test]
	fn default_if_unset_or_empty_when_set() {
		assert_eq!(
			substitute("${X:-fallback}", &vars(&[("X", "real")])).unwrap(),
			"real"
		);
	}

	// ${VAR-default}

	#[test]
	fn default_if_unset_when_unset() {
		assert_eq!(substitute("${X-fallback}", &vars(&[])).unwrap(), "fallback");
	}

	#[test]
	fn default_if_unset_when_empty_keeps_empty() {
		assert_eq!(
			substitute("${X-fallback}", &vars(&[("X", "")])).unwrap(),
			""
		);
	}

	#[test]
	fn default_if_unset_when_set() {
		assert_eq!(
			substitute("${X-fallback}", &vars(&[("X", "v")])).unwrap(),
			"v"
		);
	}

	// ${VAR:+alt}

	#[test]
	fn alt_if_set_and_nonempty_when_unset() {
		assert_eq!(substitute("${X:+alt}", &vars(&[])).unwrap(), "");
	}

	#[test]
	fn alt_if_set_and_nonempty_when_empty() {
		assert_eq!(substitute("${X:+alt}", &vars(&[("X", "")])).unwrap(), "");
	}

	#[test]
	fn alt_if_set_and_nonempty_when_set() {
		assert_eq!(
			substitute("${X:+alt}", &vars(&[("X", "v")])).unwrap(),
			"alt"
		);
	}

	// ${VAR+alt}

	#[test]
	fn alt_if_set_when_unset() {
		assert_eq!(substitute("${X+alt}", &vars(&[])).unwrap(), "");
	}

	#[test]
	fn alt_if_set_when_empty_returns_alt() {
		assert_eq!(substitute("${X+alt}", &vars(&[("X", "")])).unwrap(), "alt");
	}

	// ${VAR:?msg}

	#[test]
	fn error_if_unset_or_empty_when_unset() {
		assert!(substitute("${X:?required}", &vars(&[])).is_err());
	}

	#[test]
	fn error_if_unset_or_empty_when_empty() {
		assert!(substitute("${X:?required}", &vars(&[("X", "")])).is_err());
	}

	#[test]
	fn error_if_unset_or_empty_when_set() {
		assert_eq!(
			substitute("${X:?required}", &vars(&[("X", "ok")])).unwrap(),
			"ok"
		);
	}

	// ${VAR?msg}

	#[test]
	fn error_if_unset_when_unset() {
		assert!(substitute("${X?required}", &vars(&[])).is_err());
	}

	#[test]
	fn error_if_unset_when_empty_returns_empty() {
		assert_eq!(
			substitute("${X?required}", &vars(&[("X", "")])).unwrap(),
			""
		);
	}

	// Nested interpolation inside modifier values (compose-spec allows nesting).

	#[test]
	fn nested_default_is_interpolated() {
		// ${FOO:-${BAR}} → BAR's value when FOO is unset.
		assert_eq!(
			substitute("${FOO:-${BAR}}", &vars(&[("BAR", "b")])).unwrap(),
			"b"
		);
	}

	#[test]
	fn nested_chained_default_falls_through() {
		// ${FOO:-${BAR:-baz}} → literal baz when both FOO and BAR are unset.
		assert_eq!(
			substitute("${FOO:-${BAR:-baz}}", &vars(&[])).unwrap(),
			"baz"
		);
	}

	#[test]
	fn nested_alt_is_interpolated() {
		// ${FOO:+${BAR}} → BAR's value when FOO is set and non-empty.
		assert_eq!(
			substitute("${FOO:+${BAR}}", &vars(&[("FOO", "x"), ("BAR", "b")])).unwrap(),
			"b"
		);
	}

	#[test]
	fn nested_default_with_trailing_text() {
		// The balanced-brace scan stops at the matching close, leaving following text.
		assert_eq!(
			substitute("${FOO:-${BAR}}/tail", &vars(&[("BAR", "b")])).unwrap(),
			"b/tail"
		);
	}

	// Malformed / pathological references

	#[test]
	fn empty_name_is_error() {
		assert!(substitute("${}", &vars(&[])).is_err());
	}

	#[test]
	fn digit_leading_name_is_error() {
		assert!(substitute("${1BAD}", &vars(&[])).is_err());
	}

	#[test]
	fn unterminated_modifier_is_error() {
		// The missing `}` must error rather than consume the rest of the input.
		assert!(substitute("${TAG:-latest\nmore", &vars(&[])).is_err());
	}

	#[test]
	fn deeply_nested_defaults_error_instead_of_overflowing() {
		// A pathological `${A:-${A:-…}}` chain (all default branches taken, A unset)
		// returns a clean error past the depth cap rather than overflowing the stack.
		let depth = MAX_INTERP_DEPTH + 50;
		let mut s = String::new();
		for _ in 0..depth {
			s.push_str("${A:-");
		}
		s.push('x');
		for _ in 0..depth {
			s.push('}');
		}
		let err = substitute(&s, &vars(&[])).expect_err("over-deep nesting must error");
		assert!(matches!(
			err,
			crate::error::ComposeError::InvalidSubstitution(_)
		));
	}

	#[test]
	fn moderate_nesting_still_resolves() {
		// Well within the cap, nested defaults resolve normally.
		assert_eq!(
			substitute("${A:-${B:-${C:-deep}}}", &vars(&[])).unwrap(),
			"deep"
		);
	}

	// Multiple substitutions in one string

	#[test]
	fn multiple_vars_in_string() {
		let v = vars(&[("A", "hello"), ("B", "world")]);
		assert_eq!(substitute("$A ${B}!", &v).unwrap(), "hello world!");
	}

	// load_dotenv

	#[test]
	fn load_dotenv_strips_double_quoted_value() {
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(dir.path().join(".env"), "FOO=\"bar\"\n").unwrap();
		let map = load_dotenv(dir.path());
		assert_eq!(map.get("FOO").map(|s| s.as_str()), Some("bar"));
	}

	#[test]
	fn load_dotenv_strips_single_quoted_value() {
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(dir.path().join(".env"), "FOO='bar'\n").unwrap();
		let map = load_dotenv(dir.path());
		assert_eq!(map.get("FOO").map(|s| s.as_str()), Some("bar"));
	}

	#[test]
	fn load_dotenv_parses_key_value() {
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(dir.path().join(".env"), "FOO=bar\nBAZ=qux\n").unwrap();
		let map = load_dotenv(dir.path());
		assert_eq!(map.get("FOO").map(|s| s.as_str()), Some("bar"));
		assert_eq!(map.get("BAZ").map(|s| s.as_str()), Some("qux"));
	}

	#[test]
	fn load_dotenv_skips_comments_and_blank_lines() {
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(dir.path().join(".env"), "# comment\n\nFOO=bar\n").unwrap();
		let map = load_dotenv(dir.path());
		assert_eq!(map.len(), 1);
		assert_eq!(map["FOO"], "bar");
	}

	#[test]
	fn load_dotenv_bare_key_is_not_set_to_empty() {
		// A bare key (no `=`) no longer becomes an empty string. In `.env` it
		// resolves from the host, but `load_dotenv` already drops host-present
		// keys (process env wins), so either way a bare key never lands in the map
		// as `""` — it's host-provided for interpolation or absent.
		std::env::set_var("PODUP_DOTENV_ENV_PRESENT", "h");
		std::env::remove_var("PODUP_DOTENV_ENV_ABSENT");
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(
			dir.path().join(".env"),
			"PODUP_DOTENV_ENV_PRESENT\nPODUP_DOTENV_ENV_ABSENT\n",
		)
		.unwrap();
		let map = load_dotenv(dir.path());
		// host-present → dropped (process env wins); host-absent → omitted. Never "".
		assert!(!map.contains_key("PODUP_DOTENV_ENV_PRESENT"));
		assert!(!map.contains_key("PODUP_DOTENV_ENV_ABSENT"));
		std::env::remove_var("PODUP_DOTENV_ENV_PRESENT");
	}

	#[test]
	fn load_dotenv_missing_file_returns_empty() {
		let dir = tempfile::tempdir().unwrap();
		let map = load_dotenv(dir.path());
		assert!(map.is_empty());
	}

	// build_vars_with_env_files

	#[test]
	fn env_file_replaces_dotenv() {
		let dir = tempfile::tempdir().unwrap();
		// Compose v2: an explicit `--env-file` replaces the default `.env`, so the
		// dotenv-only key is absent and the extra file's value wins for a shared key.
		std::fs::write(
			dir.path().join(".env"),
			"FROM_DOTENV=base\nPODUP_TEST_SHARED=dotenv\n",
		)
		.unwrap();
		std::fs::write(
			dir.path().join("extra.env"),
			"FROM_EXTRA=more\nPODUP_TEST_SHARED=extra\n",
		)
		.unwrap();

		let vars =
			build_vars_with_env_files_strict(dir.path(), &["extra.env".to_string()]).unwrap();
		assert_eq!(vars.get("FROM_DOTENV"), None);
		assert_eq!(vars.get("FROM_EXTRA").map(String::as_str), Some("more"));
		assert_eq!(
			vars.get("PODUP_TEST_SHARED").map(String::as_str),
			Some("extra")
		);
	}

	#[test]
	fn later_env_file_wins() {
		let dir = tempfile::tempdir().unwrap();
		// Among several `--env-file`s the last one listed wins.
		std::fs::write(dir.path().join("a.env"), "FROM_A=a\nSHARED=a\n").unwrap();
		std::fs::write(dir.path().join("b.env"), "FROM_B=b\nSHARED=b\n").unwrap();

		let vars = build_vars_with_env_files_strict(
			dir.path(),
			&["a.env".to_string(), "b.env".to_string()],
		)
		.unwrap();
		assert_eq!(vars.get("FROM_A").map(String::as_str), Some("a"));
		assert_eq!(vars.get("FROM_B").map(String::as_str), Some("b"));
		assert_eq!(vars.get("SHARED").map(String::as_str), Some("b"));
	}

	#[test]
	fn process_env_wins_over_env_file() {
		let dir = tempfile::tempdir().unwrap();
		std::env::set_var("PODUP_ENVFILE_PROCESS_WINS", "from-process");
		std::fs::write(
			dir.path().join("x.env"),
			"PODUP_ENVFILE_PROCESS_WINS=from-file\n",
		)
		.unwrap();

		let vars = build_vars_with_env_files_strict(dir.path(), &["x.env".to_string()]).unwrap();
		assert_eq!(
			vars.get("PODUP_ENVFILE_PROCESS_WINS").map(String::as_str),
			Some("from-process")
		);
		std::env::remove_var("PODUP_ENVFILE_PROCESS_WINS");
	}

	#[test]
	fn no_env_file_loads_dotenv() {
		let dir = tempfile::tempdir().unwrap();
		// With no `--env-file`, `.env` is loaded as before.
		std::fs::write(dir.path().join(".env"), "FROM_DOTENV=base\n").unwrap();
		let vars = build_vars_with_env_files_strict(dir.path(), &[]).unwrap();
		assert_eq!(vars.get("FROM_DOTENV").map(String::as_str), Some("base"));
	}

	#[test]
	fn strict_build_vars_errors_on_missing_extra_file() {
		let dir = tempfile::tempdir().unwrap();
		// An explicitly-passed `--env-file` that does not exist is a hard error
		// (docker compose parity), not a silent fall-back to defaults.
		let err =
			build_vars_with_env_files_strict(dir.path(), &["absent.env".to_string()]).unwrap_err();
		assert!(
			matches!(err, crate::error::ComposeError::EnvFile(_)),
			"expected EnvFile error, got {err:?}"
		);
		assert!(err.to_string().contains("env file not found"));
	}

	#[test]
	fn strict_build_vars_errors_on_unterminated_quote() {
		let dir = tempfile::tempdir().unwrap();
		std::fs::write(dir.path().join("bad.env"), "A=\"oops\nB=keep\n").unwrap();
		let err =
			build_vars_with_env_files_strict(dir.path(), &["bad.env".to_string()]).unwrap_err();
		assert!(matches!(err, crate::error::ComposeError::EnvFile(_)));
	}

	#[test]
	fn lenient_build_vars_skips_missing_extra_file() {
		let dir = tempfile::tempdir().unwrap();
		// The backward-compatible shim never errors: a missing extra file is
		// silently skipped rather than failing.
		let vars = build_vars_with_env_files(dir.path(), &["absent.env".to_string()]);
		assert!(!vars.contains_key("FROM_EXTRA"));
	}

	#[test]
	fn first_disallowed_control_char_allows_tab_newline_cr() {
		// Legitimate dotenv escapes / multi-line values must pass.
		assert_eq!(first_disallowed_control_char("plain value"), None);
		assert_eq!(first_disallowed_control_char("a\tb\nc\rd"), None);
		// NUL, ESC and other C0/C1 controls are rejected.
		assert_eq!(first_disallowed_control_char("a\0b"), Some('\0'));
		assert_eq!(first_disallowed_control_char("x\x1by"), Some('\x1b'));
	}

	#[test]
	fn strict_build_vars_errors_on_control_char_value_naming_file_and_key() {
		let dir = tempfile::tempdir().unwrap();
		// A NUL in an env-file value is rejected at load time, before any compose
		// parse, with an error that names the originating env file and key — not a
		// misattributed parse offset into the post-substitution document (#885).
		std::fs::write(dir.path().join("bad.env"), "SECRET=ab\0cd\n").unwrap();
		let err =
			build_vars_with_env_files_strict(dir.path(), &["bad.env".to_string()]).unwrap_err();
		assert!(
			matches!(err, crate::error::ComposeError::EnvFile(_)),
			"expected EnvFile error, got {err:?}"
		);
		let msg = err.to_string();
		assert!(msg.contains("bad.env"), "names the env file: {msg}");
		assert!(msg.contains("SECRET"), "names the offending key: {msg}");
		assert!(
			msg.contains("control"),
			"explains the control-char cause: {msg}"
		);
	}

	#[test]
	fn strict_build_vars_allows_multiline_and_tab_values() {
		let dir = tempfile::tempdir().unwrap();
		// A multi-line quoted value (real newline) and a `\t` escape are legitimate
		// and must not be rejected by the control-char guard.
		std::fs::write(
			dir.path().join("ok.env"),
			"MULTI=\"line one\nline two\"\nTABBED=\"a\\tb\"\n",
		)
		.unwrap();
		let vars = build_vars_with_env_files_strict(dir.path(), &["ok.env".to_string()]).unwrap();
		assert_eq!(
			vars.get("MULTI").map(String::as_str),
			Some("line one\nline two")
		);
		assert_eq!(vars.get("TABBED").map(String::as_str), Some("a\tb"));
	}
}