addEnv method

void addEnv(
  1. String key,
  2. String value
)

add KEY=value to .env.example and .env when the key is not in the file. A key that is there is never changed. A file that is not there is skipped.

Implementation

void addEnv(String key, String value) {
  List<String> added = <String>[];
  List<String> skipped = <String>[];
  RegExp line = RegExp(
    '^[ \\t]*(export[ \\t]+)?${RegExp.escape(key)}[ \\t]*=',
    multiLine: true,
  );
  for (String name in <String>['.env.example', '.env']) {
    File file = _file(name);
    if (!file.existsSync()) continue;
    String text = file.readAsStringSync();
    if (line.hasMatch(text)) {
      skipped.add(name);
      continue;
    }
    if (text.isNotEmpty && !text.endsWith('\n')) text = '$text\n';
    file.writeAsStringSync('$text$key=$value\n');
    added.add(name);
  }
  if (added.isNotEmpty) note('added    $key to ${added.join(', ')}');
  if (skipped.isNotEmpty) {
    note('skipped  $key in ${skipped.join(', ')} (already there)');
  }
  if (added.isEmpty && skipped.isEmpty) {
    note('skipped  $key: there is no .env or .env.example');
  }
}