parseInput method
Parses the input for the various code and description segments, and returns a set of template injections in the order found.
Implementation
List<TemplateInjection> parseInput(CodeSample sample) {
bool inCodeBlock = false;
final List<SourceLine> description = <SourceLine>[];
final List<TemplateInjection> components = <TemplateInjection>[];
String? language;
final RegExp codeStartEnd =
RegExp(r'^\s*```(?<language>[-\w]+|[-\w]+ (?<section>[-\w]+))?\s*$');
for (final SourceLine line in sample.input) {
final RegExpMatch? match = codeStartEnd.firstMatch(line.text);
if (match != null) {
// If we saw the start or end of a code block
inCodeBlock = !inCodeBlock;
if (match.namedGroup('language') != null) {
language = match[1];
if (match.namedGroup('section') != null) {
components.add(TemplateInjection(
'code-${match.namedGroup('section')}', <SourceLine>[],
language: language!));
} else {
components.add(
TemplateInjection('code', <SourceLine>[], language: language!));
}
} else {
language = null;
}
continue;
}
if (!inCodeBlock) {
description.add(line);
} else {
assert(language != null);
components.last.contents.add(line);
}
}
final List<String> descriptionLines = <String>[];
bool lastWasWhitespace = false;
for (final String line in description
.map<String>((SourceLine line) => line.text.trimRight())) {
final bool onlyWhitespace = line.trim().isEmpty;
if (onlyWhitespace && descriptionLines.isEmpty) {
// Don't add whitespace lines until we see something without whitespace.
lastWasWhitespace = onlyWhitespace;
continue;
}
if (onlyWhitespace && lastWasWhitespace) {
// Don't add more than one whitespace line in a row.
continue;
}
descriptionLines.add(line);
lastWasWhitespace = onlyWhitespace;
}
sample.description = descriptionLines.join('\n').trimRight();
sample.parts = <TemplateInjection>[
if (sample is SnippetSample)
TemplateInjection('#assumptions', sample.assumptions),
...components,
];
return sample.parts;
}