Skip to content

Commit 0099ae1

Browse files
authored
[go_router_builder] Report duplicate route paths at build time (flutter#12399)
Adds build-time detection of routes that resolve to the same URL pattern. `go_router` matches the first route that fits, so a duplicated path silently makes the later route's page unreachable, and `LaterRoute().go(context)` navigates you to `EarlierRoute`'s page instead. Today nothing surfaces that until you run into the issue at runtime. Reported as a warning by default, and new `duplicate_route_paths` builder option accepts `warning` (the default), `error`, and `ignore`, so teams whose duplicates are mistakes can fail the build instead. **Before**, `go_router_builder`'s own example app built clean despite two duplicate registrations: ``` $ dart run build_runner build [INFO] Succeeded after 14s with 36 outputs ``` **After**: ``` $ dart run build_runner build W go_router_builder on lib/all_types.dart: Duplicate route path detected: DoubleRoute is declared more than once at "double-route/:requiredDoubleField". ``` That duplicate was real. `DoubleRoute` had been registered twice since flutter/packages#2395 (2022) and `DoubleExtensionRoute` since flutter/packages#9458 (2025). Both were unreachable, and this PR removes them. The only change to the generated output is the dead route entries. What competes for a URL namespace: - Sibling routes, with path parameters normalized, so `product/:id` and `product/:productId` are one pattern. - Routes inside shell routes and `StatefulShellRoute` branches, since those own no path of their own and their children compete with the routes around them. - Relative routes, which own their path like any other route, so `/home/details/edit` and `/home/edit` stay distinct. - Routes from separate annotations, since the generated `$appRoutes` collects them into one list. Scope is the library, `part` files included. **Testing:** five new golden inputs in `test_inputs/` cover sibling duplicates, parameter-name-only differences, `StatefulShellRoute` branches, relative routes, cross-annotation duplicates, and the sound same-class grouping case. The golden harness gained two optional companion files per input, documented in the README: `<name>.dart.options` supplies JSON builder options so each severity is exercised through the real option-parsing path, and `<name>.dart.warnings` asserts logged warnings, with an empty file asserting silence. Fixes flutter#190741 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 4ca43c3 commit 0099ae1

57 files changed

Lines changed: 1290 additions & 43 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/go_router_builder/CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
## 4.5.0
2+
3+
- Detects routes that resolve to the same URL pattern. Routes are compared by
4+
the whole URL each one resolves to, so a collision is caught wherever the two
5+
routes sit in the route tree, including across shell routes and
6+
`StatefulShellRoute` branches, between relative routes, and between separate
7+
annotations in one library. Paths that differ only in a parameter name, or
8+
only in casing where the earlier route sets `caseSensitive: false`, count as
9+
the same pattern. These are reported as build warnings by default. The new
10+
`duplicate_route_paths` builder option raises them to build errors with
11+
`error`, or silences them with `ignore`.
12+
113
## 4.4.1
214

315
* Adds support for analyzer 14.

‎packages/go_router_builder/README.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,49 @@ dart run build_runner build
4242
Read more about using
4343
[`build_runner` on pub.dev](https://pub.dev/packages/build_runner).
4444

45+
### Builder options
46+
47+
#### `duplicate_route_paths`
48+
49+
When two routes resolve to the same URL, `go_router` matches the first and the
50+
second becomes unreachable. Navigating to the second one's `location` shows the
51+
first one's page. The builder warns about this at build time.
52+
53+
Routes are compared by the URL they resolve to, not by the path they declare, so
54+
depth in the route tree does not matter. A route at `section/detail` collides with
55+
a route at `section` holding a child at `detail`. Parameter names are ignored, so
56+
`product/:id` and `product/:productId` are the same URL, though a parameter's
57+
regex constraint still counts, so `product/:id(\d+)` and `product/:id(\w+)` are
58+
not. Casing is ignored when the earlier route sets `caseSensitive: false`, since
59+
it then matches any casing.
60+
61+
The whole library is compared, `part` files included. Shell routes and
62+
`StatefulShellRoute` branches contribute nothing to the URLs beneath them.
63+
64+
Use `build.yaml` to change what a duplicate does:
65+
66+
```yaml
67+
targets:
68+
$default:
69+
builders:
70+
go_router_builder:
71+
options:
72+
duplicate_route_paths: error
73+
```
74+
75+
Accepted values are `warning` (the default), `error`, and `ignore`.
76+
77+
Warning is the default because some duplicates work. Matching backtracks, so
78+
naming one route class twice at the same path, each declaration carrying
79+
different children, is fine. Both resolve to the same class and every child stays
80+
reachable, which makes it a way to group children by feature. The builder still
81+
warns, because it cannot tell that from a mistake, so use `ignore` if you write
82+
it deliberately. Their children are a different story: a child path repeated
83+
across the two declarations is a genuine collision and is reported on its own.
84+
85+
`error` applies to the whole package with no per-route exception, so it fails on
86+
the deliberate grouping too.
87+
4588
## Migration Guides
4689
- [Migrating to 4.0.0](https://flutter.dev/go/go-router-builder-v4-breaking-changes).
4790

@@ -505,4 +548,13 @@ Relative routing methods are not idempotent and will cause an error when the rel
505548

506549
To run unit tests, run command `dart tool/run_tests.dart` from `packages/go_router_builder/`.
507550

551+
Each `.dart` file in `test_inputs/` is a test case, paired with a `.expect` file
552+
holding either the generated output or the error message the builder must
553+
produce. Two optional companion files tune a case:
554+
555+
* `<name>.dart.options` holds a JSON map of builder options, matching what
556+
`build.yaml` would pass to the builder.
557+
* `<name>.dart.warnings` holds the warnings the builder must log, one per line.
558+
An empty file asserts that the builder logs nothing.
559+
508560
To run tests in examples, run `flutter test` from `packages/go_router_builder/example`.

‎packages/go_router_builder/example/lib/all_extension_types.dart‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ part 'all_extension_types.g.dart';
2626
),
2727
TypedGoRoute<IntExtensionRoute>(path: 'int-route/:requiredIntField'),
2828
TypedGoRoute<NumExtensionRoute>(path: 'num-route/:requiredNumField'),
29-
TypedGoRoute<DoubleExtensionRoute>(
30-
path: 'double-route/:requiredDoubleField',
31-
),
3229
TypedGoRoute<EnumExtensionRoute>(path: 'enum-route/:requiredEnumField'),
3330
TypedGoRoute<EnhancedEnumExtensionRoute>(
3431
path: 'enhanced-enum-route/:requiredEnumField',

‎packages/go_router_builder/example/lib/all_extension_types.g.dart‎

Lines changed: 0 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/go_router_builder/example/lib/all_types.dart‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ part 'all_types.g.dart';
2020
TypedGoRoute<DoubleRoute>(path: 'double-route/:requiredDoubleField'),
2121
TypedGoRoute<IntRoute>(path: 'int-route/:requiredIntField'),
2222
TypedGoRoute<NumRoute>(path: 'num-route/:requiredNumField'),
23-
TypedGoRoute<DoubleRoute>(path: 'double-route/:requiredDoubleField'),
2423
TypedGoRoute<EnumRoute>(path: 'enum-route/:requiredEnumField'),
2524
TypedGoRoute<EnhancedEnumRoute>(
2625
path: 'enhanced-enum-route/:requiredEnumField',

‎packages/go_router_builder/example/lib/all_types.g.dart‎

Lines changed: 0 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/go_router_builder/lib/go_router_builder.dart‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,13 @@ library go_router_builder;
1515
import 'package:build/build.dart';
1616
import 'package:source_gen/source_gen.dart';
1717

18+
import 'src/duplicate_path_severity.dart';
1819
import 'src/go_router_generator.dart';
1920

2021
/// Supports `package:build_runner` creation and configuration of
2122
/// `go_router`.
2223
///
2324
/// Not meant to be invoked by hand-authored code.
24-
Builder goRouterBuilder(BuilderOptions options) =>
25-
SharedPartBuilder(const <Generator>[GoRouterGenerator()], 'go_router');
25+
Builder goRouterBuilder(BuilderOptions options) => SharedPartBuilder(<Generator>[
26+
GoRouterGenerator(duplicatePathSeverity: duplicatePathSeverityFromOptions(options)),
27+
], 'go_router');
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:build/build.dart';
6+
import 'package:collection/collection.dart';
7+
8+
/// The `build.yaml` option that selects a [DuplicatePathSeverity].
9+
const String duplicateRoutePathsOption = 'duplicate_route_paths';
10+
11+
/// How the builder reports sibling routes that resolve to the same URL pattern.
12+
enum DuplicatePathSeverity {
13+
/// Duplicate paths are not reported at all.
14+
ignore,
15+
16+
/// Duplicate paths are reported as build warnings.
17+
///
18+
/// Code is still generated for every route. This is the default, because a
19+
/// duplicate path is legal at runtime and is not always dead code.
20+
///
21+
/// `go_router` tries sibling routes in declaration order and takes the first
22+
/// one that matches the whole URL. So when two different route classes share
23+
/// a path, navigating to the second class's location lands on the first
24+
/// class's page, which is almost always a mistake. But matching backtracks:
25+
/// when a route matches only a prefix and none of its children complete the
26+
/// URL, matching moves on to the next sibling. Declaring one route class
27+
/// twice with different children is therefore sound, and is one way to group
28+
/// children by feature area. Both shapes are reported, since the builder
29+
/// cannot tell a deliberate grouping from an accidental duplicate.
30+
warning,
31+
32+
/// Duplicate paths fail the build.
33+
error,
34+
}
35+
36+
/// Reads the [DuplicatePathSeverity] from `build.yaml` builder [options].
37+
///
38+
/// Defaults to [DuplicatePathSeverity.warning] when the option is absent.
39+
DuplicatePathSeverity duplicatePathSeverityFromOptions(BuilderOptions options) {
40+
final Object? value = options.config[duplicateRoutePathsOption];
41+
if (value == null) {
42+
return DuplicatePathSeverity.warning;
43+
}
44+
final DuplicatePathSeverity? severity = DuplicatePathSeverity.values.firstWhereOrNull(
45+
(DuplicatePathSeverity severity) => severity.name == value,
46+
);
47+
if (severity == null) {
48+
throw ArgumentError.value(
49+
value,
50+
duplicateRoutePathsOption,
51+
'Must be one of '
52+
'${DuplicatePathSeverity.values.map((DuplicatePathSeverity e) => e.name).join(', ')}',
53+
);
54+
}
55+
return severity;
56+
}

‎packages/go_router_builder/lib/src/go_router_generator.dart‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import 'package:analyzer/dart/element/type.dart';
99
import 'package:build/build.dart';
1010
import 'package:source_gen/source_gen.dart';
1111

12+
import 'duplicate_path_severity.dart';
1213
import 'route_config.dart';
1314
import 'type_helpers.dart';
1415

@@ -25,7 +26,10 @@ const Map<String, String> _annotations = <String, String>{
2526
/// A [Generator] for classes annotated with a typed go route annotation.
2627
class GoRouterGenerator extends Generator {
2728
/// Creates a new instance of [GoRouterGenerator].
28-
const GoRouterGenerator();
29+
const GoRouterGenerator({this.duplicatePathSeverity = DuplicatePathSeverity.warning});
30+
31+
/// How sibling routes that resolve to the same URL pattern are reported.
32+
final DuplicatePathSeverity duplicatePathSeverity;
2933

3034
TypeChecker get _typeChecker => TypeChecker.any(
3135
_annotations.keys.map((String annotation) => TypeChecker.fromUrl('$_routeDataUrl#$annotation')),
@@ -57,17 +61,26 @@ ${getters.map((String e) => "$e,").join('\n')}
5761
/// This public method is for testing purposes and should not be called
5862
/// directly.
5963
void generateForAnnotation(LibraryReader library, Set<String> values, Set<String> getters) {
64+
// Every annotation in the library contributes a top-level route to the
65+
// generated `$appRoutes`, so they all have to be built before their paths
66+
// can be compared against each other.
67+
final configs = <RouteBaseConfig>[];
6068
for (final AnnotatedElement annotatedElement in library.annotatedWith(_typeChecker)) {
61-
final InfoIterable generatedValue = _generateForAnnotatedElement(
62-
annotatedElement.element,
63-
annotatedElement.annotation,
69+
configs.add(
70+
_configForAnnotatedElement(annotatedElement.element, annotatedElement.annotation),
6471
);
72+
}
73+
74+
reportDuplicateRoutePaths(configs, duplicatePathSeverity);
75+
76+
for (final config in configs) {
77+
final InfoIterable generatedValue = config.generateMembers();
6578
getters.add(generatedValue.routeGetterName);
6679
values.addAll(generatedValue.members);
6780
}
6881
}
6982

70-
InfoIterable _generateForAnnotatedElement(Element element, ConstantReader annotation) {
83+
RouteBaseConfig _configForAnnotatedElement(Element element, ConstantReader annotation) {
7184
final String typedAnnotation = withoutNullability(
7285
annotation.objectValue.type!.getDisplayString(),
7386
);
@@ -89,6 +102,6 @@ ${getters.map((String e) => "$e,").join('\n')}
89102
);
90103
}
91104

92-
return RouteBaseConfig.fromAnnotation(annotation, element).generateMembers();
105+
return RouteBaseConfig.fromAnnotation(annotation, element);
93106
}
94107
}

‎packages/go_router_builder/lib/src/path_utils.dart‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,21 @@ Set<String> pathParametersFromPattern(String pattern) => <String>{
1818
for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) match[1]!,
1919
};
2020

21+
/// Replaces the parameter names in a [pattern] with a placeholder, so that
22+
/// patterns differing only in those names compare as equal.
23+
///
24+
/// A parameter's regex constraint is kept, since it changes which URLs the
25+
/// pattern matches.
26+
///
27+
/// For example:
28+
///
29+
/// ```dart
30+
/// normalizePathParameters('item/:id'); // 'item/:_'
31+
/// normalizePathParameters(r'item/:id(\d+)'); // r'item/:_(\d+)'
32+
/// ```
33+
String normalizePathParameters(String pattern) =>
34+
pattern.replaceAllMapped(_parameterRegExp, (Match match) => ':_${match[2] ?? ''}');
35+
2136
/// Reconstructs the full path from a [pattern] and path parameters.
2237
///
2338
/// For example:

0 commit comments

Comments
 (0)