Unverified Commit 6e950672 authored by Christopher Fujino's avatar Christopher Fujino Committed by GitHub

[flutter_tools] Fix _CastError in HotRunner._resetDirtyAssets (#108771)

parent 965912d8
......@@ -12,6 +12,7 @@ import 'context.dart';
import 'io.dart' as io;
import 'logger.dart';
// TODO(fujino): This should be direct injected, rather than mutable global state.
@visibleForTesting
Future<dds.DartDevelopmentService> Function(
Uri remoteVmServiceUri, {
......
......@@ -123,7 +123,7 @@ class _DaemonServer {
// We have to listen to socket.done. Otherwise when the connection is
// reset, we will receive an uncatchable exception.
// https://github.com/dart-lang/sdk/issues/25518
final Future<void> socketDone = socket.done.catchError((dynamic error, StackTrace stackTrace) {
final Future<void> socketDone = socket.done.catchError((Object error, StackTrace stackTrace) {
logger!.printError('Socket error: $error');
logger!.printTrace('$stackTrace');
});
......@@ -145,8 +145,8 @@ class _DaemonServer {
}
}
typedef CommandHandler = Future<dynamic>? Function(Map<String, dynamic> args);
typedef CommandHandlerWithBinary = Future<dynamic> Function(Map<String, dynamic> args, Stream<List<int>>? binary);
typedef CommandHandler = Future<Object?>? Function(Map<String, Object?> args);
typedef CommandHandlerWithBinary = Future<Object?> Function(Map<String, Object?> args, Stream<List<int>>? binary);
class Daemon {
Daemon(
......@@ -221,7 +221,7 @@ class Daemon {
throw DaemonException('no domain for method: $method');
}
_domainMap[prefix]!.handleCommand(name, id, castStringKeyedMap(request.data['params']) ?? const <String, dynamic>{}, request.binary);
_domainMap[prefix]!.handleCommand(name, id, castStringKeyedMap(request.data['params']) ?? const <String, Object?>{}, request.binary);
} on Exception catch (error, trace) {
connection.sendErrorResponse(id, _toJsonable(error), trace);
}
......@@ -268,52 +268,53 @@ abstract class Domain {
@override
String toString() => name;
void handleCommand(String command, Object id, Map<String, dynamic> args, Stream<List<int>>? binary) {
Future<dynamic>.sync(() {
void handleCommand(String command, Object id, Map<String, Object?> args, Stream<List<int>>? binary) {
Future<Object?>.sync(() {
if (_handlers.containsKey(command)) {
return _handlers[command]!(args);
} else if (_handlersWithBinary.containsKey(command)) {
return _handlersWithBinary[command]!(args, binary);
}
throw DaemonException('command not understood: $name.$command');
}).then<dynamic>((dynamic result) {
}).then<Object?>((Object? result) {
daemon.connection.sendResponse(id, _toJsonable(result));
return null;
}).catchError((Object error, StackTrace stackTrace) {
daemon.connection.sendErrorResponse(id, _toJsonable(error), stackTrace);
});
}
void sendEvent(String name, [ dynamic args, List<int>? binary ]) {
void sendEvent(String name, [ Object? args, List<int>? binary ]) {
daemon.connection.sendEvent(name, _toJsonable(args), binary);
}
String? _getStringArg(Map<String, dynamic> args, String name, { bool required = false }) {
String? _getStringArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! String) {
throw DaemonException('$name is not a String');
}
return val as String?;
}
bool? _getBoolArg(Map<String, dynamic> args, String name, { bool required = false }) {
bool? _getBoolArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! bool) {
throw DaemonException('$name is not a bool');
}
return val as bool?;
}
int? _getIntArg(Map<String, dynamic> args, String name, { bool required = false }) {
int? _getIntArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! int) {
throw DaemonException('$name is not an int');
}
......@@ -334,7 +335,7 @@ class DaemonDomain extends Domain {
sendEvent(
'daemon.connected',
<String, dynamic>{
<String, Object?>{
'version': protocolVersion,
'pid': pid,
},
......@@ -357,13 +358,13 @@ class DaemonDomain extends Domain {
}
} else {
if (message.stackTrace != null) {
sendEvent('daemon.logMessage', <String, dynamic>{
sendEvent('daemon.logMessage', <String, Object?>{
'level': message.level,
'message': message.message,
'stackTrace': message.stackTrace.toString(),
});
} else {
sendEvent('daemon.logMessage', <String, dynamic>{
sendEvent('daemon.logMessage', <String, Object?>{
'level': message.level,
'message': message.message,
});
......@@ -374,7 +375,7 @@ class DaemonDomain extends Domain {
StreamSubscription<LogMessage>? _subscription;
Future<String> version(Map<String, dynamic> args) {
Future<String> version(Map<String, Object?> args) {
return Future<String>.value(protocolVersion);
}
......@@ -384,16 +385,16 @@ class DaemonDomain extends Domain {
/// --web-allow-expose-url switch. The client may return the same URL back if
/// tunnelling is not required for a given URL.
Future<String> exposeUrl(String url) async {
final dynamic res = await daemon.connection.sendRequest('app.exposeUrl', <String, String>{'url': url});
if (res is Map<String, dynamic> && res['url'] is String) {
return res['url'] as String;
final Object? res = await daemon.connection.sendRequest('app.exposeUrl', <String, String>{'url': url});
if (res is Map<String, Object?> && res['url'] is String) {
return res['url']! as String;
} else {
globals.printError('Invalid response to exposeUrl - params should include a String url field');
return url;
}
}
Future<void> shutdown(Map<String, dynamic> args) {
Future<void> shutdown(Map<String, Object?> args) {
Timer.run(daemon.shutdown);
return Future<void>.value();
}
......@@ -408,7 +409,7 @@ class DaemonDomain extends Domain {
/// This does not filter based on the current workflow restrictions, such
/// as whether command line tools are installed or whether the host platform
/// is correct.
Future<Map<String, Object>> getSupportedPlatforms(Map<String, dynamic> args) async {
Future<Map<String, Object>> getSupportedPlatforms(Map<String, Object?> args) async {
final String? projectRoot = _getStringArg(args, 'projectRoot', required: true);
final List<String> result = <String>[];
try {
......@@ -442,7 +443,7 @@ class DaemonDomain extends Domain {
'platforms': result,
};
} on Exception catch (err, stackTrace) {
sendEvent('log', <String, dynamic>{
sendEvent('log', <String, Object?>{
'log': 'Failed to parse project metadata',
'stackTrace': stackTrace.toString(),
'error': true,
......@@ -604,7 +605,7 @@ class AppDomain extends Domain {
logger.domain = this;
logger.app = app;
_sendAppEvent(app, 'start', <String, dynamic>{
_sendAppEvent(app, 'start', <String, Object?>{
'deviceId': device.id,
'directory': projectDirectory,
'supportsRestart': isRestartSupported(enableHotReload, device),
......@@ -619,7 +620,7 @@ class AppDomain extends Domain {
// As it just writes to stdout.
unawaited(connectionInfoCompleter.future.then<void>(
(DebugConnectionInfo info) {
final Map<String, dynamic> params = <String, dynamic>{
final Map<String, Object?> params = <String, Object?>{
// The web vmservice proxy does not have an http address.
'port': info.httpUri?.port ?? info.wsUri!.port,
'wsUri': info.wsUri.toString(),
......@@ -646,7 +647,7 @@ class AppDomain extends Domain {
);
_sendAppEvent(app, 'stop');
} on Exception catch (error, trace) {
_sendAppEvent(app, 'stop', <String, dynamic>{
_sendAppEvent(app, 'stop', <String, Object?>{
'error': _toJsonable(error),
'trace': '$trace',
});
......@@ -665,7 +666,7 @@ class AppDomain extends Domain {
final int _hotReloadDebounceDurationMs = 50;
Future<OperationResult>? restart(Map<String, dynamic> args) async {
Future<OperationResult>? restart(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
final bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
......@@ -727,18 +728,18 @@ class AppDomain extends Domain {
/// "type":"_extensionType",
/// "method":"ext.flutter.platformOverride"
/// }
Future<Map<String, dynamic>> callServiceExtension(Map<String, dynamic> args) async {
Future<Map<String, Object?>> callServiceExtension(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final String methodName = _getStringArg(args, 'methodName')!;
final Map<String, dynamic>? params = args['params'] == null ? <String, dynamic>{} : castStringKeyedMap(args['params']);
final Map<String, Object?>? params = args['params'] == null ? <String, Object?>{} : castStringKeyedMap(args['params']);
final AppInstance? app = _getApp(appId);
if (app == null) {
throw DaemonException("app '$appId' not found");
}
final FlutterDevice device = app.runner!.flutterDevices.first!;
final FlutterDevice device = app.runner!.flutterDevices.first;
final List<FlutterView> views = await device.vmService!.getFlutterViews();
final Map<String, dynamic>? result = await device
final Map<String, Object?>? result = await device
.vmService!
.invokeFlutterExtensionRpcRaw(
methodName,
......@@ -752,13 +753,13 @@ class AppDomain extends Domain {
if (result.containsKey('error')) {
// ignore: only_throw_errors
throw result['error']! as Object;
throw result['error']!;
}
return result;
}
Future<bool> stop(Map<String, dynamic> args) async {
Future<bool> stop(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final AppInstance? app = _getApp(appId);
......@@ -768,8 +769,8 @@ class AppDomain extends Domain {
return app.stop().then<bool>(
(void value) => true,
onError: (dynamic error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, dynamic>{'log': '$error', 'error': true});
onError: (Object? error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true});
app.closeLogger();
_apps.remove(app);
return false;
......@@ -777,7 +778,7 @@ class AppDomain extends Domain {
);
}
Future<bool> detach(Map<String, dynamic> args) async {
Future<bool> detach(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final AppInstance? app = _getApp(appId);
......@@ -787,8 +788,8 @@ class AppDomain extends Domain {
return app.detach().then<bool>(
(void value) => true,
onError: (dynamic error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, dynamic>{'log': '$error', 'error': true});
onError: (Object? error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true});
app.closeLogger();
_apps.remove(app);
return false;
......@@ -805,8 +806,8 @@ class AppDomain extends Domain {
return null;
}
void _sendAppEvent(AppInstance app, String name, [ Map<String, dynamic>? args ]) {
sendEvent('app.$name', <String, dynamic>{
void _sendAppEvent(AppInstance app, String name, [ Map<String, Object?>? args ]) {
sendEvent('app.$name', <String, Object?>{
'appId': app.id,
...?args,
});
......@@ -876,8 +877,8 @@ class DeviceDomain extends Domain {
/// Return a list of the current devices, with each device represented as a map
/// of properties (id, name, platform, ...).
Future<List<Map<String, dynamic>>> getDevices([ Map<String, dynamic>? args ]) async {
return <Map<String, dynamic>>[
Future<List<Map<String, Object?>>> getDevices([ Map<String, Object?>? args ]) async {
return <Map<String, Object?>>[
for (final PollingDeviceDiscovery discoverer in _discoverers)
for (final Device device in await discoverer.devices)
await _deviceToMap(device),
......@@ -885,8 +886,8 @@ class DeviceDomain extends Domain {
}
/// Return a list of the current devices, discarding existing cache of devices.
Future<List<Map<String, dynamic>>> discoverDevices([ Map<String, dynamic>? args ]) async {
return <Map<String, dynamic>>[
Future<List<Map<String, Object?>>> discoverDevices([ Map<String, Object?>? args ]) async {
return <Map<String, Object?>>[
for (final PollingDeviceDiscovery discoverer in _discoverers)
for (final Device device in await discoverer.discoverDevices())
await _deviceToMap(device),
......@@ -894,21 +895,21 @@ class DeviceDomain extends Domain {
}
/// Enable device events.
Future<void> enable(Map<String, dynamic> args) async {
Future<void> enable(Map<String, Object?> args) async {
for (final PollingDeviceDiscovery discoverer in _discoverers) {
discoverer.startPolling();
}
}
/// Disable device events.
Future<void> disable(Map<String, dynamic> args) async {
Future<void> disable(Map<String, Object?> args) async {
for (final PollingDeviceDiscovery discoverer in _discoverers) {
discoverer.stopPolling();
}
}
/// Forward a host port to a device port.
Future<Map<String, dynamic>> forward(Map<String, dynamic> args) async {
Future<Map<String, Object?>> forward(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true)!;
int? hostPort = _getIntArg(args, 'hostPort');
......@@ -920,11 +921,11 @@ class DeviceDomain extends Domain {
hostPort = await device.portForwarder!.forward(devicePort, hostPort: hostPort);
return <String, dynamic>{'hostPort': hostPort};
return <String, Object?>{'hostPort': hostPort};
}
/// Removes a forwarded port.
Future<void> unforward(Map<String, dynamic> args) async {
Future<void> unforward(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true)!;
final int hostPort = _getIntArg(args, 'hostPort', required: true)!;
......@@ -938,7 +939,7 @@ class DeviceDomain extends Domain {
}
/// Returns whether a device supports runtime mode.
Future<bool> supportsRuntimeMode(Map<String, dynamic> args) async {
Future<bool> supportsRuntimeMode(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
......@@ -949,7 +950,7 @@ class DeviceDomain extends Domain {
}
/// Creates an application package from a file in the temp directory.
Future<String> uploadApplicationPackage(Map<String, dynamic> args) async {
Future<String> uploadApplicationPackage(Map<String, Object?> args) async {
final TargetPlatform targetPlatform = getTargetPlatformForName(_getStringArg(args, 'targetPlatform', required: true)!);
final File applicationBinary = daemon.proxyDomain.tempDirectory.childFile(_getStringArg(args, 'applicationBinary', required: true)!);
final ApplicationPackage? applicationPackage = await ApplicationPackageFactory.instance!.getPackageForPlatform(
......@@ -962,7 +963,7 @@ class DeviceDomain extends Domain {
}
/// Starts the log reader on the device.
Future<String> startLogReader(Map<String, dynamic> args) async {
Future<String> startLogReader(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
......@@ -981,13 +982,13 @@ class DeviceDomain extends Domain {
}
/// Stops a log reader that was previously started.
Future<void> stopLogReader(Map<String, dynamic> args) async {
Future<void> stopLogReader(Map<String, Object?> args) async {
final String? id = _getStringArg(args, 'id', required: true);
_logReaders.remove(id)?.dispose();
}
/// Starts an app on a device.
Future<Map<String, dynamic>> startApp(Map<String, dynamic> args) async {
Future<Map<String, Object?>> startApp(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
......@@ -1010,14 +1011,14 @@ class DeviceDomain extends Domain {
ipv6: _getBoolArg(args, 'ipv6') ?? false,
userIdentifier: _getStringArg(args, 'userIdentifier'),
);
return <String, dynamic>{
return <String, Object?>{
'started': result.started,
'observatoryUri': result.observatoryUri?.toString(),
};
}
/// Stops an app.
Future<bool> stopApp(Map<String, dynamic> args) async {
Future<bool> stopApp(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
......@@ -1032,7 +1033,7 @@ class DeviceDomain extends Domain {
}
/// Takes a screenshot.
Future<String?> takeScreenshot(Map<String, dynamic> args) async {
Future<String?> takeScreenshot(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
......@@ -1082,10 +1083,10 @@ class DevToolsDomain extends Domain {
DevtoolsLauncher? _devtoolsLauncher;
Future<Map<String, dynamic>> serve([ Map<String, dynamic>? args ]) async {
Future<Map<String, Object?>> serve([ Map<String, Object?>? args ]) async {
_devtoolsLauncher ??= DevtoolsLauncher.instance;
final DevToolsServerAddress? server = await _devtoolsLauncher?.serve();
return<String, dynamic>{
return<String, Object?>{
'host': server?.host,
'port': server?.port,
};
......@@ -1097,8 +1098,8 @@ class DevToolsDomain extends Domain {
}
}
Future<Map<String, dynamic>> _deviceToMap(Device device) async {
return <String, dynamic>{
Future<Map<String, Object?>> _deviceToMap(Device device) async {
return <String, Object?>{
'id': device.id,
'name': device.name,
'platform': getNameForTargetPlatform(await device.targetPlatform),
......@@ -1120,8 +1121,8 @@ Future<Map<String, dynamic>> _deviceToMap(Device device) async {
};
}
Map<String, dynamic> _emulatorToMap(Emulator emulator) {
return <String, dynamic>{
Map<String, Object?> _emulatorToMap(Emulator emulator) {
return <String, Object?>{
'id': emulator.id,
'name': emulator.name,
'category': emulator.category.toString(),
......@@ -1129,15 +1130,15 @@ Map<String, dynamic> _emulatorToMap(Emulator emulator) {
};
}
Map<String, dynamic> _operationResultToMap(OperationResult result) {
return <String, dynamic>{
Map<String, Object?> _operationResultToMap(OperationResult result) {
return <String, Object?>{
'code': result.code,
'message': result.message,
};
}
Object? _toJsonable(dynamic obj) {
if (obj is String || obj is int || obj is bool || obj is Map<dynamic, dynamic> || obj is List<dynamic> || obj == null) {
Object? _toJsonable(Object? obj) {
if (obj is String || obj is int || obj is bool || obj is Map<Object?, Object?> || obj is List<Object?> || obj == null) {
return obj;
}
if (obj is OperationResult) {
......@@ -1250,7 +1251,7 @@ class NotifyingLogger extends DelegatingLogger {
}
@override
void sendEvent(String name, [Map<String, dynamic>? args]) { }
void sendEvent(String name, [Map<String, Object?>? args]) { }
@override
bool get supportsColor => throw UnimplementedError();
......@@ -1305,12 +1306,12 @@ class EmulatorDomain extends Domain {
androidWorkflow: androidWorkflow!,
);
Future<List<Map<String, dynamic>>> getEmulators([ Map<String, dynamic>? args ]) async {
Future<List<Map<String, Object?>>> getEmulators([ Map<String, Object?>? args ]) async {
final List<Emulator> list = await emulators.getAllAvailableEmulators();
return list.map<Map<String, dynamic>>(_emulatorToMap).toList();
return list.map<Map<String, Object?>>(_emulatorToMap).toList();
}
Future<void> launch(Map<String, dynamic> args) async {
Future<void> launch(Map<String, Object?> args) async {
final String emulatorId = _getStringArg(args, 'emulatorId', required: true)!;
final bool coldBoot = _getBoolArg(args, 'coldBoot') ?? false;
final List<Emulator> matches =
......@@ -1324,10 +1325,10 @@ class EmulatorDomain extends Domain {
}
}
Future<Map<String, dynamic>> create(Map<String, dynamic> args) async {
Future<Map<String, Object?>> create(Map<String, Object?> args) async {
final String? name = _getStringArg(args, 'name');
final CreateEmulatorResult res = await emulators.createEmulator(name: name);
return <String, dynamic>{
return <String, Object?>{
'success': res.success,
'emulatorName': res.emulatorName,
'error': res.error,
......@@ -1349,7 +1350,7 @@ class ProxyDomain extends Domain {
int _id = 0;
/// Writes to a file in a local temporary directory.
Future<void> writeTempFile(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<void> writeTempFile(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
await file.parent.create(recursive: true);
......@@ -1357,7 +1358,7 @@ class ProxyDomain extends Domain {
}
/// Calculate rolling hashes for a file in the local temporary directory.
Future<Map<String, dynamic>?> calculateFileHashes(Map<String, dynamic> args) async {
Future<Map<String, Object?>?> calculateFileHashes(Map<String, Object?> args) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
if (!await file.exists()) {
......@@ -1367,20 +1368,20 @@ class ProxyDomain extends Domain {
return result.toJson();
}
Future<bool?> updateFile(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<bool?> updateFile(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
if (!await file.exists()) {
return null;
}
final List<Map<String, dynamic>> deltaJson = (args['delta'] as List<dynamic>).cast<Map<String, dynamic>>();
final List<Map<String, Object?>> deltaJson = (args['delta']! as List<Object?>).cast<Map<String, Object?>>();
final List<FileDeltaBlock> delta = FileDeltaBlock.fromJsonList(deltaJson);
final bool result = await FileTransfer().rebuildFile(file, delta, binary!);
return result;
}
/// Opens a connection to a local port, and returns the connection id.
Future<String> connect(Map<String, dynamic> args) async {
Future<String> connect(Map<String, Object?> args) async {
final int targetPort = _getIntArg(args, 'port', required: true)!;
final String id = 'portForwarder_${targetPort}_${_id++}';
......@@ -1406,22 +1407,22 @@ class ProxyDomain extends Domain {
_forwardedConnections[id] = socket;
socket.listen((List<int> data) {
sendEvent('proxy.data.$id', null, data);
}, onError: (dynamic error, StackTrace stackTrace) {
}, onError: (Object error, StackTrace stackTrace) {
// Socket error, probably disconnected.
globals.logger.printTrace('Socket error: $error, $stackTrace');
});
unawaited(socket.done.catchError((dynamic error, StackTrace stackTrace) {
unawaited(socket.done.catchError((Object error, StackTrace stackTrace) {
// Socket error, probably disconnected.
globals.logger.printTrace('Socket error: $error, $stackTrace');
}).then((dynamic _) {
}).then((Object? _) {
sendEvent('proxy.disconnected.$id');
}));
return id;
}
/// Disconnects from a previously established connection.
Future<bool> disconnect(Map<String, dynamic> args) async {
Future<bool> disconnect(Map<String, Object?> args) async {
final String? id = _getStringArg(args, 'id', required: true);
if (_forwardedConnections.containsKey(id)) {
await _forwardedConnections.remove(id)?.close();
......@@ -1431,7 +1432,7 @@ class ProxyDomain extends Domain {
}
/// Writes to a previously established connection.
Future<bool> write(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<bool> write(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String? id = _getStringArg(args, 'id', required: true);
if (_forwardedConnections.containsKey(id)) {
final StreamSubscription<List<int>> subscription = binary!.listen(_forwardedConnections[id!]!.add);
......@@ -1519,7 +1520,7 @@ class AppRunLogger extends DelegatingLogger {
printStatus(message);
}
} else {
final Map<String, dynamic> event = <String, dynamic>{
final Map<String, Object?> event = <String, Object?>{
'id': eventId,
'progressId': eventType,
if (message != null) 'message': message,
......@@ -1531,7 +1532,7 @@ class AppRunLogger extends DelegatingLogger {
}
@override
void sendEvent(String name, [Map<String, dynamic>? args, List<int>? binary]) {
void sendEvent(String name, [Map<String, Object?>? args, List<int>? binary]) {
if (domain == null) {
printStatus('event sent after app closed: $name');
} else {
......
......@@ -81,14 +81,14 @@ const String kExitMessage = 'Failed to establish connection with the application
class ResidentWebRunner extends ResidentRunner {
ResidentWebRunner(
FlutterDevice? device, {
FlutterDevice device, {
String? target,
bool stayResident = true,
bool machine = false,
required this.flutterProject,
required bool? ipv6,
required DebuggingOptions debuggingOptions,
required FileSystem? fileSystem,
required FileSystem fileSystem,
required Logger? logger,
required SystemClock systemClock,
required Usage usage,
......@@ -100,8 +100,8 @@ class ResidentWebRunner extends ResidentRunner {
_usage = usage,
_urlTunneller = urlTunneller,
super(
<FlutterDevice?>[device],
target: target ?? fileSystem!.path.join('lib', 'main.dart'),
<FlutterDevice>[device],
target: target ?? fileSystem.path.join('lib', 'main.dart'),
debuggingOptions: debuggingOptions,
ipv6: ipv6,
stayResident: stayResident,
......@@ -109,7 +109,7 @@ class ResidentWebRunner extends ResidentRunner {
devtoolsHandler: devtoolsHandler,
);
final FileSystem? _fileSystem;
final FileSystem _fileSystem;
final Logger? _logger;
final SystemClock _systemClock;
final Usage _usage;
......@@ -119,7 +119,7 @@ class ResidentWebRunner extends ResidentRunner {
Logger? get logger => _logger;
@override
FileSystem? get fileSystem => _fileSystem;
FileSystem get fileSystem => _fileSystem;
FlutterDevice? get device => flutterDevices.first;
final FlutterProject flutterProject;
......@@ -245,7 +245,7 @@ class ResidentWebRunner extends ResidentRunner {
}
final String modeName = debuggingOptions.buildInfo.friendlyModeName;
_logger!.printStatus(
'Launching ${getDisplayPath(target, _fileSystem!)} '
'Launching ${getDisplayPath(target, _fileSystem)} '
'on ${device!.device!.name} in $modeName mode...',
);
if (device!.device is ChromiumDevice) {
......@@ -271,7 +271,7 @@ class ResidentWebRunner extends ResidentRunner {
buildInfo: debuggingOptions.buildInfo,
enableDwds: _enableDwds,
enableDds: debuggingOptions.enableDds,
entrypoint: _fileSystem!.file(target).uri,
entrypoint: _fileSystem.file(target).uri,
expressionCompiler: expressionCompiler,
chromiumLauncher: _chromiumLauncher,
nullAssertions: debuggingOptions.nullAssertions,
......@@ -425,7 +425,7 @@ class ResidentWebRunner extends ResidentRunner {
Future<Uri> _generateEntrypoint(Uri mainUri, PackageConfig? packageConfig) async {
File? result = _generatedEntrypointDirectory?.childFile('web_entrypoint.dart');
if (_generatedEntrypointDirectory == null) {
_generatedEntrypointDirectory ??= _fileSystem!.systemTempDirectory.createTempSync('flutter_tools.')
_generatedEntrypointDirectory ??= _fileSystem.systemTempDirectory.createTempSync('flutter_tools.')
..createSync();
result = _generatedEntrypointDirectory!.childFile('web_entrypoint.dart');
......@@ -438,16 +438,17 @@ class ResidentWebRunner extends ResidentRunner {
Uri? importedEntrypoint = packageConfig!.toPackageUri(mainUri);
// Special handling for entrypoints that are not under lib, such as test scripts.
if (importedEntrypoint == null) {
final String parent = _fileSystem!.file(mainUri).parent.path;
flutterDevices.first!.generator!.addFileSystemRoot(parent);
flutterDevices.first!.generator!.addFileSystemRoot(_fileSystem!.directory('test').absolute.path);
final String parent = _fileSystem.file(mainUri).parent.path;
flutterDevices.first.generator!
..addFileSystemRoot(parent)
..addFileSystemRoot(_fileSystem.directory('test').absolute.path);
importedEntrypoint = Uri(
scheme: 'org-dartlang-app',
path: '/${mainUri.pathSegments.last}',
);
}
final LanguageVersion languageVersion = determineLanguageVersion(
_fileSystem!.file(mainUri),
_fileSystem.file(mainUri),
packageConfig[flutterProject.manifest.appName],
Cache.flutterRoot!,
);
......@@ -487,7 +488,7 @@ class ResidentWebRunner extends ResidentRunner {
);
final UpdateFSReport report = await device!.devFS!.update(
mainUri: await _generateEntrypoint(
_fileSystem!.file(mainPath).absolute.uri,
_fileSystem.file(mainPath).absolute.uri,
invalidationResult.packageConfig,
),
target: target,
......@@ -603,7 +604,7 @@ class ResidentWebRunner extends ResidentRunner {
}
if (websocketUri != null) {
if (debuggingOptions.vmserviceOutFile != null) {
_fileSystem!.file(debuggingOptions.vmserviceOutFile)
_fileSystem.file(debuggingOptions.vmserviceOutFile)
..createSync(recursive: true)
..writeAsStringSync(websocketUri.toString());
}
......
......@@ -240,7 +240,7 @@ class FlutterDevice {
bool cacheStartupProfile = false,
bool enableDds = true,
required bool allowExistingDdsInstance,
bool? ipv6 = false,
bool ipv6 = false,
}) {
final Completer<void> completer = Completer<void>();
late StreamSubscription<void> subscription;
......@@ -927,14 +927,14 @@ abstract class ResidentHandlers {
if (!supportsWriteSkSL) {
throw Exception('writeSkSL is not supported by this runner.');
}
final List<FlutterView> views = await flutterDevices
.first!
.vmService!.getFlutterViews();
final Map<String, Object> data = await (flutterDevices.first!.vmService!.getSkSLs(
final FlutterDevice flutterDevice = flutterDevices.first!;
final FlutterVmService vmService = flutterDevice.vmService!;
final List<FlutterView> views = await vmService.getFlutterViews();
final Map<String, Object?>? data = await vmService.getSkSLs(
viewId: views.first.id,
) as FutureOr<Map<String, Object>>);
final Device device = flutterDevices.first!.device!;
return sharedSkSlWriter(device, data);
);
final Device device = flutterDevice.device!;
return sharedSkSlWriter(device, data!);
}
/// Take a screenshot on the provided [device].
......@@ -1091,10 +1091,10 @@ abstract class ResidentRunner extends ResidentHandlers {
Logger? get logger => globals.logger;
@override
FileSystem? get fileSystem => globals.fs;
FileSystem get fileSystem => globals.fs;
@override
final List<FlutterDevice?> flutterDevices;
final List<FlutterDevice> flutterDevices;
final String target;
final DebuggingOptions debuggingOptions;
......@@ -1171,7 +1171,7 @@ abstract class ResidentRunner extends ResidentHandlers {
//
// Would be null if there is no device connected or
// there is no devFS associated with the first device.
Uri? get uri => flutterDevices.first?.devFS?.baseUri;
Uri? get uri => flutterDevices.first.devFS?.baseUri;
/// Returns [true] if the resident runner exited after invoking [exit()].
bool get exited => _exited;
......@@ -1257,7 +1257,7 @@ abstract class ResidentRunner extends ResidentHandlers {
void writeVmServiceFile() {
if (debuggingOptions.vmserviceOutFile != null) {
try {
final String address = flutterDevices.first!.vmService!.wsAddress.toString();
final String address = flutterDevices.first.vmService!.wsAddress.toString();
final File vmserviceOutFile = globals.fs.file(debuggingOptions.vmserviceOutFile);
vmserviceOutFile.createSync(recursive: true);
vmserviceOutFile.writeAsStringSync(address);
......@@ -1359,7 +1359,7 @@ abstract class ResidentRunner extends ResidentHandlers {
hostVmServicePort: debuggingOptions.hostVmServicePort,
getSkSLMethod: getSkSLMethod,
printStructuredErrorLogMethod: printStructuredErrorLog,
ipv6: ipv6,
ipv6: ipv6 ?? false,
disableServiceAuthCodes: debuggingOptions.disableServiceAuthCodes,
cacheStartupProfile: debuggingOptions.cacheStartupProfile,
);
......
......@@ -88,11 +88,11 @@ class ColdRunner extends ResidentRunner {
));
}
if (flutterDevices.first!.observatoryUris != null) {
if (flutterDevices.first.observatoryUris != null) {
// For now, only support one debugger connection.
connectionInfoCompleter?.complete(DebugConnectionInfo(
httpUri: flutterDevices.first!.vmService!.httpAddress,
wsUri: flutterDevices.first!.vmService!.wsAddress,
httpUri: flutterDevices.first.vmService!.httpAddress,
wsUri: flutterDevices.first.vmService!.wsAddress,
));
}
......@@ -108,7 +108,7 @@ class ColdRunner extends ResidentRunner {
if (traceStartup) {
// Only trace startup for the first device.
final FlutterDevice device = flutterDevices.first!;
final FlutterDevice device = flutterDevices.first;
if (device.vmService != null) {
globals.printStatus('Tracing startup on ${device.device!.name}.');
final String outputPath = globals.platform.environment[kFlutterTestOutputsDirEnvName] ?? getBuildDirectory();
......
......@@ -141,7 +141,7 @@ class HotRunner extends ResidentRunner {
}
if (flutterDevices.length == 1) {
final Device device = flutterDevices.first!.device!;
final Device device = flutterDevices.first.device!;
_targetPlatform = getNameForTargetPlatform(await device.targetPlatform);
_sdkName = await device.sdkNameAndVersion;
_emulator = await device.isLocalEmulator;
......@@ -257,8 +257,8 @@ class HotRunner extends ResidentRunner {
// Only handle one debugger connection.
connectionInfoCompleter.complete(
DebugConnectionInfo(
httpUri: flutterDevices.first!.vmService!.httpAddress,
wsUri: flutterDevices.first!.vmService!.wsAddress,
httpUri: flutterDevices.first.vmService!.httpAddress,
wsUri: flutterDevices.first.vmService!.wsAddress,
baseUri: baseUris.first.toString(),
),
);
......@@ -454,12 +454,13 @@ class HotRunner extends ResidentRunner {
}
final Stopwatch findInvalidationTimer = _stopwatchFactory.createStopwatch('updateDevFS')..start();
final DevFS devFS = flutterDevices[0].devFS!;
final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated(
lastCompiled: flutterDevices[0]!.devFS!.lastCompiled,
urisToMonitor: flutterDevices[0]!.devFS!.sources,
lastCompiled: devFS.lastCompiled,
urisToMonitor: devFS.sources,
packagesPath: packagesFilePath,
asyncScanning: hotRunnerConfig!.asyncScanning,
packageConfig: flutterDevices[0]!.devFS!.lastPackageConfig
packageConfig: devFS.lastPackageConfig
?? debuggingOptions.buildInfo.packageConfig,
);
findInvalidationTimer.stop();
......@@ -474,7 +475,7 @@ class HotRunner extends ResidentRunner {
}
final UpdateFSReport results = UpdateFSReport(
success: true,
scannedSourcesCount: flutterDevices[0]!.devFS!.sources.length,
scannedSourcesCount: devFS.sources.length,
findInvalidatedDuration: findInvalidationTimer.elapsed,
);
for (final FlutterDevice? device in flutterDevices) {
......@@ -497,21 +498,27 @@ class HotRunner extends ResidentRunner {
}
void _resetDirtyAssets() {
for (final FlutterDevice? device in flutterDevices) {
device!.devFS!.assetPathsToEvict.clear();
device.devFS!.shaderPathsToEvict.clear();
for (final FlutterDevice device in flutterDevices) {
final DevFS? devFS = device.devFS;
if (devFS == null) {
// This is sometimes null, however we don't know why and have not been
// able to reproduce, https://github.com/flutter/flutter/issues/108653
continue;
}
devFS.assetPathsToEvict.clear();
devFS.shaderPathsToEvict.clear();
}
}
Future<void> _cleanupDevFS() async {
final List<Future<void>> futures = <Future<void>>[];
for (final FlutterDevice? device in flutterDevices) {
if (device!.devFS != null) {
for (final FlutterDevice device in flutterDevices) {
if (device.devFS != null) {
// Cleanup the devFS, but don't wait indefinitely.
// We ignore any errors, because it's not clear what we would do anyway.
futures.add(device.devFS!.destroy()
.timeout(const Duration(milliseconds: 250))
.catchError((dynamic error) {
.catchError((Object? error) {
globals.printTrace('Ignored error while cleaning up DevFS: $error');
}));
}
......@@ -756,7 +763,7 @@ class HotRunner extends ResidentRunner {
String? restartEvent;
try {
final Stopwatch restartTimer = _stopwatchFactory.createStopwatch('fullRestartHelper')..start();
if (!(await (hotRunnerConfig!.setupHotRestart() as FutureOr<bool>))) {
if ((await hotRunnerConfig!.setupHotRestart()) != true) {
return OperationResult(1, 'setupHotRestart failed');
}
result = await _restartFromSources(reason: reason);
......@@ -885,7 +892,7 @@ class HotRunner extends ResidentRunner {
}
final Stopwatch reloadTimer = _stopwatchFactory.createStopwatch('reloadSources:reload')..start();
if (!(await (hotRunnerConfig!.setupHotReload() as FutureOr<bool>))) {
if ((await hotRunnerConfig!.setupHotReload()) != true) {
return OperationResult(1, 'setupHotReload failed');
}
final Stopwatch devFSTimer = Stopwatch()..start();
......
......@@ -13,7 +13,7 @@ import 'convert.dart';
import 'device.dart';
import 'globals.dart' as globals;
Future<String?> sharedSkSlWriter(Device device, Map<String, Object> data, {
Future<String?> sharedSkSlWriter(Device device, Map<String, Object?> data, {
File? outputFile,
Logger? logger,
}) async {
......
......@@ -493,7 +493,7 @@ class FlutterVmService {
///
/// This method will only return data if `--cache-sksl` was provided as a
/// flutter run argument, and only then on physical devices.
Future<Map<String, Object>?> getSkSLs({
Future<Map<String, Object?>?> getSkSLs({
required String viewId,
}) async {
final vm_service.Response? response = await callMethodWrapper(
......@@ -505,7 +505,7 @@ class FlutterVmService {
if (response == null) {
return null;
}
return response.json?['SkSLs'] as Map<String, Object>?;
return response.json?['SkSLs'] as Map<String, Object?>?;
}
/// Flush all tasks on the UI thread for an attached Flutter view.
......
......@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:async';
import 'package:dds/dds.dart' as dds;
......@@ -35,7 +33,6 @@ import 'package:flutter_tools/src/run_cold.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/version.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
......@@ -157,12 +154,12 @@ const FakeVmServiceRequest evictShader = FakeVmServiceRequest(
final Uri testUri = Uri.parse('foo://bar');
void main() {
Testbed testbed;
FakeFlutterDevice flutterDevice;
FakeDevFS devFS;
ResidentRunner residentRunner;
FakeDevice device;
FakeVmServiceHost fakeVmServiceHost;
late Testbed testbed;
late FakeFlutterDevice flutterDevice;
late FakeDevFS devFS;
late ResidentRunner residentRunner;
late FakeDevice device;
FakeVmServiceHost? fakeVmServiceHost;
setUp(() {
testbed = Testbed(setup: () {
......@@ -197,7 +194,7 @@ void main() {
]);
final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
final Completer<void> futureAppStart = Completer<void>.sync();
final Future<int> result = residentRunner.attach(
final Future<int?> result = residentRunner.attach(
appStartedCompleter: futureAppStart,
connectionInfoCompleter: futureConnectionInfo,
enableDevTools: true,
......@@ -208,7 +205,7 @@ void main() {
expect(futureConnectionInfo.isCompleted, true);
expect((await connectionInfo).baseUri, 'foo://bar');
expect(futureAppStart.isCompleted, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner suppresses errors for the initial compilation', () => testbed.run(() async {
......@@ -233,7 +230,7 @@ void main() {
expect(await residentRunner.run(enableDevTools: true), 0);
expect(residentCompiler.didSuppressErrors, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
// Regression test for https://github.com/flutter/flutter/issues/60613
......@@ -325,7 +322,7 @@ void main() {
expect(await residentRunner.run(enableDevTools: true), 0);
expect(residentCompiler.didSuppressErrors, false);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner can attach to device successfully with --fast-start', () => testbed.run(() async {
......@@ -335,14 +332,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakeUnpausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
listViews,
const FakeVmServiceRequest(
......@@ -382,7 +379,7 @@ void main() {
);
final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
final Completer<void> futureAppStart = Completer<void>.sync();
final Future<int> result = residentRunner.attach(
final Future<int?> result = residentRunner.attach(
appStartedCompleter: futureAppStart,
connectionInfoCompleter: futureConnectionInfo,
enableDevTools: true,
......@@ -393,7 +390,7 @@ void main() {
expect(futureConnectionInfo.isCompleted, true);
expect((await connectionInfo).baseUri, 'foo://bar');
expect(futureAppStart.isCompleted, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner can handle an RPC exception from hot reload', () => testbed.run(() async {
......@@ -424,7 +421,7 @@ void main() {
fastReassemble: false,
)),
));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -447,7 +444,7 @@ void main() {
expect(result.fatal, false);
expect(result.code, 1);
expect(result.message, contains('Device initialization has not completed.'));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner can handle an reload-barred exception from hot reload', () => testbed.run(() async {
......@@ -480,7 +477,7 @@ void main() {
fastReassemble: false,
)),
));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -527,7 +524,7 @@ void main() {
fastReassemble: false,
)),
));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -546,7 +543,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.reassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
),
......@@ -573,7 +570,7 @@ void main() {
final OperationResult result = await residentRunner.restart();
expect(result.code, 0);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner reports error with missing entrypoint file', () => testbed.run(() async {
......@@ -587,7 +584,7 @@ void main() {
'isolates': <Object>[
fakeUnpausedIsolate.toJson(),
],
}).toJson(),
})!.toJson(),
),
const FakeVmServiceRequest(
method: 'reloadSources',
......@@ -613,7 +610,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.reassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
),
......@@ -647,7 +644,7 @@ void main() {
'isolates': <Object>[
fakeUnpausedIsolate.toJson(),
],
}).toJson(),
})!.toJson(),
),
const FakeVmServiceRequest(
method: 'reloadSources',
......@@ -677,7 +674,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.reassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
),
......@@ -711,7 +708,7 @@ void main() {
'isolates': <Object>[
fakeUnpausedIsolate.toJson(),
],
}).toJson(),
})!.toJson(),
),
const FakeVmServiceRequest(
method: 'reloadSources',
......@@ -737,7 +734,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.reassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
),
......@@ -758,7 +755,7 @@ void main() {
final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
expect(event.category, 'hot');
expect(event.parameter, 'reload');
expect(event.parameters.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -800,7 +797,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.fastReassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
'className': 'FOO',
},
......@@ -811,7 +808,7 @@ void main() {
BuildInfo.debug,
FakeResidentCompiler(),
devFS,
)..vmService = fakeVmServiceHost.vmService;
)..vmService = fakeVmServiceHost!.vmService;
residentRunner = HotRunner(
<FlutterDevice>[
flutterDevice,
......@@ -844,7 +841,7 @@ void main() {
final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
expect(event.category, 'hot');
expect(event.parameter, 'reload');
expect(event.parameters.fastReassemble, true);
expect(event.parameters?.fastReassemble, true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
Platform: () => FakePlatform(),
......@@ -891,7 +888,7 @@ void main() {
),
FakeVmServiceRequest(
method: 'ext.flutter.fastReassemble',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
'className': 'FOO',
},
......@@ -902,7 +899,7 @@ void main() {
BuildInfo.debug,
FakeResidentCompiler(),
devFS,
)..vmService = fakeVmServiceHost.vmService;
)..vmService = fakeVmServiceHost!.vmService;
residentRunner = HotRunner(
<FlutterDevice>[
flutterDevice,
......@@ -949,14 +946,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakeUnpausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
listViews,
const FakeVmServiceRequest(
......@@ -996,8 +993,8 @@ void main() {
final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
expect(event.category, 'hot');
expect(event.parameter, 'restart');
expect(event.parameters.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -1009,14 +1006,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakePausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
const FakeVmServiceRequest(
method: 'setIsolatePauseMode',
......@@ -1072,7 +1069,7 @@ void main() {
final OperationResult result = await residentRunner.restart(fullRestart: true);
expect(result.isOk, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner will alternative the name of the dill file uploaded for a hot restart', () => testbed.run(() async {
......@@ -1082,14 +1079,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakeUnpausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
listViews,
const FakeVmServiceRequest(
......@@ -1116,14 +1113,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakeUnpausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
listViews,
const FakeVmServiceRequest(
......@@ -1150,14 +1147,14 @@ void main() {
listViews,
FakeVmServiceRequest(
method: 'getIsolate',
args: <String, Object>{
args: <String, Object?>{
'isolateId': fakeUnpausedIsolate.id,
},
jsonResponse: fakeUnpausedIsolate.toJson(),
),
FakeVmServiceRequest(
method: 'getVM',
jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
),
listViews,
const FakeVmServiceRequest(
......@@ -1194,7 +1191,7 @@ void main() {
await residentRunner.restart(fullRestart: true);
await residentRunner.restart(fullRestart: true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner Can handle an RPC exception from hot restart', () => testbed.run(() async {
......@@ -1225,7 +1222,7 @@ void main() {
fastReassemble: false,
)),
));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
Usage: () => TestUsage(),
}));
......@@ -1554,7 +1551,7 @@ flutter:
await residentRunner.writeSkSL();
expect(testLogger.statusText, contains('No data was received'));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('ResidentRunner can write SkSL data to a unique file with engine revision, platform, and device name', () => testbed.run(() async {
......@@ -1582,7 +1579,7 @@ flutter:
'engineRevision': 'abcdefg',
'data': <String, Object>{'A': 'B'},
});
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
FileSystemUtils: () => FileSystemUtils(
fileSystem: globals.fs,
......@@ -1606,7 +1603,7 @@ flutter:
devtoolsHandler: createNoOpHandler,
);
final Future<int> result = residentRunner.attach();
final Future<int?> result = residentRunner.attach();
expect(await result, 0);
}));
......@@ -1625,13 +1622,13 @@ flutter:
final TestFlutterDevice flutterDevice = TestFlutterDevice(
device,
);
flutterDevice.vmService = fakeVmServiceHost.vmService;
flutterDevice.vmService = fakeVmServiceHost!.vmService;
final Future<void> exitFuture = flutterDevice.exitApps();
await expectLater(exitFuture, completes);
expect(device.appStopped, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('HotRunner writes vm service file when providing debugging option', () => testbed.run(() async {
......@@ -1652,7 +1649,7 @@ flutter:
await residentRunner.run(enableDevTools: true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
expect(await globals.fs.file('foo').readAsString(), testUri.toString());
}));
......@@ -1856,7 +1853,7 @@ flutter:
await residentRunner.run(enableDevTools: true);
expect(testLogger.errorText, contains('Failed to write vmservice-out-file at foo'));
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}, overrides: <Type, Generator>{
FileSystem: () => ThrowingForwardingFileSystem(MemoryFileSystem.test()),
}));
......@@ -1879,13 +1876,13 @@ flutter:
await residentRunner.run(enableDevTools: true);
expect(await globals.fs.file('foo').readAsString(), testUri.toString());
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(fakeVmServiceHost?.hasRemainingExpectations, false);
}));
testUsingContext('FlutterDevice uses dartdevc configuration when targeting web', () async {
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript);
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -1895,16 +1892,16 @@ flutter:
),
target: null,
platform: FakePlatform(),
)).generator as DefaultResidentCompiler;
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.initializeFromDill,
expect(residentCompiler!.initializeFromDill,
globals.fs.path.join(getBuildDirectory(), 'fbbe6a61fb7a1de317d381f8df4814e5.cache.dill'));
expect(residentCompiler.librariesSpec,
globals.fs.file(globals.artifacts.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
.uri.toString());
expect(residentCompiler.targetModel, TargetModel.dartdevc);
expect(residentCompiler.sdkRoot,
'${globals.artifacts.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
'${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformKernelDill');
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
......@@ -1916,7 +1913,7 @@ flutter:
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript);
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -1926,16 +1923,16 @@ flutter:
),
target: null,
platform: FakePlatform(),
)).generator as DefaultResidentCompiler;
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.initializeFromDill,
expect(residentCompiler!.initializeFromDill,
globals.fs.path.join(getBuildDirectory(), '80b1a4cf4e7b90e1ab5f72022a0bc624.cache.dill'));
expect(residentCompiler.librariesSpec,
globals.fs.file(globals.artifacts.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
.uri.toString());
expect(residentCompiler.targetModel, TargetModel.dartdevc);
expect(residentCompiler.sdkRoot,
'${globals.artifacts.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
'${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformSoundKernelDill');
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
......@@ -1947,7 +1944,7 @@ flutter:
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice();
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -1955,10 +1952,10 @@ flutter:
treeShakeIcons: false,
extraFrontEndOptions: <String>[],
),
target: null, platform: null,
)).generator as DefaultResidentCompiler;
target: null, platform: FakePlatform(),
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.extraFrontEndOptions,
expect(residentCompiler!.extraFrontEndOptions,
contains('--flutter-widget-cache'));
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
......@@ -1972,7 +1969,7 @@ flutter:
final FakeDevice device = FakeDevice();
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -1980,10 +1977,10 @@ flutter:
treeShakeIcons: false,
extraFrontEndOptions: <String>[],
),
target: null, platform: null,
)).generator as DefaultResidentCompiler;
target: null, platform: FakePlatform(),
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.extraFrontEndOptions,
expect(residentCompiler!.extraFrontEndOptions,
contains('--enable-experiment=alternative-invalidation-strategy'));
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
......@@ -1995,7 +1992,7 @@ flutter:
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice();
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -2004,10 +2001,10 @@ flutter:
extraFrontEndOptions: <String>[],
initializeFromDill: '/foo/bar.dill',
),
target: null, platform: null,
)).generator as DefaultResidentCompiler;
target: null, platform: FakePlatform(),
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.initializeFromDill, '/foo/bar.dill');
expect(residentCompiler!.initializeFromDill, '/foo/bar.dill');
expect(residentCompiler.assumeInitializeFromDillUpToDate, false);
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
......@@ -2019,7 +2016,7 @@ flutter:
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice();
final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
device,
buildInfo: const BuildInfo(
BuildMode.debug,
......@@ -2028,10 +2025,10 @@ flutter:
extraFrontEndOptions: <String>[],
assumeInitializeFromDillUpToDate: true,
),
target: null, platform: null,
)).generator as DefaultResidentCompiler;
target: null, platform: FakePlatform(),
)).generator as DefaultResidentCompiler?;
expect(residentCompiler.assumeInitializeFromDillUpToDate, true);
expect(residentCompiler!.assumeInitializeFromDillUpToDate, true);
}, overrides: <Type, Generator>{
Artifacts: () => Artifacts.test(),
FileSystem: () => MemoryFileSystem.test(),
......@@ -2042,7 +2039,7 @@ flutter:
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
final FakeDevice device = FakeDevice()
..dds = DartDevelopmentService();
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes, bool ipv6, Uri serviceUri, List<String> cachedUserTags, dds.UriConverter uriConverter}) {
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List<String> cachedUserTags = const <String>[], dds.UriConverter? uriConverter}) {
expect(uri, Uri(scheme: 'foo', host: 'bar'));
expect(enableAuthCodes, isTrue);
expect(ipv6, isFalse);
......@@ -2062,7 +2059,7 @@ flutter:
runZonedGuarded(() {
flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete());
}, (Object e, StackTrace st) {
expect(e is ToolExit, true);
expect(e, isA<ToolExit>());
expect((e as ToolExit).message,
contains('Existing VM service clients prevent DDS from taking control.',
));
......@@ -2075,14 +2072,14 @@ flutter:
}
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources reloadSources,
Restart restart,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
io.CompressionOptions compression,
Device device,
Logger logger,
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
required Logger logger,
}) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
}));
......@@ -2091,7 +2088,7 @@ flutter:
final FakeDevice device = FakeDevice()
..dds = DartDevelopmentService();
final Completer<void>done = Completer<void>();
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes, bool ipv6, Uri serviceUri, List<String> cachedUserTags, dds.UriConverter uriConverter}) async {
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List<String> cachedUserTags = const <String>[], dds.UriConverter? uriConverter}) async {
expect(uri, Uri(scheme: 'foo', host: 'bar'));
expect(enableAuthCodes, isFalse);
expect(ipv6, isTrue);
......@@ -2099,7 +2096,7 @@ flutter:
expect(cachedUserTags, isEmpty);
expect(uriConverter, isNull);
done.complete();
return null;
return FakeDartDevelopmentService();
};
final TestFlutterDevice flutterDevice = TestFlutterDevice(
device,
......@@ -2109,14 +2106,14 @@ flutter:
await done.future;
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources reloadSources,
Restart restart,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
io.CompressionOptions compression,
Device device,
Logger logger,
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
required Logger logger,
}) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
}));
......@@ -2125,7 +2122,14 @@ flutter:
final FakeDevice device = FakeDevice()
..dds = DartDevelopmentService();
final Completer<void>done = Completer<void>();
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes, bool ipv6, Uri serviceUri, List<String> cachedUserTags, dds.UriConverter uriConverter}) async {
ddsLauncherCallback = (
Uri uri, {
bool enableAuthCodes = false,
bool ipv6 = false,
Uri? serviceUri,
List<String> cachedUserTags = const <String>[],
dds.UriConverter? uriConverter,
}) async {
expect(uri, Uri(scheme: 'foo', host: 'bar'));
expect(enableAuthCodes, isFalse);
expect(ipv6, isTrue);
......@@ -2133,7 +2137,7 @@ flutter:
expect(cachedUserTags, isEmpty);
expect(uriConverter, isNotNull);
done.complete();
return null;
return FakeDartDevelopmentService();
};
final TestFlutterDevice flutterDevice = TestFlutterDevice(
device,
......@@ -2143,14 +2147,14 @@ flutter:
await done.future;
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources reloadSources,
Restart restart,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
io.CompressionOptions compression,
Device device,
Logger logger,
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
Device? device,
required Logger logger,
}) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
dds.UriConverter: () => (String uri) => 'test',
}));
......@@ -2159,7 +2163,14 @@ flutter:
// See https://github.com/flutter/flutter/issues/72385 for context.
final FakeDevice device = FakeDevice()
..dds = DartDevelopmentService();
ddsLauncherCallback = (Uri uri, {bool enableAuthCodes, bool ipv6, Uri serviceUri, List<String> cachedUserTags, dds.UriConverter uriConverter}) {
ddsLauncherCallback = (
Uri uri, {
bool enableAuthCodes = false,
bool ipv6 = false,
Uri? serviceUri,
List<String> cachedUserTags = const <String>[],
dds.UriConverter? uriConverter,
}) {
expect(uri, Uri(scheme: 'foo', host: 'bar'));
expect(enableAuthCodes, isTrue);
expect(ipv6, isFalse);
......@@ -2177,7 +2188,7 @@ flutter:
runZonedGuarded(() {
flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete());
}, (Object e, StackTrace st) {
expect(e is StateError, true);
expect(e, isA<StateError>());
expect((e as StateError).message, contains('No URI'));
expect(testLogger.errorText, contains(
'DDS has failed to start and there is not an existing DDS instance',
......@@ -2191,14 +2202,14 @@ flutter:
}
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources reloadSources,
Restart restart,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
io.CompressionOptions compression,
Device device,
Logger logger,
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
Device? device,
required Logger logger,
}) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
}));
......@@ -2222,7 +2233,7 @@ flutter:
);
await residentRunner.cleanupAtFinish();
expect((residentRunner.residentDevtoolsHandler as NoOpDevtoolsHandler).wasShutdown, true);
expect((residentRunner.residentDevtoolsHandler! as NoOpDevtoolsHandler).wasShutdown, true);
}));
testUsingContext('HotRunner sets asset directory when first evict assets', () => testbed.run(() async {
......@@ -2241,12 +2252,12 @@ flutter:
devtoolsHandler: createNoOpHandler,
);
(flutterDevice.devFS as FakeDevFS).assetPathsToEvict = <String>{'asset'};
(flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = <String>{'asset'};
expect(flutterDevice.devFS.hasSetAssetDirectory, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, isFalse);
await (residentRunner as HotRunner).evictDirtyAssets();
expect(flutterDevice.devFS.hasSetAssetDirectory, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, isTrue);
expect(fakeVmServiceHost!.hasRemainingExpectations, isFalse);
}));
testUsingContext('HotRunner sets asset directory when first evict shaders', () => testbed.run(() async {
......@@ -2265,12 +2276,12 @@ flutter:
devtoolsHandler: createNoOpHandler,
);
(flutterDevice.devFS as FakeDevFS).shaderPathsToEvict = <String>{'foo.frag'};
(flutterDevice.devFS! as FakeDevFS).shaderPathsToEvict = <String>{'foo.frag'};
expect(flutterDevice.devFS.hasSetAssetDirectory, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
await (residentRunner as HotRunner).evictDirtyAssets();
expect(flutterDevice.devFS.hasSetAssetDirectory, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, true);
expect(fakeVmServiceHost!.hasRemainingExpectations, false);
}));
testUsingContext('HotRunner does not sets asset directory when no assets to evict', () => testbed.run(() async {
......@@ -2286,10 +2297,10 @@ flutter:
devtoolsHandler: createNoOpHandler,
);
expect(flutterDevice.devFS.hasSetAssetDirectory, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
await (residentRunner as HotRunner).evictDirtyAssets();
expect(flutterDevice.devFS.hasSetAssetDirectory, false);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
expect(fakeVmServiceHost!.hasRemainingExpectations, false);
}));
testUsingContext('HotRunner does not set asset directory if it has been set before', () => testbed.run(() async {
......@@ -2307,15 +2318,25 @@ flutter:
devtoolsHandler: createNoOpHandler,
);
(flutterDevice.devFS as FakeDevFS).assetPathsToEvict = <String>{'asset'};
flutterDevice.devFS.hasSetAssetDirectory = true;
(flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = <String>{'asset'};
flutterDevice.devFS!.hasSetAssetDirectory = true;
await (residentRunner as HotRunner).evictDirtyAssets();
expect(flutterDevice.devFS.hasSetAssetDirectory, true);
expect(fakeVmServiceHost.hasRemainingExpectations, false);
expect(flutterDevice.devFS!.hasSetAssetDirectory, true);
expect(fakeVmServiceHost!.hasRemainingExpectations, false);
}));
}
// NOTE: implements [dds.DartDevelopmentService] and NOT [DartDevelopmentService]
// from package:flutter_tools.
class FakeDartDevelopmentService extends Fake implements dds.DartDevelopmentService {
@override
Future<void> get done => Future<void>.value();
@override
Uri? get uri => null;
}
class FakeDartDevelopmentServiceException implements dds.DartDevelopmentServiceException {
FakeDartDevelopmentServiceException({this.message = defaultMessage});
......@@ -2328,18 +2349,17 @@ class FakeDartDevelopmentServiceException implements dds.DartDevelopmentServiceE
}
class TestFlutterDevice extends FlutterDevice {
TestFlutterDevice(Device device, { Stream<Uri> observatoryUris })
: super(device, buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()) {
_observatoryUris = observatoryUris;
}
TestFlutterDevice(super.device, { Stream<Uri>? observatoryUris })
: _observatoryUris = observatoryUris, super(buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler());
final Stream<Uri>? _observatoryUris;
@override
Stream<Uri> get observatoryUris => _observatoryUris;
Stream<Uri> _observatoryUris;
Stream<Uri> get observatoryUris => _observatoryUris!;
}
class ThrowingForwardingFileSystem extends ForwardingFileSystem {
ThrowingForwardingFileSystem(FileSystem delegate) : super(delegate);
ThrowingForwardingFileSystem(super.delegate);
@override
File file(dynamic path) {
......@@ -2351,19 +2371,19 @@ class ThrowingForwardingFileSystem extends ForwardingFileSystem {
}
class FakeFlutterDevice extends Fake implements FlutterDevice {
FakeVmServiceHost Function() vmServiceHost;
Uri testUri;
FakeVmServiceHost? Function()? vmServiceHost;
Uri? testUri;
UpdateFSReport report = UpdateFSReport(
success: true,
invalidatedSourcesCount: 1,
);
Exception reportError;
Exception runColdError;
Exception? reportError;
Exception? runColdError;
int runHotCode = 0;
int runColdCode = 0;
@override
ResidentCompiler generator;
ResidentCompiler? generator;
@override
DevelopmentShaderCompiler get developmentShaderCompiler => const FakeShaderCompiler();
......@@ -2372,21 +2392,21 @@ class FakeFlutterDevice extends Fake implements FlutterDevice {
TargetPlatform get targetPlatform => TargetPlatform.android;
@override
Stream<Uri> get observatoryUris => Stream<Uri>.value(testUri);
Stream<Uri?> get observatoryUris => Stream<Uri?>.value(testUri);
@override
FlutterVmService get vmService => vmServiceHost?.call()?.vmService;
FlutterVmService? get vmService => vmServiceHost?.call()?.vmService;
DevFS _devFS;
DevFS? _devFS;
@override
DevFS get devFS => _devFS;
DevFS? get devFS => _devFS;
@override
set devFS(DevFS value) { }
set devFS(DevFS? value) { }
@override
Device device;
Device? device;
@override
Future<void> stopEchoingDeviceLog() async { }
......@@ -2396,55 +2416,55 @@ class FakeFlutterDevice extends Fake implements FlutterDevice {
@override
Future<Uri> setupDevFS(String fsName, Directory rootDirectory) async {
return testUri;
return testUri!;
}
@override
Future<int> runHot({HotRunner hotRunner, String route}) async {
Future<int> runHot({required HotRunner hotRunner, String? route}) async {
return runHotCode;
}
@override
Future<int> runCold({ColdRunner coldRunner, String route}) async {
Future<int> runCold({required ColdRunner coldRunner, String? route}) async {
if (runColdError != null) {
throw runColdError;
throw runColdError!;
}
return runColdCode;
}
@override
Future<void> connect({
ReloadSources reloadSources,
Restart restart,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
int hostVmServicePort,
int ddsPort,
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
int? hostVmServicePort,
int? ddsPort,
bool disableServiceAuthCodes = false,
bool enableDds = true,
bool cacheStartupProfile = false,
@required bool allowExistingDdsInstance,
required bool allowExistingDdsInstance,
bool ipv6 = false,
}) async { }
@override
Future<UpdateFSReport> updateDevFS({
Uri mainUri,
String target,
AssetBundle bundle,
DateTime firstBuildTime,
required Uri mainUri,
String? target,
AssetBundle? bundle,
DateTime? firstBuildTime,
bool bundleFirstUpload = false,
bool bundleDirty = false,
bool fullRestart = false,
String projectRootPath,
String pathToReload,
String dillOutputPath,
List<Uri> invalidatedFiles,
PackageConfig packageConfig,
String? projectRootPath,
required String pathToReload,
required String dillOutputPath,
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
}) async {
if (reportError != null) {
throw reportError;
throw reportError!;
}
return report;
}
......@@ -2455,25 +2475,25 @@ class FakeFlutterDevice extends Fake implements FlutterDevice {
class FakeDelegateFlutterDevice extends FlutterDevice {
FakeDelegateFlutterDevice(
Device device,
super.device,
BuildInfo buildInfo,
ResidentCompiler residentCompiler,
this.fakeDevFS,
) : super(device, buildInfo: buildInfo, generator: residentCompiler, developmentShaderCompiler: const FakeShaderCompiler());
) : super(buildInfo: buildInfo, generator: residentCompiler, developmentShaderCompiler: const FakeShaderCompiler());
@override
Future<void> connect({
ReloadSources reloadSources,
Restart restart,
ReloadSources? reloadSources,
Restart? restart,
bool enableDds = true,
bool cacheStartupProfile = false,
bool disableServiceAuthCodes = false,
bool ipv6 = false,
CompileExpression compileExpression,
GetSkSLMethod getSkSLMethod,
int hostVmServicePort,
int ddsPort,
PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
int? hostVmServicePort,
int? ddsPort,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
bool allowExistingDdsInstance = false,
}) async { }
......@@ -2481,27 +2501,27 @@ class FakeDelegateFlutterDevice extends FlutterDevice {
final DevFS fakeDevFS;
@override
DevFS get devFS => fakeDevFS;
DevFS? get devFS => fakeDevFS;
@override
set devFS(DevFS value) {}
set devFS(DevFS? value) {}
}
class FakeResidentCompiler extends Fake implements ResidentCompiler {
CompilerOutput nextOutput;
CompilerOutput? nextOutput;
bool didSuppressErrors = false;
@override
Future<CompilerOutput> recompile(
Future<CompilerOutput?> recompile(
Uri mainUri,
List<Uri> invalidatedFiles, {
@required String outputPath,
@required PackageConfig packageConfig,
@required String projectRootPath,
@required FileSystem fs,
List<Uri>? invalidatedFiles, {
required String outputPath,
required PackageConfig packageConfig,
String? projectRootPath,
required FileSystem fs,
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File dartPluginRegistrant,
File? dartPluginRegistrant,
}) async {
didSuppressErrors = suppressErrors;
return nextOutput ?? const CompilerOutput('foo.dill', 0, <Uri>[]);
......@@ -2517,14 +2537,14 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
class FakeProjectFileInvalidator extends Fake implements ProjectFileInvalidator {
@override
Future<InvalidationResult> findInvalidated({
@required DateTime lastCompiled,
@required List<Uri> urisToMonitor,
@required String packagesPath,
@required PackageConfig packageConfig,
required DateTime? lastCompiled,
required List<Uri> urisToMonitor,
required String packagesPath,
required PackageConfig packageConfig,
bool asyncScanning = false,
}) async {
return InvalidationResult(
packageConfig: packageConfig ?? PackageConfig.empty,
packageConfig: packageConfig,
uris: <Uri>[Uri.parse('file:///hello_world/main.dart'),
]);
}
......@@ -2580,7 +2600,7 @@ class FakeDevice extends Fake implements Device {
String get name => 'FakeDevice';
@override
DartDevelopmentService dds;
late DartDevelopmentService dds;
@override
Future<void> dispose() async {
......@@ -2588,7 +2608,7 @@ class FakeDevice extends Fake implements Device {
}
@override
Future<bool> stopApp(covariant ApplicationPackage app, {String userIdentifier}) async {
Future<bool> stopApp(covariant ApplicationPackage? app, {String? userIdentifier}) async {
appStopped = true;
return true;
}
......@@ -2603,7 +2623,7 @@ class FakeDevice extends Fake implements Device {
@override
FutureOr<DeviceLogReader> getLogReader({
covariant ApplicationPackage app,
covariant ApplicationPackage? app,
bool includePastLogs = false,
}) => NoOpDeviceLogReader(name);
......@@ -2613,10 +2633,10 @@ class FakeDevice extends Fake implements Device {
class FakeDevFS extends Fake implements DevFS {
@override
DateTime lastCompiled = DateTime(2000);
DateTime? lastCompiled = DateTime(2000);
@override
PackageConfig lastPackageConfig = PackageConfig.empty;
PackageConfig? lastPackageConfig = PackageConfig.empty;
@override
List<Uri> sources = <Uri>[];
......@@ -2653,22 +2673,22 @@ class FakeDevFS extends Fake implements DevFS {
@override
Future<UpdateFSReport> update({
@required Uri mainUri,
@required ResidentCompiler generator,
@required bool trackWidgetCreation,
@required String pathToReload,
@required List<Uri> invalidatedFiles,
@required PackageConfig packageConfig,
@required String dillOutputPath,
@required DevelopmentShaderCompiler shaderCompiler,
DevFSWriter devFSWriter,
String target,
AssetBundle bundle,
DateTime firstBuildTime,
required Uri mainUri,
required ResidentCompiler generator,
required bool trackWidgetCreation,
required String pathToReload,
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
required String dillOutputPath,
required DevelopmentShaderCompiler shaderCompiler,
DevFSWriter? devFSWriter,
String? target,
AssetBundle? bundle,
DateTime? firstBuildTime,
bool bundleFirstUpload = false,
bool fullRestart = false,
String projectRootPath,
File dartPluginRegistrant,
String? projectRootPath,
File? dartPluginRegistrant,
}) async {
return nextUpdateReport;
}
......@@ -2678,7 +2698,7 @@ class FakeShaderCompiler implements DevelopmentShaderCompiler {
const FakeShaderCompiler();
@override
void configureCompiler(TargetPlatform platform, { @required bool enableImpeller }) { }
void configureCompiler(TargetPlatform? platform, { required bool enableImpeller }) { }
@override
Future<DevFSContent> recompileShader(DevFSContent inputShader) {
......
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