Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -9,8 +9,7 @@ import 'dart:core';
/// Throws an [ArgumentError] if the address is neither.
void validateAddress(String address) {
if (!(isIpV4Address(address) || isIpV6Address(address))) {
throw ArgumentError(
'"$address" is neither a valid IPv4 nor IPv6 address');
throw ArgumentError('"$address" is neither a valid IPv4 nor IPv6 address');
}
}

View File

@@ -14,10 +14,8 @@ final Logger _log = Logger('DartVm');
/// Signature of an asynchronous function for establishing a [vms.VmService]
/// connection to a [Uri].
typedef RpcPeerConnectionFunction = Future<vms.VmService> Function(
Uri uri, {
required Duration timeout,
});
typedef RpcPeerConnectionFunction =
Future<vms.VmService> Function(Uri uri, {required Duration timeout});
/// [DartVm] uses this function to connect to the Dart VM on Fuchsia.
///
@@ -28,10 +26,7 @@ RpcPeerConnectionFunction fuchsiaVmServiceConnectionFunction = _waitAndConnect;
/// Attempts to connect to a Dart VM service.
///
/// Gives up after `timeout` has elapsed.
Future<vms.VmService> _waitAndConnect(
Uri uri, {
Duration timeout = _kConnectTimeout,
}) async {
Future<vms.VmService> _waitAndConnect(Uri uri, {Duration timeout = _kConnectTimeout}) async {
int attempts = 0;
late WebSocket socket;
while (true) {
@@ -47,7 +42,7 @@ Future<vms.VmService> _waitAndConnect(
controller.stream,
socket.add,
disposeHandler: () => socket.close(),
streamClosed: streamClosedCompleter.future
streamClosed: streamClosedCompleter.future,
);
// This call is to ensure we are able to establish a connection instead of
// keeping on trucking and failing farther down the process.
@@ -102,10 +97,7 @@ class DartVm {
/// Attempts to connect to the given [Uri].
///
/// Throws an error if unable to connect.
static Future<DartVm> connect(
Uri uri, {
Duration timeout = _kConnectTimeout,
}) async {
static Future<DartVm> connect(Uri uri, {Duration timeout = _kConnectTimeout}) async {
if (uri.scheme == 'http') {
uri = uri.replace(scheme: 'ws', path: '/ws');
}
@@ -131,7 +123,6 @@ class DartVm {
return result;
}
/// Returns a list of [FlutterView] objects running across all Dart VM's.
///
/// If there is no associated isolate with the flutter view (used to determine
@@ -141,7 +132,8 @@ class DartVm {
Future<List<FlutterView>> getAllFlutterViews() async {
final List<FlutterView> views = <FlutterView>[];
final vms.Response rpcResponse = await _vmService.callMethod('_flutter.listViews');
for (final Map<String, dynamic> jsonView in (rpcResponse.json!['views'] as List<dynamic>).cast<Map<String, dynamic>>()) {
for (final Map<String, dynamic> jsonView
in (rpcResponse.json!['views'] as List<dynamic>).cast<Map<String, dynamic>>()) {
views.add(FlutterView._fromJson(jsonView));
}
return views;
@@ -179,8 +171,7 @@ class FlutterView {
final String? id = json['id'] as String?;
String? name;
if (id == null) {
throw RpcFormatError(
'Unable to find view name for the following JSON structure "$json"');
throw RpcFormatError('Unable to find view name for the following JSON structure "$json"');
}
if (isolate != null) {
name = isolate['name'] as String?;
@@ -228,12 +219,10 @@ class IsolateRef {
throw RpcFormatError('Type "$type" does not match for IsolateRef');
}
if (number == null) {
throw RpcFormatError(
'Unable to find number for isolate ref within JSON "$json"');
throw RpcFormatError('Unable to find number for isolate ref within JSON "$json"');
}
if (name == null) {
throw RpcFormatError(
'Unable to find name for isolate ref within JSON "$json"');
throw RpcFormatError('Unable to find name for isolate ref within JSON "$json"');
}
return IsolateRef._(name, int.parse(number), dartVm);
}

View File

@@ -32,12 +32,13 @@ final Logger _log = Logger('FuchsiaRemoteConnection');
/// Takes a remote `address`, the target device's port, and an optional
/// `interface` and `configFile`. The config file is used primarily for the
/// default SSH port forwarding configuration.
typedef PortForwardingFunction = Future<PortForwarder> Function(
String address,
int remotePort, [
String? interface,
String? configFile,
]);
typedef PortForwardingFunction =
Future<PortForwarder> Function(
String address,
int remotePort, [
String? interface,
String? configFile,
]);
/// The function for forwarding the local machine's ports to a remote Fuchsia
/// device.
@@ -104,8 +105,7 @@ class DartVmEvent {
/// This class can be connected to several instances of the Fuchsia device's
/// Dart VM at any given time.
class FuchsiaRemoteConnection {
FuchsiaRemoteConnection._(this._useIpV6, this._sshCommandRunner)
: _pollDartVms = false;
FuchsiaRemoteConnection._(this._useIpV6, this._sshCommandRunner) : _pollDartVms = false;
bool _pollDartVms;
final List<PortForwarder> _forwardedVmServicePorts = <PortForwarder>[];
@@ -123,8 +123,7 @@ class FuchsiaRemoteConnection {
/// A broadcast stream that emits events relating to Dart VM's as they update.
Stream<DartVmEvent> get onDartVmEvent => _onDartVmEvent;
late Stream<DartVmEvent> _onDartVmEvent;
final StreamController<DartVmEvent> _dartVmEventController =
StreamController<DartVmEvent>();
final StreamController<DartVmEvent> _dartVmEventController = StreamController<DartVmEvent>();
/// VM service cache to avoid repeating handshakes across function
/// calls. Keys a URI to a DartVm connection instance.
@@ -132,9 +131,13 @@ class FuchsiaRemoteConnection {
/// Same as [FuchsiaRemoteConnection.connect] albeit with a provided
/// [SshCommandRunner] instance.
static Future<FuchsiaRemoteConnection> connectWithSshCommandRunner(SshCommandRunner commandRunner) async {
static Future<FuchsiaRemoteConnection> connectWithSshCommandRunner(
SshCommandRunner commandRunner,
) async {
final FuchsiaRemoteConnection connection = FuchsiaRemoteConnection._(
isIpV6Address(commandRunner.address), commandRunner);
isIpV6Address(commandRunner.address),
commandRunner,
);
await connection._forwardOpenPortsToDeviceServicePorts();
Stream<DartVmEvent> dartVmStream() {
@@ -197,22 +200,18 @@ class FuchsiaRemoteConnection {
sshConfigPath ??= Platform.environment['FUCHSIA_SSH_CONFIG'];
if (address == null) {
throw FuchsiaRemoteConnectionError(
r'No address supplied, and $FUCHSIA_DEVICE_URL not found.');
r'No address supplied, and $FUCHSIA_DEVICE_URL not found.',
);
}
const String interfaceDelimiter = '%';
if (address.contains(interfaceDelimiter)) {
final List<String> addressAndInterface =
address.split(interfaceDelimiter);
final List<String> addressAndInterface = address.split(interfaceDelimiter);
address = addressAndInterface[0];
interface = addressAndInterface[1];
}
return FuchsiaRemoteConnection.connectWithSshCommandRunner(
SshCommandRunner(
address: address,
interface: interface,
sshConfigPath: sshConfigPath,
),
SshCommandRunner(address: address, interface: interface, sshConfigPath: sshConfigPath),
);
}
@@ -259,25 +258,32 @@ class FuchsiaRemoteConnection {
_onDartVmEvent.listen(
(DartVmEvent event) async {
if (event.eventType == DartVmEventType.started) {
_log.fine('New VM found on port: ${event.servicePort}. Searching '
'for Isolate: $pattern');
_log.fine(
'New VM found on port: ${event.servicePort}. Searching '
'for Isolate: $pattern',
);
final DartVm? vmService = await _getDartVm(event.uri);
// If the VM service is null, set the result to the empty list.
final List<IsolateRef> result = await vmService?.getMainIsolatesByPattern(pattern!) ?? <IsolateRef>[];
final List<IsolateRef> result =
await vmService?.getMainIsolatesByPattern(pattern!) ?? <IsolateRef>[];
if (result.isNotEmpty) {
if (!completer.isCompleted) {
completer.complete(result);
} else {
_log.warning('Found more than one Dart VM containing Isolates '
'that match the pattern "$pattern".');
_log.warning(
'Found more than one Dart VM containing Isolates '
'that match the pattern "$pattern".',
);
}
}
}
},
onDone: () {
if (!completer.isCompleted) {
_log.warning('Terminating isolate search for "$pattern"'
' before timeout reached.');
_log.warning(
'Terminating isolate search for "$pattern"'
' before timeout reached.',
);
}
},
);
@@ -298,37 +304,32 @@ class FuchsiaRemoteConnection {
// start with the Isolate in question.
if (_dartVmPortMap.isEmpty) {
_log.fine('No live Dart VMs found. Awaiting new VM startup');
return _waitForMainIsolatesByPattern(
pattern, timeout, vmConnectionTimeout);
return _waitForMainIsolatesByPattern(pattern, timeout, vmConnectionTimeout);
}
// Accumulate a list of eventual IsolateRef lists so that they can be loaded
// simultaneously via Future.wait.
final List<Future<List<IsolateRef>>> isolates =
<Future<List<IsolateRef>>>[];
final List<Future<List<IsolateRef>>> isolates = <Future<List<IsolateRef>>>[];
for (final PortForwarder fp in _dartVmPortMap.values) {
final DartVm? vmService =
await _getDartVm(_getDartVmUri(fp), timeout: vmConnectionTimeout);
final DartVm? vmService = await _getDartVm(_getDartVmUri(fp), timeout: vmConnectionTimeout);
if (vmService == null) {
continue;
}
isolates.add(vmService.getMainIsolatesByPattern(pattern));
}
final List<IsolateRef> result =
await Future.wait<List<IsolateRef>>(isolates)
.timeout(timeout)
.then<List<IsolateRef>>((List<List<IsolateRef>> listOfLists) {
final List<List<IsolateRef>> mutableListOfLists =
List<List<IsolateRef>>.from(listOfLists)
..retainWhere((List<IsolateRef> list) => list.isNotEmpty);
// Folds the list of lists into one flat list.
return mutableListOfLists.fold<List<IsolateRef>>(
<IsolateRef>[],
(List<IsolateRef> accumulator, List<IsolateRef> element) {
accumulator.addAll(element);
return accumulator;
},
);
});
final List<IsolateRef> result = await Future.wait<List<IsolateRef>>(
isolates,
).timeout(timeout).then<List<IsolateRef>>((List<List<IsolateRef>> listOfLists) {
final List<List<IsolateRef>> mutableListOfLists = List<List<IsolateRef>>.from(listOfLists)
..retainWhere((List<IsolateRef> list) => list.isNotEmpty);
// Folds the list of lists into one flat list.
return mutableListOfLists.fold<List<IsolateRef>>(<IsolateRef>[], (
List<IsolateRef> accumulator,
List<IsolateRef> element,
) {
accumulator.addAll(element);
return accumulator;
});
});
// If no VM instance anywhere has this, it's possible it hasn't spun up
// anywhere.
@@ -340,8 +341,7 @@ class FuchsiaRemoteConnection {
// TODO(awdavies): Set this up to handle multiple Isolates per Dart VM.
if (result.isEmpty) {
_log.fine('No instance of the Isolate found. Awaiting new VM startup');
return _waitForMainIsolatesByPattern(
pattern, timeout, vmConnectionTimeout);
return _waitForMainIsolatesByPattern(pattern, timeout, vmConnectionTimeout);
}
return result;
}
@@ -354,12 +354,15 @@ class FuchsiaRemoteConnection {
if (_dartVmPortMap.isEmpty) {
return <FlutterView>[];
}
final List<List<FlutterView>> flutterViewLists =
await _invokeForAllVms<List<FlutterView>>((DartVm vmService) async {
final List<List<FlutterView>> flutterViewLists = await _invokeForAllVms<List<FlutterView>>((
DartVm vmService,
) async {
return vmService.getAllFlutterViews();
});
final List<FlutterView> results = flutterViewLists.fold<List<FlutterView>>(
<FlutterView>[], (List<FlutterView> acc, List<FlutterView> element) {
final List<FlutterView> results = flutterViewLists.fold<List<FlutterView>>(<FlutterView>[], (
List<FlutterView> acc,
List<FlutterView> element,
) {
acc.addAll(element);
return acc;
});
@@ -382,11 +385,13 @@ class FuchsiaRemoteConnection {
await pf.stop();
_stalePorts.add(pf.remotePort);
if (queueEvents) {
_dartVmEventController.add(DartVmEvent._(
eventType: DartVmEventType.stopped,
servicePort: pf.remotePort,
uri: _getDartVmUri(pf),
));
_dartVmEventController.add(
DartVmEvent._(
eventType: DartVmEventType.stopped,
servicePort: pf.remotePort,
uri: _getDartVmUri(pf),
),
);
}
}
@@ -407,9 +412,7 @@ class FuchsiaRemoteConnection {
if (pf.openPortAddress == null) {
addr = _useIpV6 ? '[$_ipv6Loopback]' : _ipv4Loopback;
} else {
addr = isIpV6Address(pf.openPortAddress!)
? '[${pf.openPortAddress}]'
: pf.openPortAddress;
addr = isIpV6Address(pf.openPortAddress!) ? '[${pf.openPortAddress}]' : pf.openPortAddress;
}
final Uri uri = Uri.http('$addr:${pf.port}', '/');
return uri;
@@ -419,10 +422,7 @@ class FuchsiaRemoteConnection {
///
/// Returns null if either there is an [HttpException] or a
/// [TimeoutException], else a [DartVm] instance.
Future<DartVm?> _getDartVm(
Uri uri, {
Duration timeout = _kDartVmConnectionTimeout,
}) async {
Future<DartVm?> _getDartVm(Uri uri, {Duration timeout = _kDartVmConnectionTimeout}) async {
if (!_dartVmCache.containsKey(uri)) {
// When raising an HttpException this means that there is no instance of
// the Dart VM to communicate with. The TimeoutException is raised when
@@ -449,19 +449,21 @@ class FuchsiaRemoteConnection {
await _checkPorts();
final List<int> servicePorts = await getDeviceServicePorts();
for (final int servicePort in servicePorts) {
if (!_stalePorts.contains(servicePort) &&
!_dartVmPortMap.containsKey(servicePort)) {
if (!_stalePorts.contains(servicePort) && !_dartVmPortMap.containsKey(servicePort)) {
_dartVmPortMap[servicePort] = await fuchsiaPortForwardingFunction(
_sshCommandRunner.address,
servicePort,
_sshCommandRunner.interface,
_sshCommandRunner.sshConfigPath);
_sshCommandRunner.address,
servicePort,
_sshCommandRunner.interface,
_sshCommandRunner.sshConfigPath,
);
_dartVmEventController.add(DartVmEvent._(
eventType: DartVmEventType.started,
servicePort: servicePort,
uri: _getDartVmUri(_dartVmPortMap[servicePort]!),
));
_dartVmEventController.add(
DartVmEvent._(
eventType: DartVmEventType.started,
servicePort: servicePort,
uri: _getDartVmUri(_dartVmPortMap[servicePort]!),
),
);
}
}
}
@@ -469,14 +471,11 @@ class FuchsiaRemoteConnection {
/// Runs a dummy heartbeat command on all Dart VM instances.
///
/// Removes any failing ports from the cache.
Future<void> _checkPorts([ bool queueEvents = true ]) async {
Future<void> _checkPorts([bool queueEvents = true]) async {
// Filters out stale ports after connecting. Ignores results.
await _invokeForAllVms<void>(
(DartVm vmService) async {
await vmService.ping();
},
queueEvents,
);
await _invokeForAllVms<void>((DartVm vmService) async {
await vmService.ping();
}, queueEvents);
}
/// Forwards a series of open ports to the remote device.
@@ -486,15 +485,16 @@ class FuchsiaRemoteConnection {
Future<void> _forwardOpenPortsToDeviceServicePorts() async {
await stop();
final List<int> servicePorts = await getDeviceServicePorts();
final List<PortForwarder?> forwardedVmServicePorts =
await Future.wait<PortForwarder?>(
servicePorts.map<Future<PortForwarder?>>((int deviceServicePort) {
return fuchsiaPortForwardingFunction(
_sshCommandRunner.address,
deviceServicePort,
_sshCommandRunner.interface,
_sshCommandRunner.sshConfigPath);
}));
final List<PortForwarder?> forwardedVmServicePorts = await Future.wait<PortForwarder?>(
servicePorts.map<Future<PortForwarder?>>((int deviceServicePort) {
return fuchsiaPortForwardingFunction(
_sshCommandRunner.address,
deviceServicePort,
_sshCommandRunner.interface,
_sshCommandRunner.sshConfigPath,
);
}),
);
for (final PortForwarder? pf in forwardedVmServicePorts) {
// TODO(awdavies): Handle duplicates.
@@ -510,25 +510,27 @@ class FuchsiaRemoteConnection {
/// Helper for getDeviceServicePorts() to extract the vm_service_port from
/// json response.
List<int> getVmServicePortFromInspectSnapshot(dynamic inspectSnapshot) {
final List<Map<String, dynamic>> snapshot =
List<Map<String, dynamic>>.from(inspectSnapshot as List<dynamic>);
final List<Map<String, dynamic>> snapshot = List<Map<String, dynamic>>.from(
inspectSnapshot as List<dynamic>,
);
final List<int> ports = <int>[];
for (final Map<String, dynamic> item in snapshot) {
if (!item.containsKey('payload') || item['payload'] == null) {
continue;
}
final Map<String, dynamic> payload =
Map<String, dynamic>.from(item['payload'] as Map<String, dynamic>);
final Map<String, dynamic> payload = Map<String, dynamic>.from(
item['payload'] as Map<String, dynamic>,
);
if (!payload.containsKey('root') || payload['root'] == null) {
continue;
}
final Map<String, dynamic> root =
Map<String, dynamic>.from(payload['root'] as Map<String, dynamic>);
final Map<String, dynamic> root = Map<String, dynamic>.from(
payload['root'] as Map<String, dynamic>,
);
if (!root.containsKey('vm_service_port') ||
root['vm_service_port'] == null) {
if (!root.containsKey('vm_service_port') || root['vm_service_port'] == null) {
continue;
}
@@ -548,11 +550,11 @@ class FuchsiaRemoteConnection {
/// found. An exception is thrown in the event of an actual error when
/// attempting to acquire the ports.
Future<List<int>> getDeviceServicePorts() async {
final List<String> inspectResult = await _sshCommandRunner
.run("iquery --format json show '**:root:vm_service_port'");
final List<String> inspectResult = await _sshCommandRunner.run(
"iquery --format json show '**:root:vm_service_port'",
);
final dynamic inspectOutputJson = jsonDecode(inspectResult.join('\n'));
final List<int> ports =
getVmServicePortFromInspectSnapshot(inspectOutputJson);
final List<int> ports = getVmServicePortFromInspectSnapshot(inspectOutputJson);
if (ports.length > 1) {
throw StateError('More than one Flutter observatory port found');
@@ -622,8 +624,10 @@ class _SshPortForwarder implements PortForwarder {
final bool isIpV6 = isIpV6Address(address);
final ServerSocket? localSocket = await _createLocalSocket();
if (localSocket == null || localSocket.port == 0) {
_log.warning('_SshPortForwarder failed to find a local port for '
'$address:$remotePort');
_log.warning(
'_SshPortForwarder failed to find a local port for '
'$address:$remotePort',
);
throw StateError('Unable to create a socket or no available ports.');
}
// TODO(awdavies): The square-bracket enclosure for using the IPv6 loopback
@@ -632,16 +636,13 @@ class _SshPortForwarder implements PortForwarder {
// loopback (::1). Therefore, while the IPv4 loopback can be used for
// forwarding to the destination IPv6 interface, when connecting to the
// websocket, the IPV6 loopback should be used.
final String formattedForwardingUrl =
'${localSocket.port}:$_ipv4Loopback:$remotePort';
final String targetAddress =
isIpV6 && interface!.isNotEmpty ? '$address%$interface' : address;
final String formattedForwardingUrl = '${localSocket.port}:$_ipv4Loopback:$remotePort';
final String targetAddress = isIpV6 && interface!.isNotEmpty ? '$address%$interface' : address;
const String dummyRemoteCommand = 'true';
final List<String> command = <String>[
'ssh',
if (isIpV6) '-6',
if (sshConfigPath != null)
...<String>['-F', sshConfigPath],
if (sshConfigPath != null) ...<String>['-F', sshConfigPath],
'-nNT',
'-f',
'-L',
@@ -654,15 +655,25 @@ class _SshPortForwarder implements PortForwarder {
// forwarding must be completed before surfacing VM events (as the user may
// want to connect immediately after an event is surfaced).
final ProcessResult processResult = await _processManager.run(command);
_log.fine("'${command.join(' ')}' exited with exit code "
'${processResult.exitCode}');
_log.fine(
"'${command.join(' ')}' exited with exit code "
'${processResult.exitCode}',
);
if (processResult.exitCode != 0) {
throw StateError('Unable to start port forwarding');
}
final _SshPortForwarder result = _SshPortForwarder._(
address, remotePort, localSocket, interface, sshConfigPath, isIpV6);
_log.fine('Set up forwarding from ${localSocket.port} '
'to $address port $remotePort');
address,
remotePort,
localSocket,
interface,
sshConfigPath,
isIpV6,
);
_log.fine(
'Set up forwarding from ${localSocket.port} '
'to $address port $remotePort',
);
return result;
}
@@ -672,28 +683,26 @@ class _SshPortForwarder implements PortForwarder {
Future<void> stop() async {
// Cancel the forwarding request. See [start] for commentary about why this
// uses the IPv4 loopback.
final String formattedForwardingUrl =
'${_localSocket.port}:$_ipv4Loopback:$_remotePort';
final String targetAddress = _ipV6 && _interface!.isNotEmpty
? '$_remoteAddress%$_interface'
: _remoteAddress;
final String formattedForwardingUrl = '${_localSocket.port}:$_ipv4Loopback:$_remotePort';
final String targetAddress =
_ipV6 && _interface!.isNotEmpty ? '$_remoteAddress%$_interface' : _remoteAddress;
final String? sshConfigPath = _sshConfigPath;
final List<String> command = <String>[
'ssh',
if (sshConfigPath != null)
...<String>['-F', sshConfigPath],
if (sshConfigPath != null) ...<String>['-F', sshConfigPath],
'-O',
'cancel',
'-L',
formattedForwardingUrl,
targetAddress,
];
_log.fine(
'Shutting down SSH forwarding with command: ${command.join(' ')}');
_log.fine('Shutting down SSH forwarding with command: ${command.join(' ')}');
final ProcessResult result = await _processManager.run(command);
if (result.exitCode != 0) {
_log.warning('Command failed:\nstdout: ${result.stdout}'
'\nstderr: ${result.stderr}');
_log.warning(
'Command failed:\nstdout: ${result.stdout}'
'\nstderr: ${result.stderr}',
);
}
_localSocket.close();
}

View File

@@ -43,11 +43,8 @@ class SshCommandRunner {
/// [ArgumentError] is thrown in the event that `address` is neither valid
/// IPv4 nor IPv6. When connecting to a link local address (`fe80::` is
/// usually at the start of the address), an interface should be supplied.
SshCommandRunner({
required this.address,
this.interface = '',
this.sshConfigPath,
}) : _processManager = const LocalProcessManager() {
SshCommandRunner({required this.address, this.interface = '', this.sshConfigPath})
: _processManager = const LocalProcessManager() {
validateAddress(address);
}
@@ -83,11 +80,11 @@ class SshCommandRunner {
Future<List<String>> run(String command) async {
final List<String> args = <String>[
'ssh',
if (sshConfigPath != null)
...<String>['-F', sshConfigPath!],
if (isIpV6Address(address))
...<String>['-6', if (interface.isEmpty) address else '$address%$interface']
else
if (sshConfigPath != null) ...<String>['-F', sshConfigPath!],
if (isIpV6Address(address)) ...<String>[
'-6',
if (interface.isEmpty) address else '$address%$interface',
] else
address,
command,
];
@@ -95,7 +92,8 @@ class SshCommandRunner {
final ProcessResult result = await _processManager.run(args);
if (result.exitCode != 0) {
throw SshCommandError(
'Command failed: $command\nstdout: ${result.stdout}\nstderr: ${result.stderr}');
'Command failed: $command\nstdout: ${result.stdout}\nstderr: ${result.stderr}',
);
}
_log.fine('SSH command stdout in brackets:[${result.stdout}]');
return (result.stdout as String).split('\n');

View File

@@ -14,14 +14,10 @@ void main() {
late List<Uri> uriConnections;
setUp(() {
final List<Map<String, dynamic>> flutterViewCannedResponses =
<Map<String, dynamic>>[
final List<Map<String, dynamic>> flutterViewCannedResponses = <Map<String, dynamic>>[
<String, dynamic>{
'views': <Map<String, dynamic>>[
<String, dynamic>{
'type': 'FlutterView',
'id': 'flutterView0',
},
<String, dynamic>{'type': 'FlutterView', 'id': 'flutterView0'},
],
},
<String, dynamic>{
@@ -59,10 +55,7 @@ void main() {
forwardedPorts = <FakePortForwarder>[];
fakeVmServices = <FakeVmService>[];
uriConnections = <Uri>[];
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
return Future<vms.VmService>(() async {
final FakeVmService service = FakeVmService();
fakeVmServices.add(service);
@@ -138,7 +131,7 @@ void main() {
' },',
' "version": 1',
' }',
' ]'
' ]',
];
fakeRunner.address = 'fe80::8eae:4cff:fef4:9247';
fakeRunner.interface = 'eno1';
@@ -151,8 +144,7 @@ void main() {
// VMs should be accessed via localhost ports given by
// [fakePortForwardingFunction].
expect(uriConnections[0],
Uri(scheme: 'ws', host: '[::1]', port: 0, path: '/ws'));
expect(uriConnections[0], Uri(scheme: 'ws', host: '[::1]', port: 0, path: '/ws'));
final List<FlutterView> views = await connection.getFlutterViews();
expect(views, isNot(null));
@@ -224,7 +216,7 @@ void main() {
' },',
' "version": 1',
' }',
' ]'
' ]',
];
fakeRunner.address = 'fe80::8eae:4cff:fef4:9247';
fakeRunner.interface = 'eno1';
@@ -236,8 +228,10 @@ void main() {
// VMs should be accessed via the alternate address given by
// [fakePortForwardingFunction].
expect(uriConnections[0],
Uri(scheme: 'ws', host: '[fe80::1:2%25eno2]', port: 0, path: '/ws'));
expect(
uriConnections[0],
Uri(scheme: 'ws', host: '[fe80::1:2%25eno2]', port: 0, path: '/ws'),
);
final List<FlutterView> views = await connection.getFlutterViews();
expect(views, isNot(null));
@@ -308,7 +302,7 @@ void main() {
' },',
' "version": 1',
' }',
' ]'
' ]',
];
fakeRunner.address = '196.168.1.4';
@@ -319,8 +313,7 @@ void main() {
expect(forwardedPorts[0].remotePort, 12345);
// VMs should be accessed via the ipv4 loopback.
expect(uriConnections[0],
Uri(scheme: 'ws', host: '127.0.0.1', port: 0, path: '/ws'));
expect(uriConnections[0], Uri(scheme: 'ws', host: '127.0.0.1', port: 0, path: '/ws'));
final List<FlutterView> views = await connection.getFlutterViews();
expect(views, isNot(null));
@@ -341,8 +334,7 @@ void main() {
}
// Should fail as no env variable has been passed.
expect(failingFunction,
throwsA(isA<FuchsiaRemoteConnectionError>()));
expect(failingFunction, throwsA(isA<FuchsiaRemoteConnectionError>()));
});
});
}
@@ -394,7 +386,11 @@ class FakeVmService extends Fake implements vms.VmService {
}
@override
Future<vms.Response> callMethod(String method, {String? isolateId, Map<String, dynamic>? args}) async {
Future<vms.Response> callMethod(
String method, {
String? isolateId,
Map<String, dynamic>? args,
}) async {
if (method == '_flutter.listViews') {
return flutterListViews!;
}

View File

@@ -17,16 +17,12 @@ void main() {
test('disconnect closes peer', () async {
final FakeVmService service = FakeVmService();
Future<vms.VmService> fakeServiceFunction(
Uri uri, {
Duration? timeout,
}) {
Future<vms.VmService> fakeServiceFunction(Uri uri, {Duration? timeout}) {
return Future<vms.VmService>(() => service);
}
fuchsiaVmServiceConnectionFunction = fakeServiceFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://this.whatever/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://this.whatever/ws'));
expect(vm, isNot(null));
await vm.stop();
expect(service.disposed, true);
@@ -47,10 +43,7 @@ void main() {
test('basic flutter view parsing', () async {
final Map<String, dynamic> flutterViewCannedResponses = <String, dynamic>{
'views': <Map<String, dynamic>>[
<String, dynamic>{
'type': 'FlutterView',
'id': 'flutterView0',
},
<String, dynamic>{'type': 'FlutterView', 'id': 'flutterView0'},
<String, dynamic>{
'type': 'FlutterView',
'id': 'flutterView1',
@@ -76,18 +69,13 @@ void main() {
],
};
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
fakeService.flutterListViews =
vms.Response.parse(flutterViewCannedResponses);
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponses);
return Future<vms.VmService>(() => fakeService);
}
fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://whatever.com/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws'));
expect(vm, isNot(null));
final List<FlutterView> views = await vm.getAllFlutterViews();
expect(views.length, 3);
@@ -105,10 +93,7 @@ void main() {
test('basic flutter view parsing with casting checks', () async {
final Map<String, dynamic> flutterViewCannedResponses = <String, dynamic>{
'views': <dynamic>[
<String, dynamic>{
'type': 'FlutterView',
'id': 'flutterView0',
},
<String, dynamic>{'type': 'FlutterView', 'id': 'flutterView0'},
<String, dynamic>{
'type': 'FlutterView',
'id': 'flutterView1',
@@ -134,18 +119,13 @@ void main() {
],
};
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
fakeService.flutterListViews =
vms.Response.parse(flutterViewCannedResponses);
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponses);
return Future<vms.VmService>(() => fakeService);
}
fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://whatever.com/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws'));
expect(vm, isNot(null));
final List<FlutterView> views = await vm.getAllFlutterViews();
expect(views.length, 3);
@@ -161,8 +141,7 @@ void main() {
});
test('invalid flutter view missing ID', () async {
final Map<String, dynamic> flutterViewCannedResponseMissingId =
<String, dynamic>{
final Map<String, dynamic> flutterViewCannedResponseMissingId = <String, dynamic>{
'views': <Map<String, dynamic>>[
// Valid flutter view.
<String, dynamic>{
@@ -178,24 +157,17 @@ void main() {
},
// Missing ID.
<String, dynamic>{
'type': 'FlutterView',
},
<String, dynamic>{'type': 'FlutterView'},
],
};
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
fakeService.flutterListViews =
vms.Response.parse(flutterViewCannedResponseMissingId);
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponseMissingId);
return Future<vms.VmService>(() => fakeService);
}
fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://whatever.com/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws'));
expect(vm, isNot(null));
Future<void> failingFunction() async {
await vm.getAllFlutterViews();
@@ -237,29 +209,24 @@ void main() {
})!,
];
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
fakeService.vm = FakeVM(isolates: isolates);
return Future<vms.VmService>(() => fakeService);
}
fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://whatever.com/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws'));
expect(vm, isNot(null));
final List<IsolateRef> matchingFlutterIsolates =
await vm.getMainIsolatesByPattern('flutterBinary.cm');
final List<IsolateRef> matchingFlutterIsolates = await vm.getMainIsolatesByPattern(
'flutterBinary.cm',
);
expect(matchingFlutterIsolates.length, 1);
final List<IsolateRef> allIsolates =
await vm.getMainIsolatesByPattern('');
final List<IsolateRef> allIsolates = await vm.getMainIsolatesByPattern('');
expect(allIsolates.length, 4);
});
test('invalid flutter view missing ID', () async {
final Map<String, dynamic> flutterViewCannedResponseMissingIsolateName =
<String, dynamic>{
final Map<String, dynamic> flutterViewCannedResponseMissingIsolateName = <String, dynamic>{
'views': <Map<String, dynamic>>[
// Missing isolate name.
<String, dynamic>{
@@ -275,18 +242,15 @@ void main() {
],
};
Future<vms.VmService> fakeVmConnectionFunction(
Uri uri, {
Duration? timeout,
}) {
fakeService.flutterListViews =
vms.Response.parse(flutterViewCannedResponseMissingIsolateName);
Future<vms.VmService> fakeVmConnectionFunction(Uri uri, {Duration? timeout}) {
fakeService.flutterListViews = vms.Response.parse(
flutterViewCannedResponseMissingIsolateName,
);
return Future<vms.VmService>(() => fakeService);
}
fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction;
final DartVm vm =
await DartVm.connect(Uri.parse('http://whatever.com/ws'));
final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws'));
expect(vm, isNot(null));
Future<void> failingFunction() async {
await vm.getAllFlutterViews();
@@ -312,8 +276,11 @@ class FakeVmService extends Fake implements vms.VmService {
}
@override
Future<vms.Response> callMethod(String method,
{String? isolateId, Map<String, dynamic>? args}) async {
Future<vms.Response> callMethod(
String method, {
String? isolateId,
Map<String, dynamic>? args,
}) async {
if (method == '_flutter.listViews') {
return flutterListViews!;
}
@@ -325,9 +292,7 @@ class FakeVmService extends Fake implements vms.VmService {
}
class FakeVM extends Fake implements vms.VM {
FakeVM({
this.isolates = const <vms.IsolateRef>[],
});
FakeVM({this.isolates = const <vms.IsolateRef>[]});
@override
List<vms.IsolateRef>? isolates;

View File

@@ -24,8 +24,9 @@ void main() {
test('throws exception from injection constructor with invalid addr', () async {
SshCommandRunner newCommandRunner() {
return SshCommandRunner.withProcessManager(
const LocalProcessManager(),
address: '192.168.1.1.1');
const LocalProcessManager(),
address: '192.168.1.1.1',
);
}
expect(newCommandRunner, throwsArgumentError);
@@ -50,16 +51,13 @@ void main() {
sshConfigPath: '/whatever',
);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
await runner.run('ls /whatever');
expect(fakeProcessManager.runCommands.single, contains('$ipV6Addr%$interface'));
});
test('verify no percentage symbol is added when no ipv6 interface', () async {
const String ipV6Addr = 'fe80::8eae:4cff:fef4:9247';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: ipV6Addr,
);
runner = SshCommandRunner.withProcessManager(fakeProcessManager, address: ipV6Addr);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
expect(fakeProcessManager.runCommands.single, contains(ipV6Addr));
@@ -67,25 +65,19 @@ void main() {
test('verify commands are split into multiple lines', () async {
const String addr = '192.168.1.1';
runner = SshCommandRunner.withProcessManager(fakeProcessManager,
address: addr);
fakeProcessManager.fakeResult = ProcessResult(
23,
0,
'''
runner = SshCommandRunner.withProcessManager(fakeProcessManager, address: addr);
fakeProcessManager.fakeResult = ProcessResult(23, 0, '''
this
has
four
lines''',
null);
lines''', null);
final List<String> result = await runner.run('oihaw');
expect(result, hasLength(4));
});
test('verify exception on nonzero process result exit code', () async {
const String addr = '192.168.1.1';
runner = SshCommandRunner.withProcessManager(fakeProcessManager,
address: addr);
runner = SshCommandRunner.withProcessManager(fakeProcessManager, address: addr);
fakeProcessManager.fakeResult = ProcessResult(23, 1, 'whatever', null);
Future<void> failingFunction() async {
await runner.run('oihaw');
@@ -113,10 +105,7 @@ void main() {
test('verify config is excluded correctly', () async {
const String addr = 'fe80::8eae:4cff:fef4:9247';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: addr,
);
runner = SshCommandRunner.withProcessManager(fakeProcessManager, address: addr);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
final List<String?> passedCommand = fakeProcessManager.runCommands.single as List<String?>;
@@ -132,7 +121,8 @@ class FakeProcessManager extends Fake implements ProcessManager {
List<List<dynamic>> runCommands = <List<dynamic>>[];
@override
Future<ProcessResult> run(List<dynamic> command, {
Future<ProcessResult> run(
List<dynamic> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,