extractBaseCommand function

String extractBaseCommand(
  1. String command
)

Extract the base command (first word) from a shell command string, stripping variable assignments and common wrappers.

Implementation

String extractBaseCommand(String command) {
  var trimmed = command.trim();

  // Strip leading variable assignments (FOO=bar cmd).
  while (RegExp(r'^[A-Za-z_][A-Za-z0-9_]*=\S*\s+').hasMatch(trimmed)) {
    trimmed = trimmed.replaceFirst(
      RegExp(r'^[A-Za-z_][A-Za-z0-9_]*=\S*\s+'),
      '',
    );
  }

  // Strip common wrappers: env, sudo, nohup, nice, time, etc.
  const wrappers = {
    'env',
    'sudo',
    'nohup',
    'nice',
    'time',
    'timeout',
    'strace',
    'ltrace',
    'unbuffer',
    'script',
  };

  var words = trimmed.split(RegExp(r'\s+'));
  while (words.isNotEmpty && wrappers.contains(words.first)) {
    words = words.sublist(1);
    // Skip flags after wrapper commands.
    while (words.isNotEmpty && words.first.startsWith('-')) {
      words = words.sublist(1);
    }
  }

  return words.isNotEmpty ? words.first : '';
}