aboutsummaryrefslogtreecommitdiff
path: root/src/tools/heat/UtilMutator.cs
blob: 80fd470c6cfa8ac0c77c8cd8b09e4f5896d8d7b7 (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// 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.Harvesters
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using WixToolset.Harvesters.Extensibility;
    using Wix = WixToolset.Harvesters.Serialize;

    /// <summary>
    /// The template type.
    /// </summary>
    public enum TemplateType
    {
        /// <summary>
        /// A fragment template.
        /// </summary>
        Fragment,

        /// <summary>
        /// A module template.
        /// </summary>
        Module,

        /// <summary>
        /// A product template.
        /// </summary>
        Package
    }

    /// <summary>
    /// The mutator for the WiX Toolset Internet Information Services Extension.
    /// </summary>
    public sealed class UtilMutator : BaseMutatorExtension
    {
        private ArrayList components;
        private ArrayList componentGroups;
        private string componentGroupName;
        private bool createFragments;
        private ArrayList directories;
        private ArrayList directoryRefs;
        private ArrayList files;
        private ArrayList features;
        private SortedList fragments;
        private bool autogenerateGuids;
        private bool generateGuids;
        private string guidFormat = "B"; // Defaults to guid in {}
        private Wix.IParentElement rootElement;
        private bool setUniqueIdentifiers;
        private TemplateType templateType;

        /// <summary>
        /// Instantiate a new UtilMutator.
        /// </summary>
        public UtilMutator()
        {
            this.components = new ArrayList();
            this.componentGroups = new ArrayList();
            this.directories = new ArrayList();
            this.directoryRefs = new ArrayList();
            this.features = new ArrayList();
            this.files = new ArrayList();
            this.fragments = new SortedList();
        }

        /// <summary>
        /// Gets or sets the value of the component group name.
        /// </summary>
        /// <value>The component group name.</value>
        public string ComponentGroupName
        {
            get { return this.componentGroupName; }
            set { this.componentGroupName = value; }
        }

        /// <summary>
        /// Gets or sets the option to create fragments.
        /// </summary>
        /// <value>The option to create fragments.</value>
        public bool CreateFragments
        {
            get { return this.createFragments; }
            set { this.createFragments = value; }
        }

        /// <summary>
        /// Gets or sets the option to autogenerate component guids at compile time.
        /// </summary>
        /// <value>The option to autogenerate component guids.</value>
        public bool AutogenerateGuids
        {
            get { return this.autogenerateGuids; }
            set { this.autogenerateGuids = value; }
        }

        /// <summary>
        /// Gets or sets the option to generate missing guids.
        /// </summary>
        /// <value>The option to generate missing guids.</value>
        public bool GenerateGuids
        {
            get { return this.generateGuids; }
            set { this.generateGuids = value; }
        }

        /// <summary>
        /// Gets or sets the option to set the format of guids.
        /// D - 32 digits separated by hyphens:
        ///     xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        /// B - 32 digits separated by hyphens, enclosed in brackets:
        ///     {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
        /// </summary>
        /// <value>Guid format either B or D.</value>
        public string GuidFormat
        {
            get { return this.guidFormat; }
            set { this.guidFormat = value; }
        }

        /// <summary>
        /// Gets the sequence of the extension.
        /// </summary>
        /// <value>The sequence of the extension.</value>
        public override int Sequence
        {
            get { return 1000; }
        }

        /// <summary>
        /// Gets of sets the option to set unique identifiers.
        /// </summary>
        /// <value>The option to set unique identifiers.</value>
        public bool SetUniqueIdentifiers
        {
            get { return this.setUniqueIdentifiers; }
            set { this.setUniqueIdentifiers = value; }
        }

        /// <summary>
        /// Gets or sets the template type.
        /// </summary>
        /// <value>The template type.</value>
        public TemplateType TemplateType
        {
            get { return this.templateType; }
            set { this.templateType = value; }
        }

        /// <summary>
        /// Mutate a WiX document.
        /// </summary>
        /// <param name="wix">The Wix document element.</param>
        public override void Mutate(Wix.Wix wix)
        {
            this.components.Clear();
            this.directories.Clear();
            this.directoryRefs.Clear();
            this.features.Clear();
            this.files.Clear();
            this.fragments.Clear();
            this.rootElement = null;

            // index elements in this wix document
            this.IndexElement(wix);

            this.MutateWix(wix);

            this.MutateFiles();

            this.MutateDirectories();

            this.MutateComponents();

            if (null != this.componentGroupName)
            {
                this.CreateComponentGroup(wix);
            }

            // add the components to the product feature after all the identifiers have been set
            if (TemplateType.Package  == this.templateType)
            {
                var feature = (Wix.Feature)this.features[0];

                foreach (Wix.ComponentGroup group in this.componentGroups)
                {
                    var componentGroupRef = new Wix.ComponentGroupRef();
                    componentGroupRef.Id = group.Id;

                    feature.AddChild(componentGroupRef);
                }
            }
            else if (TemplateType.Module == this.templateType)
            {
                foreach (Wix.ISchemaElement element in wix.Children)
                {
                    if (element is Wix.Module)
                    {
                        foreach (Wix.ComponentGroup group in this.componentGroups)
                        {
                            var componentGroupRef = new Wix.ComponentGroupRef();
                            componentGroupRef.Id = group.Id;

                            ((Wix.IParentElement)element).AddChild(componentGroupRef);
                        }
                        break;
                    }
                }
            }

            //if(!this.createFragments && TemplateType.Package
            foreach (Wix.Fragment fragment in this.fragments.Values)
            {
                wix.AddChild(fragment);
            }
        }

        /// <summary>
        /// Creates a component group with a given name.
        /// </summary>
        /// <param name="wix">The Wix document element.</param>
        private void CreateComponentGroup(Wix.Wix wix)
        {
            var componentGroup = new Wix.ComponentGroup();
            componentGroup.Id = this.componentGroupName;
            this.componentGroups.Add(componentGroup);

            var cgFragment = new Wix.Fragment();
            cgFragment.AddChild(componentGroup);
            wix.AddChild(cgFragment);

            var componentCount = 0;
            for (; componentCount < this.components.Count; componentCount++)
            {
                var c = this.components[componentCount] as Wix.Component;

                if (this.createFragments)
                {
                    if (c.ParentElement is Wix.Directory)
                    {
                        var parentDirectory = c.ParentElement as Wix.Directory;

                        componentGroup.AddChild(c);
                        c.Directory = parentDirectory.Id;
                        parentDirectory.RemoveChild(c);
                    }
                    else if (c.ParentElement is Wix.DirectoryRef || c.ParentElement is Wix.StandardDirectory)
                    {
                        var parentDirectory = c.ParentElement as Wix.DirectoryBase;

                        componentGroup.AddChild(c);
                        c.Directory = parentDirectory.Id;
                        parentDirectory.RemoveChild(c);

                        // Remove whole fragment if moving the component to the component group just leaves an empty DirectoryRef
                        if (0 < this.fragments.Count && parentDirectory.ParentElement is Wix.Fragment)
                        {
                            var parentFragment = parentDirectory.ParentElement as Wix.Fragment;
                            var childCount = 0;
                            foreach (Wix.ISchemaElement element in parentFragment.Children)
                            {
                                childCount++;
                            }

                            // Component should always have an Id but the SortedList creation allows for null and bases the name on the fragment count which we cannot reverse engineer here.
                            if (1 == childCount && !String.IsNullOrEmpty(c.Id))
                            {
                                var removeIndex = this.fragments.IndexOfKey(String.Concat("Component:", c.Id));
                                if (0 <= removeIndex)
                                {
                                    this.fragments.RemoveAt(removeIndex);
                                }
                            }
                        }
                    }
                }
                else
                {
                    var componentRef = new Wix.ComponentRef();
                    componentRef.Id = c.Id;
                    componentGroup.AddChild(componentRef);
                }
            }
        }

        /// <summary>
        /// Index an element.
        /// </summary>
        /// <param name="element">The element to index.</param>
        private void IndexElement(Wix.ISchemaElement element)
        {
            if (element is Wix.Component)
            {
                this.components.Add(element);
            }
            else if (element is Wix.ComponentGroup)
            {
                this.componentGroups.Add(element);
            }
            else if (element is Wix.Directory)
            {
                this.directories.Add(element);
            }
            else if (element is Wix.DirectoryRef)
            {
                this.directoryRefs.Add(element);
            }
            else if (element is Wix.Feature)
            {
                this.features.Add(element);
            }
            else if (element is Wix.File)
            {
                this.files.Add(element);
            }
            else if (element is Wix.Module || element is Wix.PatchCreation || element is Wix.Package)
            {
                Debug.Assert(null == this.rootElement);
                this.rootElement = (Wix.IParentElement)element;
            }

            // index the child elements
            if (element is Wix.IParentElement parentElement)
            {
                foreach (Wix.ISchemaElement childElement in parentElement.Children)
                {
                    this.IndexElement(childElement);
                }
            }
        }

        /// <summary>
        /// Mutate the components.
        /// </summary>
        private void MutateComponents()
        {
            var identifierGenerator = new IdentifierGenerator("Component", this.Core);
            if (TemplateType.Module == this.templateType)
            {
                identifierGenerator.MaxIdentifierLength = IdentifierGenerator.MaxModuleIdentifierLength;
            }

            foreach (Wix.Component component in this.components)
            {
                if (null == component.Id)
                {
                    var firstFileId = String.Empty;

                    // attempt to create a possible identifier from the first file identifier in the component
                    foreach (Wix.File file in component[typeof(Wix.File)])
                    {
                        firstFileId = file.Id;
                        break;
                    }

                    if (String.IsNullOrEmpty(firstFileId))
                    {
                        firstFileId = this.GetGuid();
                    }

                    component.Id = identifierGenerator.GetIdentifier(firstFileId);
                }

                if (null == component.Guid)
                {
                    if (this.AutogenerateGuids)
                    {
                        component.Guid = "*";
                    }
                    else
                    {
                        component.Guid = this.GetGuid();
                    }
                }

                if (this.createFragments && component.ParentElement is Wix.Directory directory)
                {
                    // parent directory must have an identifier to create a reference to it
                    if (null == directory.Id)
                    {
                        break;
                    }

                    if (this.rootElement is Wix.Module)
                    {
                        // add a ComponentRef for the Component
                        var componentRef = new Wix.ComponentRef();
                        componentRef.Id = component.Id;
                        this.rootElement.AddChild(componentRef);
                    }

                    // create a new Fragment
                    var fragment = new Wix.Fragment();
                    this.fragments.Add(String.Concat("Component:", component.Id ?? this.fragments.Count.ToString()), fragment);

                    // create a new DirectoryRef
                    var directoryRef = DirectoryHelper.CreateDirectoryReference(directory.Id);
                    fragment.AddChild(directoryRef);

                    // move the Component from the the Directory to the DirectoryRef
                    directory.RemoveChild(component);
                    directoryRef.AddChild(component);
                }
            }
        }

        /// <summary>
        /// Mutate the directories.
        /// </summary>
        private void MutateDirectories()
        {
            if (!this.setUniqueIdentifiers)
            {
                // assign all identifiers before fragmenting (because fragmenting requires them all to be present)
                var identifierGenerator = new IdentifierGenerator("Directory", this.Core);
                if (TemplateType.Module == this.templateType)
                {
                    identifierGenerator.MaxIdentifierLength = IdentifierGenerator.MaxModuleIdentifierLength;
                }

                foreach (Wix.Directory directory in this.directories)
                {
                    if (null == directory.Id)
                    {
                        directory.Id = identifierGenerator.GetIdentifier(directory.Name);
                    }
                }
            }

            if (this.createFragments)
            {
                foreach (Wix.Directory directory in this.directories)
                {
                    if (directory.ParentElement is Wix.Directory)
                    {
                        var parentDirectory = (Wix.DirectoryBase)directory.ParentElement;

                        // parent directory must have an identifier to create a reference to it
                        if (null == parentDirectory.Id)
                        {
                            return;
                        }

                        // create a new Fragment
                        var fragment = new Wix.Fragment();
                        this.fragments.Add(String.Concat("Directory:", ("TARGETDIR" == directory.Id ? null : (null != directory.Id ? directory.Id : this.fragments.Count.ToString()))), fragment);

                        // create a new DirectoryRef
                        var directoryRef = DirectoryHelper.CreateDirectoryReference(parentDirectory.Id);
                        fragment.AddChild(directoryRef);

                        // move the Directory from the parent Directory to DirectoryRef
                        parentDirectory.RemoveChild(directory);
                        directoryRef.AddChild(directory);
                    }
                    else if (directory.ParentElement is Wix.Fragment parent)
                    {
                        // When creating fragments, remove any top-level Directory elements;
                        // the fragments should be pulled in by their DirectoryRefs instead.
                        parent.RemoveChild(directory);

                        // Remove the fragment if it is empty.
                        if (parent.Children.GetEnumerator().Current == null && parent.ParentElement != null)
                        {
                            ((Wix.IParentElement)parent.ParentElement).RemoveChild(parent);
                        }
                    }
                    else if (directory.ParentElement == this.rootElement)
                    {
                        // create a new Fragment
                        var fragment = new Wix.Fragment();
                        this.fragments.Add(String.Concat("Directory:", ("TARGETDIR" == directory.Id ? null : (null != directory.Id ? directory.Id : this.fragments.Count.ToString()))), fragment);

                        // move the Directory from the root element to the Fragment
                        this.rootElement.RemoveChild(directory);
                        fragment.AddChild(directory);
                    }
                }
            }
        }

        /// <summary>
        /// Mutate the files.
        /// </summary>
        private void MutateFiles()
        {
            var identifierGenerator = new IdentifierGenerator("File", this.Core);
            if (TemplateType.Module == this.templateType)
            {
                identifierGenerator.MaxIdentifierLength = IdentifierGenerator.MaxModuleIdentifierLength;
            }

            foreach (Wix.File file in this.files)
            {
                if (null == file.Id)
                {
                    file.Id = identifierGenerator.GetIdentifier(Path.GetFileName(file.Source));
                }
            }
        }

        /// <summary>
        /// Mutate a Wix element.
        /// </summary>
        /// <param name="wix">The Wix element to mutate.</param>
        private void MutateWix(Wix.Wix wix)
        {
            if (TemplateType.Fragment != this.templateType)
            {
                if (null != this.rootElement || 0 != this.features.Count)
                {
                    throw new Exception("The template option cannot be used with Feature, Package, or Module elements present.");
                }

                // create a package element although it won't always be used
                var package = new Wix.SummaryInformation();
                if (TemplateType.Module == this.templateType)
                {
                    package.Id = this.GetGuid();
                }
                else
                {
                    package.Compressed = Wix.YesNoType.yes;
                }

                package.InstallerVersion = 200;

                var targetDir = new Wix.Directory();
                targetDir.Id = "TARGETDIR";
                targetDir.Name = "SourceDir";

                foreach (Wix.DirectoryRef directoryRef in this.directoryRefs)
                {
                    if (String.Equals(directoryRef.Id, "TARGETDIR", StringComparison.OrdinalIgnoreCase))
                    {
                        var parent = directoryRef.ParentElement as Wix.IParentElement;

                        foreach (Wix.ISchemaElement element in directoryRef.Children)
                        {
                            targetDir.AddChild(element);
                        }

                        parent.RemoveChild(directoryRef);

                        if (null != ((Wix.ISchemaElement)parent).ParentElement)
                        {
                            var i = 0;

                            foreach (Wix.ISchemaElement element in parent.Children)
                            {
                                i++;
                            }

                            if (0 == i)
                            {
                                var supParent = (Wix.IParentElement)((Wix.ISchemaElement)parent).ParentElement;
                                supParent.RemoveChild((Wix.ISchemaElement)parent);
                            }
                        }

                        break;
                    }
                }

                if (TemplateType.Module == this.templateType)
                {
                    var module = new Wix.Module();
                    module.Id = "PUT-MODULE-NAME-HERE";
                    module.Language = "1033";
                    module.Version = "1.0.0.0";

                    package.Manufacturer = "PUT-COMPANY-NAME-HERE";
                    module.AddChild(package);
                    module.AddChild(targetDir);

                    wix.AddChild(module);
                    this.rootElement = module;
                }
                else // product
                {
                    var product = new Wix.Package();
                    product.Id = this.GetGuid();
                    product.Language = "1033";
                    product.Manufacturer = "PUT-COMPANY-NAME-HERE";
                    product.Name = "PUT-PRODUCT-NAME-HERE";
                    product.UpgradeCode = this.GetGuid();
                    product.Version = "1.0.0.0";
                    product.AddChild(package);
                    product.AddChild(targetDir);

                    var media = new Wix.Media();
                    media.Id = "1";
                    media.Cabinet = "product.cab";
                    media.EmbedCab = Wix.YesNoType.yes;
                    product.AddChild(media);

                    var feature = new Wix.Feature();
                    feature.Id = "ProductFeature";
                    feature.Title = "PUT-FEATURE-TITLE-HERE";
                    feature.Level = 1;
                    product.AddChild(feature);
                    this.features.Add(feature);

                    wix.AddChild(product);
                    this.rootElement = product;
                }
            }
        }

        /// <summary>
        /// Get a generated guid or a placeholder for a guid.
        /// </summary>
        /// <returns>A generated guid or placeholder.</returns>
        private string GetGuid()
        {
            if (this.generateGuids)
            {
                return Guid.NewGuid().ToString(this.guidFormat, CultureInfo.InvariantCulture).ToUpper(CultureInfo.InvariantCulture);
            }
            else
            {
                return "PUT-GUID-HERE";
            }
        }
    }
}