substituteCLIArguments method
Substitutes CLI command arguments in a string with their execution results.
This function finds patterns like %{{COMMAND}} or %{COMMAND} and replaces them
with the output of executing the command.
Parameters:
input- The input string containing command placeholders (can be null)
Returns the string with command placeholders replaced by their execution results. If a command fails, it returns stderr output or empty string on error.
Implementation
Future<String> substituteCLIArguments(String? input) async {
if (input == null) return "";
// Pattern matches %{{COMMAND}} OR %{COMMAND}
final pattern = RegExp(r'\%\{\{([^\}]+)\}\}|\%\{([^\}]+)\}');
// Use replaceAllMapped to handle each match individually and asynchronously
final matches = pattern.allMatches(input).toList();
if (matches.isEmpty) return input;
// Since replaceAllMapped cannot be async, we process matches manually
String result = input;
for (final match in matches.reversed) {
final value = match.group(1) ?? match.group(2) ?? "";
String processResults;
try {
if (value.trim().isEmpty) {
processResults = "";
} else if (value.contains(" ")) {
final args = _parseCommandArguments(value);
final process = await Process.run(args.first, args.sublist(1));
processResults = process.exitCode == 0
? process.stdout.toString().trim()
: process.stderr.toString().trim();
} else {
final process = await Process.run(value, []);
processResults = process.exitCode == 0
? process.stdout.toString().trim()
: process.stderr.toString().trim();
}
} catch (e) {
processResults = "";
}
// Replace only the current match
result = result.replaceRange(match.start, match.end, processResults);
}
return result;
}