withEnvFile method

DockerContainer withEnvFile(
  1. String envFile
)

Reads environment variables from a .env-style file and merges them into env.

The file is parsed line by line:

  • Blank lines and lines starting with # are skipped.
  • Each line must contain =; the part before the first = is the key, the rest is the value (both are whitespace-stripped).
  • ${VAR} references in values are expanded using variables already resolved earlier in the same file (same semantics as python-dotenv's dotenv_values()).

Returns this for chaining.

Implementation

DockerContainer withEnvFile(String envFile) {
  final file = File(envFile);
  final resolved = <String, String>{};
  for (final rawLine in file.readAsLinesSync()) {
    final line = rawLine.trim();
    // Skip blank lines and comments
    if (line.isEmpty || line.startsWith('#')) {
      continue;
    }
    final idx = line.indexOf('=');
    if (idx < 0) {
      continue;
    }
    final key = line.substring(0, idx).trim();
    final rawValue = line.substring(idx + 1).trim();
    // Expand ${VAR} references using already-resolved variables (dotenv semantics)
    final value = rawValue.replaceAllMapped(
      RegExp(r'\$\{([^}]+)\}'),
      (m) => resolved[m.group(1)] ?? '',
    );
    resolved[key] = value;
    _env[key] = value;
  }
  return this;
}