penv
.env loader for Dart

Advanced Parsing

Part of the Examples. Quoting, escaping, variable expansion, and required-key validation in one file.

Source: example/advanced_example.dart

// Run this example from the package root:
//   dart run example/advanced_example.dart
//
// This example writes a small demo .env file itself so it runs start to
// finish in one shot, then loads it with penvload to show off the
// features added on top of the basic loader in penv_example.dart:
// `export` prefixes, inline comments, escaped characters, ${VAR}
// expansion, typed accessors, required-key validation, and the optional
// (non-throwing) penvloadOrNull.

// print() is fine in example scripts; avoid it in production code instead.
// ignore_for_file: avoid_print

import 'dart:io';

import 'package:penv/penv.dart';

const _demoPath = 'example/.env.advanced';

void main() {
  File(_demoPath).writeAsStringSync('''
# Demonstrates the advanced parsing features of penv.
export API_KEY=demo-key-123
PORT=8080 # inline comments like this are stripped
GREETING="Hello\\nWorld"
BASE_URL=https://example.com
FULL_URL=\${BASE_URL}/api
DEBUG=true
''');

  final env = penvload(_demoPath, required: ['API_KEY', 'BASE_URL']);

  print('Loaded ${env.length} variable(s):');
  env.forEach((key, value) => print('  $key=$value'));

  // Typed accessors save the int.parse(...)/bool-parsing boilerplate.
  print('PORT as int: ${env.getInt('PORT', defaultValue: 3000)}');
  print('DEBUG as bool: ${env.getBool('DEBUG', defaultValue: false)}');

  // FULL_URL referenced ${BASE_URL}, which was defined earlier in the file.
  print('FULL_URL (expanded): ${env['FULL_URL']}');

  // penvloadOrNull returns null instead of throwing for an optional file.
  final overrides = penvloadOrNull('example/.env.missing');
  print('Optional overrides file present: ${overrides != null}');

  File(_demoPath).deleteSync();
}

Run it from the package root:

dart run example/advanced_example.dart