forked from OctopusDeploy/Calamari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.cake
372 lines (321 loc) · 12.6 KB
/
build.cake
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
//////////////////////////////////////////////////////////////////////
// TOOLS
//////////////////////////////////////////////////////////////////////
#tool "nuget:?package=GitVersion.CommandLine&version=4.0.0-beta0012"
#addin "nuget:?package=Cake.Incubator&version=5.0.1"
using Path = System.IO.Path;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var testFilter = Argument("where", "");
var signingCertificatePath = Argument("signing_certificate_path", "");
var signingCertificatePassword = Argument("signing_certificate_password", "");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var localPackagesDir = "../LocalPackages";
var sourceFolder = "./source/";
var artifactsDir = "./artifacts";
var publishDir = "./publish";
var signToolPath = MakeAbsolute(File("./certificates/signtool.exe"));
GitVersion gitVersionInfo;
string nugetVersion;
// From time to time the timestamping services go offline, let's try a few of them so our builds are more resilient
var timestampUrls = new string[]
{
"http://timestamp.globalsign.com/scripts/timestamp.dll",
"http://www.startssl.com/timestamp",
"http://timestamp.comodoca.com/rfc3161",
"http://timestamp.verisign.com/scripts/timstamp.dll",
"http://tsa.starfieldtech.com"
};
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(context =>
{
gitVersionInfo = GitVersion(new GitVersionSettings {
OutputType = GitVersionOutput.Json,
LogFilePath = "gitversion.log"
});
nugetVersion = gitVersionInfo.NuGetVersion;
Information("Building Calamari v{0}", nugetVersion);
});
Teardown(context =>
{
Information("Finished running tasks.");
});
//////////////////////////////////////////////////////////////////////
// PRIVATE TASKS
//////////////////////////////////////////////////////////////////////
Task("SetTeamCityVersion")
.Does(() => {
if(BuildSystem.IsRunningOnTeamCity)
BuildSystem.TeamCity.SetBuildNumber(gitVersionInfo.NuGetVersion);
});
Task("Clean")
.IsDependentOn("SetTeamCityVersion")
.Does(() =>
{
CleanDirectories(publishDir);
CleanDirectories(artifactsDir);
CleanDirectories("./**/bin");
CleanDirectories("./**/obj");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() => DotNetCoreRestore("source", new DotNetCoreRestoreSettings
{
ArgumentCustomization = args => args.Append($"--verbosity normal")
}));
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetCoreBuild("./source/Calamari.sln", new DotNetCoreBuildSettings
{
Configuration = configuration,
ArgumentCustomization = args => args.Append($"/p:Version={nugetVersion}").Append($"--verbosity normal")
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var projects = GetFiles("./source/**/*Tests.csproj");
foreach(var project in projects)
DotNetCoreTest(project.FullPath, new DotNetCoreTestSettings
{
Configuration = configuration,
NoBuild = true,
ArgumentCustomization = args => {
if(!string.IsNullOrEmpty(testFilter)) {
args = args.Append("--where").AppendQuoted(testFilter);
}
return args.Append("--logger:trx")
.Append($"--verbosity normal");
}
});
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
DoPackage("Calamari", "net40", nugetVersion);
DoPackage("Calamari", "net452", nugetVersion, "Cloud");
Zip("./source/Calamari.Tests/bin/Release/net452/", Path.Combine(artifactsDir, "Binaries.zip"));
// Create a portable .NET Core package
DoPackage("Calamari", "netcoreapp2.2", nugetVersion, "portable");
// Create the self-contained Calamari packages for each runtime ID defined in Calamari.csproj
foreach(var rid in GetProjectRuntimeIds(@".\source\Calamari\Calamari.csproj"))
{
DoPackage("Calamari", "netcoreapp2.2", nugetVersion, rid);
}
// Create a Zip for each runtime for testing
foreach(var rid in GetProjectRuntimeIds(@".\source\Calamari.Tests\Calamari.Tests.csproj"))
{
var publishedLocation = DoPublish("Calamari.Tests", "netcoreapp2.2", nugetVersion, rid);
var zipName = $"Calamari.Tests.netcoreapp2.{rid}.{nugetVersion}.zip";
Zip(Path.Combine(publishedLocation, rid), Path.Combine(artifactsDir, zipName));
}
});
Task("CopyToLocalPackages")
.WithCriteria(BuildSystem.IsLocalBuild)
.IsDependentOn("Pack")
.Does(() =>
{
CreateDirectory(localPackagesDir);
CopyFiles(Path.Combine(artifactsDir, $"Calamari.*.nupkg"), localPackagesDir);
});
private string DoPublish(string project, string framework, string version, string runtimeId = null) {
var projectDir = Path.Combine("./source", project);
var publishedTo = Path.Combine(publishDir, project, framework);
var publishSettings = new DotNetCorePublishSettings
{
Configuration = configuration,
OutputDirectory = publishedTo,
Framework = framework,
ArgumentCustomization = args => args.Append($"/p:Version={nugetVersion}").Append($"--verbosity normal")
};
if (!string.IsNullOrEmpty(runtimeId))
{
publishSettings.OutputDirectory = Path.Combine(publishedTo, runtimeId);
// "portable" is not an actual runtime ID. We're using it to represent the portable .NET core build.
publishSettings.Runtime = (runtimeId != null && runtimeId != "portable") ? runtimeId : null;
}
DotNetCorePublish(projectDir, publishSettings);
SignAndTimestampBinaries(publishSettings.OutputDirectory.FullPath);
return publishedTo;
}
private void DoPackage(string project, string framework, string version, string runtimeId = null)
{
var publishedTo = Path.Combine(publishDir, project, framework);
var projectDir = Path.Combine("./source", project);
var packageId = $"{project}";
var nugetPackProperties = new Dictionary<string,string>();
var publishSettings = new DotNetCorePublishSettings
{
Configuration = configuration,
OutputDirectory = publishedTo,
Framework = framework,
ArgumentCustomization = args => args.Append($"/p:Version={nugetVersion}").Append($"--verbosity normal")
};
if (!string.IsNullOrEmpty(runtimeId))
{
publishedTo = Path.Combine(publishedTo, runtimeId);
publishSettings.OutputDirectory = publishedTo;
// "portable" is not an actual runtime ID. We're using it to represent the portable .NET core build.
publishSettings.Runtime = (runtimeId != null && runtimeId != "portable") ? runtimeId : null;
packageId = $"{project}.{runtimeId}";
nugetPackProperties.Add("runtimeId", runtimeId);
}
var nugetPackSettings = new NuGetPackSettings
{
Id = packageId,
OutputDirectory = artifactsDir,
BasePath = publishedTo,
Version = nugetVersion,
Verbosity = NuGetVerbosity.Normal,
Properties = nugetPackProperties
};
DotNetCorePublish(projectDir, publishSettings);
SignAndTimestampBinaries(publishSettings.OutputDirectory.FullPath);
var nuspec = $"{publishedTo}/{packageId}.nuspec";
CopyFile($"{projectDir}/{project}.nuspec", nuspec);
NuGetPack(nuspec, nugetPackSettings);
}
private void SignAndTimestampBinaries(string outputDirectory)
{
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*.exe",
outputDirectory + "/Calamari*.dll",
outputDirectory + "/Octo*.exe",
outputDirectory + "/Octo*.dll")
.Where(f => !HasAuthenticodeSignature(f))
.ToArray();
Information($"Using signtool in {signToolPath}");
SignFiles(unsignedExecutablesAndLibraries, signingCertificatePath, signingCertificatePassword);
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 SignFiles(IEnumerable<FilePath> files, FilePath certificatePath, string certificatePassword, string display = "", string displayUrl = "")
{
if (!FileExists(signToolPath))
{
throw new Exception($"The signing tool was expected to be at the path '{signToolPath}' but wasn't available.");
}
if (!FileExists(certificatePath))
throw new Exception($"The code-signing certificate was not found at {certificatePath}.");
Information($"Signing {files.Count()} files using certificate at '{certificatePath}'...");
var signArguments = new ProcessArgumentBuilder()
.Append("sign")
.Append("/fd SHA256")
.Append("/f").AppendQuoted(certificatePath.FullPath)
.Append($"/p").AppendQuotedSecret(certificatePassword);
if (!string.IsNullOrWhiteSpace(display))
{
signArguments
.Append("/d").AppendQuoted(display)
.Append("/du").AppendQuoted(displayUrl);
}
foreach (var file in files)
{
signArguments.AppendQuoted(file.FullPath);
}
Information($"Executing: {signToolPath} {signArguments.RenderSafe()}");
var exitCode = StartProcess(signToolPath, new ProcessSettings
{
Arguments = signArguments
});
if (exitCode != 0)
{
throw new Exception($"Signing files failed with the exit code {exitCode}. Look for 'SignTool Error' in the logs.");
}
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);
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.");
}
// Returns the runtime identifiers from the project file
private IEnumerable<string> GetProjectRuntimeIds(string projectFile)
{
var doc = new XmlDocument();
doc.Load(projectFile);
var rids = doc.SelectSingleNode("Project/PropertyGroup/RuntimeIdentifiers").InnerText;
return rids.Split(';');
}
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("SetTeamCityVersion")
.IsDependentOn("CopyToLocalPackages");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);