runAsync function

Future<String> runAsync(
  1. String executable, {
  2. List<String> arguments = const [],
  3. RunOptions? runOptions,
  4. bool quiet = false,
  5. String? workingDirectory,
})

Asynchronously run an executable.

If quiet is false, logs the stdout as line breaks are encountered. The stderr is always logged.

Returns a future for the stdout.

All other optional parameters are forwarded to Process.start.

Implementation

Future<String> runAsync(String executable,
    {List<String> arguments = const [],
    RunOptions? runOptions,
    bool quiet = false,
    String? workingDirectory}) async {
  runOptions = mergeWorkingDirectory(workingDirectory, runOptions);
  if (!quiet) log("$executable ${arguments.join(' ')}");
  final stdout = <int>[], stderr = <int>[];

  var process = await Process.start(executable, arguments,
      workingDirectory: runOptions.workingDirectory,
      environment: runOptions.environment,
      includeParentEnvironment: runOptions.includeParentEnvironment,
      runInShell: runOptions.runInShell);
  // Handle stdout.
  var broadcastStdout = process.stdout.asBroadcastStream();
  var stdoutLines = toLineStream(broadcastStdout, runOptions.stdoutEncoding);
  broadcastStdout.listen((List<int> data) => stdout.addAll(data));
  if (!quiet) {
    stdoutLines.listen(logStdout);
  }

  // Handle stderr.
  var broadcastStderr = process.stderr.asBroadcastStream();
  var stderrLines = toLineStream(broadcastStderr, runOptions.stderrEncoding);
  broadcastStderr.listen((List<int> data) => stderr.addAll(data));
  stderrLines.listen(logStderr);

  var encoding = runOptions.stdoutEncoding;
  var code = await process.exitCode;
  var stdoutString = encoding.decode(stdout);

  if (code != 0) {
    throw ProcessException._(
        executable, code, stdoutString, encoding.decode(stderr));
  }

  return stdoutString;
}