linkSwiftPlugin function

void linkSwiftPlugin(
  1. String pluginName,
  2. List<Map<String, String>> modules, {
  3. String baseDir = '.',
})

Implementation

void linkSwiftPlugin(String pluginName, List<Map<String, String>> modules, {String baseDir = '.'}) {
  final iosDir = Directory(p.join(baseDir, 'ios'));
  if (!iosDir.existsSync()) return;
  final pluginFiles = iosDir
      .listSync(recursive: true, followLinks: false)
      .whereType<File>()
      .where((f) => !f.path.contains('.symlinks'))
      .where((f) => f.path.endsWith('Plugin.swift'))
      .toList();
  if (pluginFiles.isEmpty) return;
  final pluginFile = pluginFiles.first;
  var content = pluginFile.readAsStringSync();
  bool modified = false;
  for (final m in modules) {
    final name = m['module']!;
    final lib = (m['lib'] ?? name.toLowerCase()).replaceAll('-', '_');
    final reg = '${name}Registry';
    final impl = name.endsWith('Module') ? '${name}Impl' : '${name}ModuleImpl';

    // ── 1. Ensure import is present ─────────────────────────────────────────
    final importLine = 'import nitro_${lib}_module';
    if (!content.contains(importLine)) {
      final importMatches = RegExp(r'^import .+$', multiLine: true).allMatches(content);
      if (importMatches.isNotEmpty) {
        final lastImport = importMatches.last;
        content = content.replaceRange(lastImport.end, lastImport.end, '\n$importLine');
      } else {
        content = '$importLine\n\n$content';
      }
      modified = true;
    }

    // ── 2. Ensure register() call is present ────────────────────────────────
    if (!content.contains('$reg.register')) {
      final match = RegExp(r'\w+Registry\.register\(.*?\)\)').allMatches(content);
      if (match.isNotEmpty) {
        content = content.replaceFirst(match.last.group(0)!, '${match.last.group(0)!}\n        $reg.register($impl())');
        modified = true;
      } else {
        content = content.replaceFirst(
          'public static func register(with registrar: FlutterPluginRegistrar) {',
          'public static func register(with registrar: FlutterPluginRegistrar) {\n        $reg.register($impl())',
        );
        modified = true;
      }
    }
  }
  if (modified) pluginFile.writeAsStringSync(content);
}