refactorAndroidPackage function
Refactors the Android package structure for Kotlin source files.
This function updates the package declarations in all .kt files under
android/app/src/main/kotlin to match the new config.androidId, and moves
the files to the corresponding directory structure. It also cleans up empty
directories left behind.
config - The configuration containing the new Android ID.
Implementation
void refactorAndroidPackage(RenameConfig config) {
final kotlinRoot = Directory(
p.join('android', 'app', 'src', 'main', 'kotlin'),
);
if (!kotlinRoot.existsSync()) {
Logger.warn('No Kotlin source directory found');
return;
}
final newPackage = config.androidId;
final newPath = p.joinAll(newPackage.split('.'));
final ktFiles = kotlinRoot
.listSync(recursive: true)
.whereType<File>()
.where((f) => f.path.endsWith('.kt'))
.toList();
for (final file in ktFiles) {
final content = file.readAsStringSync();
final updated = content.replaceFirst(
RegExp(r'^package\s+[\w.]+', multiLine: true),
'package $newPackage',
);
final newFile = File(
p.join(kotlinRoot.path, newPath, p.basename(file.path)),
);
newFile.parent.createSync(recursive: true);
newFile.writeAsStringSync(updated);
if (file.path != newFile.path) {
file.deleteSync();
}
}
_cleanupEmptyDirs(kotlinRoot);
Logger.success('Android Kotlin package path refactored');
}