Fix crash when checking code with bad import (#3392)
Closes #1731
If an import attempts to use string interpolation it will have a null
`stringValue` in the analyzer. Fix the resulting crash trying to parse
the null string.
Refactor to `Uri.tryParse` instead of catching the `FormatException`.
diff --git a/lib/src/validator/strict_dependencies.dart b/lib/src/validator/strict_dependencies.dart
index 84f7a09..ea481f5 100644
--- a/lib/src/validator/strict_dependencies.dart
+++ b/lib/src/validator/strict_dependencies.dart
@@ -42,11 +42,9 @@
for (var directive in directives) {
Uri? url;
- try {
- url = Uri.parse(directive.uri.stringValue!);
- } on FormatException catch (_) {
- // Ignore a format exception. [url] will be null, and we'll emit an
- // "Invalid URL" warning below.
+ final uriString = directive.uri.stringValue;
+ if (uriString != null) {
+ url = Uri.tryParse(uriString);
}
// If the URL could not be parsed or it is a `package:` URL AND there
diff --git a/test/validator/strict_dependencies_test.dart b/test/validator/strict_dependencies_test.dart
index a6b0833..18ee9c7 100644
--- a/test/validator/strict_dependencies_test.dart
+++ b/test/validator/strict_dependencies_test.dart
@@ -183,6 +183,14 @@
group('should consider a package invalid if it', () {
setUp(d.validPackage.create);
+ test('has an invalid String value', () async {
+ await d.file(path.join(appPath, 'lib', 'library.dart'), r'''
+ import 'package:$bad';
+ ''').create();
+
+ await expectValidation(strictDeps, errors: [matches('Invalid URL.')]);
+ });
+
test('does not declare an "import" as a dependency', () async {
await d.file(path.join(appPath, 'lib', 'library.dart'), r'''
import 'package:silly_monkey/silly_monkey.dart';