You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Use 'CommandLineStringSplitter.Instance.Split' parse bug. #1740
Can you explain a bit more about what you're trying to do and why this output is your expectation? Also, examples using precise strings without the C# escaping would be a little clearer, I think.
For context, the CommandLineStringSplitter is intended to reproduce the way command line input to a .NET console app is split into the args array that gets passed to Main.
Let's use a Program.cs containing this to verify the behavior this is designed to reproduce:
foreach(vararginargs){Console.WriteLine(arg);}
Your raw variable contains the following actual, unescaped string:
Running the above program from the command line in PowerShell (keeping in mind that these examples will differ in other shells) with that string produces this output:
usingSystem.CommandLine;usingSystem.CommandLine.NamingConventionBinder;varrootCommand=newRootCommand("A set command.");rootCommand.Name="SET";rootCommand.AddArgument(newArgument(){Name="key",ValueType=typeof(string),Description="A string"});rootCommand.AddArgument(newArgument(){Name="value",ValueType=typeof(string),Description="A string"});rootCommand.Handler=CommandHandler.Create<SetCommand>(cmd =>{returncmd.InvokeAsync();});while(true){Console.Write("> ");varline=Console.ReadLine();if(line==null||(line=line.Trim()).Length==0)continue;if(line=="exit")break;try{awaitrootCommand.InvokeAsync(line);}catch(Exceptionex){Console.WriteLine(ex);}}classSetCommand{publicstringKey{get;set;}=null!;publicstring?Value{get;set;}=null!;publicTask<int>InvokeAsync(){Console.WriteLine("Key: {0}",this.Key);Console.WriteLine("Value: {0}",this.Value);returnTask.FromResult(0);}}
So, When i call SET text abc, it's work. But, when i want to set a json value, not working.
Input
text abc
say Hello\"
json {\"a\":1}
json "{\"a\":1}"
json {"a":1}
Output
> text abc
Key: text
Value: abc
> say Hello\"
Key: say
Value: Hello\
> json {\"a\":1}
Key: json
Value: {\a\:1}
> json "{\"a\":1}"
Unrecognized command or argument 'a\:1}'.
Description:
A set command.
Usage:
SET <key> <value> [options]
Arguments:
<key> A string
<value> A string
Options:
--version Show version information
-?, -h, --help Show help and usage information
> json {"a":1}
Key: json
Value: {a:1}
This is complicated and hard to talk clearly about. 😅
Going back to the previous example and taking System.CommandLine out of the picture for a moment, the following would work for PowerShell when starting your app (i.e. for the args values passed to Main):
> json '"{\"a\":1}"'
Here's what's happening:
PowerShell treats the text inside the single quotes as literal text
Main receives the string with the double quotes intact, which is valid JSON, in the args array.
If you were to now pass that args array to e.g. rootCommand.InvokeAsync(args), the CommandLineStringSplitter never even gets called, because the split has already happened before Main. (CommandLineStringSplitter is typically only used in testing or when calculating completions).
But, since you're building more of a REPL-style interaction, this shell escaping won't affect the value you get from Console.ReadLine. You'll get the exact string back, including the double and single quotes. When it's passed to CommandLineStringSplitter.Split, that method assumes this is command line input and tries to treat the quotes as delimiters for the command line, but that's not what they represent inside this JSON block. Since you know it's JSON, you might consider an alternative way to parse it, because otherwise your users will have to escape the quotes inside the JSON, which is not intuitive.
/// <summary>/// 表示一个命令行的解析器。/// </summary>publicstaticclassCommandLineParser{privatestaticboolTryReadFirstChar(thisStringReaderreader,outcharc){vari=reader.Read();if(i==-1){c=char.MinValue;returnfalse;}else{c=(char)i;if(char.IsWhiteSpace(c))returnreader.TryReadFirstChar(outc);returntrue;}}privatestaticIEnumerable<char>ParseToken(StringReaderreader){if(!reader.TryReadFirstChar(outvarc))yieldbreak;varisQueteString=false;varqc=char.MinValue;if(cis'=' or ':'){yieldbreak;}elseif(cis'\"' or '\''){isQueteString=true;qc=c;if(reader.Peek()==-1){thrownewInvalidDataException("Invalid quete in the string.");}}else{yieldreturnc;}inti;while(true){i=reader.Read();if(i==-1)break;c=(char)i;if(isQueteString){varpi=reader.Peek();if(pi==-1)thrownewInvalidDataException("Invalid quete in the string.");varpeek=(char)pi;if(peek==qc){reader.Read();if(c=='\\'){yieldreturnpeek;}else{yieldreturnc;yieldbreak;}}elseif(c=='\\'&&peek=='\\'){reader.Read();yieldreturnpeek;}else{yieldreturnc;}}else{if(char.IsWhiteSpace(c)||(cis':' or '='))yieldbreak;yieldreturnc;}}}/// <summary>/// 解析指定的命令行。/// </summary>/// <param name="commandLine">命令行。</param>/// <returns>一个命令行参数的列表。</returns>publicstaticIEnumerable<string>Parse(stringcommandLine){if(string.IsNullOrWhiteSpace(commandLine))yieldbreak;commandLine=commandLine.Trim();usingvarreader=newStringReader(commandLine);do{varchars=ParseToken(reader).ToArray();if(chars.Length==0)continue;if(chars.Length==1&&(chars[0]is':' or '='))continue;vararg=newstring(chars);yieldreturnarg;}while(reader.Peek()!=-1);}}
xunit
[Fact]publicvoidAllTest(){Assert.Equal(newstring[]{"text","abc"},CommandLineParser.Parse("text abc"));Assert.Equal(newstring[]{"text","Hello\""},CommandLineParser.Parse("text Hello\""));Assert.Equal(newstring[]{"text","Hello\""},CommandLineParser.Parse(" \t text Hello\"\t "));}[Fact]publicvoidQueteTest(){varargs1="\"{\\\"a\\t\\\":1}\"";Assert.Equal(newstring[]{"text","{\"a\\t\":1}"},CommandLineParser.Parse("text "+args1).ToArray());}[Fact]publicvoidQuete2Test(){varargs1="'{\"a\\t\":1}'";Assert.Equal(newstring[]{"text","{\"a\\t\":1}"},CommandLineParser.Parse("text "+args1).ToArray());}[Fact]publicvoidSetTest(){Assert.Equal(newstring[]{"a","b","c","d","e","f","g","h"},CommandLineParser.Parse("a=b c =d e = f g= h").ToArray());Assert.Equal(newstring[]{"a","b","c","d","e","f","g","h"},CommandLineParser.Parse("a:b c :d e : f g: h").ToArray());Assert.Equal(newstring[]{"a",":b"},CommandLineParser.Parse(" a= ':b'").ToArray());}
If you were to now pass that args array to e.g. rootCommand.InvokeAsync(args), the CommandLineStringSplitter never even gets called, because the split has already happened before Main. (CommandLineStringSplitter is typically only used in testing or when calculating completions).
I'm not using CommandLineStringSplitter, but am passing JSON into an application and was running into the same issues. I determined that passing a single-quoted string that contains double quotes results in PowerShell stripping the double quotes before the C# application even gets it's args, while cmd does not. I'll just have to use cmd to run this command in my application.
Activity
jonsequitur commentedon May 19, 2022
Can you explain a bit more about what you're trying to do and why this output is your expectation? Also, examples using precise strings without the C# escaping would be a little clearer, I think.
For context, the
CommandLineStringSplitteris intended to reproduce the way command line input to a .NET console app is split into theargsarray that gets passed toMain.Let's use a
Program.cscontaining this to verify the behavior this is designed to reproduce:Your
rawvariable contains the following actual, unescaped string:"dotnet publish \"xxx.csproj\" -c Release -o \"./bin/latest/\" -r linux-x64 --self-contained false"Running the above program from the command line in PowerShell (keeping in mind that these examples will differ in other shells) with that string produces this output:
So that looks like it's working as designed, but at least in this example, it's probably not what you're really looking for.
treenewlyn commentedon May 20, 2022
So, When i call
SET text abc, it's work. But, when i want to set a json value, not working.Input
Output
How set char
"in Value argument?jonsequitur commentedon May 20, 2022
This is complicated and hard to talk clearly about. 😅
Going back to the previous example and taking System.CommandLine out of the picture for a moment, the following would work for PowerShell when starting your app (i.e. for the
argsvalues passed toMain):> json '"{\"a\":1}"'Here's what's happening:
Mainreceives the string with the double quotes intact, which is valid JSON, in theargsarray.If you were to now pass that
argsarray to e.g.rootCommand.InvokeAsync(args), theCommandLineStringSplitternever even gets called, because the split has already happened beforeMain. (CommandLineStringSplitteris typically only used in testing or when calculating completions).But, since you're building more of a REPL-style interaction, this shell escaping won't affect the value you get from
Console.ReadLine. You'll get the exact string back, including the double and single quotes. When it's passed toCommandLineStringSplitter.Split, that method assumes this is command line input and tries to treat the quotes as delimiters for the command line, but that's not what they represent inside this JSON block. Since you know it's JSON, you might consider an alternative way to parse it, because otherwise your users will have to escape the quotes inside the JSON, which is not intuitive.treenewlyn commentedon May 20, 2022
OK. I see. share my code
xunit
jonorossi commentedon Jul 24, 2023
Thanks @jonsequitur for the insight.
I'm not using
CommandLineStringSplitter, but am passing JSON into an application and was running into the same issues. I determined that passing a single-quoted string that contains double quotes results in PowerShell stripping the double quotes before the C# application even gets it'sargs, whilecmddoes not. I'll just have to usecmdto run this command in my application.