aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/CommandLine/CommandLine.cs
diff options
context:
space:
mode:
authorRob Mensching <rob@firegiant.com>2017-09-17 15:35:20 -0700
committerRob Mensching <rob@firegiant.com>2017-09-17 16:00:11 -0700
commitd3d3649a68cb1fa589fdd987a6690dbd5d671f0d (patch)
tree44fe37ee352b7e3a355cc1e08b1d7d5988c14cc0 /src/WixToolset.Core/CommandLine/CommandLine.cs
parenta62610d23d6feb98be3b1e529a4e81b19d77d9d8 (diff)
downloadwix-d3d3649a68cb1fa589fdd987a6690dbd5d671f0d.tar.gz
wix-d3d3649a68cb1fa589fdd987a6690dbd5d671f0d.tar.bz2
wix-d3d3649a68cb1fa589fdd987a6690dbd5d671f0d.zip
Initial code commit
Diffstat (limited to 'src/WixToolset.Core/CommandLine/CommandLine.cs')
-rw-r--r--src/WixToolset.Core/CommandLine/CommandLine.cs592
1 files changed, 592 insertions, 0 deletions
diff --git a/src/WixToolset.Core/CommandLine/CommandLine.cs b/src/WixToolset.Core/CommandLine/CommandLine.cs
new file mode 100644
index 00000000..440ae9ef
--- /dev/null
+++ b/src/WixToolset.Core/CommandLine/CommandLine.cs
@@ -0,0 +1,592 @@
1// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
2
3namespace WixToolset.Core
4{
5 using System;
6 using System.Collections.Generic;
7 using System.IO;
8 using System.Linq;
9 using System.Text;
10 using System.Text.RegularExpressions;
11 using WixToolset.Data;
12 using WixToolset.Extensibility;
13
14 internal enum Commands
15 {
16 Unknown,
17 Build,
18 Preprocess,
19 Compile,
20 Link,
21 Bind,
22 }
23
24 public class CommandLine
25 {
26 private CommandLine()
27 {
28 }
29
30 public static string ExpectedArgument { get; } = "expected argument";
31
32 public string ActiveCommand { get; private set; }
33
34 public string[] OriginalArguments { get; private set; }
35
36 public Queue<string> RemainingArguments { get; } = new Queue<string>();
37
38 public ExtensionManager ExtensionManager { get; } = new ExtensionManager();
39
40 public string ErrorArgument { get; set; }
41
42 public bool ShowHelp { get; set; }
43
44 public static ICommand ParseStandardCommandLine(string commandLineString)
45 {
46 var args = CommandLine.ParseArgumentsToArray(commandLineString).ToArray();
47
48 return ParseStandardCommandLine(args);
49 }
50
51 public static ICommand ParseStandardCommandLine(string[] args)
52 {
53 var next = String.Empty;
54
55 var command = Commands.Unknown;
56 var showLogo = true;
57 var showVersion = false;
58 var outputFolder = String.Empty;
59 var outputFile = String.Empty;
60 var sourceFile = String.Empty;
61 var verbose = false;
62 var files = new List<string>();
63 var defines = new List<string>();
64 var includePaths = new List<string>();
65 var locFiles = new List<string>();
66 var suppressedWarnings = new List<int>();
67
68 var cultures = new List<string>();
69 var contentsFile = String.Empty;
70 var outputsFile = String.Empty;
71 var builtOutputsFile = String.Empty;
72 var wixProjectFile = String.Empty;
73
74 var cli = CommandLine.Parse(args, (cmdline, arg) => Enum.TryParse(arg, true, out command), (cmdline, arg) =>
75 {
76 if (cmdline.IsSwitch(arg))
77 {
78 var parameter = arg.TrimStart(new[] { '-', '/' });
79 switch (parameter.ToLowerInvariant())
80 {
81 case "?":
82 case "h":
83 case "help":
84 cmdline.ShowHelp = true;
85 return true;
86
87 case "cultures":
88 cmdline.GetNextArgumentOrError(cultures);
89 return true;
90 case "contentsfile":
91 cmdline.GetNextArgumentOrError(ref contentsFile);
92 return true;
93 case "outputsfile":
94 cmdline.GetNextArgumentOrError(ref outputsFile);
95 return true;
96 case "builtoutputsfile":
97 cmdline.GetNextArgumentOrError(ref builtOutputsFile);
98 return true;
99 case "wixprojectfile":
100 cmdline.GetNextArgumentOrError(ref wixProjectFile);
101 return true;
102
103 case "d":
104 case "define":
105 cmdline.GetNextArgumentOrError(defines);
106 return true;
107
108 case "i":
109 case "includepath":
110 cmdline.GetNextArgumentOrError(includePaths);
111 return true;
112
113 case "loc":
114 cmdline.GetNextArgumentAsFilePathOrError(locFiles, "localization files");
115 return true;
116
117 case "o":
118 case "out":
119 cmdline.GetNextArgumentOrError(ref outputFile);
120 return true;
121
122 case "nologo":
123 showLogo = false;
124 return true;
125
126 case "v":
127 case "verbose":
128 verbose = true;
129 return true;
130
131 case "version":
132 case "-version":
133 showVersion = true;
134 return true;
135 }
136
137 return false;
138 }
139 else
140 {
141 files.AddRange(cmdline.GetFiles(arg, "source code"));
142 return true;
143 }
144 });
145
146 if (showVersion)
147 {
148 return new VersionCommand();
149 }
150
151 if (showLogo)
152 {
153 AppCommon.DisplayToolHeader();
154 }
155
156 if (cli.ShowHelp)
157 {
158 return new HelpCommand(command);
159 }
160
161 switch (command)
162 {
163 case Commands.Build:
164 {
165 var sourceFiles = GatherSourceFiles(files, outputFolder);
166 var variables = GatherPreprocessorVariables(defines);
167 var extensions = cli.ExtensionManager;
168 return new BuildCommand(sourceFiles, variables, locFiles, outputFile, cultures, contentsFile, outputsFile, builtOutputsFile, wixProjectFile);
169 }
170
171 case Commands.Compile:
172 {
173 var sourceFiles = GatherSourceFiles(files, outputFolder);
174 var variables = GatherPreprocessorVariables(defines);
175 return new CompileCommand(sourceFiles, variables);
176 }
177 }
178
179 return null;
180 }
181
182 private static CommandLine Parse(string commandLineString, Func<CommandLine, string, bool> parseArgument)
183 {
184 var arguments = CommandLine.ParseArgumentsToArray(commandLineString).ToArray();
185
186 return CommandLine.Parse(arguments, null, parseArgument);
187 }
188
189 private static CommandLine Parse(string[] commandLineArguments, Func<CommandLine, string, bool> parseArgument)
190 {
191 return CommandLine.Parse(commandLineArguments, null, parseArgument);
192 }
193
194 private static CommandLine Parse(string[] commandLineArguments, Func<CommandLine, string, bool> parseCommand, Func<CommandLine, string, bool> parseArgument)
195 {
196 var cmdline = new CommandLine();
197
198 cmdline.FlattenArgumentsWithResponseFilesIntoOriginalArguments(commandLineArguments);
199
200 cmdline.QueueArgumentsAndLoadExtensions(cmdline.OriginalArguments);
201
202 cmdline.ProcessRemainingArguments(parseArgument, parseCommand);
203
204 return cmdline;
205 }
206
207 private static IEnumerable<SourceFile> GatherSourceFiles(IEnumerable<string> sourceFiles, string intermediateDirectory)
208 {
209 var files = new List<SourceFile>();
210
211 foreach (var item in sourceFiles)
212 {
213 var sourcePath = item;
214 var outputPath = Path.Combine(intermediateDirectory, Path.GetFileNameWithoutExtension(sourcePath) + ".wir");
215
216 files.Add(new SourceFile(sourcePath, outputPath));
217 }
218
219 return files;
220 }
221
222 private static IDictionary<string, string> GatherPreprocessorVariables(IEnumerable<string> defineConstants)
223 {
224 var variables = new Dictionary<string, string>();
225
226 foreach (var pair in defineConstants)
227 {
228 string[] value = pair.Split(new[] { '=' }, 2);
229
230 if (variables.ContainsKey(value[0]))
231 {
232 Messaging.Instance.OnMessage(WixErrors.DuplicateVariableDefinition(value[0], (1 == value.Length) ? String.Empty : value[1], variables[value[0]]));
233 continue;
234 }
235
236 variables.Add(value[0], (1 == value.Length) ? String.Empty : value[1]);
237 }
238
239 return variables;
240 }
241
242
243 /// <summary>
244 /// Get a set of files that possibly have a search pattern in the path (such as '*').
245 /// </summary>
246 /// <param name="searchPath">Search path to find files in.</param>
247 /// <param name="fileType">Type of file; typically "Source".</param>
248 /// <returns>An array of files matching the search path.</returns>
249 /// <remarks>
250 /// This method is written in this verbose way because it needs to support ".." in the path.
251 /// It needs the directory path isolated from the file name in order to use Directory.GetFiles
252 /// or DirectoryInfo.GetFiles. The only way to get this directory path is manually since
253 /// Path.GetDirectoryName does not support ".." in the path.
254 /// </remarks>
255 /// <exception cref="WixFileNotFoundException">Throws WixFileNotFoundException if no file matching the pattern can be found.</exception>
256 public string[] GetFiles(string searchPath, string fileType)
257 {
258 if (null == searchPath)
259 {
260 throw new ArgumentNullException(nameof(searchPath));
261 }
262
263 // Convert alternate directory separators to the standard one.
264 string filePath = searchPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
265 int lastSeparator = filePath.LastIndexOf(Path.DirectorySeparatorChar);
266 string[] files = null;
267
268 try
269 {
270 if (0 > lastSeparator)
271 {
272 files = Directory.GetFiles(".", filePath);
273 }
274 else // found directory separator
275 {
276 files = Directory.GetFiles(filePath.Substring(0, lastSeparator + 1), filePath.Substring(lastSeparator + 1));
277 }
278 }
279 catch (DirectoryNotFoundException)
280 {
281 // Don't let this function throw the DirectoryNotFoundException. This exception
282 // occurs for non-existant directories and invalid characters in the searchPattern.
283 }
284 catch (ArgumentException)
285 {
286 // Don't let this function throw the ArgumentException. This exception
287 // occurs in certain situations such as when passing a malformed UNC path.
288 }
289 catch (IOException)
290 {
291 throw new WixFileNotFoundException(searchPath, fileType);
292 }
293
294 if (null == files || 0 == files.Length)
295 {
296 throw new WixFileNotFoundException(searchPath, fileType);
297 }
298
299 return files;
300 }
301
302 /// <summary>
303 /// Validates that a valid switch (starts with "/" or "-"), and returns a bool indicating its validity
304 /// </summary>
305 /// <param name="args">The list of strings to check.</param>
306 /// <param name="index">The index (in args) of the commandline parameter to be validated.</param>
307 /// <returns>True if a valid switch exists there, false if not.</returns>
308 public bool IsSwitch(string arg)
309 {
310 return arg != null && ('/' == arg[0] || '-' == arg[0]);
311 }
312
313 /// <summary>
314 /// Validates that a valid switch (starts with "/" or "-"), and returns a bool indicating its validity
315 /// </summary>
316 /// <param name="args">The list of strings to check.</param>
317 /// <param name="index">The index (in args) of the commandline parameter to be validated.</param>
318 /// <returns>True if a valid switch exists there, false if not.</returns>
319 public bool IsSwitchAt(IEnumerable<string> args, int index)
320 {
321 var arg = args.ElementAtOrDefault(index);
322 return IsSwitch(arg);
323 }
324
325 public void GetNextArgumentOrError(ref string arg)
326 {
327 this.TryGetNextArgumentOrError(out arg);
328 }
329
330 public void GetNextArgumentOrError(IList<string> args)
331 {
332 if (this.TryGetNextArgumentOrError(out var arg))
333 {
334 args.Add(arg);
335 }
336 }
337
338 public void GetNextArgumentAsFilePathOrError(IList<string> args, string fileType)
339 {
340 if (this.TryGetNextArgumentOrError(out var arg))
341 {
342 foreach (var path in this.GetFiles(arg, fileType))
343 {
344 args.Add(path);
345 }
346 }
347 }
348
349 public bool TryGetNextArgumentOrError(out string arg)
350 {
351 //if (this.RemainingArguments.TryDequeue(out arg) && !this.IsSwitch(arg))
352 if (TryDequeue(this.RemainingArguments, out arg) && !this.IsSwitch(arg))
353 {
354 return true;
355 }
356
357 this.ErrorArgument = arg ?? CommandLine.ExpectedArgument;
358
359 return false;
360 }
361
362 private static bool TryDequeue(Queue<string> q, out string arg)
363 {
364 if (q.Count> 0)
365 {
366 arg = q.Dequeue();
367 return true;
368 }
369
370 arg = null;
371 return false;
372 }
373
374 private void FlattenArgumentsWithResponseFilesIntoOriginalArguments(string[] commandLineArguments)
375 {
376 List<string> args = new List<string>();
377
378 foreach (var arg in commandLineArguments)
379 {
380 if ('@' == arg[0])
381 {
382 var responseFileArguments = CommandLine.ParseResponseFile(arg.Substring(1));
383 args.AddRange(responseFileArguments);
384 }
385 else
386 {
387 args.Add(arg);
388 }
389 }
390
391 this.OriginalArguments = args.ToArray();
392 }
393
394 private void QueueArgumentsAndLoadExtensions(string[] args)
395 {
396 for (var i = 0; i < args.Length; ++i)
397 {
398 var arg = args[i];
399
400 if ("-ext" == arg || "/ext" == arg)
401 {
402 if (!this.IsSwitchAt(args, ++i))
403 {
404 this.ExtensionManager.Load(args[i]);
405 }
406 else
407 {
408 this.ErrorArgument = arg;
409 break;
410 }
411 }
412 else
413 {
414 this.RemainingArguments.Enqueue(arg);
415 }
416 }
417 }
418
419 private void ProcessRemainingArguments(Func<CommandLine, string, bool> parseArgument, Func<CommandLine, string, bool> parseCommand)
420 {
421 var extensions = this.ExtensionManager.Create<IExtensionCommandLine>();
422
423 while (!this.ShowHelp &&
424 String.IsNullOrEmpty(this.ErrorArgument) &&
425 TryDequeue(this.RemainingArguments, out var arg))
426 {
427 if (String.IsNullOrWhiteSpace(arg)) // skip blank arguments.
428 {
429 continue;
430 }
431
432 if ('-' == arg[0] || '/' == arg[0])
433 {
434 if (!parseArgument(this, arg) &&
435 !this.TryParseCommandLineArgumentWithExtension(arg, extensions))
436 {
437 this.ErrorArgument = arg;
438 }
439 }
440 else if (String.IsNullOrEmpty(this.ActiveCommand) && parseCommand != null) // First non-switch must be the command, if commands are supported.
441 {
442 if (parseCommand(this, arg))
443 {
444 this.ActiveCommand = arg;
445 }
446 else
447 {
448 this.ErrorArgument = arg;
449 }
450 }
451 else if (!this.TryParseCommandLineArgumentWithExtension(arg, extensions) &&
452 !parseArgument(this, arg))
453 {
454 this.ErrorArgument = arg;
455 }
456 }
457 }
458
459 private bool TryParseCommandLineArgumentWithExtension(string arg, IEnumerable<IExtensionCommandLine> extensions)
460 {
461 foreach (var extension in extensions)
462 {
463 //if (extension.ParseArgument(this, arg))
464 //{
465 // return true;
466 //}
467 }
468
469 return false;
470 }
471
472 /// <summary>
473 /// Parses a response file.
474 /// </summary>
475 /// <param name="responseFile">The file to parse.</param>
476 /// <returns>The array of arguments.</returns>
477 private static List<string> ParseResponseFile(string responseFile)
478 {
479 string arguments;
480
481 using (StreamReader reader = new StreamReader(responseFile))
482 {
483 arguments = reader.ReadToEnd();
484 }
485
486 return CommandLine.ParseArgumentsToArray(arguments);
487 }
488
489 /// <summary>
490 /// Parses an argument string into an argument array based on whitespace and quoting.
491 /// </summary>
492 /// <param name="arguments">Argument string.</param>
493 /// <returns>Argument array.</returns>
494 private static List<string> ParseArgumentsToArray(string arguments)
495 {
496 // Scan and parse the arguments string, dividing up the arguments based on whitespace.
497 // Unescaped quotes cause whitespace to be ignored, while the quotes themselves are removed.
498 // Quotes may begin and end inside arguments; they don't necessarily just surround whole arguments.
499 // Escaped quotes and escaped backslashes also need to be unescaped by this process.
500
501 // Collects the final list of arguments to be returned.
502 var argsList = new List<string>();
503
504 // True if we are inside an unescaped quote, meaning whitespace should be ignored.
505 var insideQuote = false;
506
507 // Index of the start of the current argument substring; either the start of the argument
508 // or the start of a quoted or unquoted sequence within it.
509 var partStart = 0;
510
511 // The current argument string being built; when completed it will be added to the list.
512 var arg = new StringBuilder();
513
514 for (int i = 0; i <= arguments.Length; i++)
515 {
516 if (i == arguments.Length || (Char.IsWhiteSpace(arguments[i]) && !insideQuote))
517 {
518 // Reached a whitespace separator or the end of the string.
519
520 // Finish building the current argument.
521 arg.Append(arguments.Substring(partStart, i - partStart));
522
523 // Skip over the whitespace character.
524 partStart = i + 1;
525
526 // Add the argument to the list if it's not empty.
527 if (arg.Length > 0)
528 {
529 argsList.Add(CommandLine.ExpandEnvVars(arg.ToString()));
530 arg.Length = 0;
531 }
532 }
533 else if (i > partStart && arguments[i - 1] == '\\')
534 {
535 // Check the character following an unprocessed backslash.
536 // Unescape quotes, and backslashes followed by a quote.
537 if (arguments[i] == '"' || (arguments[i] == '\\' && arguments.Length > i + 1 && arguments[i + 1] == '"'))
538 {
539 // Unescape the quote or backslash by skipping the preceeding backslash.
540 arg.Append(arguments.Substring(partStart, i - 1 - partStart));
541 arg.Append(arguments[i]);
542 partStart = i + 1;
543 }
544 }
545 else if (arguments[i] == '"')
546 {
547 // Add the quoted or unquoted section to the argument string.
548 arg.Append(arguments.Substring(partStart, i - partStart));
549
550 // And skip over the quote character.
551 partStart = i + 1;
552
553 insideQuote = !insideQuote;
554 }
555 }
556
557 return argsList;
558 }
559
560 /// <summary>
561 /// Expand enxironment variables contained in the passed string
562 /// </summary>
563 /// <param name="arguments"></param>
564 /// <returns></returns>
565 private static string ExpandEnvVars(string arguments)
566 {
567 var id = Environment.GetEnvironmentVariables();
568
569 var regex = new Regex("(?<=\\%)(?:[\\w\\.]+)(?=\\%)");
570 MatchCollection matches = regex.Matches(arguments);
571
572 string value = String.Empty;
573 for (int i = 0; i <= (matches.Count - 1); i++)
574 {
575 try
576 {
577 var key = matches[i].Value;
578 regex = new Regex(String.Concat("(?i)(?:\\%)(?:", key, ")(?:\\%)"));
579 value = id[key].ToString();
580 arguments = regex.Replace(arguments, value);
581 }
582 catch (NullReferenceException)
583 {
584 // Collapse unresolved environment variables.
585 arguments = regex.Replace(arguments, value);
586 }
587 }
588
589 return arguments;
590 }
591 }
592}