parse static method

Map<String, String> parse(
  1. String contents, {
  2. Map<String, String> known = const <String, String>{},
  3. bool expand = false,
})

Reads the text of a .env file.

  • KEY=value, one per line. Lines that start with # are comments. export KEY=value is read like KEY=value.
  • KEY=value # note: a # after a space starts a comment.
  • KEY="a # b": quotes (", ' or `) keep the value as it is, also a #. The quotes are removed.
  • KEY=abc#def stays abc#def and KEY=#fff stays #fff (no space before the #).
  • One line is one value. A quoted value can not go over more lines. With expand, write a new line as \n inside " quotes.

With expand (CoreFlags.envExpand):

  • ${OTHER} is the value of OTHER, in an unquoted or a " value. A real environment variable wins, then a key above this line (or in known). An unknown name stays as it is: ${OTHER}.
  • In a " value, \n, \t, \", \\ and \$ become a new line, a tab, ", \ and $. A ' or ` value stays raw.

Implementation

static Map<String, String> parse(
  String contents, {
  Map<String, String> known = const <String, String>{},
  bool expand = false,
}) {
  Map<String, String> data = <String, String>{};
  String? lookup(String name) =>
      Platform.environment[name] ?? data[name] ?? known[name];
  for (String line in contents.split('\n')) {
    String text = line.trim();
    if (text.isEmpty || text.startsWith('#')) continue;
    text = text.replaceFirst(_export, '');
    int equal = text.indexOf('=');
    if (equal < 1) continue;
    data[text.substring(0, equal).trim()] = _value(
      text.substring(equal + 1),
      expand ? lookup : null,
    );
  }
  return data;
}