watchForInput method

void watchForInput()

Implementation

void watchForInput() {
  try {
    _inputSubscription ??= io.stdin.listen((event) {
      var key = utf8.decode(event).toLowerCase();
      if (key.isEmpty && event.length == 1) {
        key = '${event[0]}';
      }
      logger.detail('key: $key');

      final _ = switch (key) {
        'r' || 'R' => _reload().ignore(),
        'c' || 'C' => _cleanConsole(),
        'q' || 'Q' => stop().ignore(),
        _ => null,
      };
    });
  } catch (e) {
    logger
      ..err('Failed to connect to stdin, cannot watch for input')
      ..detail('$e');
    return;
  }

  logger.detail('Watching for kill signal');

  var attemptsToKill = 0;
  final stream = Platform.isWindows
      ? ProcessSignal.sigint.watch()
      : StreamGroup.merge([
          ProcessSignal.sigterm.watch(),
          ProcessSignal.sigint.watch(),
        ]);

  _killSubscription ??= stream.listen((event) {
    logger.detail('Received SIGINT');
    if (attemptsToKill > 0) {
      exit(1);
    } else if (attemptsToKill == 0) {
      stop().ignore();
    }

    attemptsToKill++;
  });
}