Skip to content

Commit

Permalink
Add strict-cast analysis option (#3919)
Browse files Browse the repository at this point in the history
  • Loading branch information
bsutton authored Jun 1, 2023
1 parent fbb6f75 commit 5a3f21b
Show file tree
Hide file tree
Showing 60 changed files with 380 additions and 292 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.buildlog
.DS_Store
.idea
.vscode
.dart_tool/
.settings/
/build/
Expand Down
3 changes: 3 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ analyzer:
exclude:
- lib/src/third_party/**

language:
strict-casts: true

linter:
rules:
- avoid_catching_errors
Expand Down
7 changes: 4 additions & 3 deletions bin/dependency_services.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,18 @@ import 'package:pub/src/command/dependency_services.dart';
import 'package:pub/src/exit_codes.dart' as exit_codes;
import 'package:pub/src/io.dart';
import 'package:pub/src/log.dart' as log;
import 'package:pub/src/utils.dart';

class _DependencyServicesCommandRunner extends CommandRunner<int>
implements PubTopLevel {
@override
String get directory => argResults['directory'];
String get directory => argResults.option('directory');

@override
bool get captureStackChains => argResults['verbose'];
bool get captureStackChains => argResults.flag('verbose');

@override
bool get trace => argResults['verbose'];
bool get trace => argResults.flag('verbose');

ArgResults? _argResults;

Expand Down
Empty file modified bin/pub.dart
100644 → 100755
Empty file.
2 changes: 1 addition & 1 deletion lib/src/command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ abstract class PubCommand extends Command<int> {

String get directory {
return (argResults.options.contains('directory')
? argResults['directory']
? argResults.optionWithoutDefault('directory')
: null) ??
_pubTopLevel.directory;
}
Expand Down
20 changes: 10 additions & 10 deletions lib/src/command/add.dart
Original file line number Diff line number Diff line change
Expand Up @@ -766,21 +766,21 @@ class _ParseResult {
}

extension on ArgResults {
bool get isDev => this['dev'];
bool get isDryRun => this['dry-run'];
String? get gitUrl => this['git-url'];
String? get gitPath => this['git-path'];
String? get gitRef => this['git-ref'];
String? get hostedUrl => this['hosted-url'];
String? get path => this['path'];
String? get sdk => this['sdk'];
bool get isDev => flag('dev');
bool get isDryRun => flag('dry-run');
String? get gitUrl => this['git-url'] as String?;
String? get gitPath => this['git-path'] as String?;
String? get gitRef => this['git-ref'] as String?;
String? get hostedUrl => this['hosted-url'] as String?;
String? get path => this['path'] as String?;
String? get sdk => this['sdk'] as String?;
bool get hasOldStyleOptions =>
hasGitOptions ||
path != null ||
sdk != null ||
hostedUrl != null ||
isDev;
bool get shouldPrecompile => this['precompile'];
bool get example => this['example'];
bool get shouldPrecompile => flag('precompile');
bool get example => flag('example');
bool get hasGitOptions => gitUrl != null || gitRef != null || gitPath != null;
}
7 changes: 4 additions & 3 deletions lib/src/command/cache_add.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:pub_semver/pub_semver.dart';

import '../command.dart';
import '../log.dart' as log;
import '../package_name.dart';
import '../utils.dart';

/// Handles the `cache add` pub command.
Expand Down Expand Up @@ -52,7 +53,7 @@ class CacheAddCommand extends PubCommand {
var constraint = VersionConstraint.any;
if (argResults['version'] != null) {
try {
constraint = VersionConstraint.parse(argResults['version']);
constraint = VersionConstraint.parse(argResults['version'] as String);
} on FormatException catch (error) {
usageException(error.message);
}
Expand All @@ -71,14 +72,14 @@ class CacheAddCommand extends PubCommand {
fail('Package $package has no versions that match $constraint.');
}

Future<void> downloadVersion(id) async {
Future<void> downloadVersion(PackageId id) async {
final result = await cache.downloadPackage(id);
if (!result.didUpdate) {
log.message('Already cached ${id.name} ${id.version}.');
}
}

if (argResults['all']) {
if (argResults.flag('all')) {
// Install them in ascending order.
ids.sort((id1, id2) => id1.version.compareTo(id2.version));
await Future.forEach(ids, downloadVersion);
Expand Down
3 changes: 2 additions & 1 deletion lib/src/command/cache_clean.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import '../command.dart';
import '../command_runner.dart';
import '../io.dart';
import '../log.dart' as log;
import '../utils.dart';

class CacheCleanCommand extends PubCommand {
@override
Expand All @@ -27,7 +28,7 @@ class CacheCleanCommand extends PubCommand {
@override
Future<void> runProtected() async {
if (dirExists(cache.rootDir)) {
if (argResults['force'] || await confirm('''
if (argResults.flag('force') || await confirm('''
This will remove everything inside ${cache.rootDir}.
You will have to run `$topLevelProgram pub get` again in each project.
Are you sure?''')) {
Expand Down
10 changes: 6 additions & 4 deletions lib/src/command/cache_repair.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ class CacheRepairCommand extends PubCommand {

if (successes.isNotEmpty) {
var packages = pluralize('package', successes.length);
log.message('Reinstalled ${log.green(successes.length)} $packages.');
log.message(
'Reinstalled ${log.green(successes.length.toString())} $packages.',
);
}

if (failures.isNotEmpty) {
var packages = pluralize('package', failures.length);
var buffer = StringBuffer(
'Failed to reinstall ${log.red(failures.length)} $packages:\n',
'Failed to reinstall ${log.red(failures.length.toString())} $packages:\n',
);

for (var failure in failures) {
Expand All @@ -62,14 +64,14 @@ class CacheRepairCommand extends PubCommand {
if (globalRepairResults.first.isNotEmpty) {
var packages = pluralize('package', globalRepairResults.first.length);
log.message(
'Reactivated ${log.green(globalRepairResults.first.length)} $packages.',
'Reactivated ${log.green(globalRepairResults.first.length.toString())} $packages.',
);
}

if (globalRepairResults.last.isNotEmpty) {
var packages = pluralize('package', globalRepairResults.last.length);
log.message(
'Failed to reactivate ${log.red(globalRepairResults.last.length)} $packages:',
'Failed to reactivate ${log.red(globalRepairResults.last.length.toString())} $packages:',
);
log.message(
globalRepairResults.last
Expand Down
28 changes: 15 additions & 13 deletions lib/src/command/dependency_services.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ class DependencyServicesReportCommand extends PubCommand {
} else {
final resolution = await _tryResolve(entrypoint.root.pubspec, cache) ??
(throw DataException('Failed to resolve pubspec'));
currentPackages =
Map<String, PackageId>.fromIterable(resolution, key: (e) => e.name);
currentPackages = Map<String, PackageId>.fromIterable(
resolution,
key: (e) => (e as PackageId).name,
);
}
currentPackages.remove(entrypoint.root.name);

Expand Down Expand Up @@ -361,13 +363,13 @@ class DependencyServicesApplyCommand extends PubCommand {
YamlEditor(readTextFile(entrypoint.pubspecPath));
final toApply = <_PackageVersion>[];
final input = json.decode(await utf8.decodeStream(stdin));
for (final change in input['dependencyChanges']) {
for (final change in input['dependencyChanges'] as Iterable) {
toApply.add(
_PackageVersion(
change['name'],
change['version'],
change['name'] as String,
change['version'] as String?,
change['constraint'] != null
? VersionConstraint.parse(change['constraint'])
? VersionConstraint.parse(change['constraint'] as String)
: null,
),
);
Expand Down Expand Up @@ -421,23 +423,23 @@ class DependencyServicesApplyCommand extends PubCommand {
}
if (lockFileEditor != null) {
if (targetVersion != null &&
lockFileYaml['packages'].containsKey(targetPackage)) {
(lockFileYaml['packages'] as Map).containsKey(targetPackage)) {
lockFileEditor.update(
['packages', targetPackage, 'version'],
targetVersion.toString(),
);
// Remove the now outdated content-hash - it will be restored below
// after resolution.
if (lockFileEditor
.parseAt(['packages', targetPackage, 'description'])
.value
.containsKey('sha256')) {
var packageMap = lockFileEditor
.parseAt(['packages', targetPackage, 'description']).value as Map;
var hasSha = packageMap.containsKey('sha256');
if (hasSha) {
lockFileEditor.remove(
['packages', targetPackage, 'description', 'sha256'],
);
}
} else if (targetRevision != null &&
lockFileYaml['packages'].containsKey(targetPackage)) {
(lockFileYaml['packages'] as Map).containsKey(targetPackage)) {
final ref = entrypoint.lockFile.packages[targetPackage]!.toRef();
final currentDescription = ref.description as GitDescription;
final updatedRef = PackageRef(
Expand Down Expand Up @@ -468,7 +470,7 @@ class DependencyServicesApplyCommand extends PubCommand {
);
} else if (targetVersion == null &&
targetRevision == null &&
!lockFileYaml['packages'].containsKey(targetPackage)) {
!(lockFileYaml['packages'] as Map).containsKey(targetPackage)) {
dataError(
'Trying to remove non-existing transitive dependency $targetPackage.',
);
Expand Down
8 changes: 4 additions & 4 deletions lib/src/command/deps.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class DepsCommand extends PubCommand {
bool get takesArguments => false;

/// Whether to include dev dependencies.
bool get _includeDev => argResults['dev'];
bool get _includeDev => argResults.flag('dev');

DepsCommand() {
argParser.addOption(
Expand Down Expand Up @@ -75,7 +75,7 @@ class DepsCommand extends PubCommand {
await entrypoint.ensureUpToDate();
final buffer = StringBuffer();

if (argResults['json']) {
if (argResults.flag('json')) {
if (argResults.wasParsed('dev')) {
usageException(
'Cannot combine --json and --dev.\nThe json output contains the dependency type in the output.',
Expand Down Expand Up @@ -150,7 +150,7 @@ class DepsCommand extends PubCommand {
),
);
} else {
if (argResults['executables']) {
if (argResults.flag('executables')) {
_outputExecutables(buffer);
} else {
for (var sdk in sdks.values) {
Expand All @@ -174,7 +174,7 @@ class DepsCommand extends PubCommand {
}
}

log.message(buffer);
log.message(buffer.toString());
}

/// Outputs a list of all of the package's immediate, dev, override, and
Expand Down
7 changes: 4 additions & 3 deletions lib/src/command/downgrade.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'dart:async';
import '../command.dart';
import '../log.dart' as log;
import '../solver.dart';
import '../utils.dart';

/// Handles the `downgrade` pub command.
class DowngradeCommand extends PubCommand {
Expand All @@ -21,7 +22,7 @@ class DowngradeCommand extends PubCommand {
String get docUrl => 'https://dart.dev/tools/pub/cmd/pub-downgrade';

@override
bool get isOffline => argResults['offline'];
bool get isOffline => argResults.flag('offline');

DowngradeCommand() {
argParser.addFlag(
Expand Down Expand Up @@ -62,7 +63,7 @@ class DowngradeCommand extends PubCommand {
),
);
}
var dryRun = argResults['dry-run'];
var dryRun = argResults.flag('dry-run');

await entrypoint.acquireDependencies(
SolveType.downgrade,
Expand All @@ -71,7 +72,7 @@ class DowngradeCommand extends PubCommand {
analytics: analytics,
);
var example = entrypoint.example;
if (argResults['example'] && example != null) {
if (argResults.flag('example') && example != null) {
await example.acquireDependencies(
SolveType.get,
unlock: argResults.rest,
Expand Down
17 changes: 9 additions & 8 deletions lib/src/command/get.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'dart:async';
import '../command.dart';
import '../log.dart' as log;
import '../solver.dart';
import '../utils.dart';

/// Handles the `get` pub command.
class GetCommand extends PubCommand {
Expand All @@ -17,7 +18,7 @@ class GetCommand extends PubCommand {
@override
String get docUrl => 'https://dart.dev/tools/pub/cmd/pub-get';
@override
bool get isOffline => argResults['offline'];
bool get isOffline => argResults.flag('offline');
@override
String get argumentsDescription => '';

Expand Down Expand Up @@ -75,21 +76,21 @@ class GetCommand extends PubCommand {

await entrypoint.acquireDependencies(
SolveType.get,
dryRun: argResults['dry-run'],
precompile: argResults['precompile'],
dryRun: argResults.flag('dry-run'),
precompile: argResults.flag('precompile'),
analytics: analytics,
enforceLockfile: argResults['enforce-lockfile'],
enforceLockfile: argResults.flag('enforce-lockfile'),
);

var example = entrypoint.example;
if (argResults['example'] && example != null) {
if ((argResults['example'] as bool? ?? false) && example != null) {
await example.acquireDependencies(
SolveType.get,
dryRun: argResults['dry-run'],
precompile: argResults['precompile'],
dryRun: argResults.flag('dry-run'),
precompile: argResults.flag('precompile'),
analytics: analytics,
summaryOnly: true,
enforceLockfile: argResults['enforce-lockfile'],
enforceLockfile: argResults.flag('enforce-lockfile'),
);
}
}
Expand Down
11 changes: 6 additions & 5 deletions lib/src/command/global_activate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ class GlobalActivateCommand extends PubCommand {
usageException('Cannot pass both --no-executables and --executable.');
}

executables = argResults['executable'];
} else if (argResults['no-executables']) {
executables = argResults['executable'] as List<String>?;
} else if (argResults.flag('no-executables')) {
// An empty list means no executables.
executables = [];
}
Expand Down Expand Up @@ -126,16 +126,17 @@ class GlobalActivateCommand extends PubCommand {
repo,
executables,
overwriteBinStubs: overwrite,
path: argResults['git-path'],
ref: argResults['git-ref'],
path: argResults['git-path'] as String?,
ref: argResults['git-ref'] as String?,
);

case 'hosted':
var package = readArg('No package to activate given.');

PackageRef ref;
try {
ref = cache.hosted.refFor(package, url: argResults['hosted-url']);
ref = cache.hosted
.refFor(package, url: argResults['hosted-url'] as String?);
} on FormatException catch (e) {
usageException('Invalid hosted-url: $e');
}
Expand Down
3 changes: 2 additions & 1 deletion lib/src/command/global_run.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ class GlobalRunCommand extends PubCommand {
Executable.adaptProgramName(package, executable),
args,
vmArgs: vmArgs,
enableAsserts: argResults['enable-asserts'] || argResults['checked'],
enableAsserts:
argResults.flag('enable-asserts') || argResults.flag('checked'),
recompile: (executable) => log.errorsOnlyUnlessTerminal(
() => globalEntrypoint.precompileExecutable(executable),
),
Expand Down
Loading

0 comments on commit 5a3f21b

Please sign in to comment.