parseDotenv function
Parses KEY=value lines. Blank lines, # comment lines, and a #
comment after an unquoted value are skipped. An export prefix is
allowed, and values may be wrapped in single or double quotes.
Implementation
Map<String, String> parseDotenv(String content) {
final result = <String, String>{};
for (final rawLine in const LineSplitter().convert(content)) {
var line = rawLine.trim();
if (line.isEmpty || line.startsWith('#')) {
continue;
}
if (line.startsWith('export ')) {
line = line.substring('export '.length).trimLeft();
}
final equals = line.indexOf('=');
if (equals <= 0) {
continue;
}
final key = line.substring(0, equals).trim();
var value = line.substring(equals + 1).trim();
final quoted =
value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")));
if (quoted) {
value = value.substring(1, value.length - 1);
} else {
final comment = value.indexOf(' #');
if (comment != -1) {
value = value.substring(0, comment).trimRight();
}
}
result[key] = value;
}
return result;
}