executeCommand static method

Future<ProcessResult> executeCommand(
  1. String command, {
  2. Map<String, String>? env,
  3. String? exitCondition,
})

Execute Pipeline stages commands with improved robustness.

Implementation

static Future<ProcessResult> executeCommand(
  String command, {
  Map<String, String>? env,
  String? exitCondition,
}) async {
  if (command.trim().isEmpty) {
    print('⚠️ Error: Command is empty. Skipping execution.');
    return ProcessResult(0, 1, '', 'Command is empty');
  }

  final shellType = Platform.isWindows ? 'powershell' : 'bash';
  final shellFlag = Platform.isWindows ? '-Command' : '-c';

  print('🔧 Executing Command: $command');

  // Start the process
  final process = await Process.start(
    shellType,
    [shellFlag, command],
    environment: env,
    runInShell: true,
  );

  // Store output in memory
  StringBuffer stdoutBuffer = StringBuffer();
  StringBuffer stderrBuffer = StringBuffer();

  // Listen to stdout
  stdout.write('📜 Output:');
  final stdoutSubscription =
      process.stdout.transform(SystemEncoding().decoder).listen((data) {
    stdout.write(data);
    stdoutBuffer.write(data);
  });

  // Listen to stderr
  final stderrSubscription =
      process.stderr.transform(SystemEncoding().decoder).listen((data) {
    stderr.write('⚠️ Error: $data');
    stderrBuffer.write(data);
  });

  // Wait for completion
  final exitCode = await process.exitCode;

  // Cancel subscriptions
  await stdoutSubscription.cancel();
  await stderrSubscription.cancel();

  // Get collected output
  final stdoutData = stdoutBuffer.toString();
  final stderrData = stderrBuffer.toString();

  // Custom exit condition handling
  if (exitCondition != null) {
    final customCondition = RegExp(exitCondition);
    if (customCondition.hasMatch(stdoutData) ||
        customCondition.hasMatch(stderrData)) {
      print("❌ Custom exit condition matched. Stopping the pipeline.");
      return ProcessResult(
          process.pid, 1, stdoutData, 'Custom exit condition matched');
    }
  }

  return ProcessResult(process.pid, exitCode, stdoutData, stderrData);
}