detectRootPackageForVmService static method

  1. @visibleForTesting
Future<DetectRootPackageResponse> detectRootPackageForVmService({
  1. required String vmServiceUriAsString,
  2. required Uri vmServiceUri,
  3. required bool connected,
  4. required ServerApi api,
  5. required DartToolingDaemon dtd,
})

Implementation

@visibleForTesting
static Future<DetectRootPackageResponse> detectRootPackageForVmService({
  required String vmServiceUriAsString,
  required Uri vmServiceUri,
  required bool connected,
  required ServerApi api,
  required DartToolingDaemon dtd,
}) async {
  final Uri rootPackageUri;
  if (connected) {
    // TODO(kenz): should we first try to lookup the root from
    // [_packageRootsForVmServiceConnections]? Could the root library of the
    // main isolate change during the lifetime of a VM service instance?

    VmService? vmService;
    try {
      vmService = await connect<VmService>(
        uri: vmServiceUri,
        finishedCompleter: Completer<void>(),
        serviceFactory: VmService.defaultFactory,
      );

      final root = await vmService.rootPackageDirectoryForMainIsolate(dtd);
      if (root == null) {
        return (
          success: false,
          message: 'No root library found for main isolate '
              '($vmServiceUriAsString).',
          uri: null,
        );
      }
      rootPackageUri = Uri.parse(root);
      _packageRootsForVmServiceConnections[vmServiceUriAsString] =
          rootPackageUri;
    } catch (e) {
      return (
        success: false,
        message: 'Error detecting project roots ($vmServiceUriAsString)\n$e',
        uri: null,
      );
    } finally {
      await vmService?.dispose();
      vmService = null;
    }
  } else {
    final cachedRootForVmService =
        _packageRootsForVmServiceConnections[vmServiceUriAsString];
    if (cachedRootForVmService == null) {
      // If there is no root to remove, there is nothing for us to do.
      return (success: true, message: null, uri: null);
    }
    rootPackageUri = cachedRootForVmService;
  }
  return (success: true, message: null, uri: rootPackageUri);
}