interpolateTemplate function

String interpolateTemplate(
  1. List<TemplateInjection> injections,
  2. String template,
  3. Map<String, Object?> metadata, {
  4. bool addSectionMarkers = false,
  5. bool addCopyright = false,
})

Injects the injections into the template, while turning the "description" injection into a comment.

Implementation

String interpolateTemplate(
  List<TemplateInjection> injections,
  String template,
  Map<String, Object?> metadata, {
  bool addSectionMarkers = false,
  bool addCopyright = false,
}) {
  String wrapSectionMarker(Iterable<String> contents, {required String name}) {
    if (contents.join().trim().isEmpty) {
      // Skip empty sections.
      return '';
    }
    // We don't wrap some sections, because otherwise they generate invalid files.
    const Set<String> skippedSections = <String>{'element', 'copyright'};
    final bool addMarkers =
        addSectionMarkers && !skippedSections.contains(name);
    final String result = <String>[
      if (addMarkers) sectionArrows(name),
      ...contents,
      if (addMarkers) sectionArrows(name, start: false),
    ].join('\n');
    final RegExp wrappingNewlines = RegExp(r'^\n*(.*)\n*$', dotAll: true);
    return result.replaceAllMapped(
        wrappingNewlines, (Match match) => match.group(1)!);
  }

  return '${addCopyright ? '{{copyright}}\n\n' : ''}$template'
      .replaceAllMapped(RegExp(r'{{([^}]+)}}'), (Match match) {
    final String name = match[1]!;
    final int componentIndex = injections
        .indexWhere((TemplateInjection injection) => injection.name == name);
    if (metadata[name] != null && componentIndex == -1) {
      // If the match isn't found in the injections, then just return the
      // metadata entry.
      return wrapSectionMarker((metadata[name]! as String).split('\n'),
          name: name);
    }
    return wrapSectionMarker(
        componentIndex >= 0
            ? injections[componentIndex].stringContents
            : <String>[],
        name: name);
  }).replaceAll(RegExp(r'\n\n+'), '\n\n');
}