Files
Letterboxd-Unwatched-Generator/LetterBoxdUnwatchedGenerator/CommandLineSplit.cs
Arne Moerman ea58deab8c initial commit
2024-12-15 19:04:29 +01:00

92 lines
2.9 KiB
C#

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<string> 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<string> 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<string> Split(this string str, Func<char, bool> 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<string> arguments, char joinChar = ' ')
{
return string.Join(joinChar, arguments.Select(a => a.Contains(joinChar) ? $"\"{a}\"" : a));
}
}
}