addRouteToRouter function

Future<void> addRouteToRouter(
  1. String projectPath,
  2. String pageName,
  3. String pagePath
)

Implementation

Future<void> addRouteToRouter(
  String projectPath,
  String pageName,
  String pagePath,
) async {
  final routerFile = File(p.join(projectPath, 'lib', 'routes', 'app_router.dart'));

  if (!routerFile.existsSync()) {
    print('🛣️  app_router.dart not found. Initializing...');
    await initializeRouter(projectPath);
  }

  String content = routerFile.readAsStringSync();
  final String camelCaseName = toPascalCase(pageName);

  // Clean up path for import
  final String normalizedPath = pagePath.replaceAll(r'\', '/').replaceFirst('lib/', '');
  final String projectName = getProjectName(projectPath);
  final String importStatement = "import 'package:$projectName/$normalizedPath';";

  if (content.contains(importStatement)) {
    print('ℹ️ Route for $camelCaseName already exists in router.');
    return;
  }

  final String routeSnippet = '''
      GoRoute(
        path: '/${pageName.replaceAll('_', '-')}',
        builder: (context, state) => const ${camelCaseName}Page(),
      ),
      // [ROUTE_MARKER]''';

  // Add import at the top (after other imports)
  if (!content.contains(importStatement)) {
    final lines = content.split('\n');
    int lastImportIndex = lines.lastIndexWhere((line) => line.startsWith('import '));
    if (lastImportIndex != -1) {
      lines.insert(lastImportIndex + 1, importStatement);
    } else {
      lines.insert(0, importStatement);
    }
    content = lines.join('\n');
  }

  // Add route at marker
  if (content.contains('// [ROUTE_MARKER]')) {
    content = content.replaceFirst('// [ROUTE_MARKER]', routeSnippet);
  } else if (content.contains('routes: [')) {
    // Fallback if marker is missing but routes list exists
    content = content.replaceFirst('routes: [', 'routes: [\n$routeSnippet');
  } else {
    print('⚠️ Could not find [ROUTE_MARKER] or routes list in app_router.dart. Appending at end.');
    content += "\n// Manually added route for $camelCaseName\n// $routeSnippet";
  }

  safeWriteFile(routerFile.path, content, projectPath: projectPath, overwrite: true);
  print('🛣️  Route added for $pageName in app_router.dart');
}