Skip to content

Instantly share code, notes, and snippets.

@venkatd
Created March 10, 2021 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save venkatd/48fd24154de9635678f0ee84111e9c97 to your computer and use it in GitHub Desktop.
Save venkatd/48fd24154de9635678f0ee84111e9c97 to your computer and use it in GitHub Desktop.
import 'dart:io';
import 'package:file/local.dart';
import 'package:glob/glob.dart';
import 'package:path/path.dart' as path;
void main(List<String> args) async {
assert(args.length == 1);
await updateRelativeImportsInPackage(args[0]);
}
Future<void> updateRelativeImportsInPackage(String packagePath) async {
final globPattern = Glob('**.dart');
final libPath = path.join(packagePath, 'lib');
final files = await globPattern
.listFileSystem(
const LocalFileSystem(),
root: libPath,
)
.toList();
for (final file in files) {
final filePath = file.path;
await updateImportsInFile(
filePath,
(ref) {
if (!isImportRelative(ref)) return ref;
return relativeImportToPackageImport(
filePath: filePath,
ref: ref,
libPath: libPath,
);
},
);
}
}
bool isImportRelative(String ref) {
if (ref.startsWith('package:')) return false;
return ref.contains('..');
}
String relativeImportToPackageImport({
required String ref,
required String filePath,
required String libPath,
}) {
assert(isImportRelative(ref));
final fullPath = path.join(path.dirname(filePath), ref);
final libName = path.basename(path.dirname(libPath));
final pathRelativeToLibDir = path.relative(fullPath, from: libPath);
// don't wanna look into why I need to do this replacement of ../ at the start
return 'package:$libName/' + pathRelativeToLibDir.replaceFirst('../', '');
}
final importRegex = RegExp("import '(.+)';");
Future<void> updateImportsInFile(
String filePath, String Function(String) update) {
return updateFileContents(filePath, (code) {
return code.replaceAllMapped(importRegex, (match) {
final importRef = match.group(1)!;
final newImportRef = update(importRef);
return "import '${newImportRef}';";
});
});
}
Future<void> updateFileContents(
String filePath, String Function(String) update) async {
final file = File(filePath);
final fileContents = await file.readAsString();
final newFileContents = update(fileContents);
await file.writeAsString(newFileContents, mode: FileMode.write);
print('UPDATED: $filePath');
// print(newFileContents.split('\n').take(25).join('\n'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment