tomSecretsWithBlock function
text with its block's lines replaced by block (marks added), or the
block removed when block is null. A new block goes at the top when
atTop, else at the end; an existing one stays where it is. Every line
outside the block is kept as it was (line ends as text has them).
Implementation
String tomSecretsWithBlock(
String text,
List<String>? block, {
bool atTop = false,
}) {
final eol = text.contains('\r\n') ? '\r\n' : '\n';
final lines = text.isEmpty ? <String>[] : text.split(RegExp(r'\r?\n'));
// A final line end makes an empty last element.
final endsWithEol = lines.isNotEmpty && lines.last.isEmpty;
if (endsWithEol) lines.removeLast();
final begin = lines.indexWhere((l) => l.trim() == tomSecretsBlockBegin);
final end = begin < 0
? -1
: lines.indexWhere((l) => l.trim() == tomSecretsBlockEnd, begin);
final marked = block == null
? const <String>[]
: [tomSecretsBlockBegin, ...block, tomSecretsBlockEnd];
if (begin >= 0 && end >= 0) {
lines.replaceRange(begin, end + 1, marked);
} else if (block != null) {
if (atTop) {
lines.insertAll(0, [...marked, '']);
} else {
if (lines.isNotEmpty && lines.last.trim().isNotEmpty) lines.add('');
lines.addAll(marked);
}
}
// A removed block takes the blank line that set it apart with it.
if (block == null && begin >= 0 && end >= 0) {
final after = begin < lines.length ? lines[begin] : null;
final before = begin > 0 ? lines[begin - 1] : null;
if (after != null &&
after.trim().isEmpty &&
(before == null || before.trim().isEmpty)) {
lines.removeAt(begin);
} else if (before != null &&
before.trim().isEmpty &&
(after == null || after.trim().isEmpty)) {
lines.removeAt(begin - 1);
}
}
if (lines.isEmpty) return '';
return '${lines.join(eol)}$eol';
}