Skip to content

Commit c9a02cd

Browse files
committed
Fix behavior when spaces are in the path (fixes #6)
1 parent a2a1eef commit c9a02cd

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs

+33-3
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ namespace Antlr4.Build.Tasks
4242
#else
4343
using Registry = Microsoft.Win32.Registry;
4444
#endif
45+
using StringBuilder = System.Text.StringBuilder;
4546

4647
internal class AntlrClassGenerationTaskInternal : MarshalByRefObject
4748
{
@@ -243,11 +244,11 @@ public bool Execute()
243244

244245
List<string> arguments = new List<string>();
245246
arguments.Add("-cp");
246-
arguments.Add('"' + ToolPath + '"');
247+
arguments.Add(ToolPath);
247248
arguments.Add("org.antlr.v4.CSharpTool");
248249

249250
arguments.Add("-o");
250-
arguments.Add('"' + OutputPath + '"');
251+
arguments.Add(OutputPath);
251252

252253
if (GenerateListener)
253254
arguments.Add("-listener");
@@ -288,7 +289,7 @@ public bool Execute()
288289

289290
arguments.AddRange(SourceCodeFiles);
290291

291-
ProcessStartInfo startInfo = new ProcessStartInfo(java, string.Join(" ", arguments.ToArray()))
292+
ProcessStartInfo startInfo = new ProcessStartInfo(java, JoinArguments(arguments))
292293
{
293294
UseShellExecute = false,
294295
CreateNoWindow = true,
@@ -330,6 +331,35 @@ public bool Execute()
330331
}
331332
}
332333

334+
private static string JoinArguments(IEnumerable<string> arguments)
335+
{
336+
if (arguments == null)
337+
throw new ArgumentNullException("arguments");
338+
339+
StringBuilder builder = new StringBuilder();
340+
foreach (string argument in arguments)
341+
{
342+
if (builder.Length > 0)
343+
builder.Append(' ');
344+
345+
if (argument.IndexOfAny(new[] { '"', ' ' }) < 0)
346+
{
347+
builder.Append(argument);
348+
continue;
349+
}
350+
351+
// escape a backslash appearing before a quote
352+
string arg = argument.Replace("\\\"", "\\\\\"");
353+
// escape double quotes
354+
arg = arg.Replace("\"", "\\\"");
355+
356+
// wrap the argument in outer quotes
357+
builder.Append('"').Append(arg).Append('"');
358+
}
359+
360+
return builder.ToString();
361+
}
362+
333363
private static readonly Regex GeneratedFileMessageFormat = new Regex(@"^Generating file '(?<OUTPUT>.*?)' for grammar '(?<GRAMMAR>.*?)'$", RegexOptions.Compiled);
334364

335365
private void HandleErrorDataReceived(object sender, DataReceivedEventArgs e)

0 commit comments

Comments
 (0)