ensureStarted method

Future<void> ensureStarted({
  1. void onPhase(
    1. String phase
    )?,
  2. Duration timeout = const Duration(seconds: 180),
})

Reuses a runner already answering from these same sources, else builds (once per Xcode) and starts one; onPhase names each slow step.

Implementation

Future<void> ensureStarted(
    {void Function(String phase)? onPhase, Duration timeout = const Duration(seconds: 180)}) async {
  final running = await _statusOwn() ?? await _clearStuckHost();
  if (_isCurrent(running)) {
    _dead = false;
    _suspect = false;
    return;
  }
  if (running != null) await _retire();
  final xctestrun = await build(onPhase: onPhase);
  onPhase?.call('starting the XCTest runner on $udid');
  Directory(cacheDir).createSync(recursive: true);
  final log = File('$cacheDir/runner-$udid.log').openWrite();
  final process = await startHelper(
      runnerPurpose,
      'xcodebuild',
      [
        'test-without-building',
        '-xctestrun',
        xctestrun,
        '-destination',
        'platform=iOS Simulator,id=$udid',
        '-only-testing:GlintRunnerUITests/RunnerTests/testServe',
      ],
      device: udid,
      owner: 'sim:$udid',
      life: HelperLife.attachment,
      environment: {
        'TEST_RUNNER_GLINT_RUNNER_PORT': '$port',
        'TEST_RUNNER_GLINT_RUNNER_PARENT_PID': '$pid',
        'TEST_RUNNER_GLINT_RUNNER_STAMP': identity,
      });
  CallProgress.release(process);
  _process = process;
  process.stdout.listen(log.add);
  process.stderr.listen(log.add);
  var exited = false;
  unawaited(process.exitCode.then((_) {
    exited = true;
    log.close().ignore();
  }));
  final deadline = DateTime.now().add(timeout);
  while (DateTime.now().isBefore(deadline)) {
    if (await isCurrent()) {
      _dead = false;
      _suspect = false;
      _generation++;
      return;
    }
    if (exited) break;
    await Future<void>.delayed(const Duration(seconds: 1));
  }
  await stop();
  throw XcTestRunnerError(
    exited
        ? 'the XCTest runner exited before it answered'
        : 'the XCTest runner did not answer within ${timeout.inSeconds}s',
    detail: 'log: $cacheDir/runner-$udid.log',
    nextSteps: const ['read the runner log for the xcodebuild error', 'or attach again with iosBackend:bridge'],
  );
}