execProc function

Future<int> execProc(
  1. Future<Process> process, {
  2. String name = '',
  3. bool isCodeSuccessful(
    1. int
    ) = _onlyZero,
  4. StreamRedirectMode successMode = StreamRedirectMode.none,
  5. StreamRedirectMode errorMode = StreamRedirectMode.stdoutAndStderr,
})

Executes the given process, returning its exit code.

This method is similar to exec, but simpler to use for cases where it is desirable to redirect the process' streams and automatically fail depending on the exit code.

A StreamRedirectMode can be provided to configure whether the process' output should be redirected to the calling process's streams in case of success or failure. Whether the result is a success or a failure is determined by the isCodeSuccessful function (only 0 is success, by default).

This method throws ProcessExitCodeException in case the process' exit code is not considered successful by isCodeSuccessful, or ProcessException in case the process could not be executed at all.

By default, both streams are redirected in case of failure, but none in case of success.

Implementation

Future<int> execProc(Future<Process> process,
    {String name = '',
    bool Function(int) isCodeSuccessful = _onlyZero,
    StreamRedirectMode successMode = StreamRedirectMode.none,
    StreamRedirectMode errorMode = StreamRedirectMode.stdoutAndStderr}) async {
  final allDisabled = successMode == StreamRedirectMode.none &&
      errorMode == StreamRedirectMode.none;
  final stdoutConsumer = StdStreamConsumer(keepLines: !allDisabled);
  final stderrConsumer = StdStreamConsumer(keepLines: !allDisabled);
  final code = await _exec(await process, name, stdoutConsumer, stderrConsumer);
  final success = isCodeSuccessful(code);
  if (allDisabled) {
    if (success) {
      return code;
    } else {
      throw ProcessExitCodeException(
          code, name, stdoutConsumer.lines, stderrConsumer.lines);
    }
  }
  Future<void> redirect(StreamRedirectMode mode) async {
    switch (mode) {
      case StreamRedirectMode.none:
        break;
      case StreamRedirectMode.stderr:
        stderr
          ..writeAll(stderrConsumer.lines, '\n')
          ..writeln();
        break;
      case StreamRedirectMode.stdout:
        stdout
          ..writeAll(stdoutConsumer.lines, '\n')
          ..writeln();
        break;
      case StreamRedirectMode.stdoutAndStderr:
        stdout
          ..writeAll(stdoutConsumer.lines, '\n')
          ..writeln();
        stderr
          ..writeAll(stderrConsumer.lines, '\n')
          ..writeln();
    }
  }

  await redirect(success ? successMode : errorMode);
  if (success) {
    return code;
  }
  throw ProcessExitCodeException(
      code, name, stdoutConsumer.lines, stderrConsumer.lines);
}