using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LetterBoxdUnwatchedGenerator { internal static class CommandLineSplitExt { //public static IEnumerable SplitCommandLine(this string commandLine, char splitChar = ' ') //{ // bool inQuotes = false; // bool isEscaping = false; // StringBuilder currentArg = new StringBuilder(); // foreach (char c in commandLine) // { // if (c == '\\' && !isEscaping) { isEscaping = true; continue; } // if (c == '\"' && !isEscaping) inQuotes = !inQuotes; // isEscaping = false; // if (!inQuotes && (splitChar == ' ' ? Char.IsWhiteSpace(c) : c == splitChar)) // { // if (currentArg.Length > 0) // { // yield return currentArg.ToString(); // currentArg.Clear(); // } // } // else // { // currentArg.Append(c); // } // } // if (currentArg.Length > 0) // { // yield return currentArg.ToString(); // } //} public static IEnumerable SplitCommandLine(this string commandLine, char splitChar = ' ') { bool inQuotes = false; bool isEscaping = false; return commandLine.Split(c => { if (c == '\\' && !isEscaping) { isEscaping = true; return false; } if (c == '\"' && !isEscaping) inQuotes = !inQuotes; isEscaping = false; return !inQuotes && (splitChar == ' ' ? Char.IsWhiteSpace(c) : c == splitChar); //Char.IsWhiteSpace(c)/*c == ' '*/; }).Select(arg => arg.Trim().TrimMatchingQuotes('\"').Replace("\\\"", "\"")); } public static IEnumerable Split(this string str, Func controller) { int nextPiece = 0; for (int c = 0; c < str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } public static string TrimMatchingQuotes(this string input, char quote) { if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote)) return input.Substring(1, input.Length - 2); return input; } public static string JoinCommandLine(this IEnumerable arguments, char joinChar = ' ') { return string.Join(joinChar, arguments.Select(a => a.Contains(joinChar) ? $"\"{a}\"" : a)); } } }