This repository was archived by the owner on May 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.cake
More file actions
355 lines (298 loc) · 12.3 KB
/
Copy pathbuild.cake
File metadata and controls
355 lines (298 loc) · 12.3 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
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
//////////////////////////////////////////////////////////////////////
// TOOLS
//////////////////////////////////////////////////////////////////////
#module nuget:?package=Cake.DotNetTool.Module&version=0.4.0
#tool "dotnet:?package=GitVersion.Tool&version=5.3.5"
#tool "dotnet:?package=AzureSignTool&version=3.0.0"
#addin "Cake.FileHelpers&version=3.2.0"
#addin "nuget:?package=Cake.Incubator&version=5.0.1"
#addin "nuget:?package=Cake.FileHelpers&version=4.0.1"
using Path = System.IO.Path;
using IO = System.IO;
using Cake.Common.Xml;
using System.Security.Cryptography.X509Certificates;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var signFiles = Argument<bool>("sign_files", false);
var signToolPath = MakeAbsolute(File("./certificates/signtool.exe"));
var keyVaultUrl = Argument("AzureKeyVaultUrl", "");
var keyVaultAppId = Argument("AzureKeyVaultAppId", "");
var keyVaultTenantId = Argument("AzureKeyVaultTenantId", "");
var keyVaultAppSecret = Argument("AzureKeyVaultAppSecret", "");
var keyVaultCertificateName = Argument("AzureKeyVaultCertificateName", "");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var publishDir = "./publish";
var artifactsDir = "./artifacts/";
var localPackagesDir = "../LocalPackages";
GitVersion gitVersionInfo;
string nugetVersion;
var timestampUrls = new string[]
{
"http://timestamp.digicert.com?alg=sha256",
"http://timestamp.comodoca.com"
};
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(context =>
{
gitVersionInfo = GitVersion(new GitVersionSettings {
OutputType = GitVersionOutput.Json
});
if(BuildSystem.IsRunningOnTeamCity)
BuildSystem.TeamCity.SetBuildNumber(gitVersionInfo.NuGetVersion);
nugetVersion = gitVersionInfo.NuGetVersion;
Information("Building Sashimi v{0}", nugetVersion);
Information("Informational Version {0}", gitVersionInfo.InformationalVersion);
});
Teardown(context =>
{
Information("Finished running tasks.");
});
//////////////////////////////////////////////////////////////////////
// PRIVATE TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(publishDir);
CleanDirectory(artifactsDir);
CleanDirectories("./source/**/bin");
CleanDirectories("./source/**/obj");
CleanDirectories("./source/**/TestResults");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() => {
DotNetCoreRestore("source");
});
Task("Build")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetCoreBuild("./source", new DotNetCoreBuildSettings
{
Configuration = configuration,
ArgumentCustomization = args => args.Append($"/p:Version={nugetVersion}")
});
});
Task("Test")
.IsDependentOn("Build")
.WithCriteria(BuildSystem.IsLocalBuild)
.Does(() => {
var projects = GetFiles("./source/**/*Tests.csproj");
Parallel.ForEach(projects, project => {
DotNetCoreTest(project.FullPath, new DotNetCoreTestSettings
{
Configuration = configuration,
NoBuild = true
});
});
});
Task("PublishCalamariProjects")
.IsDependentOn("Build")
.Does(() => {
var projects = GetFiles("./source/**/Calamari*.csproj"); //We need Calamari & Calamari.Tests
foreach(var project in projects)
{
var calamariFlavour = XmlPeek(project, "Project/PropertyGroup/AssemblyName");
var frameworks = XmlPeek(project, "Project/PropertyGroup/TargetFrameworks") ??
XmlPeek(project, "Project/PropertyGroup/TargetFramework");
foreach(var framework in frameworks.Split(';'))
{
void RunPublish(string runtime, string platform) {
var publishSettings = new DotNetCorePublishSettings
{
Configuration = configuration,
OutputDirectory = $"{publishDir}/{calamariFlavour}/{platform}",
Framework = framework,
Runtime = runtime
};
DotNetCorePublish(project.FullPath, publishSettings);
SignAndTimestampBinaries(publishSettings.OutputDirectory.FullPath);
CopyFiles("./global.json", $"{publishDir}/{calamariFlavour}/{platform}");
}
if(framework.Equals("net6.0"))
{
var runtimes = XmlPeek(project, "Project/PropertyGroup/RuntimeIdentifiers").Split(';');
foreach(var runtime in runtimes)
RunPublish(runtime, runtime);
}
else
{
RunPublish(null, "netfx");
}
}
Verbose($"{publishDir}/{calamariFlavour}");
Zip($"{publishDir}/{calamariFlavour}", $"{artifactsDir}{calamariFlavour}.zip");
}
});
Task("PublishSashimiTestProjects")
.IsDependentOn("Build")
.Does(() => {
var projects = GetFiles("./source/**/Sashimi.Tests.csproj");
foreach(var project in projects)
{
var sashimiFlavour = XmlPeek(project, "Project/PropertyGroup/AssemblyName");
void RunPublish() {
DotNetCorePublish(project.FullPath, new DotNetCorePublishSettings
{
Configuration = configuration,
OutputDirectory = $"{publishDir}/{sashimiFlavour}"
});
CopyFiles("./global.json", $"{publishDir}/{sashimiFlavour}");
}
RunPublish();
Verbose($"{publishDir}/{sashimiFlavour}");
Zip($"{publishDir}/{sashimiFlavour}", $"{artifactsDir}{sashimiFlavour}.zip");
}
});
Task("PackSashimi")
.IsDependentOn("PublishSashimiTestProjects")
.IsDependentOn("PublishCalamariProjects")
.Does(() =>
{
SignAndTimestampBinaries("./source/Sashimi/bin/Release/net6.0");
DotNetCorePack("source", new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = artifactsDir,
NoBuild = false, // Don't change this flag we need it because of https://github.com/dotnet/msbuild/issues/5566
IncludeSource = true,
ArgumentCustomization = args => args.Append($"/p:Version={nugetVersion}")
});
DeleteFiles(artifactsDir + "*symbols*");
});
Task("CopyToLocalPackages")
.IsDependentOn("Test")
.IsDependentOn("PackSashimi")
.WithCriteria(BuildSystem.IsLocalBuild)
.Does(() =>
{
CreateDirectory(localPackagesDir);
CopyFiles(Path.Combine(artifactsDir, $"Sashimi.*.{nugetVersion}.nupkg"), localPackagesDir);
});
Task("Default")
.IsDependentOn("CopyToLocalPackages");
void SignAndPack(string project, string binPath, DotNetCorePackSettings dotNetCorePackSettings){
Information("SignAndPack project: " + project);
Information("SignAndPack bin path: " + binPath);
SignAndTimestampBinaries(binPath);
DotNetCorePack(project, dotNetCorePackSettings);
}
private void SignAndTimestampBinaries(string outputDirectory)
{
if (BuildSystem.IsLocalBuild && !signFiles) return;
Information($"Signing binaries in {outputDirectory}");
// check that any unsigned libraries, that Octopus Deploy authors, get signed to play nice with security scanning tools
// refer: https://octopusdeploy.slack.com/archives/C0K9DNQG5/p1551655877004400
// decision re: no signing everything: https://octopusdeploy.slack.com/archives/C0K9DNQG5/p1557938890227100
var unsignedExecutablesAndLibraries =
GetFiles(outputDirectory + "/{Calamari,Sashimi}*.{exe,dll}")
.Where(f => !HasAuthenticodeSignature(f))
.ToArray();
Information("Signing files using azuresigntool and the production code signing certificate");
SignFilesWithAzureSignTool(unsignedExecutablesAndLibraries, keyVaultUrl, keyVaultAppId, keyVaultTenantId, keyVaultAppSecret, keyVaultCertificateName);
TimeStampFiles(unsignedExecutablesAndLibraries);
}
// note: Doesn't check if existing signatures are valid, only that one exists
// source: https://blogs.msdn.microsoft.com/windowsmobile/2006/05/17/programmatically-checking-the-authenticode-signature-on-a-file/
private bool HasAuthenticodeSignature(FilePath filePath)
{
try
{
X509Certificate.CreateFromSignedFile(filePath.FullPath);
return true;
}
catch
{
return false;
}
}
void SignFilesWithAzureSignTool(IEnumerable<FilePath> files, string vaultUrl, string vaultAppId, string vaultTenantId, string vaultAppSecret, string vaultCertificateName, string display = "", string displayUrl = "")
{
var signArguments = new ProcessArgumentBuilder()
.Append("sign")
.Append("--azure-key-vault-url").AppendQuoted(vaultUrl)
.Append("--azure-key-vault-client-id").AppendQuoted(vaultAppId)
.Append("--azure-key-vault-tenant-id").AppendQuoted(vaultTenantId)
.Append("--azure-key-vault-client-secret").AppendQuotedSecret(vaultAppSecret)
.Append("--azure-key-vault-certificate").AppendQuoted(vaultCertificateName)
.Append("--file-digest sha256");
if (!string.IsNullOrWhiteSpace(display))
{
signArguments
.Append("--description").AppendQuoted(display)
.Append("--description-url").AppendQuoted(displayUrl);
}
foreach (var file in files)
{
Information("Adding file to sign: " + file.FullPath);
signArguments.AppendQuoted(file.FullPath);
}
var azureSignToolPath = MakeAbsolute(File("./tools/azuresigntool.exe"));
if (!FileExists(azureSignToolPath))
throw new Exception($"The azure signing tool was expected to be at the path '{azureSignToolPath}' but wasn't available.");
Information($"Executing: {azureSignToolPath} {signArguments.RenderSafe()}");
var exitCode = StartProcess(azureSignToolPath.FullPath, signArguments.Render());
if (exitCode != 0)
throw new Exception($"AzureSignTool failed with the exit code {exitCode}.");
Information($"Finished signing {files.Count()} files.");
}
private void TimeStampFiles(IEnumerable<FilePath> files)
{
if (!FileExists(signToolPath))
{
throw new Exception($"The signing tool was expected to be at the path '{signToolPath}' but wasn't available.");
}
Information($"Timestamping {files.Count()} files...");
var timestamped = false;
foreach (var url in timestampUrls)
{
var timestampArguments = new ProcessArgumentBuilder()
.Append($"timestamp")
.Append("/tr").AppendQuoted(url)
.Append("/td").Append("sha256");
foreach (var file in files)
{
timestampArguments.AppendQuoted(file.FullPath);
}
try
{
Information($"Executing: {signToolPath} {timestampArguments.RenderSafe()}");
var exitCode = StartProcess(signToolPath, new ProcessSettings
{
Arguments = timestampArguments
});
if (exitCode == 0)
{
timestamped = true;
break;
}
else
{
throw new Exception($"Timestamping files failed with the exit code {exitCode}. Look for 'SignTool Error' in the logs.");
}
}
catch (Exception ex)
{
Warning(ex.Message);
Warning($"Failed to timestamp files using {url}. Maybe we can try another timestamp service...");
}
}
if (!timestamped)
{
throw new Exception($"Failed to timestamp files even after we tried all of the timestamp services we use.");
}
Information($"Finished timestamping {files.Count()} files.");
}
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);