Unverified Commit 92034482 authored by Jonah Williams's avatar Jonah Williams Committed by GitHub

[flutter_tool] partial null safety migration of tool source code (#105798)

parent a7ddb9b6
......@@ -339,6 +339,7 @@ Future<void> _runGeneralToolTests() async {
_toolsPath,
testPaths: <String>[path.join('test', 'general.shard')],
enableFlutterToolAsserts: false,
// Detect unit test time regressions (poor time delay handling, etc).
// This overrides the 15 minute default for tools tests.
// See the README.md and dart_test.yaml files in the flutter_tools package.
......
......@@ -2,10 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'package:meta/meta.dart';
import 'runner.dart' as runner;
import 'src/artifacts.dart';
import 'src/base/context.dart';
......@@ -110,7 +106,7 @@ Future<void> main(List<String> args) async {
// devtools source code.
DevtoolsLauncher: () => DevtoolsServerLauncher(
processManager: globals.processManager,
dartExecutable: globals.artifacts.getHostArtifact(HostArtifact.engineDartBinary).path,
dartExecutable: globals.artifacts!.getHostArtifact(HostArtifact.engineDartBinary).path,
logger: globals.logger,
botDetector: globals.botDetector,
),
......@@ -134,8 +130,8 @@ Future<void> main(List<String> args) async {
}
List<FlutterCommand> generateCommands({
@required bool verboseHelp,
@required bool verbose,
required bool verboseHelp,
required bool verbose,
}) => <FlutterCommand>[
AnalyzeCommand(
verboseHelp: verboseHelp,
......@@ -144,7 +140,7 @@ List<FlutterCommand> generateCommands({
processManager: globals.processManager,
logger: globals.logger,
terminal: globals.terminal,
artifacts: globals.artifacts,
artifacts: globals.artifacts!,
),
AssembleCommand(verboseHelp: verboseHelp, buildSystem: globals.buildSystem),
AttachCommand(verboseHelp: verboseHelp),
......@@ -210,9 +206,9 @@ List<FlutterCommand> generateCommands({
/// Our logger class hierarchy and runtime requirements are overly complicated.
class LoggerFactory {
LoggerFactory({
@required Terminal terminal,
@required Stdio stdio,
@required OutputPreferences outputPreferences,
required Terminal terminal,
required Stdio stdio,
required OutputPreferences outputPreferences,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
}) : _terminal = terminal,
_stdio = stdio,
......@@ -226,11 +222,11 @@ class LoggerFactory {
/// Create the appropriate logger for the current platform and configuration.
Logger createLogger({
@required bool verbose,
@required bool prefixedErrors,
@required bool machine,
@required bool daemon,
@required bool windows,
required bool verbose,
required bool prefixedErrors,
required bool machine,
required bool daemon,
required bool windows,
}) {
Logger logger;
if (windows) {
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
......@@ -31,9 +31,9 @@ Future<int> run(
bool muteCommandLogging = false,
bool verbose = false,
bool verboseHelp = false,
bool reportCrashes,
String flutterVersion,
Map<Type, Generator> overrides,
bool? reportCrashes,
String? flutterVersion,
Map<Type, Generator>? overrides,
}) async {
if (muteCommandLogging) {
// Remove the verbose option; for help and doctor, users don't need to see
......@@ -55,8 +55,8 @@ Future<int> run(
);
String getVersion() => flutterVersion ?? globals.flutterVersion.getVersionString(redactUnknownBranches: true);
Object firstError;
StackTrace firstStackTrace;
Object? firstError;
StackTrace? firstStackTrace;
return runZoned<Future<int>>(() async {
try {
await runner.run(args);
......@@ -74,7 +74,7 @@ Future<int> run(
// This catches all exceptions to send to crash logging, etc.
firstError = error;
firstStackTrace = stackTrace;
return _handleToolError(error, stackTrace, verbose, args, reportCrashes, getVersion);
return _handleToolError(error, stackTrace, verbose, args, reportCrashes!, getVersion);
}
}, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use
// If sending a crash report throws an error into the zone, we don't want
......@@ -82,14 +82,14 @@ Future<int> run(
// to send the original error that triggered the crash report.
firstError ??= error;
firstStackTrace ??= stackTrace;
await _handleToolError(firstError, firstStackTrace, verbose, args, reportCrashes, getVersion);
await _handleToolError(firstError!, firstStackTrace, verbose, args, reportCrashes!, getVersion);
});
}, overrides: overrides);
}
Future<int> _handleToolError(
dynamic error,
StackTrace stackTrace,
Object error,
StackTrace? stackTrace,
bool verbose,
List<String> args,
bool reportCrashes,
......@@ -102,7 +102,7 @@ Future<int> _handleToolError(
return _exit(64);
} else if (error is ToolExit) {
if (error.message != null) {
globals.printError(error.message);
globals.printError(error.message!);
}
if (verbose) {
globals.printError('\n$stackTrace\n');
......@@ -138,7 +138,7 @@ Future<int> _handleToolError(
);
await crashReportSender.sendReport(
error: error,
stackTrace: stackTrace,
stackTrace: stackTrace!,
getFlutterVersion: getFlutterVersion,
command: args.join(' '),
);
......@@ -159,17 +159,17 @@ Future<int> _handleToolError(
final CrashDetails details = CrashDetails(
command: _crashCommand(args),
error: error,
stackTrace: stackTrace,
stackTrace: stackTrace!,
doctorText: doctorText,
);
final File file = await _createLocalCrashReport(details);
await globals.crashReporter.informUser(details, file);
await globals.crashReporter!.informUser(details, file);
return _exit(1);
// This catch catches all exceptions to ensure the message below is printed.
} catch (error) { // ignore: avoid_catches_without_on_clauses
} catch (error, st) { // ignore: avoid_catches_without_on_clauses
globals.stdio.stderrWrite(
'Unable to generate crash report due to secondary error: $error\n'
'Unable to generate crash report due to secondary error: $error\n$st\n'
'${globals.userMessages.flutterToolBugInstructions}\n',
);
// Any exception thrown here (including one thrown by `_exit()`) will
......@@ -241,7 +241,7 @@ Future<int> _exit(int code) async {
}
// Run shutdown hooks before flushing logs
await globals.shutdownHooks.runShutdownHooks();
await globals.shutdownHooks!.runShutdownHooks();
final Completer<void> completer = Completer<void>();
......
......@@ -271,7 +271,7 @@ class AndroidValidator extends DoctorValidator {
/// SDK have been accepted.
class AndroidLicenseValidator extends DoctorValidator {
AndroidLicenseValidator({
required AndroidSdk androidSdk,
required AndroidSdk? androidSdk,
required Platform platform,
required OperatingSystemUtils operatingSystemUtils,
required FileSystem fileSystem,
......@@ -291,7 +291,7 @@ class AndroidLicenseValidator extends DoctorValidator {
_userMessages = userMessages,
super('Android license subvalidator');
final AndroidSdk _androidSdk;
final AndroidSdk? _androidSdk;
final AndroidStudio? _androidStudio;
final Stdio _stdio;
final OperatingSystemUtils _operatingSystemUtils;
......@@ -309,13 +309,13 @@ class AndroidLicenseValidator extends DoctorValidator {
final List<ValidationMessage> messages = <ValidationMessage>[];
// Match pre-existing early termination behavior
if (_androidSdk == null || _androidSdk.latestVersion == null ||
_androidSdk.validateSdkWellFormed().isNotEmpty ||
if (_androidSdk == null || _androidSdk?.latestVersion == null ||
_androidSdk!.validateSdkWellFormed().isNotEmpty ||
! await _checkJavaVersionNoOutput()) {
return ValidationResult(ValidationType.missing, messages);
}
final String sdkVersionText = _userMessages.androidStatusInfo(_androidSdk.latestVersion!.buildToolsVersionName);
final String sdkVersionText = _userMessages.androidStatusInfo(_androidSdk!.latestVersion!.buildToolsVersionName);
// Check for licenses.
switch (await licensesAccepted) {
......@@ -392,8 +392,8 @@ class AndroidLicenseValidator extends DoctorValidator {
try {
final Process process = await _processManager.start(
<String>[_androidSdk.sdkManagerPath!, '--licenses'],
environment: _androidSdk.sdkManagerEnv,
<String>[_androidSdk!.sdkManagerPath!, '--licenses'],
environment: _androidSdk!.sdkManagerEnv,
);
process.stdin.write('n\n');
// We expect logcat streams to occasionally contain invalid utf-8,
......@@ -432,8 +432,8 @@ class AndroidLicenseValidator extends DoctorValidator {
try {
final Process process = await _processManager.start(
<String>[_androidSdk.sdkManagerPath!, '--licenses'],
environment: _androidSdk.sdkManagerEnv,
<String>[_androidSdk!.sdkManagerPath!, '--licenses'],
environment: _androidSdk!.sdkManagerEnv,
);
// The real stdin will never finish streaming. Pipe until the child process
......@@ -463,7 +463,7 @@ class AndroidLicenseValidator extends DoctorValidator {
return exitCode == 0;
} on ProcessException catch (e) {
throwToolExit(_userMessages.androidCannotRunSdkManager(
_androidSdk.sdkManagerPath ?? '',
_androidSdk?.sdkManagerPath ?? '',
e.toString(),
_platform,
));
......@@ -471,7 +471,7 @@ class AndroidLicenseValidator extends DoctorValidator {
}
bool _canRunSdkManager() {
final String? sdkManagerPath = _androidSdk.sdkManagerPath;
final String? sdkManagerPath = _androidSdk?.sdkManagerPath;
if (sdkManagerPath == null) {
return false;
}
......
......@@ -97,7 +97,7 @@ class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackag
/// Creates a new AndroidApk based on the information in the Android manifest.
static Future<AndroidApk?> fromAndroidProject(
AndroidProject androidProject, {
required AndroidSdk androidSdk,
required AndroidSdk? androidSdk,
required ProcessManager processManager,
required UserMessages userMessages,
required ProcessUtils processUtils,
......@@ -113,7 +113,7 @@ class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackag
// the application Id, so we need to look at what was actually built.
return AndroidApk.fromApk(
apkFile,
androidSdk: androidSdk,
androidSdk: androidSdk!,
processManager: processManager,
logger: logger,
userMessages: userMessages,
......
......@@ -157,9 +157,9 @@ class SettingsFile {
/// Given a data structure which is a Map of String to dynamic values, return
/// the same structure (`Map<String, dynamic>`) with the correct runtime types.
Map<String, dynamic>? castStringKeyedMap(dynamic untyped) {
Map<String, Object?>? castStringKeyedMap(Object? untyped) {
final Map<dynamic, dynamic>? map = untyped as Map<dynamic, dynamic>?;
return map?.cast<String, dynamic>();
return map?.cast<String, Object?>();
}
/// Smallest column that will be used for text wrapping. If the requested column
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
......@@ -49,10 +49,10 @@ import 'run.dart';
class DriveCommand extends RunCommandBase {
DriveCommand({
bool verboseHelp = false,
@visibleForTesting FlutterDriverFactory flutterDriverFactory,
@required FileSystem fileSystem,
@required Logger logger,
@required Platform platform,
@visibleForTesting FlutterDriverFactory? flutterDriverFactory,
required FileSystem fileSystem,
required Logger? logger,
required Platform platform,
}) : _flutterDriverFactory = flutterDriverFactory,
_fileSystem = fileSystem,
_logger = logger,
......@@ -156,15 +156,15 @@ class DriveCommand extends RunCommandBase {
// specified not to.
@override
bool get shouldRunPub {
if (argResults.wasParsed('pub') && !boolArgDeprecated('pub')) {
if (argResults!.wasParsed('pub') && !boolArgDeprecated('pub')) {
return false;
}
return true;
}
FlutterDriverFactory _flutterDriverFactory;
FlutterDriverFactory? _flutterDriverFactory;
final FileSystem _fileSystem;
final Logger _logger;
final Logger? _logger;
final FileSystemUtils _fsUtils;
@override
......@@ -179,9 +179,9 @@ class DriveCommand extends RunCommandBase {
@override
final List<String> aliases = <String>['driver'];
String get userIdentifier => stringArgDeprecated(FlutterOptions.kDeviceUser);
String? get userIdentifier => stringArgDeprecated(FlutterOptions.kDeviceUser);
String get screenshot => stringArgDeprecated('screenshot');
String? get screenshot => stringArgDeprecated('screenshot');
@override
bool get startPausedDefault => true;
......@@ -192,7 +192,7 @@ class DriveCommand extends RunCommandBase {
@override
Future<void> validateCommand() async {
if (userIdentifier != null) {
final Device device = await findTargetDevice();
final Device? device = await findTargetDevice();
if (device is! AndroidDevice) {
throwToolExit('--${FlutterOptions.kDeviceUser} is only supported for Android');
}
......@@ -202,39 +202,39 @@ class DriveCommand extends RunCommandBase {
@override
Future<FlutterCommandResult> runCommand() async {
final String testFile = _getTestFile();
final String testFile = _getTestFile()!;
if (testFile == null) {
throwToolExit(null);
}
if (await _fileSystem.type(testFile) != FileSystemEntityType.file) {
throwToolExit('Test file not found: $testFile');
}
final String applicationBinaryPath = stringArgDeprecated(FlutterOptions.kUseApplicationBinary);
final Device device = await findTargetDevice(includeUnsupportedDevices: applicationBinaryPath == null);
final String? applicationBinaryPath = stringArgDeprecated(FlutterOptions.kUseApplicationBinary);
final Device? device = await findTargetDevice(includeUnsupportedDevices: applicationBinaryPath == null);
if (device == null) {
throwToolExit(null);
}
if (screenshot != null && !device.supportsScreenshot) {
_logger.printError('Screenshot not supported for ${device.name}.');
_logger!.printError('Screenshot not supported for ${device.name}.');
}
final bool web = device is WebServerDevice || device is ChromiumDevice;
_flutterDriverFactory ??= FlutterDriverFactory(
applicationPackageFactory: ApplicationPackageFactory.instance,
logger: _logger,
applicationPackageFactory: ApplicationPackageFactory.instance!,
logger: _logger!,
processUtils: globals.processUtils,
dartSdkPath: globals.artifacts.getHostArtifact(HostArtifact.engineDartBinary).path,
devtoolsLauncher: DevtoolsLauncher.instance,
dartSdkPath: globals.artifacts!.getHostArtifact(HostArtifact.engineDartBinary).path,
devtoolsLauncher: DevtoolsLauncher.instance!,
);
final PackageConfig packageConfig = await loadPackageConfigWithLogging(
_fileSystem.file('.packages'),
logger: _logger,
logger: _logger!,
throwOnError: false,
) ?? PackageConfig.empty;
final DriverService driverService = _flutterDriverFactory.createDriverService(web);
);
final DriverService driverService = _flutterDriverFactory!.createDriverService(web);
final BuildInfo buildInfo = await getBuildInfo();
final DebuggingOptions debuggingOptions = await createDebuggingOptions(web);
final File applicationBinary = applicationBinaryPath == null
final File? applicationBinary = applicationBinaryPath == null
? null
: _fileSystem.file(applicationBinaryPath);
......@@ -245,7 +245,7 @@ class DriveCommand extends RunCommandBase {
buildInfo,
device,
debuggingOptions,
ipv6,
ipv6 ?? false,
applicationBinary: applicationBinary,
route: route,
userIdentifier: userIdentifier,
......@@ -260,7 +260,7 @@ class DriveCommand extends RunCommandBase {
}
);
} else {
final Uri uri = Uri.tryParse(stringArgDeprecated('use-existing-app'));
final Uri? uri = Uri.tryParse(stringArgDeprecated('use-existing-app')!);
if (uri == null) {
throwToolExit('Invalid VM Service URI: ${stringArgDeprecated('use-existing-app')}');
}
......@@ -268,7 +268,7 @@ class DriveCommand extends RunCommandBase {
uri,
device,
debuggingOptions,
ipv6,
ipv6 ?? false,
);
}
......@@ -279,10 +279,10 @@ class DriveCommand extends RunCommandBase {
packageConfig,
chromeBinary: stringArgDeprecated('chrome-binary'),
headless: boolArgDeprecated('headless'),
browserDimension: stringArgDeprecated('browser-dimension').split(','),
browserDimension: stringArgDeprecated('browser-dimension')!.split(','),
browserName: stringArgDeprecated('browser-name'),
driverPort: stringArgDeprecated('driver-port') != null
? int.tryParse(stringArgDeprecated('driver-port'))
? int.tryParse(stringArgDeprecated('driver-port')!)
: null,
androidEmulator: boolArgDeprecated('android-emulator'),
profileMemory: stringArgDeprecated('profile-memory'),
......@@ -293,10 +293,10 @@ class DriveCommand extends RunCommandBase {
screenshotTaken = true;
}
if (boolArgDeprecated('keep-app-running') ?? (argResults['use-existing-app'] != null)) {
_logger.printStatus('Leaving the application running.');
if (boolArgDeprecated('keep-app-running')) {
_logger!.printStatus('Leaving the application running.');
} else {
final File skslFile = stringArgDeprecated('write-sksl-on-exit') != null
final File? skslFile = stringArgDeprecated('write-sksl-on-exit') != null
? _fileSystem.file(stringArgDeprecated('write-sksl-on-exit'))
: null;
await driverService.stop(userIdentifier: userIdentifier, writeSkslOnExit: skslFile);
......@@ -316,8 +316,8 @@ class DriveCommand extends RunCommandBase {
return FlutterCommandResult.success();
}
String _getTestFile() {
if (argResults['driver'] != null) {
String? _getTestFile() {
if (argResults!['driver'] != null) {
return stringArgDeprecated('driver');
}
......@@ -332,7 +332,7 @@ class DriveCommand extends RunCommandBase {
// for the corresponding test file relative to it.
if (!_fileSystem.path.isRelative(appFile)) {
if (!_fileSystem.path.isWithin(packageDir, appFile)) {
_logger.printError(
_logger!.printError(
'Application file $appFile is outside the package directory $packageDir'
);
return null;
......@@ -344,7 +344,7 @@ class DriveCommand extends RunCommandBase {
final List<String> parts = _fileSystem.path.split(appFile);
if (parts.length < 2) {
_logger.printError(
_logger!.printError(
'Application file $appFile must reside in one of the sub-directories '
'of the package structure, not in the root directory.'
);
......@@ -372,9 +372,9 @@ class DriveCommand extends RunCommandBase {
'png',
);
await device.takeScreenshot(outputFile);
_logger.printStatus('Screenshot written to ${outputFile.path}');
_logger!.printStatus('Screenshot written to ${outputFile.path}');
} on Exception catch (error) {
_logger.printError('Error taking screenshot: $error');
_logger!.printError('Error taking screenshot: $error');
}
}
}
......@@ -2,10 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'package:meta/meta.dart';
import '../base/common.dart';
import '../base/logger.dart';
import '../base/platform.dart';
......@@ -18,10 +14,10 @@ import '../runner/flutter_command.dart';
class PrecacheCommand extends FlutterCommand {
PrecacheCommand({
bool verboseHelp = false,
@required Cache cache,
@required Platform platform,
@required Logger logger,
@required FeatureFlags featureFlags,
required Cache? cache,
required Platform platform,
required Logger logger,
required FeatureFlags featureFlags,
}) : _cache = cache,
_platform = platform,
_logger = logger,
......@@ -30,39 +26,39 @@ class PrecacheCommand extends FlutterCommand {
help: 'Precache artifacts for all host platforms.');
argParser.addFlag('force', abbr: 'f', negatable: false,
help: 'Force re-downloading of artifacts.');
argParser.addFlag('android', negatable: true, defaultsTo: false,
argParser.addFlag('android',
help: 'Precache artifacts for Android development.',
hide: !verboseHelp);
argParser.addFlag('android_gen_snapshot', negatable: true, defaultsTo: false,
argParser.addFlag('android_gen_snapshot',
help: 'Precache gen_snapshot for Android development.',
hide: !verboseHelp);
argParser.addFlag('android_maven', negatable: true, defaultsTo: false,
argParser.addFlag('android_maven',
help: 'Precache Gradle dependencies for Android development.',
hide: !verboseHelp);
argParser.addFlag('android_internal_build', negatable: true, defaultsTo: false,
argParser.addFlag('android_internal_build',
help: 'Precache dependencies for internal Android development.',
hide: !verboseHelp);
argParser.addFlag('ios', negatable: true, defaultsTo: false,
argParser.addFlag('ios',
help: 'Precache artifacts for iOS development.');
argParser.addFlag('web', negatable: true, defaultsTo: false,
argParser.addFlag('web',
help: 'Precache artifacts for web development.');
argParser.addFlag('linux', negatable: true, defaultsTo: false,
argParser.addFlag('linux',
help: 'Precache artifacts for Linux desktop development.');
argParser.addFlag('windows', negatable: true, defaultsTo: false,
argParser.addFlag('windows',
help: 'Precache artifacts for Windows desktop development.');
argParser.addFlag('macos', negatable: true, defaultsTo: false,
argParser.addFlag('macos',
help: 'Precache artifacts for macOS desktop development.');
argParser.addFlag('fuchsia', negatable: true, defaultsTo: false,
argParser.addFlag('fuchsia',
help: 'Precache artifacts for Fuchsia development.');
argParser.addFlag('universal', negatable: true, defaultsTo: true,
argParser.addFlag('universal', defaultsTo: true,
help: 'Precache artifacts required for any development platform.');
argParser.addFlag('flutter_runner', negatable: true, defaultsTo: false,
argParser.addFlag('flutter_runner',
help: 'Precache the flutter runner artifacts.', hide: !verboseHelp);
argParser.addFlag('use-unsigned-mac-binaries', negatable: true, defaultsTo: false,
argParser.addFlag('use-unsigned-mac-binaries',
help: 'Precache the unsigned macOS binaries when available.', hide: !verboseHelp);
}
final Cache _cache;
final Cache? _cache;
final Logger _logger;
final Platform _platform;
final FeatureFlags _featureFlags;
......@@ -106,9 +102,9 @@ class PrecacheCommand extends FlutterCommand {
Set<String> _explicitArtifactSelections() {
final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap();
final Set<String> selections = <String>{};
bool explicitlySelected(String name) => boolArgDeprecated(name) && argResults.wasParsed(name);
bool explicitlySelected(String name) => boolArgDeprecated(name) && argResults!.wasParsed(name);
for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) {
final String umbrellaName = umbrellaForArtifact[artifact.name];
final String? umbrellaName = umbrellaForArtifact[artifact.name];
if (explicitlySelected(artifact.name) ||
(umbrellaName != null && explicitlySelected(umbrellaName))) {
selections.add(artifact.name);
......@@ -120,11 +116,11 @@ class PrecacheCommand extends FlutterCommand {
@override
Future<void> validateCommand() {
_expandedArtifacts.forEach((String umbrellaName, List<String> childArtifactNames) {
if (!argResults.arguments.contains('--no-$umbrellaName')) {
if (!argResults!.arguments.contains('--no-$umbrellaName')) {
return;
}
for (final String childArtifactName in childArtifactNames) {
if (argResults.arguments.contains('--$childArtifactName')) {
if (argResults!.arguments.contains('--$childArtifactName')) {
throwToolExit('--$childArtifactName requires --$umbrellaName');
}
}
......@@ -137,21 +133,21 @@ class PrecacheCommand extends FlutterCommand {
Future<FlutterCommandResult> runCommand() async {
// Re-lock the cache.
if (_platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') {
await _cache.lock();
await _cache!.lock();
}
if (boolArgDeprecated('force')) {
_cache.clearStampFiles();
_cache!.clearStampFiles();
}
final bool includeAllPlatforms = boolArgDeprecated('all-platforms');
if (includeAllPlatforms) {
_cache.includeAllPlatforms = true;
_cache!.includeAllPlatforms = true;
}
if (boolArgDeprecated('use-unsigned-mac-binaries')) {
_cache.useUnsignedMacBinaries = true;
_cache!.useUnsignedMacBinaries = true;
}
final Set<String> explicitlyEnabled = _explicitArtifactSelections();
_cache.platformOverrideArtifacts = explicitlyEnabled;
_cache!.platformOverrideArtifacts = explicitlyEnabled;
// If the user did not provide any artifact flags, then download
// all artifacts that correspond to an enabled platform.
......@@ -159,7 +155,7 @@ class PrecacheCommand extends FlutterCommand {
final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap();
final Set<DevelopmentArtifact> requiredArtifacts = <DevelopmentArtifact>{};
for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) {
if (artifact.feature != null && !_featureFlags.isEnabled(artifact.feature)) {
if (artifact.feature != null && !_featureFlags.isEnabled(artifact.feature!)) {
continue;
}
......@@ -168,8 +164,8 @@ class PrecacheCommand extends FlutterCommand {
requiredArtifacts.add(artifact);
}
}
if (!await _cache.isUpToDate()) {
await _cache.updateAll(requiredArtifacts);
if (!await _cache!.isUpToDate()) {
await _cache!.updateAll(requiredArtifacts);
} else {
_logger.printStatus('Already up-to-date.');
}
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:math' as math;
......@@ -95,7 +95,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests',
)
..addFlag('start-paused',
defaultsTo: false,
negatable: false,
help: 'Start in a paused mode and wait for a debugger to connect.\n'
'You must specify a single test file to run, explicitly.\n'
......@@ -103,23 +102,19 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
'console once the test has started.',
)
..addFlag('run-skipped',
defaultsTo: false,
help: 'Run skipped tests instead of skipping them.',
)
..addFlag('disable-service-auth-codes',
defaultsTo: false,
negatable: false,
hide: !verboseHelp,
help: '(deprecated) Allow connections to the VM service without using authentication codes. '
'(Not recommended! This can open your device to remote code execution attacks!)'
)
..addFlag('coverage',
defaultsTo: false,
negatable: false,
help: 'Whether to collect coverage information.',
)
..addFlag('merge-coverage',
defaultsTo: false,
negatable: false,
help: 'Whether to merge coverage data with "coverage/lcov.base.info".\n'
'Implies collecting coverage data. (Requires lcov.)',
......@@ -153,7 +148,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
)
..addFlag('test-assets',
defaultsTo: true,
negatable: true,
help: 'Whether to build the assets bundle for testing. '
'This takes additional time before running the tests. '
'Consider using "--no-test-assets" if assets are not required.',
......@@ -191,7 +185,6 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
'them separately.'
)
..addFlag('enable-vmservice',
defaultsTo: false,
hide: !verboseHelp,
help: 'Enables the VM service without "--start-paused". This flag is '
'intended for use with tests that will use "dart:developer" to '
......@@ -255,8 +248,8 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
String get category => FlutterCommandCategory.project;
@override
Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) {
_testFiles = argResults.rest.map<String>(globals.fs.path.absolute).toList();
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) {
_testFiles = argResults!.rest.map<String>(globals.fs.path.absolute).toList();
if (_testFiles.isEmpty) {
// We don't scan the entire package, only the test/ subdirectory, so that
// files with names like "hit_test.dart" don't get run.
......@@ -305,8 +298,8 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
final bool buildTestAssets = boolArgDeprecated('test-assets');
final List<String> names = stringsArg('name');
final List<String> plainNames = stringsArg('plain-name');
final String tags = stringArgDeprecated('tags');
final String excludeTags = stringArgDeprecated('exclude-tags');
final String? tags = stringArgDeprecated('tags');
final String? excludeTags = stringArgDeprecated('exclude-tags');
final BuildInfo buildInfo = await getBuildInfo(forcedBuildMode: BuildMode.debug);
if (buildInfo.packageConfig['test_api'] == null) {
......@@ -320,11 +313,11 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
);
}
String testAssetDirectory;
String? testAssetDirectory;
if (buildTestAssets) {
await _buildTestAsset();
testAssetDirectory = globals.fs.path.
join(flutterProject?.directory?.path ?? '', 'build', 'unit_test_assets');
join(flutterProject.directory.path, 'build', 'unit_test_assets');
}
final bool startPaused = boolArgDeprecated('start-paused');
......@@ -335,14 +328,14 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
);
}
int jobs = int.tryParse(stringArgDeprecated('concurrency'));
int? jobs = int.tryParse(stringArgDeprecated('concurrency')!);
if (jobs == null || jobs <= 0 || !jobs.isFinite) {
throwToolExit(
'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
);
}
if (_isIntegrationTest) {
if (argResults.wasParsed('concurrency')) {
if (argResults!.wasParsed('concurrency')) {
globals.printStatus(
'-j/--concurrency was parsed but will be ignored, this option is not '
'supported when running Integration Tests.',
......@@ -353,13 +346,13 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
jobs = 1;
}
final int shardIndex = int.tryParse(stringArgDeprecated('shard-index') ?? '');
final int? shardIndex = int.tryParse(stringArgDeprecated('shard-index') ?? '');
if (shardIndex != null && (shardIndex < 0 || !shardIndex.isFinite)) {
throwToolExit(
'Could not parse --shard-index=$shardIndex argument. It must be an integer greater than -1.');
}
final int totalShards = int.tryParse(stringArgDeprecated('total-shards') ?? '');
final int? totalShards = int.tryParse(stringArgDeprecated('total-shards') ?? '');
if (totalShards != null && (totalShards <= 0 || !totalShards.isFinite)) {
throwToolExit(
'Could not parse --total-shards=$totalShards argument. It must be an integer greater than zero.');
......@@ -375,7 +368,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
}
final bool machine = boolArgDeprecated('machine');
CoverageCollector collector;
CoverageCollector? collector;
if (boolArgDeprecated('coverage') || boolArgDeprecated('merge-coverage')) {
final String projectName = flutterProject.manifest.appName;
collector = CoverageCollector(
......@@ -385,7 +378,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
);
}
TestWatcher watcher;
TestWatcher? watcher;
if (machine) {
watcher = EventPrinter(parent: collector, out: globals.stdio.stdout);
} else if (collector != null) {
......@@ -402,7 +395,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
nullAssertions: boolArgDeprecated(FlutterOptions.kNullAssertions),
);
Device integrationTestDevice;
Device? integrationTestDevice;
if (_isIntegrationTest) {
integrationTestDevice = await findTargetDevice();
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
......@@ -70,12 +70,12 @@ import 'windows/windows_workflow.dart';
Future<T> runInContext<T>(
FutureOr<T> Function() runner, {
Map<Type, Generator> overrides,
Map<Type, Generator>? overrides,
}) async {
// Wrap runner with any asynchronous initialization that should run with the
// overrides and callbacks.
bool runningOnBot;
late bool runningOnBot;
FutureOr<T> runnerWrapper() async {
runningOnBot = await globals.isRunningOnBot;
return runner();
......@@ -90,9 +90,9 @@ Future<T> runInContext<T>(
logger: globals.logger,
processManager: globals.processManager,
fileSystem: globals.fs,
artifacts: globals.artifacts,
artifacts: globals.artifacts!,
usage: globals.flutterUsage,
gradleUtils: globals.gradleUtils,
gradleUtils: globals.gradleUtils!,
platform: globals.platform,
),
AndroidLicenseValidator: () => AndroidLicenseValidator(
......@@ -158,11 +158,11 @@ Future<T> runInContext<T>(
processManager: globals.processManager,
logger: globals.logger,
platform: globals.platform,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
usage: globals.flutterUsage,
),
CocoaPodsValidator: () => CocoaPodsValidator(
globals.cocoaPods,
globals.cocoaPods!,
globals.userMessages,
),
Config: () => Config(
......@@ -187,29 +187,29 @@ Future<T> runInContext<T>(
processManager: globals.processManager,
platform: globals.platform,
androidSdk: globals.androidSdk,
iosSimulatorUtils: globals.iosSimulatorUtils,
iosSimulatorUtils: globals.iosSimulatorUtils!,
featureFlags: featureFlags,
fileSystem: globals.fs,
iosWorkflow: globals.iosWorkflow,
artifacts: globals.artifacts,
iosWorkflow: globals.iosWorkflow!,
artifacts: globals.artifacts!,
flutterVersion: globals.flutterVersion,
androidWorkflow: androidWorkflow,
fuchsiaWorkflow: fuchsiaWorkflow,
xcDevice: globals.xcdevice,
androidWorkflow: androidWorkflow!,
fuchsiaWorkflow: fuchsiaWorkflow!,
xcDevice: globals.xcdevice!,
userMessages: globals.userMessages,
windowsWorkflow: windowsWorkflow,
windowsWorkflow: windowsWorkflow!,
macOSWorkflow: MacOSWorkflow(
platform: globals.platform,
featureFlags: featureFlags,
),
fuchsiaSdk: globals.fuchsiaSdk,
fuchsiaSdk: globals.fuchsiaSdk!,
operatingSystemUtils: globals.os,
terminal: globals.terminal,
customDevicesConfig: globals.customDevicesConfig,
),
DevtoolsLauncher: () => DevtoolsServerLauncher(
processManager: globals.processManager,
dartExecutable: globals.artifacts.getHostArtifact(HostArtifact.engineDartBinary).path,
dartExecutable: globals.artifacts!.getHostArtifact(HostArtifact.engineDartBinary).path,
logger: globals.logger,
botDetector: globals.botDetector,
),
......@@ -220,7 +220,7 @@ Future<T> runInContext<T>(
processManager: globals.processManager,
logger: globals.logger,
fileSystem: globals.fs,
androidWorkflow: androidWorkflow,
androidWorkflow: androidWorkflow!,
),
FeatureFlags: () => FlutterFeatureFlags(
flutterVersion: globals.flutterVersion,
......@@ -234,7 +234,7 @@ Future<T> runInContext<T>(
FuchsiaWorkflow: () => FuchsiaWorkflow(
featureFlags: featureFlags,
platform: globals.platform,
fuchsiaArtifacts: globals.fuchsiaArtifacts,
fuchsiaArtifacts: globals.fuchsiaArtifacts!,
),
GradleUtils: () => GradleUtils(
fileSystem: globals.fs,
......@@ -247,11 +247,11 @@ Future<T> runInContext<T>(
IOSSimulatorUtils: () => IOSSimulatorUtils(
logger: globals.logger,
processManager: globals.processManager,
xcode: globals.xcode,
xcode: globals.xcode!,
),
IOSWorkflow: () => IOSWorkflow(
featureFlags: featureFlags,
xcode: globals.xcode,
xcode: globals.xcode!,
platform: globals.platform,
),
LocalEngineLocator: () => LocalEngineLocator(
......@@ -259,7 +259,7 @@ Future<T> runInContext<T>(
logger: globals.logger,
platform: globals.platform,
fileSystem: globals.fs,
flutterRoot: Cache.flutterRoot,
flutterRoot: Cache.flutterRoot!,
),
Logger: () => globals.platform.isWindows
? WindowsStdoutLogger(
......@@ -287,7 +287,7 @@ Future<T> runInContext<T>(
processManager: globals.processManager,
),
OutputPreferences: () => OutputPreferences(
wrapText: globals.stdio.hasTerminal ?? false,
wrapText: globals.stdio.hasTerminal,
showColor: globals.platform.stdoutSupportsAnsi,
stdio: globals.stdio,
),
......@@ -318,7 +318,7 @@ Future<T> runInContext<T>(
SystemClock: () => const SystemClock(),
Usage: () => Usage(
runningOnBot: runningOnBot,
firstRunMessenger: FirstRunMessenger(persistentToolState: globals.persistentToolState),
firstRunMessenger: FirstRunMessenger(persistentToolState: globals.persistentToolState!),
),
UserMessages: () => UserMessages(),
VisualStudioValidator: () => VisualStudioValidator(
......@@ -343,17 +343,17 @@ Future<T> runInContext<T>(
processManager: globals.processManager,
platform: globals.platform,
fileSystem: globals.fs,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
),
XCDevice: () => XCDevice(
processManager: globals.processManager,
logger: globals.logger,
artifacts: globals.artifacts,
artifacts: globals.artifacts!,
cache: globals.cache,
platform: globals.platform,
xcode: globals.xcode,
xcode: globals.xcode!,
iproxy: IProxy(
iproxyPath: globals.artifacts.getHostArtifact(
iproxyPath: globals.artifacts!.getHostArtifact(
HostArtifact.iproxy,
).path,
logger: globals.logger,
......
......@@ -301,7 +301,7 @@ class DaemonConnection {
}
/// Sends an error response to the other end of the connection.
void sendErrorResponse(Object id, Object error, StackTrace trace) {
void sendErrorResponse(Object id, Object? error, StackTrace trace) {
_daemonStreams.send(<String, Object?>{
'id': id,
'error': error,
......
......@@ -44,7 +44,7 @@ abstract class DesktopDevice extends Device {
final DesktopLogReader _deviceLogReader = DesktopLogReader();
@override
DevFSWriter createDevFSWriter(covariant ApplicationPackage app, String userIdentifier) {
DevFSWriter createDevFSWriter(covariant ApplicationPackage? app, String? userIdentifier) {
return LocalDevFSWriter(fileSystem: _fileSystem);
}
......
......@@ -477,7 +477,7 @@ class DevFS {
final StopwatchFactory _stopwatchFactory;
final String fsName;
final Directory rootDirectory;
final Directory? rootDirectory;
final Set<String> assetPathsToEvict = <String>{};
// A flag to indicate whether we have called `setAssetDirectory` on the target device.
......@@ -497,7 +497,7 @@ class DevFS {
final String baseUriString = baseUri.toString();
if (deviceUriString.startsWith(baseUriString)) {
final String deviceUriSuffix = deviceUriString.substring(baseUriString.length);
return rootDirectory.uri.resolve(deviceUriSuffix);
return rootDirectory!.uri.resolve(deviceUriSuffix);
}
return deviceUri;
}
......
......@@ -557,8 +557,8 @@ abstract class Device {
/// For example, the desktop device classes can use a writer which
/// copies the files across the local file system.
DevFSWriter? createDevFSWriter(
covariant ApplicationPackage app,
String userIdentifier,
covariant ApplicationPackage? app,
String? userIdentifier,
) {
return null;
}
......@@ -593,7 +593,7 @@ abstract class Device {
/// [platformArgs] allows callers to pass platform-specific arguments to the
/// start call. The build mode is not used by all platforms.
Future<LaunchResult> startApp(
covariant ApplicationPackage package, {
covariant ApplicationPackage? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
......@@ -624,7 +624,7 @@ abstract class Device {
///
/// Specify [userIdentifier] to stop app installed to a profile (Android only).
Future<bool> stopApp(
covariant ApplicationPackage app, {
covariant ApplicationPackage? app, {
String? userIdentifier,
});
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
......@@ -20,10 +20,10 @@ import 'resident_runner.dart';
/// start a server instance.
class DevtoolsServerLauncher extends DevtoolsLauncher {
DevtoolsServerLauncher({
@required ProcessManager processManager,
@required String dartExecutable,
@required Logger logger,
@required BotDetector botDetector,
required ProcessManager processManager,
required String dartExecutable,
required Logger? logger,
required BotDetector botDetector,
}) : _processManager = processManager,
_dartExecutable = dartExecutable,
_logger = logger,
......@@ -31,14 +31,14 @@ class DevtoolsServerLauncher extends DevtoolsLauncher {
final ProcessManager _processManager;
final String _dartExecutable;
final Logger _logger;
final Logger? _logger;
final BotDetector _botDetector;
final Completer<void> _processStartCompleter = Completer<void>();
io.Process _devToolsProcess;
io.Process? _devToolsProcess;
bool _devToolsProcessKilled = false;
@visibleForTesting
Future<void> devToolsProcessExit;
Future<void>? devToolsProcessExit;
static final RegExp _serveDevToolsPattern =
RegExp(r'Serving DevTools at ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+?)\.?$');
......@@ -47,7 +47,7 @@ class DevtoolsServerLauncher extends DevtoolsLauncher {
Future<void> get processStart => _processStartCompleter.future;
@override
Future<void> launch(Uri vmServiceUri, {List<String> additionalArguments}) async {
Future<void> launch(Uri? vmServiceUri, {List<String>? additionalArguments}) async {
// Place this entire method in a try/catch that swallows exceptions because
// this method is guaranteed not to return a Future that throws.
try {
......@@ -60,23 +60,23 @@ class DevtoolsServerLauncher extends DevtoolsLauncher {
]);
_processStartCompleter.complete();
final Completer<Uri> completer = Completer<Uri>();
_devToolsProcess.stdout
_devToolsProcess!.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String line) {
final Match match = _serveDevToolsPattern.firstMatch(line);
final Match? match = _serveDevToolsPattern.firstMatch(line);
if (match != null) {
final String url = match[1];
final String url = match[1]!;
completer.complete(Uri.parse(url));
}
});
_devToolsProcess.stderr
_devToolsProcess!.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(_logger.printError);
.listen(_logger!.printError);
final bool runningOnBot = await _botDetector.isRunningOnBot;
devToolsProcessExit = _devToolsProcess.exitCode.then(
devToolsProcessExit = _devToolsProcess!.exitCode.then(
(int exitCode) {
if (!_devToolsProcessKilled && runningOnBot) {
throwToolExit('DevTools process failed: exitCode=$exitCode');
......@@ -86,12 +86,12 @@ class DevtoolsServerLauncher extends DevtoolsLauncher {
devToolsUrl = await completer.future;
} on Exception catch (e, st) {
_logger.printError('Failed to launch DevTools: $e', stackTrace: st);
_logger!.printError('Failed to launch DevTools: $e', stackTrace: st);
}
}
@override
Future<DevToolsServerAddress> serve() async {
Future<DevToolsServerAddress?> serve() async {
if (activeDevToolsServer == null) {
await launch(null);
}
......@@ -105,7 +105,7 @@ class DevtoolsServerLauncher extends DevtoolsLauncher {
}
if (_devToolsProcess != null) {
_devToolsProcessKilled = true;
_devToolsProcess.kill();
_devToolsProcess!.kill();
}
}
}
......@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
import 'package:dds/dds.dart' as dds;
......@@ -25,11 +23,11 @@ import 'web_driver_service.dart';
class FlutterDriverFactory {
FlutterDriverFactory({
@required ApplicationPackageFactory applicationPackageFactory,
@required Logger logger,
@required ProcessUtils processUtils,
@required String dartSdkPath,
@required DevtoolsLauncher devtoolsLauncher,
required ApplicationPackageFactory applicationPackageFactory,
required Logger logger,
required ProcessUtils processUtils,
required String dartSdkPath,
required DevtoolsLauncher devtoolsLauncher,
}) : _applicationPackageFactory = applicationPackageFactory,
_logger = logger,
_processUtils = processUtils,
......@@ -69,10 +67,10 @@ abstract class DriverService {
Device device,
DebuggingOptions debuggingOptions,
bool ipv6, {
File applicationBinary,
String route,
String userIdentifier,
String mainPath,
File? applicationBinary,
String? route,
String? userIdentifier,
String? mainPath,
Map<String, Object> platformArgs = const <String, Object>{},
});
......@@ -94,13 +92,13 @@ abstract class DriverService {
List<String> arguments,
Map<String, String> environment,
PackageConfig packageConfig, {
bool headless,
String chromeBinary,
String browserName,
bool androidEmulator,
int driverPort,
List<String> browserDimension,
String profileMemory,
bool? headless,
String? chromeBinary,
String? browserName,
bool? androidEmulator,
int? driverPort,
List<String>? browserDimension,
String? profileMemory,
});
/// Stop the running application and uninstall it from the device.
......@@ -109,8 +107,8 @@ abstract class DriverService {
/// and write SkSL to the file. This is only supported on mobile and
/// desktop devices.
Future<void> stop({
File writeSkslOnExit,
String userIdentifier,
File? writeSkslOnExit,
String? userIdentifier,
});
}
......@@ -118,11 +116,11 @@ abstract class DriverService {
/// applications.
class FlutterDriverService extends DriverService {
FlutterDriverService({
@required ApplicationPackageFactory applicationPackageFactory,
@required Logger logger,
@required ProcessUtils processUtils,
@required String dartSdkPath,
@required DevtoolsLauncher devtoolsLauncher,
required ApplicationPackageFactory applicationPackageFactory,
required Logger logger,
required ProcessUtils processUtils,
required String dartSdkPath,
required DevtoolsLauncher devtoolsLauncher,
@visibleForTesting VMServiceConnector vmServiceConnector = connectToVmService,
}) : _applicationPackageFactory = applicationPackageFactory,
_logger = logger,
......@@ -140,10 +138,10 @@ class FlutterDriverService extends DriverService {
final VMServiceConnector _vmServiceConnector;
final DevtoolsLauncher _devtoolsLauncher;
Device _device;
ApplicationPackage _applicationPackage;
String _vmServiceUri;
FlutterVmService _vmService;
Device? _device;
ApplicationPackage? _applicationPackage;
late String _vmServiceUri;
late FlutterVmService _vmService;
@override
Future<void> start(
......@@ -151,11 +149,11 @@ class FlutterDriverService extends DriverService {
Device device,
DebuggingOptions debuggingOptions,
bool ipv6, {
File applicationBinary,
String route,
String userIdentifier,
File? applicationBinary,
String? route,
String? userIdentifier,
Map<String, Object> platformArgs = const <String, Object>{},
String mainPath,
String? mainPath,
}) async {
if (buildInfo.isRelease) {
throwToolExit(
......@@ -173,7 +171,7 @@ class FlutterDriverService extends DriverService {
applicationBinary: applicationBinary,
);
int attempt = 0;
LaunchResult result;
LaunchResult? result;
bool prebuiltApplication = applicationBinary != null;
while (attempt < _kLaunchAttempts) {
result = await device.startApp(
......@@ -197,7 +195,7 @@ class FlutterDriverService extends DriverService {
throwToolExit('Application failed to start. Will not run test. Quitting.', exitCode: 1);
}
return reuseApplication(
result.observatoryUri,
result.observatoryUri!,
device,
debuggingOptions,
ipv6,
......@@ -251,13 +249,13 @@ class FlutterDriverService extends DriverService {
List<String> arguments,
Map<String, String> environment,
PackageConfig packageConfig, {
bool headless,
String chromeBinary,
String browserName,
bool androidEmulator,
int driverPort,
List<String> browserDimension,
String profileMemory,
bool? headless,
String? chromeBinary,
String? browserName,
bool? androidEmulator,
int? driverPort,
List<String>? browserDimension,
String? profileMemory,
}) async {
if (profileMemory != null) {
unawaited(_devtoolsLauncher.launch(
......@@ -285,35 +283,35 @@ class FlutterDriverService extends DriverService {
@override
Future<void> stop({
File writeSkslOnExit,
String userIdentifier,
File? writeSkslOnExit,
String? userIdentifier,
}) async {
if (writeSkslOnExit != null) {
final FlutterView flutterView = (await _vmService.getFlutterViews()).first;
final Map<String, Object> result = await _vmService.getSkSLs(
final Map<String, Object> result = await (_vmService.getSkSLs(
viewId: flutterView.id
);
await sharedSkSlWriter(_device, result, outputFile: writeSkslOnExit, logger: _logger);
) as FutureOr<Map<String, Object>>);
await sharedSkSlWriter(_device!, result, outputFile: writeSkslOnExit, logger: _logger);
}
// If the application package is available, stop and uninstall.
if (_applicationPackage != null) {
if (!await _device.stopApp(_applicationPackage, userIdentifier: userIdentifier)) {
if (!await _device!.stopApp(_applicationPackage, userIdentifier: userIdentifier)) {
_logger.printError('Failed to stop app');
}
if (!await _device.uninstallApp(_applicationPackage, userIdentifier: userIdentifier)) {
if (!await _device!.uninstallApp(_applicationPackage!, userIdentifier: userIdentifier)) {
_logger.printError('Failed to uninstall app');
}
} else if (_device.supportsFlutterExit) {
} else if (_device!.supportsFlutterExit) {
// Otherwise use the VM Service URI to stop the app as a best effort approach.
final vm_service.VM vm = await _vmService.service.getVM();
final vm_service.IsolateRef isolateRef = vm.isolates
final vm_service.IsolateRef isolateRef = vm.isolates!
.firstWhere((vm_service.IsolateRef element) {
return !element.isSystemIsolate;
}, orElse: () => null);
unawaited(_vmService.flutterExit(isolateId: isolateRef.id));
return !element.isSystemIsolate!;
});
unawaited(_vmService.flutterExit(isolateId: isolateRef.id!));
} else {
_logger.printTrace('No application package for $_device, leaving app running');
}
await _device.dispose();
await _device!.dispose();
}
}
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
import 'dart:math' as math;
......@@ -28,9 +28,9 @@ import 'drive_service.dart';
/// An implementation of the driver service for web debug and release applications.
class WebDriverService extends DriverService {
WebDriverService({
@required ProcessUtils processUtils,
@required String dartSdkPath,
@required Logger logger,
required ProcessUtils processUtils,
required String dartSdkPath,
required Logger logger,
}) : _processUtils = processUtils,
_dartSdkPath = dartSdkPath,
_logger = logger;
......@@ -39,15 +39,15 @@ class WebDriverService extends DriverService {
final String _dartSdkPath;
final Logger _logger;
ResidentRunner _residentRunner;
Uri _webUri;
late ResidentRunner _residentRunner;
Uri? _webUri;
/// The result of [ResidentRunner.run].
///
/// This is expected to stay `null` throughout the test, as the application
/// must be running until [stop] is called. If it becomes non-null, it likely
/// indicates a bug.
int _runResult;
int? _runResult;
@override
Future<void> start(
......@@ -55,10 +55,10 @@ class WebDriverService extends DriverService {
Device device,
DebuggingOptions debuggingOptions,
bool ipv6, {
File applicationBinary,
String route,
String userIdentifier,
String mainPath,
File? applicationBinary,
String? route,
String? userIdentifier,
String? mainPath,
Map<String, Object> platformArgs = const <String, Object>{},
}) async {
final FlutterDevice flutterDevice = await FlutterDevice.create(
......@@ -67,7 +67,7 @@ class WebDriverService extends DriverService {
buildInfo: buildInfo,
platform: globals.platform,
);
_residentRunner = webRunnerFactory.createWebRunner(
_residentRunner = webRunnerFactory!.createWebRunner(
flutterDevice,
target: mainPath,
ipv6: ipv6,
......@@ -90,21 +90,21 @@ class WebDriverService extends DriverService {
systemClock: globals.systemClock,
);
final Completer<void> appStartedCompleter = Completer<void>.sync();
final Future<int> runFuture = _residentRunner.run(
final Future<int?> runFuture = _residentRunner.run(
appStartedCompleter: appStartedCompleter,
route: route,
);
bool isAppStarted = false;
await Future.any<Object>(<Future<Object>>[
runFuture.then((int result) {
runFuture.then((int? result) {
_runResult = result;
return null;
}),
} as FutureOr<Object> Function(int?)),
appStartedCompleter.future.then((_) {
isAppStarted = true;
return null;
}),
} as FutureOr<Object> Function(void)),
]);
if (_runResult != null) {
......@@ -126,22 +126,25 @@ class WebDriverService extends DriverService {
}
@override
Future<int> startTest(String testFile, List<String> arguments, Map<String, String> environment, PackageConfig packageConfig, {
@required bool headless,
String chromeBinary,
@required String browserName,
bool androidEmulator,
int driverPort,
List<String> browserDimension,
String profileMemory,
Future<int> startTest(
String testFile,
List<String> arguments,
Map<String, String> environment,
PackageConfig packageConfig, {
bool? headless,
String? chromeBinary,
String? browserName,
bool? androidEmulator,
int? driverPort,
List<String>? browserDimension,
String? profileMemory,
}) async {
async_io.WebDriver webDriver;
late async_io.WebDriver webDriver;
final Browser browser = _browserNameToEnum(browserName);
try {
webDriver = await async_io.createDriver(
uri: Uri.parse('http://localhost:$driverPort/'),
desired: getDesiredCapabilities(browser, headless, chromeBinary),
spec: async_io.WebDriverSpec.Auto
);
} on SocketException catch (error) {
_logger.printTrace('$error');
......@@ -156,11 +159,11 @@ class WebDriverService extends DriverService {
final bool isAndroidChrome = browser == Browser.androidChrome;
// Do not set the window size for android chrome browser.
if (!isAndroidChrome) {
assert(browserDimension.length == 2);
int x;
int y;
assert(browserDimension!.length == 2);
late int x;
late int y;
try {
x = int.parse(browserDimension[0]);
x = int.parse(browserDimension![0]);
y = int.parse(browserDimension[1]);
} on FormatException catch (ex) {
throwToolExit('Dimension provided to --browser-dimension is invalid: $ex');
......@@ -184,7 +187,7 @@ class WebDriverService extends DriverService {
}
@override
Future<void> stop({File writeSkslOnExit, String userIdentifier}) async {
Future<void> stop({File? writeSkslOnExit, String? userIdentifier}) async {
final bool appDidFinishPrematurely = _runResult != null;
await _residentRunner.exitApp();
await _residentRunner.cleanupAtFinish();
......@@ -197,7 +200,7 @@ class WebDriverService extends DriverService {
}
}
Map<String, String> _additionalDriverEnvironment(async_io.WebDriver webDriver, String browserName, bool androidEmulator) {
Map<String, String> _additionalDriverEnvironment(async_io.WebDriver webDriver, String? browserName, bool? androidEmulator) {
return <String, String>{
'DRIVER_SESSION_ID': webDriver.id,
'DRIVER_SESSION_URI': webDriver.uri.toString(),
......@@ -205,7 +208,7 @@ class WebDriverService extends DriverService {
'DRIVER_SESSION_CAPABILITIES': json.encode(webDriver.capabilities),
'SUPPORT_TIMELINE_ACTION': (_browserNameToEnum(browserName) == Browser.chrome).toString(),
'FLUTTER_WEB_TEST': 'true',
'ANDROID_CHROME_ON_EMULATOR': (_browserNameToEnum(browserName) == Browser.androidChrome && androidEmulator).toString(),
'ANDROID_CHROME_ON_EMULATOR': (_browserNameToEnum(browserName) == Browser.androidChrome && androidEmulator!).toString(),
};
}
......@@ -234,7 +237,7 @@ enum Browser {
/// Returns desired capabilities for given [browser], [headless] and
/// [chromeBinary].
@visibleForTesting
Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless, [String chromeBinary]) {
Map<String, dynamic> getDesiredCapabilities(Browser browser, bool? headless, [String? chromeBinary]) {
switch (browser) {
case Browser.chrome:
return <String, dynamic>{
......@@ -258,7 +261,7 @@ Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless, [Str
'--no-default-browser-check',
'--no-sandbox',
'--no-first-run',
if (headless) '--headless',
if (headless!) '--headless',
],
'perfLoggingPrefs': <String, String>{
'traceCategories':
......@@ -268,14 +271,13 @@ Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless, [Str
},
},
};
break;
case Browser.firefox:
return <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'firefox',
'moz:firefoxOptions' : <String, dynamic>{
'args': <String>[
if (headless) '-headless',
if (headless!) '-headless',
],
'prefs': <String, dynamic>{
'dom.file.createInChild': true,
......@@ -290,18 +292,15 @@ Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless, [Str
'log': <String, String>{'level': 'trace'},
},
};
break;
case Browser.edge:
return <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'edge',
};
break;
case Browser.safari:
return <String, dynamic>{
'browserName': 'safari',
};
break;
case Browser.iosSafari:
return <String, dynamic>{
'platformName': 'ios',
......@@ -318,11 +317,10 @@ Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless, [Str
},
};
}
throw UnsupportedError('Browser $browser not supported.'); // dead code; remove with null safety migration
}
/// Converts [browserName] string to [Browser]
Browser _browserNameToEnum(String browserName) {
Browser _browserNameToEnum(String? browserName) {
switch (browserName) {
case 'android-chrome': return Browser.androidChrome;
case 'chrome': return Browser.chrome;
......
......@@ -25,7 +25,7 @@ import 'windows/application_package.dart';
/// A package factory that supports all Flutter target platforms.
class FlutterApplicationPackageFactory extends ApplicationPackageFactory {
FlutterApplicationPackageFactory({
required AndroidSdk androidSdk,
required AndroidSdk? androidSdk,
required ProcessManager processManager,
required Logger logger,
required UserMessages userMessages,
......@@ -38,7 +38,7 @@ class FlutterApplicationPackageFactory extends ApplicationPackageFactory {
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
final AndroidSdk _androidSdk;
final AndroidSdk? _androidSdk;
final ProcessManager _processManager;
final Logger _logger;
final ProcessUtils _processUtils;
......@@ -72,7 +72,7 @@ class FlutterApplicationPackageFactory extends ApplicationPackageFactory {
applicationBinary,
processManager: _processManager,
logger: _logger,
androidSdk: _androidSdk,
androidSdk: _androidSdk!,
userMessages: _userMessages,
processUtils: _processUtils,
);
......
......@@ -40,7 +40,7 @@ class FlutterDeviceManager extends DeviceManager {
required Platform platform,
required ProcessManager processManager,
required FileSystem fileSystem,
required AndroidSdk androidSdk,
required AndroidSdk? androidSdk,
required FeatureFlags featureFlags,
required IOSSimulatorUtils iosSimulatorUtils,
required XCDevice xcDevice,
......
......@@ -338,7 +338,7 @@ class IOSSimulator extends Device {
final SimControl _simControl;
@override
DevFSWriter createDevFSWriter(covariant ApplicationPackage app, String userIdentifier) {
DevFSWriter createDevFSWriter(covariant ApplicationPackage? app, String? userIdentifier) {
return LocalDevFSWriter(fileSystem: globals.fs);
}
......
......@@ -2,10 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
// ignore: import_of_legacy_library_into_null_safe
import 'package:dwds/dwds.dart';
import '../artifacts.dart';
......@@ -17,12 +16,12 @@ class SdkWebConfigurationProvider extends SdkConfigurationProvider {
SdkWebConfigurationProvider(this._artifacts);
final Artifacts _artifacts;
SdkConfiguration _configuration;
SdkConfiguration? _configuration;
/// Create and validate configuration matching the default SDK layout.
/// Create configuration matching the default SDK layout.
@override
Future<SdkConfiguration> get configuration async {
Future<SdkConfiguration?> get configuration async {
if (_configuration == null) {
final String sdkDir = _artifacts.getHostArtifact(HostArtifact.flutterWebSdk).path;
final String unsoundSdkSummaryPath = _artifacts.getHostArtifact(HostArtifact.webPlatformKernelDill).path;
......@@ -40,7 +39,7 @@ class SdkWebConfigurationProvider extends SdkConfigurationProvider {
}
/// Validate that SDK configuration exists on disk.
static void validate(SdkConfiguration configuration, { FileSystem fileSystem }) {
static void validate(SdkConfiguration configuration, { required FileSystem fileSystem }) {
configuration.validateSdkDir(fileSystem: fileSystem);
configuration.validateSummaries(fileSystem: fileSystem);
configuration.validateLibrariesSpec(fileSystem: fileSystem);
......
......@@ -181,7 +181,7 @@ class PreviewDevice extends Device {
}
@override
DevFSWriter createDevFSWriter(covariant ApplicationPackage app, String userIdentifier) {
DevFSWriter createDevFSWriter(covariant ApplicationPackage? app, String? userIdentifier) {
return LocalDevFSWriter(fileSystem: _fileSystem);
}
}
......@@ -2,18 +2,12 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
import 'package:meta/meta.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'build_info.dart';
import 'device.dart';
import 'globals.dart' as globals;
import 'resident_devtools_handler.dart';
import 'resident_runner.dart';
import 'tracing.dart';
import 'vmservice.dart';
......@@ -21,31 +15,24 @@ import 'vmservice.dart';
const String kFlutterTestOutputsDirEnvName = 'FLUTTER_TEST_OUTPUTS_DIR';
class ColdRunner extends ResidentRunner {
ColdRunner(
List<FlutterDevice> devices, {
@required String target,
@required DebuggingOptions debuggingOptions,
super.devices, {
required super.target,
required super.debuggingOptions,
this.traceStartup = false,
this.awaitFirstFrameWhenTracing = true,
this.applicationBinary,
this.multidexEnabled = false,
bool ipv6 = false,
bool stayResident = true,
bool machine = false,
ResidentDevtoolsHandlerFactory devtoolsHandler = createDefaultHandler,
bool super.ipv6 = false,
super.stayResident,
super.machine,
super.devtoolsHandler,
}) : super(
devices,
target: target,
debuggingOptions: debuggingOptions,
hotMode: false,
stayResident: stayResident,
ipv6: ipv6,
machine: machine,
devtoolsHandler: devtoolsHandler,
);
final bool traceStartup;
final bool awaitFirstFrameWhenTracing;
final File applicationBinary;
final File? applicationBinary;
final bool multidexEnabled;
bool _didAttach = false;
......@@ -60,14 +47,14 @@ class ColdRunner extends ResidentRunner {
@override
Future<int> run({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<void> appStartedCompleter,
Completer<DebugConnectionInfo>? connectionInfoCompleter,
Completer<void>? appStartedCompleter,
bool enableDevTools = false,
String route,
String? route,
}) async {
try {
for (final FlutterDevice device in flutterDevices) {
final int result = await device.runCold(
for (final FlutterDevice? device in flutterDevices) {
final int result = await device!.runCold(
coldRunner: this,
route: route,
);
......@@ -95,38 +82,38 @@ class ColdRunner extends ResidentRunner {
if (enableDevTools && debuggingEnabled) {
// The method below is guaranteed never to return a failing future.
unawaited(residentDevtoolsHandler.serveAndAnnounceDevTools(
unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools(
devToolsServerAddress: debuggingOptions.devToolsServerAddress,
flutterDevices: flutterDevices,
));
}
if (flutterDevices.first.observatoryUris != null) {
if (flutterDevices.first!.observatoryUris != null) {
// For now, only support one debugger connection.
connectionInfoCompleter?.complete(DebugConnectionInfo(
httpUri: flutterDevices.first.vmService.httpAddress,
wsUri: flutterDevices.first.vmService.wsAddress,
httpUri: flutterDevices.first!.vmService!.httpAddress,
wsUri: flutterDevices.first!.vmService!.wsAddress,
));
}
globals.printTrace('Application running.');
for (final FlutterDevice device in flutterDevices) {
if (device.vmService == null) {
for (final FlutterDevice? device in flutterDevices) {
if (device!.vmService == null) {
continue;
}
await device.initLogReader();
globals.printTrace('Connected to ${device.device.name}');
globals.printTrace('Connected to ${device.device!.name}');
}
if (traceStartup) {
// Only trace startup for the first device.
final FlutterDevice device = flutterDevices.first;
final FlutterDevice device = flutterDevices.first!;
if (device.vmService != null) {
globals.printStatus('Tracing startup on ${device.device.name}.');
globals.printStatus('Tracing startup on ${device.device!.name}.');
final String outputPath = globals.platform.environment[kFlutterTestOutputsDirEnvName] ?? getBuildDirectory();
await downloadStartupTrace(
device.vmService,
device.vmService!,
awaitFirstFrame: awaitFirstFrameWhenTracing,
logger: globals.logger,
output: globals.fs.directory(outputPath),
......@@ -148,8 +135,8 @@ class ColdRunner extends ResidentRunner {
@override
Future<int> attach({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<void> appStartedCompleter,
Completer<DebugConnectionInfo>? connectionInfoCompleter,
Completer<void>? appStartedCompleter,
bool allowExistingDdsInstance = false,
bool enableDevTools = false,
bool needsFullRestart = true,
......@@ -165,11 +152,11 @@ class ColdRunner extends ResidentRunner {
return 2;
}
for (final FlutterDevice device in flutterDevices) {
await device.initLogReader();
for (final FlutterDevice? device in flutterDevices) {
await device!.initLogReader();
}
for (final FlutterDevice device in flutterDevices) {
final List<FlutterView> views = await device.vmService.getFlutterViews();
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
globals.printTrace('Connected to $view.');
}
......@@ -177,7 +164,7 @@ class ColdRunner extends ResidentRunner {
if (enableDevTools && debuggingEnabled) {
// The method below is guaranteed never to return a failing future.
unawaited(residentDevtoolsHandler.serveAndAnnounceDevTools(
unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools(
devToolsServerAddress: debuggingOptions.devToolsServerAddress,
flutterDevices: flutterDevices,
));
......@@ -202,16 +189,16 @@ class ColdRunner extends ResidentRunner {
@override
Future<void> cleanupAtFinish() async {
for (final FlutterDevice flutterDevice in flutterDevices) {
await flutterDevice.device.dispose();
for (final FlutterDevice? flutterDevice in flutterDevices) {
await flutterDevice!.device!.dispose();
}
await residentDevtoolsHandler.shutdown();
await residentDevtoolsHandler!.shutdown();
await stopEchoingDeviceLog();
}
@override
void printHelp({ @required bool details }) {
void printHelp({ required bool details }) {
globals.printStatus('Flutter run key commands.');
if (details) {
printHelpDetails();
......@@ -229,10 +216,10 @@ class ColdRunner extends ResidentRunner {
@override
Future<void> preExit() async {
for (final FlutterDevice device in flutterDevices) {
for (final FlutterDevice? device in flutterDevices) {
// If we're running in release mode, stop the app using the device logic.
if (device.vmService == null) {
await device.device.stopApp(device.package, userIdentifier: device.userIdentifier);
if (device!.vmService == null) {
await device.device!.stopApp(device.package, userIdentifier: device.userIdentifier);
}
}
await super.preExit();
......
This diff is collapsed.
......@@ -4,6 +4,8 @@
// @dart = 2.8
// ignore_for_file: avoid_redundant_argument_values
import 'dart:io' hide Directory, File;
import 'package:flutter_tools/src/artifacts.dart';
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment