-
Notifications
You must be signed in to change notification settings - Fork 296
/
BuildRegistryScript.ps1
304 lines (265 loc) · 9.75 KB
/
BuildRegistryScript.ps1
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
# The parameters should be supplied by the Build event of the project
# in order to take macros from Visual Studio to avoid hard-coding
# the paths. To simplify the process, the project should have a
# reference to the projects that needs to be registered, so that
# their DLL files will be present in the $(TargetDir) macro.
#
# Possible syntax for Post Build event of the project to invoke this:
# C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
# -command "$(ProjectDir)BuildRegistryScript.ps1
# -config '$(ConfigurationName)'
# -builderAssemblyPath '$(TargetPath)'
# -netToolsDir '$(FrameworkSDKDir)bin\NETFX 4.6.1 Tools\'
# -wixToolsDir '$(SolutionDir)packages\WiX.Toolset.3.9.1208.0\tools\wix\'
# -sourceDir '$(TargetDir)'
# -targetDir '$(TargetDir)'
# -projectDir '$(ProjectDir)'
# -includeDir '$(ProjectDir)InnoSetup\Includes\'
# -filesToExtract 'Rubberduck.dll'"
param (
[Parameter(Mandatory=$true)][string]$config,
[Parameter(Mandatory=$true)][string]$builderAssemblyPath,
[Parameter(Mandatory=$true)][string]$netToolsDir,
[Parameter(Mandatory=$true)][string]$wixToolsDir,
[Parameter(Mandatory=$true)][string]$sourceDir,
[Parameter(Mandatory=$true)][string]$targetDir,
[Parameter(Mandatory=$true)][string]$projectDir,
[Parameter(Mandatory=$true)][string]$includeDir,
[Parameter(Mandatory=$true)][string]$filesToExtract
)
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value;
Split-Path $Invocation.MyCommand.Path;
}
# Invokes a Cmd.exe shell script and updates the environment.
function Invoke-CmdScript {
param(
[String] $scriptName
)
$cmdLine = """$scriptName"" $args & set"
& $Env:SystemRoot\system32\cmd.exe /c $cmdLine |
select-string '^([^=]*)=(.*)$' | foreach-object {
$varName = $_.Matches[0].Groups[1].Value
$varValue = $_.Matches[0].Groups[2].Value
set-item Env:$varName $varValue
}
}
# Returns the current environment.
function Get-Environment {
get-childitem Env:
}
# Restores the environment to a previous state.
function Restore-Environment {
param(
[parameter(Mandatory=$TRUE)]
[System.Collections.DictionaryEntry[]] $oldEnv
)
# Remove any added variables.
compare-object $oldEnv $(Get-Environment) -property Key -passthru |
where-object { $_.SideIndicator -eq "=>" } |
foreach-object { remove-item Env:$($_.Name) }
# Revert any changed variables to original values.
compare-object $oldEnv $(Get-Environment) -property Value -passthru |
where-object { $_.SideIndicator -eq "<=" } |
foreach-object { set-item Env:$($_.Name) $_.Value }
}
# Remove older imported registry scripts for debug builds.
function Clean-OldImports
{
param(
[String] $dir
)
$i = 0;
Get-ChildItem $dir -Filter DebugRegistryEntries.reg.imported_*.txt |
Sort-Object Name -Descending |
Foreach-Object {
if($i -ge 10) {
$_.Delete();
}
$i++;
}
}
Set-StrictMode -Version latest;
$ErrorActionPreference = "Stop";
$DebugUnregisterRun = $false;
try
{
# Clean imports older than 10 builds
Clean-OldImports ((Get-ScriptDirectory) + "\LocalRegistryEntries");;
# Allow multiple DLL files to be registered if necessary
$separator = "|";
$option = [System.StringSplitOptions]::RemoveEmptyEntries;
$files = $filesToExtract.Split($separator, $option);
# Load the Deployment DLL
[System.Reflection.Assembly]::LoadFrom($builderAssemblyPath);
# Determine if MIDL is available for building
$devPath = Resolve-Path -Path "C:\Program Files*\Microsoft Visual Studio\*\*\Common*\Tools\VsDevCmd.bat";
if($devPath)
{
# Additional verifications as some versions of VsDevCmd.bat might not initialize the environment for C++ build tools
$result = Get-Module -ListAvailable -Name "VSSetup" -ErrorAction SilentlyContinue;
if(!$result)
{
Write-Warning "VSSetup not installed; extracting...";
Expand-Archive "$projectDir\OleWoo\VSSetup.zip" "$([Environment]::GetFolderPath("MyDocuments"))\WindowsPowerShell\Modules\VSSetup" -Force
}
try {
Import-Module VSSetup -Force:$true;
$result = Get-VSSetupInstance | Select-VSSetupInstance -Latest -Require Microsoft.VisualStudio.Component.VC.Tools.x86.x64;
} catch {
$result = $null;
Write-Warning "Error occurred with using VSSetup module";
Write-Error ($_);
}
if(!$result)
{
$devPath = $null;
Write-Warning "Cannot locate the VS Setup instance capable of building with C++ build tools";
}
}
if(!$devPath)
{
Write-Warning "Cannot locate the VsDevCmd.bat to initialize C++ build tools; falling back to tlbexp.exe....";
}
Write-Host "";
foreach($file in $files)
{
Write-Host "Processing '$file'";
Write-Host "";
$dllFile = [System.String]$file;
$idlFile = [System.String]($file -replace ".dll", ".idl");
$tlb32File = [System.String]($file -replace ".dll", ".x32.tlb");
$tlb64File = [System.String]($file -replace ".dll", ".x64.tlb");
$sourceDll = $sourceDir + $file;
$targetDll = $targetDir + $file;
$sourceTlb32 = $sourceDir + $tlb32File;
$targetTlb32 = $targetDir + $tlb32File;
$sourceTlb64 = $sourceDir + $tlb64File;
$targetTlb64 = $targetDir + $tlb64File;
$dllXml = $targetDll + ".xml";
$tlbXml = $targetTlb32 + ".xml";
# Write-Host "Variable printout:"
# Write-Host "dllFile = $dllFile";
# Write-Host "idlFile = $idlFile";
# Write-Host "tlb32File = $tlb32File";
# Write-Host "tlb64File = $tlb64File";
# Write-Host "sourceDll = $sourceDll";
# Write-Host "targetDll = $targetDll";
# Write-Host "sourceTlb32 = $sourceTlb32";
# Write-Host "targetTlb32 = $targetTlb32";
# Write-Host "sourceTlb64 = $sourceTlb64";
# Write-Host "targetTlb64 = $targetTlb64";
# Write-Host "dllXml = $dllXml";
# Write-Host "tlbXml = $tlbXml";
# Write-Host "targetDir = $targetDir";
# Write-Host "";
# Use for debugging issues with passing parameters to the external programs
# Note that it is not legal to have syntax like `& $cmdIncludingArguments` or `& $cmd $args`
# For simplicity, the arguments are pass in literally.
# & "C:\GitHub\Rubberduck\Rubberduck\Rubberduck.Deployment\echoargs.exe" ""$sourceDll"" /win32 /out:""$sourceTlb"";
# Compile TLB files using MIDL
if($devPath)
{
$idlGenerator = New-Object Rubberduck.Deployment.IdlGeneration.IdlGenerator;
$idl = $idlGenerator.GenerateIdl($sourceDll);
$encoding = New-Object System.Text.UTF8Encoding $true;
[System.IO.File]::WriteAllLines($idlFile, $idl, $encoding);
$origEnv = Get-Environment;
try {
Invoke-CmdScript "$devPath";
if($targetDir.EndsWith("\"))
{
$targetDirWithoutSlash = $targetDir.Substring(0,$targetDir.Length-1);
}
else
{
$targetDirWithoutSlash = $targetDir;
}
& midl.exe /win32 /tlb ""$tlb32File"" ""$idlFile"" /out ""$targetDirWithoutSlash"";
& midl.exe /amd64 /tlb ""$tlb64File"" ""$idlFile"" /out ""$targetDirWithoutSlash"";
} catch {
throw;
} finally {
Restore-Environment $origEnv;
}
}
# Compile TLB files using tlbexp.exe
if(!$devPath)
{
$cmd = "{0}tlbexp.exe" -f $netToolsDir;
& $cmd ""$sourceDll"" /win32 /out:""$sourceTlb32"";
& $cmd ""$sourceDll"" /win64 /out:""$sourceTlb64"";
}
# Harvest both DLL and TLB files using WiX's heat.exe, generating XML files
$cmd = "{0}heat.exe" -f $wixToolsDir;
& $cmd file ""$sourceDll"" -out ""$dllXml"";
& $cmd file ""$sourceTlb32"" -out ""$tlbXml"";
# Initialize the registry builder with the provided XML files
$builder = New-Object Rubberduck.Deployment.Builders.RegistryEntryBuilder;
$entries = $builder.Parse($tlbXml, $dllXml);
# For debugging
# $entries | Format-Table | Out-String |% {Write-Host $_};
$writer = New-Object Rubberduck.Deployment.Writers.InnoSetupRegistryWriter;
$content = $writer.Write($entries, $dllFile, $tlb32File, $tlb64File);
# The file must be encoded in UTF-8 BOM
$regFile = ($includeDir + ($file -replace ".dll", ".reg.iss"));
$encoding = New-Object System.Text.UTF8Encoding $true;
[System.IO.File]::WriteAllLines($regFile, $content, $encoding);
$content = $null;
# Register the debug build on the local machine
if($config -eq "Debug")
{
if(!$DebugUnregisterRun)
{
# First see if there are registry script from the previous build
# If so, execute them to delete previous build's keys (which may
# no longer exist for the current build and thus won't be overwritten)
$dir = ((Get-ScriptDirectory) + "\LocalRegistryEntries");
$regFileDebug = $dir + "\DebugRegistryEntries.reg";
if (Test-Path -Path $dir -PathType Container)
{
if (Test-Path -Path $regFileDebug -PathType Leaf)
{
$datetime = Get-Date;
if ([Environment]::Is64BitOperatingSystem)
{
& reg.exe import $regFileDebug /reg:32;
& reg.exe import $regFileDebug /reg:64;
}
else
{
& reg.exe import $regFileDebug;
}
& reg.exe import ($dir + "\RubberduckAddinRegistry.reg");
Move-Item -Path $regFileDebug -Destination ($regFileDebug + ".imported_" + $datetime.ToUniversalTime().ToString("yyyyMMddHHmmss") + ".txt" );
}
}
else
{
New-Item $dir -ItemType Directory;
}
$DebugUnregisterRun = $true;
}
# NOTE: The local writer will perform the actual registry changes; the return
# is a registry script with deletion instructions for the keys to be deleted
# in the next build.
$writer = New-Object Rubberduck.Deployment.Writers.LocalDebugRegistryWriter;
$content = $writer.Write($entries, $dllFile, $tlb32File, $tlb64File);
$encoding = New-Object System.Text.ASCIIEncoding;
[System.IO.File]::AppendAllText($regFileDebug, $content, $encoding);
}
Write-Host "Finished processing '$file'";
Write-Host "";
}
Write-Host "Finished processing all files";
}
catch
{
Write-Error ($_);
# Cause the build to fail
throw;
}
# for debugging locally
# Write-Host "Press any key to continue...";
# Read-Host -Prompt "Press Enter to continue";