Skip to content

Commit

Permalink
Continue cleanup of inferred dynamic
Browse files Browse the repository at this point in the history
  • Loading branch information
parlough committed Feb 10, 2024
1 parent 7dcb60d commit 9ef0c4c
Show file tree
Hide file tree
Showing 26 changed files with 52 additions and 49 deletions.
1 change: 1 addition & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
errors:
unused_import: error
unused_local_variable: error
Expand Down
2 changes: 1 addition & 1 deletion bin/batch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import 'package:pana/src/batch/batch_run_command.dart';
///
/// dart bin/batch.dart run --packages packages.txt --config config.yaml
Future<void> main(List<String> args) async {
final runner = CommandRunner('batch',
final runner = CommandRunner<void>('batch',
'Runs analysis on multiple packages and compares granted score impact.')
..addCommand(BatchQueryCommand())
..addCommand(BatchCompareCommand())
Expand Down
4 changes: 2 additions & 2 deletions bin/pana.dart
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ ${LineSplitter.split(_parser.usage).map((l) => ' $l').join('\n')}''');
exit(ExitCode.usage.code);
}

Future main(List<String> args) async {
ArgResults result;
Future<void> main(List<String> args) async {
final ArgResults result;
try {
result = _parser.parse(args);
} on FormatException catch (e) {
Expand Down
7 changes: 4 additions & 3 deletions lib/src/analysis_options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,10 @@ String updatePassthroughOptions({
if (origAnalyzer is Map) {
final origErrors = origAnalyzer['errors'];
if (origErrors is Map) {
final customAnalyzer = customMap.putIfAbsent('analyzer', () => {}) as Map;
final customErrors =
customAnalyzer.putIfAbsent('errors', () => {}) as Map;
final customAnalyzer =
customMap.putIfAbsent('analyzer', () => <String, Object?>{}) as Map;
final customErrors = customAnalyzer.putIfAbsent(
'errors', () => <String, Object?>{}) as Map;

for (var key in _analyzerErrorKeys) {
if (origErrors.containsKey(key)) {
Expand Down
2 changes: 1 addition & 1 deletion lib/src/batch/batch_compare_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import '../utils.dart' show withTempDir;
import 'batch_model.dart';

/// Compares pana outcomes on the selected packages.
class BatchCompareCommand extends Command {
class BatchCompareCommand extends Command<void> {
@override
String get name => 'compare';

Expand Down
2 changes: 1 addition & 1 deletion lib/src/batch/batch_query_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import 'package:http/http.dart' as http;
///
/// Additional filters are applied in the order of this list, up to the
/// `--limit` parameter.
class BatchQueryCommand extends Command {
class BatchQueryCommand extends Command<void> {
final _client = http.Client();

@override
Expand Down
2 changes: 1 addition & 1 deletion lib/src/batch/batch_run_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import '../utils.dart' show withTempDir;
import 'batch_model.dart';

/// Runs pana on the selected packages.
class BatchRunCommand extends Command {
class BatchRunCommand extends Command<void> {
@override
String get name => 'run';

Expand Down
2 changes: 1 addition & 1 deletion lib/src/dartdoc/dartdoc_index.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DartdocIndex {
return DartdocIndex.fromJsonList(json.decode(content) as List);
}

factory DartdocIndex.fromJsonList(List jsonList) {
factory DartdocIndex.fromJsonList(List<Object?> jsonList) {
final list = jsonList
.map((item) => DartdocIndexEntry.fromJson(item as Map<String, dynamic>))
.toList();
Expand Down
3 changes: 2 additions & 1 deletion lib/src/download_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ class UrlChecker {
}

/// Extracts a `.tar.gz` file from [tarball] to [destination].
Future _extractTarGz(Stream<List<int>> tarball, String destination) async {
Future<void> _extractTarGz(
Stream<List<int>> tarball, String destination) async {
log.fine('Extracting .tar.gz stream to $destination.');
final reader = TarReader(tarball.transform(gzip.decoder));
while (await reader.moveNext()) {
Expand Down
2 changes: 1 addition & 1 deletion lib/src/license_detection/tokenizer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ String _normalizeWord(String text) {
return text;
}

final _headers = HashSet.from(
final _headers = HashSet.of(
'q w e r t y u i o p a s d f g h j k l z x c v b n m i ii iii iv vi vii ix xi xii xiii xiv xv'
.split(' '));

Expand Down
4 changes: 2 additions & 2 deletions lib/src/maintenance.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ List<String> exampleFileCandidates(String package) {
}

/// Returns a markdown-formatted error message for pubspec.yaml parse error.
String pubspecParseError(error) {
String pubspecParseError(Object error) {
// TODO: remove this after json_annotation is updated with CheckedFromJsonException.toString()
var message = error?.toString();
var message = error.toString();
if (error is CheckedFromJsonException) {
final msg =
error.message ?? 'Error with `${error.key}`: ${error.innerError}';
Expand Down
2 changes: 1 addition & 1 deletion lib/src/messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

String runningDartanalyzerFailed(bool usesFlutter, errorMsg) {
String runningDartAnalyzerFailed(bool usesFlutter, String errorMsg) {
final message = usesFlutter ? 'flutter analyze' : 'dart analyze .';

return 'Running `$message` failed with the following output:\n\n'
Expand Down
2 changes: 1 addition & 1 deletion lib/src/package_analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ class PackageAnalyzer {
analyzerItems = await context.staticAnalysis();
} on ToolException catch (e) {
context.errors
.add(runningDartanalyzerFailed(context.usesFlutter, e.message));
.add(runningDartAnalyzerFailed(context.usesFlutter, e.message));
}
} else {
analyzerItems = <CodeProblem>[];
Expand Down
2 changes: 1 addition & 1 deletion lib/src/package_context.dart
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ class PackageContext {
_codeProblems = await _staticAnalysis(packageDir: packageDir);
return _codeProblems!;
} on ToolException catch (e) {
errors.add(messages.runningDartanalyzerFailed(usesFlutter, e.message));
errors.add(messages.runningDartAnalyzerFailed(usesFlutter, e.message));
rethrow;
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/report/dependencies.dart
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ class OutdatedVersionDescription {
Future<List<OutdatedVersionDescription>> computeOutdatedVersions(
PackageContext context, OutdatedPackage package) async {
const acceptableUpdateDelay = Duration(days: 30);
T? tryGetFromJson<T>(Map<String, dynamic> json, String key) {
T? tryGetFromJson<T>(Map<String, Object?> json, String key) {
final element = json[key];
return element is T ? element : null;
}
Expand Down Expand Up @@ -293,7 +293,7 @@ Future<List<OutdatedVersionDescription>> computeOutdatedVersions(
pubHostedUrl: hostedDependency.hosted?.url ?? pubHostedUriFromEnv));

try {
final versions = tryGetFromJson<List>(
final versions = tryGetFromJson<List<Object?>>(
versionListing as Map<String, dynamic>, 'versions');
if (versions == null) {
// Bad response from pub host.
Expand Down
4 changes: 2 additions & 2 deletions lib/src/report/template.dart
Original file line number Diff line number Diff line change
Expand Up @@ -266,18 +266,18 @@ Future<ReportSection> followsTemplate(PackageContext context) async {

Subsection _licenseSection(LicenseTags tags) {
const title = 'Use an OSI-approved license';
late List<Paragraph> paragraphs;
final maxPoints = 10;
var grantedPoints = 0;
var reportStatus = ReportStatus.failed;

String licensePluralized(List value) =>
String licensePluralized(List<License> value) =>
value.length > 1 ? 'licenses' : 'license';
String licenseList(List<License> values) =>
values.map((e) => '`${e.spdxIdentifier}`').join(', ');
final detected = RawParagraph(
'Detected ${licensePluralized(tags.licenses)}: ${licenseList(tags.licenses)}.');

final List<Paragraph> paragraphs;
if (tags.isOnlyOsiApproved) {
paragraphs = [detected];
grantedPoints = maxPoints;
Expand Down
4 changes: 2 additions & 2 deletions lib/src/repository/check_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Future<VerifiedRepository?> checkRepository({
}
}

void failVerification(String message, [error, StackTrace? st]) {
void failVerification(String message, [Object? error, StackTrace? st]) {
verificationFailure = message;
log.info(message, error, st);
}
Expand Down Expand Up @@ -109,7 +109,7 @@ Future<VerifiedRepository?> checkRepository({
// TODO: consider to allow the exceptions to pass here, to allow an
// unrelated, but badly formatted pubspec.yaml in the repository.
// ignore: prefer_typing_uninitialized_variables
var yamlDoc;
Object? yamlDoc;
try {
yamlDoc = yaml.loadYaml(content);
} on FormatException catch (e, st) {
Expand Down
5 changes: 3 additions & 2 deletions lib/src/sdk_env.dart
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class ToolEnvironment {

PanaRuntimeInfo get runtimeInfo => _runtimeInfo!;

Future _init() async {
Future<void> _init() async {
final dartVersionResult = await runConstrained(
[..._dartSdk.dartCmd, '--version'],
environment: _dartSdk.environment,
Expand Down Expand Up @@ -547,7 +547,8 @@ class ToolEnvironment {
// and throws an exception if it is missing. While we no longer accept
// new packages without such constraint, the old versions are still valid
// and should be analyzed.
final environment = parsed.putIfAbsent('environment', () => {});
final environment =
parsed.putIfAbsent('environment', () => <String, Object?>{});
if (environment is Map) {
VersionConstraint? vc;
if (environment['sdk'] is String) {
Expand Down
7 changes: 3 additions & 4 deletions lib/src/tool/run_constrained.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ Future<PanaProcessResult> _runConstrained(
killProc('Exceeded timeout of $timeout');
});

var items = await Future.wait(<Future>[
final (exitCode, _, _) = await (
process.exitCode,
process.stdout.forEach((outLine) {
stdoutLines.add(outLine);
Expand All @@ -108,12 +108,11 @@ Future<PanaProcessResult> _runConstrained(
killProc('Output exceeded $maxOutputBytes bytes.');
}
})
]);
).wait;

timer.cancel();

final exitCode = items[0] as int;
late PanaProcessResult result;
final PanaProcessResult result;
if (killed) {
final encoding = systemEncoding;
result = PanaProcessResult(
Expand Down
12 changes: 6 additions & 6 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ List<String> dartFilesFromLib(String packageDir) {
}

@visibleForTesting
dynamic sortedJson(obj) {
var fullJson = json.decode(json.encode(obj));
Object? sortedJson(Object? obj) {
final fullJson = json.decode(json.encode(obj));
return _toSortedMap(fullJson);
}

dynamic _toSortedMap(dynamic item) {
Object? _toSortedMap(Object? item) {
if (item is Map) {
return SplayTreeMap<String, dynamic>.fromIterable(item.keys,
return SplayTreeMap<String, Object?>.fromIterable(item.keys,
value: (k) => _toSortedMap(item[k]));
} else if (item is List) {
return item.map(_toSortedMap).toList();
Expand All @@ -73,7 +73,7 @@ dynamic _toSortedMap(dynamic item) {
}
}

Map<String, dynamic>? yamlToJson(String? yamlContent) {
Map<String, Object?>? yamlToJson(String? yamlContent) {
if (yamlContent == null) {
return null;
}
Expand All @@ -84,7 +84,7 @@ Map<String, dynamic>? yamlToJson(String? yamlContent) {

// A bit paranoid, but I want to make sure this is valid JSON before we got to
// the encode phase.
return sortedJson(json.decode(json.encode(yamlMap))) as Map<String, dynamic>;
return sortedJson(json.decode(json.encode(yamlMap))) as Map<String, Object?>;
}

/// Returns the list of directories to focus on (e.g. bin, lib) - if they exist.
Expand Down
14 changes: 7 additions & 7 deletions test/end2end_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void main() {
}) {
final filename = '$package-$version.json';
group('end2end: $package $version', () {
Map<String, dynamic>? actualMap;
late final Map<String, Object?> actualMap;

setUpAll(() async {
final dartdocOutputDir = p.join(tempDir, 'doc', '$package-version');
Expand Down Expand Up @@ -102,11 +102,11 @@ void main() {
'the Dart version used by the latest stable Flutter ({{flutter-dart-version}})')
.replaceAll(RegExp('that was published [0-9]+ days ago'),
'that was published N days ago');
actualMap = json.decode(updated) as Map<String, dynamic>?;
actualMap = json.decode(updated) as Map<String, Object?>;
});

test('matches known good', () {
void removeDependencyDetails(Map map) {
void removeDependencyDetails(Map<String, dynamic> map) {
if (map.containsKey('pkgResolution') &&
(map['pkgResolution'] as Map).containsKey('dependencies')) {
final deps = (map['pkgResolution']['dependencies'] as List)
Expand All @@ -120,7 +120,7 @@ void main() {

// Reduce the time-invariability of the tests: resolved and available
// versions may change over time or because of SDK version changes.
removeDependencyDetails(actualMap!);
removeDependencyDetails(actualMap);

final json =
'${const JsonEncoder.withIndent(' ').convert(actualMap)}\n';
Expand All @@ -134,7 +134,7 @@ void main() {
});

test('Report matches known good', () {
final jsonReport = actualMap!['report'] as Map<String, dynamic>?;
final jsonReport = actualMap['report'] as Map<String, Object?>?;
if (jsonReport != null) {
final report = Report.fromJson(jsonReport);
final renderedSections = report.sections
Expand All @@ -150,7 +150,7 @@ void main() {
});

test('Summary can round-trip', () {
var summary = Summary.fromJson(actualMap!);
var summary = Summary.fromJson(actualMap);

var roundTrip = json.decode(json.encode(summary));
expect(roundTrip, actualMap);
Expand All @@ -159,7 +159,7 @@ void main() {
test('Summary tags check', () {
final tagsFileContent =
File('lib/src/tag/pana_tags.dart').readAsStringSync();
final summary = Summary.fromJson(actualMap!);
final summary = Summary.fromJson(actualMap);
final tags = summary.tags;
if (tags != null) {
for (final tag in tags) {
Expand Down
4 changes: 2 additions & 2 deletions test/package_descriptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ d.DirectoryDescriptor packageWithPathDeps(String name,
{String? sdkConstraint,
List<String> dependencies = const [],
List<d.Descriptor> lib = const [],
Map pubspecExtras = const {},
Map<String, Object> pubspecExtras = const {},
List<d.Descriptor> extraFiles = const []}) {
final pubspec = json.encode(
{
Expand Down Expand Up @@ -57,7 +57,7 @@ d.DirectoryDescriptor package(String name,
{String? sdkConstraint,
Map<String, Object> dependencies = const {},
List<d.Descriptor> lib = const [],
Map pubspecExtras = const {},
Map<String, Object> pubspecExtras = const {},
List<d.Descriptor> extraFiles = const []}) {
final pubspec = json.encode(
{
Expand Down
2 changes: 1 addition & 1 deletion test/package_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ class _ServedPackage {

/// A package that's intended to be served.
class _ServedPackageVersion {
final Map pubspec;
final Map<String, Object> pubspec;
final List<d.Descriptor> contents;
final DateTime? published;

Expand Down
2 changes: 1 addition & 1 deletion test/pubspec_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ final Pubspec emptyPubspec = Pubspec({
final Pubspec flutterPluginPubspec = Pubspec({
'name': 'sample',
'flutter': {
'plugin': {},
'plugin': <String, Object>{},
},
});

Expand Down
2 changes: 1 addition & 1 deletion test/repository/git_local_repository_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ void main() {
await repo.delete();
});

void setupBranchFailures(Future Function(String branch) fn) {
void setupBranchFailures(Future<void> Function(String branch) fn) {
test('no such branch', () async {
await expectLater(
() => fn('branchdoesnotexists'), throwsA(isA<GitToolException>()));
Expand Down
4 changes: 2 additions & 2 deletions test/screenshot_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ void main() {
}, skip: hasWebpTools);

test('Report shows screenshot problems', () async {
Map pubspecExtras = <String, List>{
final pubspecExtras = {
'screenshots': [
{'description': '', 'path': 'doesNotExist'}
]
Expand Down Expand Up @@ -228,7 +228,7 @@ void main() {

test('Successful report', () async {
if (!hasWebpTools) return;
Map pubspecExtras = <String, List>{
final pubspecExtras = {
'screenshots': [
{'description': 'description', 'path': 'static.webp'}
]
Expand Down

0 comments on commit 9ef0c4c

Please sign in to comment.