aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.BuildTasks/DoIt.cs
blob: 977a2326ff48fcf945f70dab19d38731f79a6419 (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
// 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.BuildTasks
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;
    using WixToolset.Core;
    using WixToolset.Data;
    using WixToolset.Extensibility;
    using WixToolset.Extensibility.Services;

    /// <summary>
    /// An MSBuild task to run the WiX compiler.
    /// </summary>
    public sealed class DoIt : Task
    {
        public DoIt() : this(null)
        {
        }

        public DoIt(IMessageListener listener)
        {
            this.Listener = listener ?? new MsbuildMessageListener(this.Log, "WIX", "wix.exe");
        }

        public string AdditionalOptions { get; set; }

        public string Cultures { get; set; }

        public string[] DefineConstants { get; set; }

        public ITaskItem[] Extensions { get; set; }

        public string ExtensionDirectory { get; set; }

        public string[] IncludeSearchPaths { get; set; }

        public string InstallerPlatform { get; set; }

        [Required]
        public ITaskItem IntermediateDirectory { get; set; }

        public ITaskItem[] LocalizationFiles { get; set; }

        public bool NoLogo { get; set; }

        public ITaskItem[] LibraryFiles { get; set; }

        [Output]
        [Required]
        public ITaskItem OutputFile { get; set; }

        public string OutputType { get; set; }

        public string PdbOutputFile { get; set; }

        public bool Pedantic { get; set; }

        [Required]
        public ITaskItem[] SourceFiles { get; set; }

        public string[] ReferencePaths { get; set; }


        /// <summary>
        /// Gets or sets whether all warnings should be suppressed.
        /// </summary>
        public bool SuppressAllWarnings { get; set; }

        /// <summary>
        /// Gets or sets a list of specific warnings to be suppressed.
        /// </summary>
        public string[] SuppressSpecificWarnings { get; set; }

        /// <summary>
        /// Gets or sets whether all warnings should be treated as errors.
        /// </summary>
        public bool TreatWarningsAsErrors { get; set; }

        /// <summary>
        /// Gets or sets a list of specific warnings to treat as errors.
        /// </summary>
        public string[] TreatSpecificWarningsAsErrors { get; set; }

        /// <summary>
        /// Gets or sets whether to display verbose output.
        /// </summary>
        public bool VerboseOutput { get; set; }


        public ITaskItem[] BindInputPaths { get; set; }

        public bool BindFiles { get; set; }

        public ITaskItem BindContentsFile { get; set; }

        public ITaskItem BindOutputsFile { get; set; }

        public ITaskItem BindBuiltOutputsFile { get; set; }

        public string CabinetCachePath { get; set; }
        public int CabinetCreationThreadCount { get; set; }
        public string DefaultCompressionLevel { get; set; }

        [Output]
        public ITaskItem UnreferencedSymbolsFile { get; set; }

        public ITaskItem WixProjectFile { get; set; }
        public string[] WixVariables { get; set; }

        public bool SuppressValidation { get; set; }
        public string[] SuppressIces { get; set; }
        public string AdditionalCub { get; set; }

        private IMessageListener Listener { get; }

        public override bool Execute()
        {
            try
            {
                this.ExecuteCore();
            }
            catch (Exception e)
            {
                this.Log.LogErrorFromException(e);

                if (e is NullReferenceException || e is SEHException)
                {
                    throw;
                }
            }

            return !this.Log.HasLoggedErrors;
        }

        private void ExecuteCore()
        {
            var commandLineBuilder = new WixCommandLineBuilder();

            commandLineBuilder.AppendTextUnquoted("build");

            commandLineBuilder.AppendSwitchIfNotNull("-out ", this.OutputFile);
            commandLineBuilder.AppendSwitchIfNotNull("-outputType ", this.OutputType);
            commandLineBuilder.AppendIfTrue("-nologo", this.NoLogo);
            commandLineBuilder.AppendSwitchIfNotNull("-cultures ", this.Cultures);
            commandLineBuilder.AppendArrayIfNotNull("-d ", this.DefineConstants);
            commandLineBuilder.AppendArrayIfNotNull("-I ", this.IncludeSearchPaths);
            commandLineBuilder.AppendExtensions(this.Extensions, this.ExtensionDirectory, this.ReferencePaths);
            commandLineBuilder.AppendIfTrue("-sval", this.SuppressValidation);
            commandLineBuilder.AppendArrayIfNotNull("-sice ", this.SuppressIces);
            commandLineBuilder.AppendSwitchIfNotNull("-usf ", this.UnreferencedSymbolsFile);
            commandLineBuilder.AppendSwitchIfNotNull("-cc ", this.CabinetCachePath);
            commandLineBuilder.AppendSwitchIfNotNull("-intermediatefolder ", this.IntermediateDirectory);
            commandLineBuilder.AppendSwitchIfNotNull("-contentsfile ", this.BindContentsFile);
            commandLineBuilder.AppendSwitchIfNotNull("-outputsfile ", this.BindOutputsFile);
            commandLineBuilder.AppendSwitchIfNotNull("-builtoutputsfile ", this.BindBuiltOutputsFile);

            commandLineBuilder.AppendIfTrue("-bindFiles", this.BindFiles);
            commandLineBuilder.AppendArrayIfNotNull("-bindPath ", this.CalculateBindPathStrings());
            commandLineBuilder.AppendArrayIfNotNull("-loc ", this.LocalizationFiles);
            commandLineBuilder.AppendArrayIfNotNull("-lib ", this.LibraryFiles);
            commandLineBuilder.AppendTextIfNotWhitespace(this.AdditionalOptions);
            commandLineBuilder.AppendFileNamesIfNotNull(this.SourceFiles, " ");

            var commandLineString = commandLineBuilder.ToString();

            this.Log.LogMessage(MessageImportance.Normal, "wix.exe " + commandLineString);

            var serviceProvider = new WixToolsetServiceProvider();

            var messaging = serviceProvider.GetService<IMessaging>();
            messaging.SetListener(this.Listener);

            var arguments = serviceProvider.GetService<ICommandLineArguments>();
            arguments.Populate(commandLineString);

            var context = serviceProvider.GetService<ICommandLineContext>();
            context.Messaging = messaging;
            context.ExtensionManager = this.CreateExtensionManagerWithStandardBackends(serviceProvider, arguments.Extensions);
            context.Arguments = arguments;

            var commandLine = serviceProvider.GetService<ICommandLine>();
            var command = commandLine.ParseStandardCommandLine(context);
            command?.Execute();
        }

        private IExtensionManager CreateExtensionManagerWithStandardBackends(IServiceProvider serviceProvider, string[] extensions)
        {
            var extensionManager = serviceProvider.GetService<IExtensionManager>();

            foreach (var type in new[] { typeof(WixToolset.Core.Burn.WixToolsetStandardBackend), typeof(WixToolset.Core.WindowsInstaller.WixToolsetStandardBackend) })
            {
                extensionManager.Add(type.Assembly);
            }

            foreach (var extension in extensions)
            {
                extensionManager.Load(extension);
            }

            return extensionManager;
        }

        private void DisplayMessage(object sender, DisplayEventArgs e)
        {
            this.Log.LogMessageFromText(e.Message, MessageImportance.Normal);
        }

        private IEnumerable<string> CalculateBindPathStrings()
        {
            if (null != this.BindInputPaths)
            {
                foreach (var item in this.BindInputPaths)
                {
                    var path = item.GetMetadata("FullPath");

                    var bindName = item.GetMetadata("BindName");
                    if (!String.IsNullOrEmpty(bindName))
                    {
                        yield return String.Concat(bindName, "=", path);
                    }
                    else
                    {
                        yield return path;
                    }
                }
            }
        }

        ///// <summary>
        ///// Builds a command line from options in this task.
        ///// </summary>
        //protected override void BuildCommandLine(WixCommandLineBuilder commandLineBuilder)
        //{
        //    base.BuildCommandLine(commandLineBuilder);

        //    commandLineBuilder.AppendIfTrue("-p", this.PreprocessToStdOut);
        //    commandLineBuilder.AppendSwitchIfNotNull("-p", this.PreprocessToFile);
        //    commandLineBuilder.AppendSwitchIfNotNull("-out ", this.OutputFile);
        //    commandLineBuilder.AppendArrayIfNotNull("-d", this.DefineConstants);
        //    commandLineBuilder.AppendArrayIfNotNull("-I", this.IncludeSearchPaths);
        //    commandLineBuilder.AppendIfTrue("-pedantic", this.Pedantic);
        //    commandLineBuilder.AppendSwitchIfNotNull("-arch ", this.InstallerPlatform);
        //    commandLineBuilder.AppendExtensions(this.Extensions, this.ExtensionDirectory, this.referencePaths);
        //    commandLineBuilder.AppendTextIfNotNull(this.AdditionalOptions);

        //    // Support per-source-file output by looking at the SourceFiles items to
        //    // see if there is any "CandleOutput" metadata.  If there is, we do our own
        //    // appending, otherwise we fall back to the built-in "append file names" code.
        //    // Note also that the wix.targets "Compile" target does *not* automagically
        //    // fix the "@(CompileObjOutput)" list to include these new output names.
        //    // If you really want to use this, you're going to have to clone the target
        //    // in your own .targets file and create the output list yourself.
        //    bool usePerSourceOutput = false;
        //    if (this.SourceFiles != null)
        //    {
        //        foreach (ITaskItem item in this.SourceFiles)
        //        {
        //            if (!String.IsNullOrEmpty(item.GetMetadata("CandleOutput")))
        //            {
        //                usePerSourceOutput = true;
        //                break;
        //            }
        //        }
        //    }

        //    if (usePerSourceOutput)
        //    {
        //        string[] newSourceNames = new string[this.SourceFiles.Length];
        //        for (int iSource = 0; iSource < this.SourceFiles.Length; ++iSource)
        //        {
        //            ITaskItem item = this.SourceFiles[iSource];
        //            if (null == item)
        //            {
        //                newSourceNames[iSource] = null;
        //            }
        //            else
        //            {
        //                string output = item.GetMetadata("CandleOutput");

        //                if (!String.IsNullOrEmpty(output))
        //                {
        //                    newSourceNames[iSource] = String.Concat(item.ItemSpec, ";", output);
        //                }
        //                else
        //                {
        //                    newSourceNames[iSource] = item.ItemSpec;
        //                }
        //            }
        //        }

        //        commandLineBuilder.AppendFileNamesIfNotNull(newSourceNames, " ");
        //    }
        //    else
        //    {
        //        commandLineBuilder.AppendFileNamesIfNotNull(this.SourceFiles, " ");
        //    }
        //}

        private class MsbuildMessageListener : IMessageListener
        {
            public MsbuildMessageListener(TaskLoggingHelper logger, string longName, string shortName)
            {
                this.Logger = logger;
                this.LongAppName = longName;
                this.ShortAppName = shortName;
            }

            public string ShortAppName { get; }

            public string LongAppName { get; }

            private TaskLoggingHelper Logger { get; }

            public void Write(Message message)
            {
                switch (message.Level)
                {
                    case MessageLevel.Error:
                        this.Logger.LogError(null, this.ShortAppName + message.Id.ToString(), null, message.SourceLineNumbers?.FileName ?? this.LongAppName, message.SourceLineNumbers?.LineNumber ?? 0, 0, 0, 0, message.ResourceNameOrFormat, message.MessageArgs);
                        break;

                    case MessageLevel.Warning:
                        this.Logger.LogWarning(null, this.ShortAppName + message.Id.ToString(), null, message.SourceLineNumbers?.FileName ?? this.LongAppName, message.SourceLineNumbers?.LineNumber ?? 0, 0, 0, 0, message.ResourceNameOrFormat, message.MessageArgs);
                        break;

                    default:
                        // TODO: Revisit this because something is going horribly awry. The commented out LogMessage call is crashing saying that the "message" parameter is null. When you look at the call stack, the code
                        //       is in the wrong LogMessage override and the "null" subcategory was passed in as the message. Not clear why it is picking the wrong overload.
                        //if (message.Id > 0)
                        //{
                        //    this.Logger.LogMessage(null, code, null, message.SourceLineNumber?.FileName, message.SourceLineNumber?.LineNumber ?? 0, 0, 0, 0, MessageImportance.Normal, message.Format, message.FormatData);
                        //}
                        //else
                        //{
                        this.Logger.LogMessage(MessageImportance.Normal, message.ResourceNameOrFormat, message.MessageArgs);
                        //}
                        break;
                }
            }

            public void Write(string message)
            {
                this.Logger.LogMessage(MessageImportance.Low, message);
            }
        }
    }
}