-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMsiEngine.cs
More file actions
280 lines (228 loc) · 10.8 KB
/
MsiEngine.cs
File metadata and controls
280 lines (228 loc) · 10.8 KB
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
#region copyright
/*
MsiEngine.cs is part of SimpleMSI.
Copyright (C) 2025 Julian Rossbach
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#endregion
using System.Text.RegularExpressions;
using WixSharp;
using WixSharp.CommonTasks;
namespace SimpleMSI;
/// <summary>
/// The main class for configuring and building MSIs.
/// </summary>
public class MsiEngine(PrintContext print = default)
{
private static bool _configApplied = false;
/// <summary>
/// Applies global configuration to the WixSharp compiler. This is persistent across all MsiEngine instances.
/// </summary>
/// <param name="enableVerbose">Enable verbose WiX output.</param>
/// <param name="force">Apply configuration even if it already was before.</param>
public static void ApplyGlobalConfiguration(bool enableVerbose, bool force = false)
{
if (_configApplied && !force)
{
throw new InvalidOperationException("Global configuration shouldn't be applied twice");
}
Compiler.AllowNonRtfLicense = true;
Compiler.SignAllFilesOptions.SignEmbeddedAssemblies = true;
Compiler.SignAllFilesOptions.SkipSignedFiles = true;
Compiler.VerboseOutput = enableVerbose;
_configApplied = true;
}
private Project? _msi;
public void ConfigureMsi(Config config)
{
// Regex matches if the name contains only letters and numbers
if (!Regex.IsMatch(config.General.Name, Config.GeneralConfig.NameValidationRegex))
{
throw new ArgumentException("Name may not be empty or contain whitespaces", nameof(config));
}
var scope = config.General.GetInstallScope() ??
throw new ArgumentException("Install Scope is not valid", nameof(config));
print.VerboseLine("Configuring msi files...");
if (config.Installation?.Destination is var installDestination && string.IsNullOrWhiteSpace(installDestination))
{
switch (scope)
{
case InstallScope.perMachine: installDestination = "%ProgramFiles%\\"; break;
case InstallScope.perUser: installDestination = "%LocalAppData%\\Programs\\"; break;
default: throw new InvalidOperationException("What the hell just happened"); //should never happen
}
if (!string.IsNullOrWhiteSpace(config.Metadata?.Manufacturer))
{
installDestination += config.Metadata.Manufacturer + '\\';
}
installDestination += config.General.Name;
}
var installFiles = (config.Installation?.Files ?? []).Select(f => (new WixSharp.File(f)) as WixEntity);
var installDirs = (config.Installation?.Dirs ?? []).Select(d =>
{
bool recursive = config.Installation?.DirsRecursive != false;
return (recursive ? new Files(d) as WixEntity : new DirFiles(d));
});
InstallDir installDir = new(installDestination, installFiles.Concat(installDirs).ToArray());
var upgrade = MajorUpgrade.Default;
if (config.General.AllowDowngrades == true)
{
upgrade.AllowDowngrades = true;
}
// Since AllowDowngrades takes precedence, only set AllowSameVersionUpgrades if downgrades are not allowed
if (config.General.AllowSameVersionUpgrades == true
&& config.General.AllowDowngrades != true)
{
upgrade.AllowSameVersionUpgrades = true;
}
print.VerboseLine("Configuring msi...");
_msi = new(config.Metadata?.DisplayName ?? config.General.Name, installDir)
{
GUID = config.General.GetGuid() ??
throw new ArgumentException("Main GUID is not valid", nameof(config)),
Platform = config.General.GetWixPlatform() ??
throw new ArgumentException("Platform is not valid", nameof(config)),
Version = config.General.GetVersion() ??
throw new ArgumentException("Version is not valid", nameof(config)),
Scope = scope,
UI = config.General.GetWixUiMode() ??
throw new ArgumentException("UI Mode is not valid", nameof(config)),
Description = config.Metadata?.Description ?? string.Empty,
MajorUpgrade = upgrade
};
_msi.ResolveWildCards();
print.VerboseLine("Configuring code signing...");
if (config.Installation?.Signing is not null)
{
var signature = new DigitalSignature()
{
CertificateId = config.Installation.Signing.CertificateName,
Password = config.Installation.Signing.Password,
Description = config.Installation.Signing.Description,
WellKnownLocations = config.Installation.Signing.SignToolLocation,
OptionalArguments = config.Installation.Signing.ExtraArguments,
OutputLevel = print.IsVerbose ? SignOutputLevel.Verbose : SignOutputLevel.Minimal
};
if (config.Installation.Signing.TimeUrl is {} url)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
throw new ArgumentException("Timestamp URL is not valid", nameof(config));
signature.TimeUrl = new Uri(url);
}
signature.HashAlgorithm = config.Installation.Signing.GetHashAlgorithm() ??
throw new ArgumentException("Signing has algorithm is invalid", nameof(config));
signature.CertificateStore = config.Installation.Signing.GetStoreType() ??
throw new ArgumentException("Signing certificate store is invalid", nameof(config));
_msi.DigitalSignature = signature;
_msi.SignAllFiles = config.Installation.Signing.SignEmbeddedFiles == true;
}
foreach (var shortcut in config.Installation?.Shortcuts ?? [])
{
var files = _msi.FindFile(f => f.Name.EndsWith(shortcut.TargetFile));
if (files.Length <= 0)
{
throw new FileNotFoundException("Shortcut file not found", shortcut.TargetFile);
}
if (files.Length > 1)
{
print.OutLine($"Warning: {files.Length} files found for shortcut for {shortcut.TargetFile}, using first hit");
}
files[0].AddShortcut(new(shortcut.Name ?? _msi.Name, shortcut.Location ?? "ProgramMenuFolder"));
}
foreach (var @var in config.Installation?.EnvironmentVariables ?? [])
{
var part = @var.GetEnvVarPart() ?? throw new ArgumentException($"Env var part for variable {@var.Name} not valid", nameof(config));
_msi.Add(
new EnvironmentVariable(@var.Name, @var.Value.Replace("@", "[INSTALLDIR]"))
{
Part = part
}
);
}
if (config.General.Reboot == true)
{
_msi.ScheduleReboot = new();
}
if (config.Metadata?.LicenseFilePath is var license && license is not null && !Path.Exists(license))
{
throw new FileNotFoundException("License file not found", license);
}
_msi.LicenceFile = license ?? string.Empty;
if (config.Metadata?.BannerImagePath is var banner && banner is not null && !Path.Exists(banner))
{
throw new FileNotFoundException("Banner image not found", banner);
}
_msi.BannerImage = banner ?? string.Empty;
if (config.Metadata?.DialogImagePath is var dialog && dialog is not null && !Path.Exists(dialog))
{
throw new FileNotFoundException("Dialog image not found", dialog);
}
_msi.BackgroundImage = dialog ?? string.Empty;
_msi.ControlPanelInfo = new()
{
InstallLocation = "[INSTALLDIR]",
Manufacturer = config.Metadata?.Manufacturer ?? config.General.Name,
Comments = config.Metadata?.Description,
HelpLink = config.Metadata?.HelpUrl,
UrlInfoAbout = config.Metadata?.AboutUrl,
UrlUpdateInfo = config.Metadata?.UpdateUrl,
NoModify = config.Metadata?.ForbidModify == true ? true : null, // WiX seems to expect null and not false, which is... odd.
NoRepair = config.Metadata?.ForbidRepair == true ? true : null,
NoRemove = config.Metadata?.ForbidUninstall == true ? true : null,
SystemComponent = config.Metadata?.HideProgramEntry == true ? true : null,
};
if (config.Metadata?.ProductIconPath is var icon && icon is not null && !Path.Exists(icon))
{
throw new FileNotFoundException("Product icon not found", icon);
}
_msi.ControlPanelInfo.ProductIcon = icon;
var outFile = config.General.OutFileName;
if (string.IsNullOrWhiteSpace(outFile))
{
var filename =
$"{config.General.Name}-{config.General.Version ?? "1.0.0"}-{config.General.Platform ?? "x64"}";
var currentDir = Environment.CurrentDirectory;
outFile = Path.Combine(currentDir, filename);
print.VerboseLine($"No output file specified, using '{outFile}'");
}
if (outFile.EndsWith(".msi"))
{
outFile = outFile[..^4]; // Remove .msi extension since WixSharp adds it automatically
}
if (Path.GetDirectoryName(outFile) is var dir && !string.IsNullOrEmpty(dir))
{
_msi.OutDir = dir;
}
if (Path.GetFileName(outFile) is var file && string.IsNullOrEmpty(file))
{
throw new ArgumentException("Filename is not valid", nameof(config));
}
_msi.OutFileName = file;
}
public void BuildMsi()
{
if (_msi is null)
{
throw new InvalidOperationException("MSI not configured");
}
_msi.BuildMsi();
}
public void BuildMsiCmd()
{
if (_msi is null)
{
throw new InvalidOperationException("MSI not configured");
}
_msi.BuildMsiCmd();
}
public void BuildWxs()
{
if (_msi is null)
{
throw new InvalidOperationException("MSI not configured");
}
_msi.BuildWxs();
}
}