runWithResult function

Future<ProcessResult> runWithResult(
  1. String cmd,
  2. List<String> args, {
  3. bool silent = false,
})

Runs a cmd with args and returns the ProcessResult.

Capture stdout/stderr and prints them to the console unless silent is true. Throws an Exception if the exit code is non-zero.

Implementation

Future<ProcessResult> runWithResult(
  String cmd,
  List<String> args, {
  bool silent = false,
}) async {
  if (!silent) print('šŸ‘‰ Running: $cmd ${args.join(" ")}\n');

  final env = getInjectedEnvironment();

  try {
    final result = await Process.run(
      cmd,
      args,
      runInShell: true,
      environment: env,
    );

    if (!silent) {
      /// āœ… STDOUT
      if (result.stdout.toString().isNotEmpty) {
        stdout.write(result.stdout);
      }

      /// āŒ STDERR
      if (result.stderr.toString().isNotEmpty) {
        stderr.write(result.stderr);
      }
    }

    /// āŒ Exit Code Check
    if (result.exitCode != 0) {
      final errorMsg = '$cmd failed with exit code ${result.exitCode}';
      if (!silent) print('\nāŒ $errorMsg');
      throw Exception(errorMsg);
    }

    if (!silent) print('\nāœ… $cmd completed\n');
    return result;
  } catch (e) {
    if (!silent) print('\nāŒ Error while running $cmd: $e');
    rethrow;
  }
}