io.dart 15.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// This file serves as the single point of entry into the `dart:io` APIs
/// within Flutter tools.
///
/// In order to make Flutter tools more testable, we use the `FileSystem` APIs
/// in `package:file` rather than using the `dart:io` file APIs directly (see
/// `file_system.dart`). Doing so allows us to swap out local file system
/// access with mockable (or in-memory) file systems, making our tests hermetic
/// vis-a-vis file system access.
///
14 15 16
/// We also use `package:platform` to provide an abstraction away from the
/// static methods in the `dart:io` `Platform` class (see `platform.dart`). As
/// such, do not export Platform from this file!
17
///
18 19 20 21 22 23 24 25 26 27
/// To ensure that all file system and platform API access within Flutter tools
/// goes through the proper APIs, we forbid direct imports of `dart:io` (via a
/// test), forcing all callers to instead import this file, which exports the
/// blessed subset of `dart:io` that is legal to use in Flutter tools.
///
/// Because of the nature of this file, it is important that **platform and file
/// APIs not be exported from `dart:io` in this file**! Moreover, be careful
/// about any additional exports that you add to this file, as doing so will
/// increase the API surface that we have to test in Flutter tools, and the APIs
/// in `dart:io` can sometimes be hard to use in tests.
28
library;
29 30 31 32 33 34

// We allow `print()` in this file as a fallback for writing to the terminal via
// regular stdout/stderr/stdio paths. Everything else in the flutter_tools
// library should route terminal I/O through the [Stdio] class defined below.
// ignore_for_file: avoid_print

35
import 'dart:async';
36 37
import 'dart:io' as io
  show
38
    IOSink,
39 40 41 42 43 44 45 46 47
    InternetAddress,
    InternetAddressType,
    NetworkInterface,
    Process,
    ProcessInfo,
    ProcessSignal,
    Stdin,
    StdinException,
    Stdout,
48
    StdoutException,
49 50 51 52
    exit,
    pid,
    stderr,
    stdin,
53
    stdout;
54

55
import 'package:file/file.dart';
56
import 'package:meta/meta.dart';
57

58
import 'async_guard.dart';
59
import 'platform.dart';
60 61
import 'process.dart';

62 63 64
export 'dart:io'
    show
        BytesBuilder,
65
        CompressionOptions,
66 67 68
        // Directory,         NO! Use `file_system.dart`
        // File,              NO! Use `file_system.dart`
        // FileSystemEntity,  NO! Use `file_system.dart`
69
        GZipCodec,
70
        HandshakeException,
71 72 73
        HttpClient,
        HttpClientRequest,
        HttpClientResponse,
74
        HttpClientResponseCompressionState,
75
        HttpException,
76 77
        HttpHeaders,
        HttpRequest,
78
        HttpResponse,
79 80
        HttpServer,
        HttpStatus,
81 82
        IOException,
        IOSink,
83 84
        InternetAddress,
        InternetAddressType,
85
        // Link              NO! Use `file_system.dart`
86
        // NetworkInterface  NO! Use `io.dart`
87
        OSError,
88
        // Platform          NO! use `platform.dart`
89 90
        Process,
        ProcessException,
91
        // ProcessInfo,      NO! use `io.dart`
92
        ProcessResult,
93
        // ProcessSignal     NO! Use [ProcessSignal] below.
94
        ProcessStartMode,
95
        // RandomAccessFile  NO! Use `file_system.dart`
96
        SecurityContext,
97
        ServerSocket,
98
        SignalException,
99 100
        Socket,
        SocketException,
101
        Stdin,
102
        StdinException,
103
        Stdout,
104
        WebSocket,
105
        WebSocketException,
106
        WebSocketTransformer,
107 108 109 110 111 112 113 114
        ZLibEncoder,
        exitCode,
        gzip,
        pid,
        // stderr,           NO! Use `io.dart`
        // stdin,            NO! Use `io.dart`
        // stdout,           NO! Use `io.dart`
        systemEncoding;
115 116

/// Exits the process with the given [exitCode].
117
typedef ExitFunction = void Function(int exitCode);
118

119
const ExitFunction _defaultExitFunction = io.exit;
120 121 122 123 124

ExitFunction _exitFunction = _defaultExitFunction;

/// Exits the process.
///
125 126 127 128
/// Throws [AssertionError] if assertions are enabled and the dart:io exit
/// is still active when called. This may indicate exit was called in
/// a test without being configured correctly.
///
129 130 131 132 133
/// This is analogous to the `exit` function in `dart:io`, except that this
/// function may be set to a testing-friendly value by calling
/// [setExitFunctionForTests] (and then restored to its default implementation
/// with [restoreExitFunction]). The default implementation delegates to
/// `dart:io`.
134 135 136 137 138 139 140 141 142 143
ExitFunction get exit {
  assert(
    _exitFunction != io.exit || !_inUnitTest(),
    'io.exit was called with assertions active in a unit test',
  );
  return _exitFunction;
}

// Whether the tool is executing in a unit test.
bool _inUnitTest() {
144
  return Zone.current[#test.declarer] != null;
145
}
146 147 148 149

/// Sets the [exit] function to a function that throws an exception rather
/// than exiting the process; this is intended for testing purposes.
@visibleForTesting
150
void setExitFunctionForTests([ ExitFunction? exitFunction ]) {
151
  _exitFunction = exitFunction ?? (int exitCode) {
152
    throw ProcessExit(exitCode, immediate: true);
153 154 155 156 157 158 159 160
  };
}

/// Restores the [exit] function to the `dart:io` implementation.
@visibleForTesting
void restoreExitFunction() {
  _exitFunction = _defaultExitFunction;
}
161 162 163 164 165 166

/// A portable version of [io.ProcessSignal].
///
/// Listening on signals that don't exist on the current platform is just a
/// no-op. This is in contrast to [io.ProcessSignal], where listening to
/// non-existent signals throws an exception.
167 168 169 170 171 172
///
/// This class does NOT implement io.ProcessSignal, because that class uses
/// private fields. This means it cannot be used with, e.g., [Process.killPid].
/// Alternative implementations of the relevant methods that take
/// [ProcessSignal] instances are available on this class (e.g. "send").
class ProcessSignal {
173
  @visibleForTesting
174 175
  const ProcessSignal(this._delegate, {@visibleForTesting Platform platform = const LocalPlatform()})
    : _platform = platform;
176

177 178 179 180 181 182
  static const ProcessSignal sigwinch = PosixProcessSignal(io.ProcessSignal.sigwinch);
  static const ProcessSignal sigterm = PosixProcessSignal(io.ProcessSignal.sigterm);
  static const ProcessSignal sigusr1 = PosixProcessSignal(io.ProcessSignal.sigusr1);
  static const ProcessSignal sigusr2 = PosixProcessSignal(io.ProcessSignal.sigusr2);
  static const ProcessSignal sigint = ProcessSignal(io.ProcessSignal.sigint);
  static const ProcessSignal sigkill = ProcessSignal(io.ProcessSignal.sigkill);
183 184

  final io.ProcessSignal _delegate;
185
  final Platform _platform;
186 187

  Stream<ProcessSignal> watch() {
188
    return _delegate.watch().map<ProcessSignal>((io.ProcessSignal signal) => this);
189 190
  }

191 192 193 194
  /// Sends the signal to the given process (identified by pid).
  ///
  /// Returns true if the signal was delivered, false otherwise.
  ///
195 196
  /// On Windows, this can only be used with [sigterm], which terminates the
  /// process.
197
  ///
198 199 200
  /// This is implemented by sending the signal using [io.Process.killPid] and
  /// therefore cannot be faked in tests. To fake sending signals in tests, use
  /// [kill] instead.
201
  bool send(int pid) {
202
    assert(!_platform.isWindows || this == ProcessSignal.sigterm);
203 204 205
    return io.Process.killPid(pid, _delegate);
  }

206 207 208 209 210 211 212 213 214 215
  /// A more testable variant of [send].
  ///
  /// Sends this signal to the given `process` by invoking [io.Process.kill].
  ///
  /// In tests this method can be faked by passing a fake implementation of the
  /// [io.Process] interface.
  bool kill(io.Process process) {
    return process.kill(_delegate);
  }

216 217 218 219 220 221 222
  @override
  String toString() => _delegate.toString();
}

/// A [ProcessSignal] that is only available on Posix platforms.
///
/// Listening to a [_PosixProcessSignal] is a no-op on Windows.
223 224
@visibleForTesting
class PosixProcessSignal extends ProcessSignal {
225

226
  const PosixProcessSignal(super.wrappedSignal, {@visibleForTesting super.platform});
227 228 229

  @override
  Stream<ProcessSignal> watch() {
230 231
    // This uses the real platform since it invokes dart:io functionality directly.
    if (_platform.isWindows) {
232
      return const Stream<ProcessSignal>.empty();
233
    }
234 235 236
    return super.watch();
  }
}
237

238 239
/// A class that wraps stdout, stderr, and stdin, and exposes the allowed
/// operations.
240 241 242 243 244 245 246
///
/// In particular, there are three ways that writing to stdout and stderr
/// can fail. A call to stdout.write() can fail:
///   * by throwing a regular synchronous exception,
///   * by throwing an exception asynchronously, and
///   * by completing the Future stdout.done with an error.
///
Lioness100's avatar
Lioness100 committed
247
/// This class encapsulates all three so that we don't have to worry about it
248
/// anywhere else.
249
class Stdio {
250 251 252 253 254 255
  Stdio();

  /// Tests can provide overrides to use instead of the stdout and stderr from
  /// dart:io.
  @visibleForTesting
  Stdio.test({
256 257
    required io.Stdout stdout,
    required io.IOSink stderr,
258 259
  }) : _stdoutOverride = stdout, _stderrOverride = stderr;

260 261
  io.Stdout? _stdoutOverride;
  io.IOSink? _stderrOverride;
262 263 264 265 266 267

  // These flags exist to remember when the done Futures on stdout and stderr
  // complete to avoid trying to write to a closed stream sink, which would
  // generate a [StateError].
  bool _stdoutDone = false;
  bool _stderrDone = false;
268 269

  Stream<List<int>> get stdin => io.stdin;
270

271 272
  io.Stdout get stdout {
    if (_stdout != null) {
273
      return _stdout!;
274 275
    }
    _stdout = _stdoutOverride ?? io.stdout;
276
    _stdout!.done.then(
277 278 279
      (void _) { _stdoutDone = true; },
      onError: (Object err, StackTrace st) { _stdoutDone = true; },
    );
280
    return _stdout!;
281
  }
282
  io.Stdout? _stdout;
283

284 285
  io.IOSink get stderr {
    if (_stderr != null) {
286
      return _stderr!;
287 288
    }
    _stderr = _stderrOverride ?? io.stderr;
289
    _stderr!.done.then(
290 291 292
      (void _) { _stderrDone = true; },
      onError: (Object err, StackTrace st) { _stderrDone = true; },
    );
293
    return _stderr!;
294
  }
295
  io.IOSink? _stderr;
296 297

  bool get hasTerminal => io.stdout.hasTerminal;
298

299
  static bool? _stdinHasTerminal;
300 301 302 303 304 305 306 307 308

  /// Determines whether there is a terminal attached.
  ///
  /// [io.Stdin.hasTerminal] only covers a subset of cases. In this check the
  /// echoMode is toggled on and off to catch cases where the tool running in
  /// a docker container thinks there is an attached terminal. This can cause
  /// runtime errors such as "inappropriate ioctl for device" if not handled.
  bool get stdinHasTerminal {
    if (_stdinHasTerminal != null) {
309
      return _stdinHasTerminal!;
310 311 312 313
    }
    if (stdin is! io.Stdin) {
      return _stdinHasTerminal = false;
    }
314
    final io.Stdin ioStdin = stdin as io.Stdin;
315 316 317 318 319 320 321 322 323 324 325 326 327
    if (!ioStdin.hasTerminal) {
      return _stdinHasTerminal = false;
    }
    try {
      final bool currentEchoMode = ioStdin.echoMode;
      ioStdin.echoMode = !currentEchoMode;
      ioStdin.echoMode = currentEchoMode;
    } on io.StdinException {
      return _stdinHasTerminal = false;
    }
    return _stdinHasTerminal = true;
  }

328 329
  int? get terminalColumns => hasTerminal ? stdout.terminalColumns : null;
  int? get terminalLines => hasTerminal ? stdout.terminalLines : null;
330
  bool get supportsAnsiEscapes => hasTerminal && stdout.supportsAnsiEscapes;
331

332 333 334 335
  /// Writes [message] to [stderr], falling back on [fallback] if the write
  /// throws any exception. The default fallback calls [print] on [message].
  void stderrWrite(
    String message, {
336
    void Function(String, dynamic, StackTrace)? fallback,
337 338 339 340 341 342 343 344 345 346 347
  }) {
    if (!_stderrDone) {
      _stdioWrite(stderr, message, fallback: fallback);
      return;
    }
    fallback == null ? print(message) : fallback(
      message,
      const io.StdoutException('stderr is done'),
      StackTrace.current,
    );
  }
348 349 350 351 352

  /// Writes [message] to [stdout], falling back on [fallback] if the write
  /// throws any exception. The default fallback calls [print] on [message].
  void stdoutWrite(
    String message, {
353
    void Function(String, dynamic, StackTrace)? fallback,
354 355 356 357 358 359 360 361 362 363 364
  }) {
    if (!_stdoutDone) {
      _stdioWrite(stdout, message, fallback: fallback);
      return;
    }
    fallback == null ? print(message) : fallback(
      message,
      const io.StdoutException('stdout is done'),
      StackTrace.current,
    );
  }
365

366
  // Helper for [stderrWrite] and [stdoutWrite].
367
  void _stdioWrite(io.IOSink sink, String message, {
368
    void Function(String, dynamic, StackTrace)? fallback,
369
  }) {
370
    asyncGuard<void>(() async {
371
      sink.write(message);
372
    }, onError: (Object error, StackTrace stackTrace) {
373 374 375
      if (fallback == null) {
        print(message);
      } else {
376
        fallback(message, error, stackTrace);
377
      }
378
    });
379
  }
380 381 382 383

  /// Adds [stream] to [stdout].
  Future<void> addStdoutStream(Stream<List<int>> stream) => stdout.addStream(stream);

384
  /// Adds [stream] to [stderr].
385
  Future<void> addStderrStream(Stream<List<int>> stream) => stderr.addStream(stream);
386 387
}

388 389
/// An overridable version of io.ProcessInfo.
abstract class ProcessInfo {
390
  factory ProcessInfo(FileSystem fs) => _DefaultProcessInfo(fs);
391

392
  factory ProcessInfo.test(FileSystem fs) => _TestProcessInfo(fs);
393 394 395 396

  int get currentRss;

  int get maxRss;
397 398

  File writePidFile(String pidFile);
399 400 401 402
}

/// The default implementation of [ProcessInfo], which uses [io.ProcessInfo].
class _DefaultProcessInfo implements ProcessInfo {
403 404 405 406
  _DefaultProcessInfo(this._fileSystem);

  final FileSystem _fileSystem;

407 408 409 410 411
  @override
  int get currentRss => io.ProcessInfo.currentRss;

  @override
  int get maxRss => io.ProcessInfo.maxRss;
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

  @override
  File writePidFile(String pidFile) {
    return _fileSystem.file(pidFile)
      ..writeAsStringSync(io.pid.toString());
  }
}

/// The test version of [ProcessInfo].
class _TestProcessInfo implements ProcessInfo {
  _TestProcessInfo(this._fileSystem);

  final FileSystem _fileSystem;

  @override
  int currentRss = 1000;

  @override
  int maxRss = 2000;

  @override
  File writePidFile(String pidFile) {
    return _fileSystem.file(pidFile)
      ..writeAsStringSync('12345');
  }
437
}
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

/// The return type for [listNetworkInterfaces].
class NetworkInterface implements io.NetworkInterface {
  NetworkInterface(this._delegate);

  final io.NetworkInterface _delegate;

  @override
  List<io.InternetAddress> get addresses => _delegate.addresses;

  @override
  int get index => _delegate.index;

  @override
  String get name => _delegate.name;

  @override
  String toString() => "NetworkInterface('$name', $addresses)";
}

typedef NetworkInterfaceLister = Future<List<NetworkInterface>> Function({
  bool includeLoopback,
  bool includeLinkLocal,
  io.InternetAddressType type,
});

464
NetworkInterfaceLister? _networkInterfaceListerOverride;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

// Tests can set up a non-default network interface lister.
@visibleForTesting
void setNetworkInterfaceLister(NetworkInterfaceLister lister) {
  _networkInterfaceListerOverride = lister;
}

@visibleForTesting
void resetNetworkInterfaceLister() {
  _networkInterfaceListerOverride = null;
}

/// This calls [NetworkInterface.list] from `dart:io` unless it is overridden by
/// [setNetworkInterfaceLister] for a test. If it is overridden for a test,
/// it should be reset with [resetNetworkInterfaceLister].
Future<List<NetworkInterface>> listNetworkInterfaces({
  bool includeLoopback = false,
  bool includeLinkLocal = false,
  io.InternetAddressType type = io.InternetAddressType.any,
}) async {
  if (_networkInterfaceListerOverride != null) {
486
    return _networkInterfaceListerOverride!.call(
487 488 489 490 491 492 493 494 495 496 497 498 499 500
      includeLoopback: includeLoopback,
      includeLinkLocal: includeLinkLocal,
      type: type,
    );
  }
  final List<io.NetworkInterface> interfaces = await io.NetworkInterface.list(
    includeLoopback: includeLoopback,
    includeLinkLocal: includeLinkLocal,
    type: type,
  );
  return interfaces.map(
    (io.NetworkInterface interface) => NetworkInterface(interface),
  ).toList();
}