insertRegistryEntry function
Adds '<key>': <value>, to the Map<String, <type>> <variable>
declared in file.
Handles the release-guarded form Metro generates
(kReleaseMode ? const {} : {...}) as well as a plain map literal.
Returns null when key is already in file or there is no such map.
Implementation
String? insertRegistryEntry(
String file, {
required String variable,
required String type,
required String key,
required String value,
}) {
if (file.contains("'$key'") || file.contains('"$key"')) return null;
final String declaration = 'final Map<String, $type> $variable = ';
final RegExpMatch? guarded = _guardedMap(variable, type).firstMatch(file);
if (guarded != null) {
final String entries = _entries(
guarded.group(1)!,
).map((String line) => ' $line\n').join();
return file.replaceRange(
guarded.start,
guarded.end,
'${declaration}kReleaseMode\n'
' ? const {}\n'
' : {\n'
'$entries'
" '$key': $value,\n"
' };',
);
}
final RegExpMatch? plain = _plainMap(variable, type).firstMatch(file);
if (plain == null) return null;
String entries = plain.group(1)!.trimRight();
if (entries.trim().isNotEmpty && !entries.endsWith(',')) entries += ',';
return file.replaceRange(
plain.start,
plain.end,
'$declaration{'
'$entries\n'
" '$key': $value,\n"
'};',
);
}