aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/CommandLine/CommandLineParser.cs
blob: 92944ab2c265d9b04f8db9b8dc0dc3909b01ae9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// 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.

namespace WixToolset.Core.CommandLine
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using WixToolset.Data;
    using WixToolset.Extensibility;
    using WixToolset.Extensibility.Data;
    using WixToolset.Extensibility.Services;

    internal enum Commands
    {
        Unknown,
        Build,
        Preprocess,
        Compile,
        Link,
        Bind,
    }

    internal class CommandLineParser : ICommandLineParser
    {
        public CommandLineParser(IServiceProvider serviceProvider)
        {
            this.ServiceProvider = serviceProvider;

            this.Messaging = this.ServiceProvider.GetService<IMessaging>();
        }

        private IServiceProvider ServiceProvider { get; }

        private IMessaging Messaging { get; set; }

        public IExtensionManager ExtensionManager { get; set; }

        public ICommandLineArguments Arguments { get; set; }

        public static string ExpectedArgument { get; } = "expected argument";

        public string ActiveCommand { get; private set; }

        public bool ShowHelp { get; private set; }

        public ICommandLineCommand ParseStandardCommandLine()
        {
            var context = this.ServiceProvider.GetService<ICommandLineContext>();
            context.ExtensionManager = this.ExtensionManager ?? this.ServiceProvider.GetService<IExtensionManager>();
            context.Arguments = this.Arguments;

            var next = String.Empty;

            var command = Commands.Unknown;
            var showLogo = true;
            var showVersion = false;
            var outputFolder = String.Empty;
            var outputFile = String.Empty;
            var outputType = String.Empty;
            var verbose = false;
            var files = new List<string>();
            var defines = new List<string>();
            var includePaths = new List<string>();
            var locFiles = new List<string>();
            var libraryFiles = new List<string>();
            var suppressedWarnings = new List<int>();

            var bindFiles = false;
            var bindPaths = new List<string>();

            var intermediateFolder = String.Empty;

            var cabCachePath = String.Empty;
            var cultures = new List<string>();
            var contentsFile = String.Empty;
            var outputsFile = String.Empty;
            var builtOutputsFile = String.Empty;

            this.Parse(context, (cmdline, arg) => Enum.TryParse(arg, true, out command), (cmdline, parser, arg) =>
            {
                if (parser.IsSwitch(arg))
                {
                    var parameter = arg.Substring(1);
                    switch (parameter.ToLowerInvariant())
                    {
                    case "?":
                    case "h":
                    case "help":
                        cmdline.ShowHelp = true;
                        return true;

                    case "bindfiles":
                        bindFiles = true;
                        return true;

                    case "bindpath":
                        parser.GetNextArgumentOrError(arg, bindPaths);
                        return true;

                    case "cc":
                        cabCachePath = parser.GetNextArgumentOrError(arg);
                        return true;

                    case "culture":
                        parser.GetNextArgumentOrError(arg, cultures);
                        return true;
                    case "contentsfile":
                        contentsFile = parser.GetNextArgumentAsFilePathOrError(arg);
                        return true;
                    case "outputsfile":
                        outputsFile = parser.GetNextArgumentAsFilePathOrError(arg);
                        return true;
                    case "builtoutputsfile":
                        builtOutputsFile = parser.GetNextArgumentAsFilePathOrError(arg);
                        return true;

                    case "d":
                    case "define":
                        parser.GetNextArgumentOrError(arg, defines);
                        return true;

                    case "i":
                    case "includepath":
                        parser.GetNextArgumentOrError(arg, includePaths);
                        return true;

                    case "intermediatefolder":
                        intermediateFolder = parser.GetNextArgumentAsDirectoryOrError(arg);
                        return true;

                    case "loc":
                        parser.GetNextArgumentAsFilePathOrError(arg, "localization files", locFiles);
                        return true;

                    case "lib":
                        parser.GetNextArgumentAsFilePathOrError(arg, "library files", libraryFiles);
                        return true;

                    case "o":
                    case "out":
                        outputFile = parser.GetNextArgumentAsFilePathOrError(arg);
                        return true;

                    case "outputtype":
                        outputType= parser.GetNextArgumentOrError(arg);
                        return true;

                    case "nologo":
                        showLogo = false;
                        return true;

                    case "v":
                    case "verbose":
                        verbose = true;
                        return true;

                    case "version":
                    case "-version":
                        showVersion = true;
                        return true;

                    case "sval":
                        // todo: implement
                        return true;
                    }

                    return false;
                }
                else
                {
                    parser.GetArgumentAsFilePathOrError(arg, "source code", files);
                    return true;
                }
            });

            this.Messaging.ShowVerboseMessages = verbose;

            if (showVersion)
            {
                return new VersionCommand();
            }

            if (showLogo)
            {
                AppCommon.DisplayToolHeader();
            }

            if (this.ShowHelp)
            {
                return new HelpCommand(command);
            }

            switch (command)
            {
            case Commands.Build:
            {
                var sourceFiles = GatherSourceFiles(files, outputFolder);
                var variables = this.GatherPreprocessorVariables(defines);
                var bindPathList = this.GatherBindPaths(bindPaths);
                var filterCultures = CalculateFilterCultures(cultures);
                var type = CalculateOutputType(outputType, outputFile);
                return new BuildCommand(this.ServiceProvider, sourceFiles, variables, locFiles, libraryFiles, filterCultures, outputFile, type, cabCachePath, bindFiles, bindPathList, includePaths, intermediateFolder, contentsFile, outputsFile, builtOutputsFile);
            }

            case Commands.Compile:
            {
                var sourceFiles = GatherSourceFiles(files, outputFolder);
                var variables = GatherPreprocessorVariables(defines);
                return new CompileCommand(this.ServiceProvider, sourceFiles, variables);
            }
            }

            return null;
        }

        private static IEnumerable<string> CalculateFilterCultures(List<string> cultures)
        {
            var result = new List<string>();

            if (cultures == null)
            {
            }
            else if (cultures.Count == 1 && cultures[0].Equals("null", StringComparison.OrdinalIgnoreCase))
            {
                // When null is used treat it as if cultures wasn't specified. This is
                // needed for batching in the MSBuild task since MSBuild doesn't support
                // empty items.
            }
            else
            {
                foreach (var culture in cultures)
                {
                    // Neutral is different from null. For neutral we still want to do culture filtering.
                    // Set the culture to the empty string = identifier for the invariant culture.
                    var filter = (culture.Equals("neutral", StringComparison.OrdinalIgnoreCase)) ? String.Empty : culture;
                    result.Add(filter);
                }
            }

            return result;
        }

        private static OutputType CalculateOutputType(string outputType, string outputFile)
        {
            if (String.IsNullOrEmpty(outputType))
            {
                outputType = Path.GetExtension(outputFile);
            }

            switch (outputType.ToLowerInvariant())
            {
            case "bundle":
            case ".exe":
                return OutputType.Bundle;

            case "library":
            case ".wixlib":
                return OutputType.Library;

            case "module":
            case ".msm":
                return OutputType.Module;

            case "patch":
            case ".msp":
                return OutputType.Patch;

            case ".pcp":
                return OutputType.PatchCreation;

            case "product":
            case "package":
            case ".msi":
                return OutputType.Product;

            case "transform":
            case ".mst":
                return OutputType.Transform;

            case "intermediatepostlink":
            case ".wixipl":
                return OutputType.IntermediatePostLink;
            }

            return OutputType.Unknown;
        }

        private ICommandLineParser Parse(ICommandLineContext context, Func<CommandLineParser, string, bool> parseCommand, Func<CommandLineParser, IParseCommandLine, string, bool> parseArgument)
        {
            var extensions = this.ExtensionManager.Create<IExtensionCommandLine>();

            foreach (var extension in extensions)
            {
                extension.PreParse(context);
            }

            var parser = context.Arguments.Parse();

            while (!this.ShowHelp &&
                   String.IsNullOrEmpty(parser.ErrorArgument) &&
                   parser.TryGetNextSwitchOrArgument(out var arg))
            {
                if (String.IsNullOrWhiteSpace(arg)) // skip blank arguments.
                {
                    continue;
                }

                if (parser.IsSwitch(arg))
                {
                    if (!parseArgument(this, parser, arg) &&
                        !this.TryParseCommandLineArgumentWithExtension(arg, parser, extensions))
                    {
                        parser.ErrorArgument = arg;
                    }
                }
                else if (String.IsNullOrEmpty(this.ActiveCommand) && parseCommand != null) // First non-switch must be the command, if commands are supported.
                {
                    if (parseCommand(this, arg))
                    {
                        this.ActiveCommand = arg;
                    }
                    else
                    {
                        parser.ErrorArgument = arg;
                    }
                }
                else if (!this.TryParseCommandLineArgumentWithExtension(arg, parser, extensions) &&
                         !parseArgument(this, parser, arg))
                {
                    parser.ErrorArgument = arg;
                }
            }

            foreach (var extension in extensions)
            {
                extension.PostParse();
            }

            return this;
        }

        private static IEnumerable<SourceFile> GatherSourceFiles(IEnumerable<string> sourceFiles, string intermediateDirectory)
        {
            var files = new List<SourceFile>();

            foreach (var item in sourceFiles)
            {
                var sourcePath = item;
                var outputPath = Path.Combine(intermediateDirectory, Path.GetFileNameWithoutExtension(sourcePath) + ".wir");

                files.Add(new SourceFile(sourcePath, outputPath));
            }

            return files;
        }

        private IDictionary<string, string> GatherPreprocessorVariables(IEnumerable<string> defineConstants)
        {
            var variables = new Dictionary<string, string>();

            foreach (var pair in defineConstants)
            {
                string[] value = pair.Split(new[] { '=' }, 2);

                if (variables.ContainsKey(value[0]))
                {
                    this.Messaging.Write(ErrorMessages.DuplicateVariableDefinition(value[0], (1 == value.Length) ? String.Empty : value[1], variables[value[0]]));
                    continue;
                }

                variables.Add(value[0], (1 == value.Length) ? String.Empty : value[1]);
            }

            return variables;
        }

        private IEnumerable<BindPath> GatherBindPaths(IEnumerable<string> bindPaths)
        {
            var result = new List<BindPath>();

            foreach (var bindPath in bindPaths)
            {
                var bp = BindPath.Parse(bindPath);

                if (Directory.Exists(bp.Path))
                {
                    result.Add(bp);
                }
                else if (File.Exists(bp.Path))
                {
                    this.Messaging.Write(ErrorMessages.ExpectedDirectoryGotFile("-bindpath", bp.Path));
                }
            }

            return result;
        }

        private bool TryParseCommandLineArgumentWithExtension(string arg, IParseCommandLine parse, IEnumerable<IExtensionCommandLine> extensions)
        {
            foreach (var extension in extensions)
            {
                if (extension.TryParseArgument(parse, arg))
                {
                    return true;
                }
            }

            return false;
        }
    }
}