io.dart 14.9 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
import 'dart:async';
29 30 31 32 33 34 35
import 'dart:io' as io
  show
    exit,
    InternetAddress,
    InternetAddressType,
    IOSink,
    NetworkInterface,
36
    pid,
37 38 39 40 41 42 43 44
    Process,
    ProcessInfo,
    ProcessSignal,
    stderr,
    stdin,
    Stdin,
    StdinException,
    Stdout,
45
    StdoutException,
46
    stdout;
47

48
import 'package:file/file.dart';
49
import 'package:meta/meta.dart';
50

51
import 'async_guard.dart';
52
import 'platform.dart';
53 54
import 'process.dart';

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

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

111
const ExitFunction _defaultExitFunction = io.exit;
112 113 114 115 116

ExitFunction _exitFunction = _defaultExitFunction;

/// Exits the process.
///
117 118 119 120
/// 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.
///
121 122 123 124 125
/// 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`.
126 127 128 129 130 131 132 133 134 135
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() {
136
  return Zone.current[#test.declarer] != null;
137
}
138 139 140 141

/// Sets the [exit] function to a function that throws an exception rather
/// than exiting the process; this is intended for testing purposes.
@visibleForTesting
142
void setExitFunctionForTests([ ExitFunction? exitFunction ]) {
143
  _exitFunction = exitFunction ?? (int exitCode) {
144
    throw ProcessExit(exitCode, immediate: true);
145 146 147 148 149 150 151 152
  };
}

/// Restores the [exit] function to the `dart:io` implementation.
@visibleForTesting
void restoreExitFunction() {
  _exitFunction = _defaultExitFunction;
}
153 154 155 156 157 158

/// 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.
159 160 161 162 163 164
///
/// 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 {
165
  @visibleForTesting
166 167
  const ProcessSignal(this._delegate, {@visibleForTesting Platform platform = const LocalPlatform()})
    : _platform = platform;
168

169 170 171 172 173 174
  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);
175 176

  final io.ProcessSignal _delegate;
177
  final Platform _platform;
178 179

  Stream<ProcessSignal> watch() {
180
    return _delegate.watch().map<ProcessSignal>((io.ProcessSignal signal) => this);
181 182
  }

183 184 185 186
  /// Sends the signal to the given process (identified by pid).
  ///
  /// Returns true if the signal was delivered, false otherwise.
  ///
187
  /// On Windows, this can only be used with [ProcessSignal.sigterm], which
188 189 190 191
  /// terminates the process.
  ///
  /// This is implemented by sending the signal using [Process.killPid].
  bool send(int pid) {
192
    assert(!_platform.isWindows || this == ProcessSignal.sigterm);
193 194 195
    return io.Process.killPid(pid, _delegate);
  }

196 197 198 199 200 201 202
  @override
  String toString() => _delegate.toString();
}

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

206 207
  const PosixProcessSignal(io.ProcessSignal wrappedSignal, {@visibleForTesting Platform platform = const LocalPlatform()})
    : super(wrappedSignal, platform: platform);
208 209 210

  @override
  Stream<ProcessSignal> watch() {
211 212
    // This uses the real platform since it invokes dart:io functionality directly.
    if (_platform.isWindows) {
213
      return const Stream<ProcessSignal>.empty();
214
    }
215 216 217
    return super.watch();
  }
}
218

219 220
/// A class that wraps stdout, stderr, and stdin, and exposes the allowed
/// operations.
221 222 223 224 225 226 227 228 229
///
/// 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.
///
/// This class enapsulates all three so that we don't have to worry about it
/// anywhere else.
230
class Stdio {
231 232 233 234 235 236
  Stdio();

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

241 242
  io.Stdout? _stdoutOverride;
  io.IOSink? _stderrOverride;
243 244 245 246 247 248

  // 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;
249 250

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

252 253
  io.Stdout get stdout {
    if (_stdout != null) {
254
      return _stdout!;
255 256
    }
    _stdout = _stdoutOverride ?? io.stdout;
257
    _stdout!.done.then(
258 259 260
      (void _) { _stdoutDone = true; },
      onError: (Object err, StackTrace st) { _stdoutDone = true; },
    );
261
    return _stdout!;
262
  }
263
  io.Stdout? _stdout;
264 265

  @visibleForTesting
266 267
  io.IOSink get stderr {
    if (_stderr != null) {
268
      return _stderr!;
269 270
    }
    _stderr = _stderrOverride ?? io.stderr;
271
    _stderr!.done.then(
272 273 274
      (void _) { _stderrDone = true; },
      onError: (Object err, StackTrace st) { _stderrDone = true; },
    );
275
    return _stderr!;
276
  }
277
  io.IOSink? _stderr;
278 279

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

281
  static bool? _stdinHasTerminal;
282 283 284 285 286 287 288 289 290

  /// 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) {
291
      return _stdinHasTerminal!;
292 293 294 295
    }
    if (stdin is! io.Stdin) {
      return _stdinHasTerminal = false;
    }
296
    final io.Stdin ioStdin = stdin as io.Stdin;
297 298 299 300 301 302 303 304 305 306 307 308 309
    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;
  }

310 311
  int? get terminalColumns => hasTerminal ? stdout.terminalColumns : null;
  int? get terminalLines => hasTerminal ? stdout.terminalLines : null;
312
  bool get supportsAnsiEscapes => hasTerminal && stdout.supportsAnsiEscapes;
313

314 315 316 317
  /// 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, {
318
    void Function(String, dynamic, StackTrace)? fallback,
319 320 321 322 323 324 325 326 327 328 329
  }) {
    if (!_stderrDone) {
      _stdioWrite(stderr, message, fallback: fallback);
      return;
    }
    fallback == null ? print(message) : fallback(
      message,
      const io.StdoutException('stderr is done'),
      StackTrace.current,
    );
  }
330 331 332 333 334

  /// 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, {
335
    void Function(String, dynamic, StackTrace)? fallback,
336 337 338 339 340 341 342 343 344 345 346
  }) {
    if (!_stdoutDone) {
      _stdioWrite(stdout, message, fallback: fallback);
      return;
    }
    fallback == null ? print(message) : fallback(
      message,
      const io.StdoutException('stdout is done'),
      StackTrace.current,
    );
  }
347

348
  // Helper for [stderrWrite] and [stdoutWrite].
349
  void _stdioWrite(io.IOSink sink, String message, {
350
    void Function(String, dynamic, StackTrace)? fallback,
351
  }) {
352
    asyncGuard<void>(() async {
353
      sink.write(message);
354
    }, onError: (Object error, StackTrace stackTrace) {
355 356 357
      if (fallback == null) {
        print(message);
      } else {
358
        fallback(message, error, stackTrace);
359
      }
360
    });
361
  }
362 363 364 365

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

366
  /// Adds [stream] to [stderr].
367
  Future<void> addStderrStream(Stream<List<int>> stream) => stderr.addStream(stream);
368 369
}

370 371
/// An overridable version of io.ProcessInfo.
abstract class ProcessInfo {
372
  factory ProcessInfo(FileSystem fs) => _DefaultProcessInfo(fs);
373

374
  factory ProcessInfo.test(FileSystem fs) => _TestProcessInfo(fs);
375 376 377 378

  int get currentRss;

  int get maxRss;
379 380

  File writePidFile(String pidFile);
381 382 383 384
}

/// The default implementation of [ProcessInfo], which uses [io.ProcessInfo].
class _DefaultProcessInfo implements ProcessInfo {
385 386 387 388
  _DefaultProcessInfo(this._fileSystem);

  final FileSystem _fileSystem;

389 390 391 392 393
  @override
  int get currentRss => io.ProcessInfo.currentRss;

  @override
  int get maxRss => io.ProcessInfo.maxRss;
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

  @override
  File writePidFile(String pidFile) {
    assert(pidFile != null);
    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) {
    assert(pidFile != null);
    return _fileSystem.file(pidFile)
      ..writeAsStringSync('12345');
  }
421
}
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

/// 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,
});

448
NetworkInterfaceLister? _networkInterfaceListerOverride;
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

// 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) {
470
    return _networkInterfaceListerOverride!.call(
471 472 473 474 475 476 477 478 479 480 481 482 483 484
      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();
}