aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core.WindowsInstaller/Bind/GenerateTransformCommand.cs
blob: faa037624f5b044e2aa101bec565345d21b7fdf4 (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
// 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.WindowsInstaller
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using WixToolset.Core.Native.Msi;
    using WixToolset.Data;
    using WixToolset.Data.Symbols;
    using WixToolset.Data.WindowsInstaller;
    using WixToolset.Extensibility.Services;

    /// <summary>
    /// Creates a transform by diffing two outputs.
    /// </summary>
    internal class GenerateTransformCommand
    {
        private const char sectionDelimiter = '/';
        private readonly IMessaging messaging;
        private SummaryInformationStreams transformSummaryInfo;

        /// <summary>
        /// Instantiates a new Differ class.
        /// </summary>
        public GenerateTransformCommand(IMessaging messaging, WindowsInstallerData targetOutput, WindowsInstallerData updatedOutput, bool preserveUnchangedRows, bool showPedanticMessages)
        {
            this.messaging = messaging;
            this.TargetOutput = targetOutput;
            this.UpdatedOutput = updatedOutput;
            this.PreserveUnchangedRows = preserveUnchangedRows;
            this.ShowPedanticMessages = showPedanticMessages;
        }

        private WindowsInstallerData TargetOutput { get; }

        private WindowsInstallerData UpdatedOutput { get; }

        private TransformFlags ValidationFlags { get; }

        /// <summary>
        /// Gets or sets the option to show pedantic messages.
        /// </summary>
        /// <value>The option to show pedantic messages.</value>
        private bool ShowPedanticMessages { get; }

        /// <summary>
        /// Gets or sets the option to suppress keeping special rows.
        /// </summary>
        /// <value>The option to suppress keeping special rows.</value>
        private bool SuppressKeepingSpecialRows { get; }

        /// <summary>
        /// Gets or sets the flag to determine if all rows, even unchanged ones will be persisted in the output.
        /// </summary>
        /// <value>The option to keep all rows including unchanged rows.</value>
        private bool PreserveUnchangedRows { get; }

        public WindowsInstallerData Transform { get; private set; }

        /// <summary>
        /// Creates a transform by diffing two outputs.
        /// </summary>
        public WindowsInstallerData Execute()
        {
            var targetOutput = this.TargetOutput;
            var updatedOutput = this.UpdatedOutput;
            var validationFlags = this.ValidationFlags;

            var transform = new WindowsInstallerData(null)
            {
                Type = OutputType.Transform,
                Codepage = updatedOutput.Codepage
            };

            this.transformSummaryInfo = new SummaryInformationStreams();

            // compare the codepages
            if (targetOutput.Codepage != updatedOutput.Codepage && 0 == (TransformFlags.ErrorChangeCodePage & validationFlags))
            {
                this.messaging.Write(ErrorMessages.OutputCodepageMismatch(targetOutput.SourceLineNumbers, targetOutput.Codepage, updatedOutput.Codepage));
                if (null != updatedOutput.SourceLineNumbers)
                {
                    this.messaging.Write(ErrorMessages.OutputCodepageMismatch2(updatedOutput.SourceLineNumbers));
                }
            }

            // compare the output types
            if (targetOutput.Type != updatedOutput.Type)
            {
                throw new WixException(ErrorMessages.OutputTypeMismatch(targetOutput.SourceLineNumbers, targetOutput.Type.ToString(), updatedOutput.Type.ToString()));
            }

            // compare the contents of the tables
            foreach (var targetTable in targetOutput.Tables)
            {
                var updatedTable = updatedOutput.Tables[targetTable.Name];
                var operation = TableOperation.None;

                var rows = this.CompareTables(targetOutput, targetTable, updatedTable, out operation);

                if (TableOperation.Drop == operation)
                {
                    var droppedTable = transform.EnsureTable(targetTable.Definition);
                    droppedTable.Operation = TableOperation.Drop;
                }
                else if (TableOperation.None == operation)
                {
                    var modifiedTable = transform.EnsureTable(updatedTable.Definition);
                    foreach (var row in rows)
                    {
                        modifiedTable.Rows.Add(row);
                    }
                }
            }

            // added tables
            foreach (var updatedTable in updatedOutput.Tables)
            {
                if (null == targetOutput.Tables[updatedTable.Name])
                {
                    var addedTable = transform.EnsureTable(updatedTable.Definition);
                    addedTable.Operation = TableOperation.Add;

                    foreach (var updatedRow in updatedTable.Rows)
                    {
                        updatedRow.Operation = RowOperation.Add;
                        updatedRow.SectionId = sectionDelimiter + updatedRow.SectionId;
                        addedTable.Rows.Add(updatedRow);
                    }
                }
            }

            // set summary information properties
            if (!this.SuppressKeepingSpecialRows)
            {
                var summaryInfoTable = transform.Tables["_SummaryInformation"];
                this.UpdateTransformSummaryInformationTable(summaryInfoTable, validationFlags);
            }

            this.Transform = transform;
            return this.Transform;
        }

        /// <summary>
        /// Add a row to the <paramref name="index"/> using the primary key.
        /// </summary>
        /// <param name="index">The indexed rows.</param>
        /// <param name="row">The row to index.</param>
        private void AddIndexedRow(Dictionary<string, Row> index, Row row)
        {
            var primaryKey = row.GetPrimaryKey();

            if (null != primaryKey)
            {
                if (index.TryGetValue(primaryKey, out var collisionRow))
                {
#if TODO_PATCH // This case doesn't seem like it can happen any longer.
                    // Overriding WixActionRows have a primary key defined and take precedence in the index.
                    if (row is WixActionRow actionRow)
                    {
                        // If the current row is not overridable, see if the indexed row is.
                        if (!actionRow.Overridable)
                        {
                            if (collisionRow is WixActionRow indexedRow && indexedRow.Overridable)
                            {
                                // The indexed key is overridable and should be replaced.
                                index[primaryKey] = actionRow;
                            }
                        }

                        // If we got this far, the row does not need to be indexed.
                        return;
                    }
#endif

                    if (this.ShowPedanticMessages)
                    {
                        this.messaging.Write(ErrorMessages.DuplicatePrimaryKey(row.SourceLineNumbers, primaryKey, row.Table.Name));
                    }
                }
                else
                {
                    index.Add(primaryKey, row);
                }
            }
            else // use the string representation of the row as its primary key (it may not be unique)
            {
                // this is provided for compatibility with unreal tables with no primary key
                // all real tables must specify at least one column as the primary key
                primaryKey = row.ToString();
                index[primaryKey] = row;
            }
        }

        private bool CompareRows(Table targetTable, Row targetRow, Row updatedRow, out Row comparedRow)
        {
            comparedRow = null;

            var keepRow = false;

            if (null == targetRow ^ null == updatedRow)
            {
                if (null == targetRow)
                {
                    updatedRow.Operation = RowOperation.Add;
                    comparedRow = updatedRow;
                }
                else if (null == updatedRow)
                {
                    targetRow.Operation = RowOperation.Delete;
                    targetRow.SectionId += sectionDelimiter;

                    comparedRow = targetRow;
                    keepRow = true;
                }
            }
            else // possibly modified
            {
                updatedRow.Operation = RowOperation.None;
                if (!this.SuppressKeepingSpecialRows && "_SummaryInformation" == targetTable.Name)
                {
                    // ignore rows that shouldn't be in a transform
                    if (Enum.IsDefined(typeof(SummaryInformation.Transform), (int)updatedRow[0]))
                    {
                        updatedRow.SectionId = targetRow.SectionId + sectionDelimiter + updatedRow.SectionId;
                        comparedRow = updatedRow;
                        keepRow = true;
                    }
                }
                else
                {
                    if (this.PreserveUnchangedRows)
                    {
                        keepRow = true;
                    }

                    for (var i = 0; i < updatedRow.Fields.Length; i++)
                    {
                        var columnDefinition = updatedRow.Fields[i].Column;

                        if (!columnDefinition.PrimaryKey)
                        {
                            var modified = false;

                            if (i >= targetRow.Fields.Length)
                            {
                                columnDefinition.Added = true;
                                modified = true;
                            }
                            else if (ColumnType.Number == columnDefinition.Type && !columnDefinition.IsLocalizable)
                            {
                                if (null == targetRow[i] ^ null == updatedRow[i])
                                {
                                    modified = true;
                                }
                                else if (null != targetRow[i] && null != updatedRow[i])
                                {
                                    modified = (targetRow.FieldAsInteger(i) != updatedRow.FieldAsInteger(i));
                                }
                            }
                            else if (ColumnType.Preserved == columnDefinition.Type)
                            {
                                updatedRow.Fields[i].PreviousData = targetRow.FieldAsString(i);

                                // keep rows containing preserved fields so the historical data is available to the binder
                                keepRow = !this.SuppressKeepingSpecialRows;
                            }
                            else if (ColumnType.Object == columnDefinition.Type)
                            {
                                var targetObjectField = (ObjectField)targetRow.Fields[i];
                                var updatedObjectField = (ObjectField)updatedRow.Fields[i];

                                updatedObjectField.PreviousEmbeddedFileIndex = targetObjectField.EmbeddedFileIndex;
                                updatedObjectField.PreviousBaseUri = targetObjectField.BaseUri;

                                // always keep a copy of the previous data even if they are identical
                                // This makes diff.wixmst clean and easier to control patch logic
                                updatedObjectField.PreviousData = (string)targetObjectField.Data;

                                // always remember the unresolved data for target build
                                updatedObjectField.UnresolvedPreviousData = targetObjectField.UnresolvedData;

                                // keep rows containing object fields so the files can be compared in the binder
                                keepRow = !this.SuppressKeepingSpecialRows;
                            }
                            else
                            {
                                modified = (targetRow.FieldAsString(i) != updatedRow.FieldAsString(i));
                            }

                            if (modified)
                            {
                                if (null != updatedRow.Fields[i].PreviousData)
                                {
                                    updatedRow.Fields[i].PreviousData = targetRow.FieldAsString(i);
                                }

                                updatedRow.Fields[i].Modified = true;
                                updatedRow.Operation = RowOperation.Modify;
                                keepRow = true;
                            }
                        }
                    }

                    if (keepRow)
                    {
                        comparedRow = updatedRow;
                        comparedRow.SectionId = targetRow.SectionId + sectionDelimiter + updatedRow.SectionId;
                    }
                }
            }

            return keepRow;
        }

        private List<Row> CompareTables(WindowsInstallerData targetOutput, Table targetTable, Table updatedTable, out TableOperation operation)
        {
            var rows = new List<Row>();
            operation = TableOperation.None;

            // dropped tables
            if (null == updatedTable ^ null == targetTable)
            {
                if (null == targetTable)
                {
                    operation = TableOperation.Add;
                    rows.AddRange(updatedTable.Rows);
                }
                else if (null == updatedTable)
                {
                    operation = TableOperation.Drop;
                }
            }
            else // possibly modified tables
            {
                var updatedPrimaryKeys = new Dictionary<string, Row>();
                var targetPrimaryKeys = new Dictionary<string, Row>();

                // compare the table definitions
                if (0 != targetTable.Definition.CompareTo(updatedTable.Definition))
                {
                    // continue to the next table; may be more mismatches
                    this.messaging.Write(ErrorMessages.DatabaseSchemaMismatch(targetOutput.SourceLineNumbers, targetTable.Name));
                }
                else
                {
                    this.IndexPrimaryKeys(targetTable, targetPrimaryKeys, updatedTable, updatedPrimaryKeys);

                    // diff the target and updated rows
                    foreach (var targetPrimaryKeyEntry in targetPrimaryKeys)
                    {
                        var targetPrimaryKey = targetPrimaryKeyEntry.Key;
                        var targetRow = targetPrimaryKeyEntry.Value;
                        updatedPrimaryKeys.TryGetValue(targetPrimaryKey, out var updatedRow);

                        var keepRow = this.CompareRows(targetTable, targetRow, updatedRow, out var compared);

                        if (keepRow)
                        {
                            rows.Add(compared);
                        }
                    }

                    // find the inserted rows
                    foreach (var updatedPrimaryKeyEntry in updatedPrimaryKeys)
                    {
                        var updatedPrimaryKey = updatedPrimaryKeyEntry.Key;

                        if (!targetPrimaryKeys.ContainsKey(updatedPrimaryKey))
                        {
                            var updatedRow = updatedPrimaryKeyEntry.Value;

                            updatedRow.Operation = RowOperation.Add;
                            updatedRow.SectionId = sectionDelimiter + updatedRow.SectionId;
                            rows.Add(updatedRow);
                        }
                    }
                }
            }

            return rows;
        }

        private void IndexPrimaryKeys(Table targetTable, Dictionary<string, Row> targetPrimaryKeys, Table updatedTable, Dictionary<string, Row> updatedPrimaryKeys)
        {
            // index the target rows
            foreach (var row in targetTable.Rows)
            {
                this.AddIndexedRow(targetPrimaryKeys, row);

                if ("Property" == targetTable.Name)
                {
                    var id = row.FieldAsString(0);

                    if ("ProductCode" == id)
                    {
                        this.transformSummaryInfo.TargetProductCode = row.FieldAsString(1);

                        if ("*" == this.transformSummaryInfo.TargetProductCode)
                        {
                            this.messaging.Write(ErrorMessages.ProductCodeInvalidForTransform(row.SourceLineNumbers));
                        }
                    }
                    else if ("ProductVersion" == id)
                    {
                        this.transformSummaryInfo.TargetProductVersion = row.FieldAsString(1);
                    }
                    else if ("UpgradeCode" == id)
                    {
                        this.transformSummaryInfo.TargetUpgradeCode = row.FieldAsString(1);
                    }
                }
                else if ("_SummaryInformation" == targetTable.Name)
                {
                    var id = row.FieldAsInteger(0);

                    if (1 == id) // PID_CODEPAGE
                    {
                        this.transformSummaryInfo.TargetSummaryInfoCodepage = row.FieldAsString(1);
                    }
                    else if (7 == id) // PID_TEMPLATE
                    {
                        this.transformSummaryInfo.TargetPlatformAndLanguage = row.FieldAsString(1);
                    }
                    else if (14 == id) // PID_PAGECOUNT
                    {
                        this.transformSummaryInfo.TargetMinimumVersion = row.FieldAsString(1);
                    }
                }
            }

            // index the updated rows
            foreach (var row in updatedTable.Rows)
            {
                this.AddIndexedRow(updatedPrimaryKeys, row);

                if ("Property" == updatedTable.Name)
                {
                    var id = row.FieldAsString(0);

                    if ("ProductCode" == id)
                    {
                        this.transformSummaryInfo.UpdatedProductCode = row.FieldAsString(1);

                        if ("*" == this.transformSummaryInfo.UpdatedProductCode)
                        {
                            this.messaging.Write(ErrorMessages.ProductCodeInvalidForTransform(row.SourceLineNumbers));
                        }
                    }
                    else if ("ProductVersion" == id)
                    {
                        this.transformSummaryInfo.UpdatedProductVersion = row.FieldAsString(1);
                    }
                }
                else if ("_SummaryInformation" == updatedTable.Name)
                {
                    var id = row.FieldAsInteger(0);

                    if (1 == id) // PID_CODEPAGE
                    {
                        this.transformSummaryInfo.UpdatedSummaryInfoCodepage = row.FieldAsString(1);
                    }
                    else if (7 == id) // PID_TEMPLATE
                    {
                        this.transformSummaryInfo.UpdatedPlatformAndLanguage = row.FieldAsString(1);
                    }
                    else if (14 == id) // PID_PAGECOUNT
                    {
                        this.transformSummaryInfo.UpdatedMinimumVersion = row.FieldAsString(1);
                    }
                }
            }
        }

        private void UpdateTransformSummaryInformationTable(Table summaryInfoTable, TransformFlags validationFlags)
        {
            // calculate the minimum version of MSI required to process the transform
            var minimumVersion = 100;

            if (Int32.TryParse(this.transformSummaryInfo.TargetMinimumVersion, out var targetMin) && Int32.TryParse(this.transformSummaryInfo.UpdatedMinimumVersion, out var updatedMin))
            {
                minimumVersion = Math.Max(targetMin, updatedMin);
            }

            var summaryRows = new Dictionary<int, Row>(summaryInfoTable.Rows.Count);

            foreach (var row in summaryInfoTable.Rows)
            {
                var id = row.FieldAsInteger(0);

                summaryRows[id] = row;

                if ((int)SummaryInformation.Transform.CodePage == id)
                {
                    row.Fields[1].Data = this.transformSummaryInfo.UpdatedSummaryInfoCodepage;
                    row.Fields[1].PreviousData = this.transformSummaryInfo.TargetSummaryInfoCodepage;
                }
                else if ((int)SummaryInformation.Transform.TargetPlatformAndLanguage == id)
                {
                    row[1] = this.transformSummaryInfo.TargetPlatformAndLanguage;
                }
                else if ((int)SummaryInformation.Transform.UpdatedPlatformAndLanguage == id)
                {
                    row[1] = this.transformSummaryInfo.UpdatedPlatformAndLanguage;
                }
                else if ((int)SummaryInformation.Transform.ProductCodes == id)
                {
                    row[1] = String.Concat(this.transformSummaryInfo.TargetProductCode, this.transformSummaryInfo.TargetProductVersion, ';', this.transformSummaryInfo.UpdatedProductCode, this.transformSummaryInfo.UpdatedProductVersion, ';', this.transformSummaryInfo.TargetUpgradeCode);
                }
                else if ((int)SummaryInformation.Transform.InstallerRequirement == id)
                {
                    row[1] = minimumVersion.ToString(CultureInfo.InvariantCulture);
                }
                else if ((int)SummaryInformation.Transform.Security == id)
                {
                    row[1] = "4";
                }
            }

            if (!summaryRows.ContainsKey((int)SummaryInformation.Transform.TargetPlatformAndLanguage))
            {
                var summaryRow = summaryInfoTable.CreateRow(null);
                summaryRow[0] = (int)SummaryInformation.Transform.TargetPlatformAndLanguage;
                summaryRow[1] = this.transformSummaryInfo.TargetPlatformAndLanguage;
            }

            if (!summaryRows.ContainsKey((int)SummaryInformation.Transform.UpdatedPlatformAndLanguage))
            {
                var summaryRow = summaryInfoTable.CreateRow(null);
                summaryRow[0] = (int)SummaryInformation.Transform.UpdatedPlatformAndLanguage;
                summaryRow[1] = this.transformSummaryInfo.UpdatedPlatformAndLanguage;
            }

            if (!summaryRows.ContainsKey((int)SummaryInformation.Transform.ValidationFlags))
            {
                var summaryRow = summaryInfoTable.CreateRow(null);
                summaryRow[0] = (int)SummaryInformation.Transform.ValidationFlags;
                summaryRow[1] = ((int)validationFlags).ToString(CultureInfo.InvariantCulture);
            }

            if (!summaryRows.ContainsKey((int)SummaryInformation.Transform.InstallerRequirement))
            {
                var summaryRow = summaryInfoTable.CreateRow(null);
                summaryRow[0] = (int)SummaryInformation.Transform.InstallerRequirement;
                summaryRow[1] = minimumVersion.ToString(CultureInfo.InvariantCulture);
            }

            if (!summaryRows.ContainsKey((int)SummaryInformation.Transform.Security))
            {
                var summaryRow = summaryInfoTable.CreateRow(null);
                summaryRow[0] = (int)SummaryInformation.Transform.Security;
                summaryRow[1] = "4";
            }
        }

        private class SummaryInformationStreams
        {
            public string TargetSummaryInfoCodepage { get; set; }

            public string TargetPlatformAndLanguage { get; set; }

            public string TargetProductCode { get; set; }

            public string TargetProductVersion { get; set; }

            public string TargetUpgradeCode { get; set; }

            public string TargetMinimumVersion { get; set; }

            public string UpdatedSummaryInfoCodepage { get; set; }

            public string UpdatedPlatformAndLanguage { get; set; }

            public string UpdatedProductCode { get; set; }

            public string UpdatedProductVersion { get; set; }

            public string UpdatedMinimumVersion { get; set; }
        }
    }
}