generateBuildScriptMethod static method

String generateBuildScriptMethod()

Generates a helper method for building a script with arguments

Implementation

static String generateBuildScriptMethod() {
  return '''
String _buildScriptWithArgs(String baseScript, List<String> args) {
  if (args.isEmpty) return baseScript;

  final lines = baseScript.split('\\n');
  final resultLines = <String>[];

  // Initialize the insert index for the set -- line
  int insertIndex = 0;

  // Skip the shebang line if it exists
  if (lines.isNotEmpty && lines[0].startsWith('#!')) {
    resultLines.add(lines[0]);
    insertIndex = 1;
  }

  // Insert the set -- line after the shebang or at the start
  final escapedArgs = args.map(_escapeShellArg).toList();
  final argsString = escapedArgs.join(' ');
  resultLines.add('set -- \$argsString');

  // Add the rest of the script lines
  resultLines.addAll(lines.skip(insertIndex));

  return resultLines.join('\\n');
}

String _escapeShellArg(String arg) {
  // Escape single quotes by replacing them with '\'' in the argument
  return "'\${arg.replaceAll(\"'\", \"'\\\"'\\\"'\")}'";
}

/// Parses raw parameter string into a list of arguments
List<String> _parseRawParameters(String rawParameters) {
  final args = <String>[];
  final buffer = StringBuffer();
  bool inQuotes = false;
  bool inSingleQuotes = false;
  bool escapeNext = false;

  for (int i = 0; i < rawParameters.length; i++) {
    final char = rawParameters[i];

    if (escapeNext) {
      buffer.write(char);
      escapeNext = false;
      continue;
    }

    switch (char) {
      case '\\\\':
        escapeNext = true;
        break;
      case '"':
        if (!inSingleQuotes) {
          inQuotes = !inQuotes;
        } else {
          buffer.write(char);
        }
        break;
      case "'":
        if (!inQuotes) {
          inSingleQuotes = !inSingleQuotes;
        } else {
          buffer.write(char);
        }
        break;
      case ' ':
      case '\\t':
      case '\\n':
        if (inQuotes || inSingleQuotes) {
          buffer.write(char);
        } else {
          if (buffer.isNotEmpty) {
            args.add(buffer.toString());
            buffer.clear();
          }
        }
        break;
      default:
        buffer.write(char);
        break;
    }
  }

  if (buffer.isNotEmpty) {
    args.add(buffer.toString());
  }

  return args;
}''';
}