addEnvGetter method
add getter (like String get dbName => 'db/dox.sqlite';, with
optional /// lines above it) to the AppEnv class of
lib/config/env.dart, when the class has no member with the same
name. Run buildRunner after it.
When the file or the class is not found, or its braces do not match, it changes nothing, adds a hint to the summary and sets ok to false.
Implementation
void addEnvGetter(String getter) {
String path = 'lib/config/env.dart';
RegExpMatch? named = RegExp(r'\bget\s+(\w+)\s*(=>|;)').firstMatch(getter);
if (named == null) throw ArgumentError('Not a getter: $getter');
String name = named.group(1)!;
File file = _file(path);
String text = file.existsSync() ? file.readAsStringSync() : '';
RegExpMatch? head = RegExp(
r'^abstract\s+class\s+AppEnv\b[^{;]*\{',
multiLine: true,
).firstMatch(text);
int end = head == null ? -1 : _closingBrace(text, head.end);
if (end == -1) {
note(
'failed $name: add `${getter.split('\n').last.trim()}` to AppEnv in $path',
);
ok = false;
return;
}
String body = text.substring(head!.end, end);
if (RegExp('\\b$name\\b').hasMatch(body)) {
note('skipped $name in AppEnv (already there)');
return;
}
String before = text.substring(0, end).trimRight();
String gap = before.endsWith('{') ? '\n' : '\n\n';
file.writeAsStringSync('$before$gap $getter\n${text.substring(end)}');
note('added $name to AppEnv in $path');
}