runStream static method

Future<int> runStream(
  1. String workDir,
  2. String command,
  3. List<String> args, {
  4. void onStdout(
    1. String command,
    2. String output
    )?,
  5. void onStderr(
    1. String command,
    2. String output
    )?,
  6. bool printStd = true,
})

Implementation

static Future<int> runStream(
  String workDir,
  String command,
  List<String> args, {
  void Function(String command, String output)? onStdout,
  void Function(String command, String error)? onStderr,
  bool printStd = true,
}) async {
  final fullCommand = '$command ${args.join(' ')}';

  Process process;
  if (Platform.isWindows) {
    process = await Process.start(
      'cmd',
      ['/c', fullCommand],
      workingDirectory: workDir,
      runInShell: true,
    );
  } else {
    process = await Process.start(
      'bash',
      ['-c', fullCommand],
      workingDirectory: workDir,
      runInShell: true,
    );
  }

  process.stdout
      .transform(SystemEncoding().decoder)
      .transform(const LineSplitter())
      .listen((line) {
        if (printStd) stdout.writeln(line);
        onStdout?.call(command, line);
      });

  process.stderr
      .transform(SystemEncoding().decoder)
      .transform(const LineSplitter())
      .listen((line) {
        if (printStd) stderr.writeln(line);
        onStderr?.call(command, line);
      });

  final exitCode = await process.exitCode;
  if (exitCode != 0) {
    throw CommandException(
      fullCommand,
      'Process exited with code $exitCode',
      exitCode: exitCode,
    );
  }
  return exitCode;
}