checkRoutes function

DoctorCheck checkRoutes({
  1. String projectRoot = '.',
})

Pages that declare a route path but aren't added to a router.

Implementation

DoctorCheck checkRoutes({String projectRoot = '.'}) {
  final _Project p = _Project(projectRoot);
  final Map<String, String> pages = {};
  p.dart(_pagesFolder).forEach((String path, String source) {
    for (final String page in _routableClasses(source)) {
      pages[page] = path;
    }
  });
  if (pages.isEmpty) {
    return const DoctorCheck('Routes', DoctorStatus.skipped, 'No pages yet');
  }

  final Set<String> routed = {
    for (final String source in p.dart('lib/routes').values)
      for (final RegExpMatch match in RegExp(
        r'\.add\s*\(\s*([A-Z]\w*)\s*\.\s*path\b',
      ).allMatches(source))
        match.group(1)!,
  };
  final List<String> unrouted = [
    for (final String page in pages.keys)
      if (!routed.contains(page)) page,
  ]..sort((String a, String b) => pages[a]!.compareTo(pages[b]!));

  if (unrouted.isEmpty) {
    return DoctorCheck(
      'Routes',
      DoctorStatus.ok,
      pages.length == 1
          ? 'The page has a route'
          : 'All ${pages.length} pages have a route',
    );
  }
  return DoctorCheck(
    'Routes',
    DoctorStatus.problem,
    unrouted.length == 1
        ? '1 page has no route: ${pages[unrouted.single]}'
        : '${unrouted.length} pages have no route',
    details: unrouted.length == 1
        ? const []
        : [for (final String page in unrouted) pages[page]!],
    fixes: [
      for (final String page in unrouted)
        'add router.add($page.path); to $routerPath',
    ],
  );
}