Skip to content

Commit bce7ef0

Browse files
committed
Fix Compilation error when string default arguments contain backslashes #138
1 parent 8e5c14c commit bce7ef0

File tree

3 files changed

+71
-4
lines changed

3 files changed

+71
-4
lines changed

sandbox/GeneratorSandbox/Program.cs

+22-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
using FilterShareProject;
33

44

5+
args = ["Output"];
56

67
var app = ConsoleApp.Create();
78

8-
var v = new OtherProjectCommand();
9-
// app.Add("", v.Execute);
10-
app.Add<MyProjectCommand>();
9+
app.Add<MyCommands>();
1110

1211
app.Run(args);
1312

@@ -19,4 +18,24 @@ public void Execute(int x)
1918
{
2019
Console.WriteLine("Hello?");
2120
}
21+
}
22+
23+
24+
public class MyCommands
25+
{
26+
[Command("Error1")]
27+
public void Error1(string msg = @"\")
28+
{
29+
Console.WriteLine(msg);
30+
}
31+
[Command("Error2")]
32+
public void Error2(string msg = "\\")
33+
{
34+
Console.WriteLine(msg);
35+
}
36+
[Command("Output")]
37+
public void Output(string msg = @"\\")
38+
{
39+
Console.WriteLine(msg); // 「\」
40+
}
2241
}

src/ConsoleAppFramework/Command.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,8 @@ public string DefaultValueToString(bool castValue = true, bool enumIncludeTypeNa
292292
}
293293
if (DefaultValue is string s)
294294
{
295-
return "\"" + s + "\"";
295+
// default string value is escaped in symbol so safe to use @
296+
return "@\"" + s + "\"";
296297
}
297298
if (DefaultValue == null)
298299
{

tests/ConsoleAppFramework.GeneratorTests/RunTest.cs

+47
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,51 @@ public class Test
121121
""", "show --aaa foo --value 100", expected);
122122

123123
}
124+
125+
[Fact]
126+
public void StringEscape()
127+
{
128+
var code = """
129+
var app = ConsoleApp.Create();
130+
app.Add<MyCommands>();
131+
app.Run(args);
132+
133+
public class MyCommands
134+
{
135+
[Command("Error1")]
136+
public void Error1(string msg = @"\")
137+
{
138+
Console.Write(msg);
139+
}
140+
[Command("Error2")]
141+
public void Error2(string msg = "\\")
142+
{
143+
Console.Write(msg);
144+
}
145+
[Command("Output")]
146+
public void Output(string msg = @"\\")
147+
{
148+
Console.Write(msg);
149+
}
150+
}
151+
""";
152+
153+
verifier.Execute(code, "Error1", @"\");
154+
verifier.Execute(code, "Error2", "\\");
155+
verifier.Execute(code, "Output", @"\\");
156+
157+
// lambda
158+
159+
verifier.Execute("""
160+
ConsoleApp.Run(args, (string msg = @"\") => Console.Write(msg));
161+
""", "", @"\");
162+
163+
verifier.Execute("""
164+
ConsoleApp.Run(args, (string msg = "\\") => Console.Write(msg));
165+
""", "", "\\");
166+
167+
verifier.Execute("""
168+
ConsoleApp.Run(args, (string msg = @"\\") => Console.Write(msg));
169+
""", "", @"\\");
170+
}
124171
}

0 commit comments

Comments
 (0)