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