From ea454fab7aad9f1be2de7597c705e7062cb527d6 Mon Sep 17 00:00:00 2001 From: Devon Carew Date: Sun, 12 Feb 2023 21:20:17 -0800 Subject: [PATCH] enable additional lints --- analysis_options.yaml | 3 +++ lib/src/failure.dart | 2 +- lib/src/model/extendable.dart | 6 ++++-- lib/src/model/package_builder.dart | 4 ++-- lib/src/model/package_graph.dart | 16 +++++++-------- lib/src/mustachio/renderer_base.dart | 2 ++ lib/src/package_meta.dart | 2 +- lib/src/tool_runner.dart | 2 +- lib/src/validator.dart | 5 +++-- test/mustachio/renderers_output_test.dart | 24 ++++++++++++++++------- test/src/test_descriptor_utils.dart | 2 +- test/src/utils.dart | 2 +- test/tool_runner_test.dart | 2 +- tool/grind.dart | 6 +++--- tool/mustachio/builder.dart | 2 +- tool/mustachio/codegen_aot_compiler.dart | 1 + tool/subprocess_launcher.dart | 5 +++-- 17 files changed, 53 insertions(+), 33 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 430cdb7362..4f269a57aa 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -19,12 +19,14 @@ linter: - always_declare_return_types - always_put_required_named_parameters_first - avoid_bool_literals_in_conditional_expressions + - avoid_catching_errors - avoid_dynamic_calls - avoid_slow_async_io - avoid_unused_constructor_parameters - directives_ordering - no_adjacent_strings_in_list - omit_local_variable_types + - only_throw_errors - package_api_docs - prefer_asserts_in_initializer_lists - prefer_null_aware_method_calls @@ -35,4 +37,5 @@ linter: - unawaited_futures - unnecessary_lambdas - unnecessary_parenthesis + - unnecessary_statements - use_super_parameters diff --git a/lib/src/failure.dart b/lib/src/failure.dart index fcee30ad2d..010d5d0b98 100644 --- a/lib/src/failure.dart +++ b/lib/src/failure.dart @@ -6,7 +6,7 @@ /// /// An instance of this is returned if dartdoc fails in an expected way (for /// instance, if there is an analysis error in the library). -class DartdocFailure { +class DartdocFailure implements Exception { final String message; DartdocFailure(this.message); diff --git a/lib/src/model/extendable.dart b/lib/src/model/extendable.dart index bb496c6b4f..3a6c6cbd6e 100644 --- a/lib/src/model/extendable.dart +++ b/lib/src/model/extendable.dart @@ -8,8 +8,10 @@ import 'package:dartdoc/src/model/model.dart'; /// extension methods. mixin Extendable on ContainerMember { /// Returns this Extendable from the [Extension] in which it was declared. - Extendable get definingExtension => throw UnimplementedError; + Extendable get definingExtension => + throw UnimplementedError('definingExtension'); @override - Container get canonicalEnclosingContainer => throw UnimplementedError; + Container get canonicalEnclosingContainer => + throw UnimplementedError('canonicalEnclosingContainer'); } diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index 34871bc366..dd7412d523 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -444,8 +444,8 @@ class PubPackageBuilder implements PackageBuilder { .difference(Set.of(knownLibraryNames)) .difference(config.exclude); if (notFound.isNotEmpty) { - throw 'Did not find: [${notFound.join(', ')}] in ' - 'known libraries: [${knownLibraryNames.join(', ')}]'; + throw StateError('Did not find: [${notFound.join(', ')}] in ' + 'known libraries: [${knownLibraryNames.join(', ')}]'); } } // Include directive does not apply to special libraries. diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index 9c33dc97fe..85ff397c83 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -215,20 +215,19 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// /// This mapping must be complete before [initializePackageGraph] is called. @visibleForTesting - final allLibraries = {}; + final Map allLibraries = {}; /// All [ModelElement]s constructed for this package; a superset of /// [_allModelElements]. - final HashMap, ModelElement?> - allConstructedModelElements = - HashMap, ModelElement?>(); + final Map, ModelElement?> + allConstructedModelElements = {}; /// Anything that might be inheritable, place here for later lookup. - final allInheritableElements = - HashMap, Set>(); + final Map, Set> + allInheritableElements = {}; /// A mapping of the list of classes which implement each class. - final _implementors = + final Map> _implementors = LinkedHashMap>( equals: (InheritingContainer a, InheritingContainer b) => a.definingContainer == b.definingContainer, @@ -857,7 +856,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // might not be where the element was defined, which is what's important // for nodoc's semantics. Looking up the defining element just to pull // a context is again, slow. - var globs = config.optionSet['nodoc'].valueAt(file.parent); + var globs = (config.optionSet['nodoc'].valueAt(file.parent) as List) + .cast(); return utils.matchGlobs(globs, fullName); }); } diff --git a/lib/src/mustachio/renderer_base.dart b/lib/src/mustachio/renderer_base.dart index 3e47a7e5d6..e3fadccd74 100644 --- a/lib/src/mustachio/renderer_base.dart +++ b/lib/src/mustachio/renderer_base.dart @@ -189,6 +189,7 @@ abstract class RendererBase { if (property != null) { try { return property.renderVariable(context, property, remainingNames); + // ignore: avoid_catching_errors } on PartialMustachioResolutionError catch (e) { // The error thrown by [Property.renderVariable] does not have all of // the names required for a decent error. We throw a new error here. @@ -199,6 +200,7 @@ abstract class RendererBase { "'$firstName' to a property on $T")); } } + // ignore: avoid_catching_errors } on _MustachioResolutionErrorWithoutSpan catch (e) { throw MustachioResolutionError(node.keySpan.message(e.message)); } diff --git a/lib/src/package_meta.dart b/lib/src/package_meta.dart index 7416de6ec5..585a0fb78b 100644 --- a/lib/src/package_meta.dart +++ b/lib/src/package_meta.dart @@ -310,7 +310,7 @@ class _FilePackageMeta extends PubPackageMeta { late final Map _pubspec = () { var pubspec = dir.getChildAssumingFile('pubspec.yaml'); assert(pubspec.exists); - return loadYaml(pubspec.readAsStringSync()); + return loadYaml(pubspec.readAsStringSync()) as YamlMap; }(); _FilePackageMeta(super.dir, super.resourceProvider); diff --git a/lib/src/tool_runner.dart b/lib/src/tool_runner.dart index 36e177ac04..1db1e912a3 100644 --- a/lib/src/tool_runner.dart +++ b/lib/src/tool_runner.dart @@ -108,7 +108,7 @@ class ToolRunner { 'Stderr output was:\n${result.stderr}\n'); return ''; } else { - return result.stdout; + return result.stdout as String; } } on ProcessException catch (exception) { toolErrorCallback('Failed to run tool "$name" as ' diff --git a/lib/src/validator.dart b/lib/src/validator.dart index 83473794e6..24bf6be30e 100644 --- a/lib/src/validator.dart +++ b/lib/src/validator.dart @@ -153,9 +153,10 @@ class Validator { // The package index isn't supposed to be in the search, so suppress the // warning. found.add(indexPath); - for (Map entry in jsonData) { + for (var entry in jsonData.cast>()) { if (entry.containsKey('href')) { - final entryPath = p.joinAll([_origin, ...p.posix.split(entry['href'])]); + final entryPath = + p.joinAll([_origin, ...p.posix.split(entry['href'] as String)]); if (!_visited.contains(entryPath)) { _warn(PackageWarning.brokenLink, entryPath, _origin, referredFrom: fullPath); diff --git a/test/mustachio/renderers_output_test.dart b/test/mustachio/renderers_output_test.dart index b87d630517..1467834084 100644 --- a/test/mustachio/renderers_output_test.dart +++ b/test/mustachio/renderers_output_test.dart @@ -5,6 +5,7 @@ library dartdoc.dartdoc_test; import 'dart:async'; +import 'dart:io'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/file_system/memory_file_system.dart'; @@ -25,18 +26,27 @@ import 'package:test/test.dart'; Future _generatorContextFromArgv( List argv) async { var optionSet = DartdocOptionRoot.fromOptionGenerators( - 'dartdoc', - [ - createDartdocOptions, - createGeneratorOptions, - ], - pubPackageMetaProvider); + 'dartdoc', + [ + createDartdocOptions, + createGeneratorOptions, + ], + pubPackageMetaProvider, + ); optionSet.parseArguments(argv); return DartdocGeneratorOptionContext.fromDefaultContextLocation( optionSet, pubPackageMetaProvider.resourceProvider); } void main() { + late Directory tempDir; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('render_test'); + }); + + tearDown(() => tempDir.deleteSync(recursive: true)); + test('source code links are visible', () async { var resourceProvider = pubPackageMetaProvider.resourceProvider; var pathContext = resourceProvider.pathContext; @@ -44,7 +54,7 @@ void main() { pathContext.absolute(pathContext.canonicalize('testing/test_package'))); var context = await _generatorContextFromArgv( - ['--input', testPackageDir.path, '--output', 'UNUSED']); + ['--input', testPackageDir.path, '--output', tempDir.path]); var dartdoc = await Dartdoc.fromContext( context, PubPackageBuilder( diff --git a/test/src/test_descriptor_utils.dart b/test/src/test_descriptor_utils.dart index 21418dd487..a8dceb8080 100644 --- a/test/src/test_descriptor_utils.dart +++ b/test/src/test_descriptor_utils.dart @@ -34,7 +34,7 @@ Future createPackage( pubspec ??= buildPubspecText(); final parsedYaml = yaml.loadYaml(pubspec) as Map; final packageName = parsedYaml['name']; - final versionConstraint = (parsedYaml['environment'] as Map)['sdk']; + final versionConstraint = (parsedYaml['environment'] as Map)['sdk'] as String; final languageVersion = RegExp(r'>=(\S*)\.0(-0)? ').firstMatch(versionConstraint)!.group(1); final packagesInfo = StringBuffer('''{ diff --git a/test/src/utils.dart b/test/src/utils.dart index d5598bf94d..7812069186 100644 --- a/test/src/utils.dart +++ b/test/src/utils.dart @@ -194,7 +194,7 @@ homepage: https://github.com/dart-lang var projectsFolder = resourceProvider.getFolder( pathContext.canonicalize(resourceProvider.convertPath('/projects'))); var projectFolder = projectsFolder.getChildAssumingFolder(packageName) - ..create; + ..create(); var projectRoot = projectFolder.path; projectFolder .getChildAssumingFile('pubspec.yaml') diff --git a/test/tool_runner_test.dart b/test/tool_runner_test.dart index b034fb982b..86cf5c4634 100644 --- a/test/tool_runner_test.dart +++ b/test/tool_runner_test.dart @@ -77,7 +77,7 @@ echo: description: 'Works on everything' '''; toolMap = ToolConfiguration.fromYamlMap( - loadYaml(yamlMap), + loadYaml(yamlMap) as YamlMap, pubPackageMetaProvider.resourceProvider.pathContext .absolute(_testPackageDir.path), pubPackageMetaProvider.resourceProvider); diff --git a/tool/grind.dart b/tool/grind.dart index 33d7ed6b11..5be25dc6ae 100644 --- a/tool/grind.dart +++ b/tool/grind.dart @@ -20,7 +20,7 @@ import 'subprocess_launcher.dart'; void main(List args) => grind(args); /// Thrown on failure to find something in a file. -class GrindTestFailure { +class GrindTestFailure implements Exception { final String message; GrindTestFailure(this.message); @@ -379,7 +379,7 @@ WarningsCollection jsonMessageIterableToWarnings( message['level'] == 'WARNING' && message.containsKey('data')) { var data = message['data'] as Map; - warningTexts.add(data['text']); + warningTexts.add(data['text'] as String); } } return warningTexts; @@ -1006,7 +1006,7 @@ String _getPackageVersion() { fail('Cannot find pubspec.yaml in ${Directory.current}'); } var yamlDoc = yaml.loadYaml(pubspec.readAsStringSync()) as yaml.YamlMap; - return yamlDoc['version']; + return yamlDoc['version'] as String; } @Task('Rebuild generated files') diff --git a/tool/mustachio/builder.dart b/tool/mustachio/builder.dart index e7fd0a509e..adebb52f96 100644 --- a/tool/mustachio/builder.dart +++ b/tool/mustachio/builder.dart @@ -155,4 +155,4 @@ class _RendererGatherer { Builder mustachioBuilder(BuilderOptions options) => MustachioBuilder( rendererClassesArePublic: - options.config[rendererClassesArePublicOption] ?? false); + options.config[rendererClassesArePublicOption] as bool? ?? false); diff --git a/tool/mustachio/codegen_aot_compiler.dart b/tool/mustachio/codegen_aot_compiler.dart index a3433bf842..3ed75c43b2 100644 --- a/tool/mustachio/codegen_aot_compiler.dart +++ b/tool/mustachio/codegen_aot_compiler.dart @@ -151,6 +151,7 @@ Future> _deduplicateRenderers( Method compiledLubRenderer; try { compiledLubRenderer = await lubCompiler._compileToRenderer(); + // ignore: avoid_catching_errors } on MustachioResolutionError { // Oops, switching to the LUB type prevents the renderer from compiling; // likely the properties accessed in the partial are not all declared on diff --git a/tool/subprocess_launcher.dart b/tool/subprocess_launcher.dart index 8cf6475be8..81cfcf424d 100644 --- a/tool/subprocess_launcher.dart +++ b/tool/subprocess_launcher.dart @@ -185,9 +185,10 @@ class SubprocessLauncher { if (perLine != null) perLine(line); Map? result; try { - result = json.decoder.convert(line); + result = json.decoder.convert(line) as Map?; } on FormatException { // Assume invalid JSON is actually a line of normal text. + // ignore: avoid_catching_errors } on TypeError catch (e, st) { // The convert function returns a String if there is no JSON in the // line. Just ignore it and leave result null. @@ -200,7 +201,7 @@ class SubprocessLauncher { line = result['message'] as String; } else if (result.containsKey('data')) { var data = result['data'] as Map; - line = data['text']; + line = data['text'] as String; } } return line.split('\n');