copyTemplate method

Future<void> copyTemplate({
  1. required String sourceDir,
  2. required String targetDir,
  3. required Map<String, String> variables,
  4. Map<String, bool>? conditions,
  5. Map<String, List<Map<String, String>>>? lists,
})

Implementation

Future<void> copyTemplate({
  required String sourceDir,
  required String targetDir,
  required Map<String, String> variables,
  Map<String, bool>? conditions,
  Map<String, List<Map<String, String>>>? lists,
}) async {
  final source = Directory(sourceDir);
  if (!source.existsSync()) {
    throw Exception('Template directory not found: $sourceDir');
  }

  final target = Directory(targetDir);
  if (!target.existsSync()) {
    target.createSync(recursive: true);
  }

  await for (final entity in source.list(
    recursive: true,
    followLinks: false,
  )) {
    var relativePath = entity.path.substring(sourceDir.length + 1);

    variables.forEach((key, value) {
      relativePath = relativePath.replaceAll('{{$key}}', value);
    });

    final targetPath = '$targetDir${Platform.pathSeparator}$relativePath';

    if (entity is Directory) {
      Directory(targetPath).createSync(recursive: true);
    } else if (entity is File) {
      final file = entity;
      if (_isTextFile(file.path)) {
        var content = await file.readAsString();
        content = renderContent(
          content,
          variables,
          conditions: conditions,
          lists: lists,
        );
        await File(targetPath).writeAsString(content);
      } else {
        await file.copy(targetPath);
      }
    }
  }
}