From c9a02cd707b637b2ef492b2579a3eff1490f0360 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Mon, 5 Aug 2013 19:37:39 -0500 Subject: [PATCH] Fix behavior when spaces are in the path (fixes #6) --- .../Antlr4ClassGenerationTaskInternal.cs | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs b/runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs index 12703a7e3..a4a376283 100644 --- a/runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs +++ b/runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs @@ -42,6 +42,7 @@ namespace Antlr4.Build.Tasks #else using Registry = Microsoft.Win32.Registry; #endif + using StringBuilder = System.Text.StringBuilder; internal class AntlrClassGenerationTaskInternal : MarshalByRefObject { @@ -243,11 +244,11 @@ namespace Antlr4.Build.Tasks List arguments = new List(); arguments.Add("-cp"); - arguments.Add('"' + ToolPath + '"'); + arguments.Add(ToolPath); arguments.Add("org.antlr.v4.CSharpTool"); arguments.Add("-o"); - arguments.Add('"' + OutputPath + '"'); + arguments.Add(OutputPath); if (GenerateListener) arguments.Add("-listener"); @@ -288,7 +289,7 @@ namespace Antlr4.Build.Tasks arguments.AddRange(SourceCodeFiles); - ProcessStartInfo startInfo = new ProcessStartInfo(java, string.Join(" ", arguments.ToArray())) + ProcessStartInfo startInfo = new ProcessStartInfo(java, JoinArguments(arguments)) { UseShellExecute = false, CreateNoWindow = true, @@ -330,6 +331,35 @@ namespace Antlr4.Build.Tasks } } + private static string JoinArguments(IEnumerable arguments) + { + if (arguments == null) + throw new ArgumentNullException("arguments"); + + StringBuilder builder = new StringBuilder(); + foreach (string argument in arguments) + { + if (builder.Length > 0) + builder.Append(' '); + + if (argument.IndexOfAny(new[] { '"', ' ' }) < 0) + { + builder.Append(argument); + continue; + } + + // escape a backslash appearing before a quote + string arg = argument.Replace("\\\"", "\\\\\""); + // escape double quotes + arg = arg.Replace("\"", "\\\""); + + // wrap the argument in outer quotes + builder.Append('"').Append(arg).Append('"'); + } + + return builder.ToString(); + } + private static readonly Regex GeneratedFileMessageFormat = new Regex(@"^Generating file '(?.*?)' for grammar '(?.*?)'$", RegexOptions.Compiled); private void HandleErrorDataReceived(object sender, DataReceivedEventArgs e)