relocateDartImports static method

String relocateDartImports({
  1. required String source,
  2. required String fromRelative,
  3. required String toRelative,
})

Rewrites relative Dart imports when a file is copied to a new folder.

Implementation

static String relocateDartImports({
  required String source,
  required String fromRelative,
  required String toRelative,
}) {
  return source.replaceAllMapped(
    RegExp(r'''^(\s*import\s+)(['"])([^'"]+)\2(.*)$''', multiLine: true),
    (match) {
      final uri = match.group(3)!;
      if (uri.startsWith('dart:') ||
          uri.startsWith('package:') ||
          uri.startsWith('http:') ||
          uri.startsWith('https:')) {
        return match.group(0)!;
      }
      final fromDir = p.posix.dirname(fromRelative.replaceAll('\\', '/'));
      final resolved = p.posix.normalize(p.posix.join(fromDir, uri));
      final relocated = posixRelativeImportUri(
        fromFile: toRelative.replaceAll('\\', '/'),
        toFile: resolved,
      );
      return '${match.group(1)}${match.group(2)}$relocated${match.group(2)}${match.group(4)}';
    },
  );
}