forked from aaubry/YamlDotNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.cake
470 lines (398 loc) · 15.8 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
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
#tool "nuget:?package=xunit.runner.console&version=2.4.1"
#tool "nuget:?package=Mono.TextTransform&version=1.0.0"
#tool "nuget:?package=GitVersion.CommandLine&version=4.0.0"
#addin "nuget:?package=Cake.Incubator&version=4.0.1"
#addin "nuget:?package=Cake.SemVer&version=3.0.0"
#addin "nuget:?package=semver&version=2.0.4"
#addin "nuget:?package=ConsoleMenuLib&version=3.2.1"
#addin "nuget:?package=System.Interactive.Async&version=3.2.0"
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Cake.Incubator.LoggingExtensions;
using ConsoleUi;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var buildVerbosity = (Verbosity)Enum.Parse(typeof(Verbosity), Argument("buildVerbosity", "Minimal"), ignoreCase: true);
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
var solutionPath = "./YamlDotNet.sln";
var releaseConfigurations = new List<string>
{
"Release"
};
if (!IsRunningOnWindows())
{
// AOT requires mono
releaseConfigurations.Add("Debug-AOT");
}
GitVersion version = null;
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Fix-GitVersionOnLinux")
.Description("Workaround to use GitVersion on Linux (and Docker)")
.WithCriteria(IsRunningOnUnix())
.Does(() =>
{
var libGitFiles = GetFiles("/usr/lib/x86_64-linux-gnu/libgit2.so.*");
var libGitPath = libGitFiles.FirstOrDefault();
if (libGitPath != null)
{
Information("Found libgit at '{0}'", libGitPath);
XmlPoke("tools/GitVersion.CommandLine.4.0.0/tools/LibGit2Sharp.dll.config", "/configuration/dllmap[@os='linux']/@target", libGitPath.FullPath);
}
else
{
Warning("Could not find libgit in '/usr/lib/x86_64-linux-gnu/libgit2.so.*'");
}
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new[]
{
"./YamlDotNet/bin",
"./YamlDotNet.AotTest/bin",
"./YamlDotNet.Samples/bin",
"./YamlDotNet.Test/bin",
"./YamlDotNet/obj",
"./YamlDotNet.AotTest/obj",
"./YamlDotNet.Samples/obj",
"./YamlDotNet.Test/obj",
});
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solutionPath);
});
Task("Get-Version")
.IsDependentOn("Fix-GitVersionOnLinux")
.Does(() =>
{
version = GitVersion(new GitVersionSettings
{
UpdateAssemblyInfo = false,
});
if (AppVeyor.IsRunningOnAppVeyor)
{
if (!string.IsNullOrEmpty(version.PreReleaseTag))
{
version.NuGetVersion = string.Format("{0}-{1}{2}", version.MajorMinorPatch, string.IsNullOrEmpty(version.PreReleaseLabel) ? "pre" : version.PreReleaseLabel, AppVeyor.Environment.Build.Version.Replace("0.0.", "").PadLeft(4, '0'));
}
AppVeyor.UpdateBuildVersion(version.NuGetVersion);
}
Information("Building release:\n{0}", version.Dump());
});
Task("Set-Build-Version")
.IsDependentOn("Get-Version")
.Does(() =>
{
var assemblyInfo = TransformTextFile("YamlDotNet/Properties/AssemblyInfo.template")
.WithToken("assemblyVersion", $"{version.Major}.0.0.0")
.WithToken("assemblyFileVersion", $"{version.MajorMinorPatch}.0")
.WithToken("assemblyInformationalVersion", version.NuGetVersion)
.ToString();
System.IO.File.WriteAllText("YamlDotNet/Properties/AssemblyInfo.cs", assemblyInfo);
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Get-Version")
.Does(() =>
{
BuildSolution(solutionPath, configuration, buildVerbosity);
});
Task("Quick-Build")
.IsDependentOn("Get-Version")
.Does(() =>
{
BuildSolution(solutionPath, configuration, buildVerbosity);
});
Task("Test")
// .IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest();
});
Task("Build-Release-Configurations")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Get-Version")
.IsDependentOn("Set-Build-Version")
.Does(() =>
{
foreach(var releaseConfiguration in releaseConfigurations)
{
Information("");
Information("----------------------------------------");
Information("Building {0}", releaseConfiguration);
Information("----------------------------------------");
BuildSolution(solutionPath, releaseConfiguration, buildVerbosity);
}
});
Task("Test-Release-Configurations")
.IsDependentOn("Build-Release-Configurations")
.Does(() =>
{
foreach(var releaseConfiguration in releaseConfigurations)
{
if (releaseConfiguration.Equals("Debug-AOT"))
{
RunProcess("mono", "--aot=full", "YamlDotNet.AotTest/bin/Debug/net45/YamlDotNet.dll");
RunProcess("mono", "--aot=full", "YamlDotNet.AotTest/bin/Debug/net45/YamlDotNet.AotTest.exe");
RunProcess("mono", "--full-aot", "YamlDotNet.AotTest/bin/Debug/net45/YamlDotNet.AotTest.exe");
}
}
DotNetCoreTest();
});
Task("Package")
.IsDependentOn("Test-Release-Configurations")
.Does(() =>
{
// Replace directory separator char
var baseNuspecFile = "YamlDotNet/YamlDotNet.nuspec";
var nuspec = System.IO.File.ReadAllText(baseNuspecFile);
var finalNuspecFile = baseNuspecFile + ".tmp";
nuspec = nuspec.Replace('\\', System.IO.Path.DirectorySeparatorChar);
System.IO.File.WriteAllText(finalNuspecFile, nuspec);
NuGetPack(finalNuspecFile, new NuGetPackSettings
{
Version = version.NuGetVersion,
OutputDirectory = Directory("YamlDotNet/bin"),
});
});
Task("Release")
.IsDependentOn("Get-Version")
.WithCriteria(() => version.BranchName == "master", "Releases must be created from the master branch")
.Does(() =>
{
// Find previous release
var releases = RunProcess("git", "tag", "--list", "--merged", "master", "--format=\"%(refname:short)\"", "v*")
.Select(tag => new
{
Tag = tag,
Version = ParseSemVer(tag.TrimStart('v')),
})
.OrderByDescending(v => v.Version)
.ToList();
var previousVersion = releases.First();
Information("The previous release was {0}", previousVersion.Version);
var releaseNotesPath = Directory("releases").Path.CombineWithFilePath($"{version.NuGetVersion}.md").FullPath;
Action scaffoldReleaseNotes = () =>
{
// Get the git log to scaffold the release notes
string currentHash = null;
var commits = RunProcess("git", "rev-list", $"{previousVersion.Tag}..HEAD", "--first-parent", "--reverse", "--pretty=tformat:%B")
.Select(l =>
{
var match = Regex.Match(l, "^commit (?<hash>[a-f0-9]+)$");
if (match.Success)
{
currentHash = match.Groups["hash"].Value;
}
return new
{
message = l,
commit = currentHash
};
})
.GroupBy(l => l.commit, (k, list) => new
{
commit = k,
message = list
.Skip(1)
.Select(l => Regex.Replace(l.message, @"\+semver:\s*\w+", "").Trim())
.Where(l => !string.IsNullOrEmpty(l))
.ToList()
});
var log = commits
.Select(c => c.message.Select((l, i) => $"{(i == 0 ? '-' : ' ')} {l}"))
.Select(c => string.Join(" \n", c));
var releaseNotes = $"# Release {version.NuGetVersion}\n\n{string.Join("\n\n", log)}";
System.IO.File.WriteAllText(releaseNotesPath, releaseNotes);
};
if (!FileExists(releaseNotesPath))
{
scaffoldReleaseNotes();
}
// Show release menu
Menu menu = null;
Action updateMenuDescription = () => menu.Description = System.IO.File.ReadAllText(releaseNotesPath);
menu = new Menu(
"Release",
new ActionMenuItem("Edit release notes", ctx =>
{
ctx.SuppressPause();
RunProcess(IsRunningOnWindows() ? "notepad" : "nano", releaseNotesPath);
updateMenuDescription();
}),
new ActionMenuItem("Scaffold release notes", async ctx =>
{
ctx.SuppressPause();
if (await ctx.UserInterface.Confirm(true, "This will erase the current draft. Are you sure ?"))
{
scaffoldReleaseNotes();
updateMenuDescription();
}
}),
new ActionMenuItem("Release", async ctx =>
{
ctx.SuppressPause();
if (await ctx.UserInterface.Confirm(true, "This will publish a new release. Are you sure ?"))
{
menu.ShouldExit = true;
var previousReleases = releases
.Select(r => new
{
r.Version,
Path = $"releases/{r.Version}.md"
})
.Where(r => FileExists(r.Path))
.Select(r => $"- [{r.Version}]({r.Path})");
var releaseNotesFile = string.Join("\n",
"# Release notes",
menu.Description.Replace("# Release", "## Release"),
"# Previous releases",
string.Join("\n", previousReleases)
);
System.IO.File.WriteAllText("RELEASE_NOTES.md", releaseNotesFile);
RunProcess("git", "add", $"\"{releaseNotesPath}\"", "RELEASE_NOTES.md");
RunProcess("git", "commit", "-m", $"\"Prepare release {version.NuGetVersion}\"");
RunProcess("git", "tag", $"v{version.NuGetVersion}");
ctx.UserInterface.Info($"Your release is ready. Remember to push it using the following commands:\n\n git push && git push origin v{version.NuGetVersion}");
}
})
);
updateMenuDescription();
new ConsoleUi.Console.ConsoleMenuRunner().Run(menu).Wait();
});
Task("Document")
.IsDependentOn("Build")
.Does(() =>
{
var samplesBinDir = "YamlDotNet.Samples/bin/" + configuration;
var testAssemblyFileName = samplesBinDir + "/YamlDotNet.Samples.dll";
var samplesAssembly = Assembly.LoadFrom(testAssemblyFileName);
XUnit2(testAssemblyFileName, new XUnit2Settings
{
OutputDirectory = Directory(samplesBinDir),
XmlReport = true
});
var samples = XDocument.Load(samplesBinDir + "/YamlDotNet.Samples.dll.xml")
.Descendants("test")
.Select(e => new
{
Title = e.Attribute("name").Value,
Type = samplesAssembly.GetType(e.Attribute("type").Value),
Method = e.Attribute("method").Value,
Output = e.Element("output") != null ? e.Element("output").Value : null,
});
var sampleList = new StringBuilder();
foreach (var sample in samples)
{
var fileName = sample.Type.Name;
Information("Generating sample documentation page for {0}", fileName);
var code = System.IO.File.ReadAllText("YamlDotNet.Samples/" + fileName + ".cs");
var sampleAttr = sample.Type
.GetMethod(sample.Method)
.GetCustomAttributes()
.Single(a => a.GetType().Name == "SampleAttribute");
var description = UnIndent((string)sampleAttr.GetType().GetProperty("Description").GetValue(sampleAttr, null));
var samplePage = TransformTextFile("YamlDotNet.Samples/build/SampleTransform.md")
.WithToken("title", sample.Title)
.WithToken("description", description)
.WithToken("code", code)
.WithToken("output", sample.Output)
.ToString();
System.IO.File.WriteAllText("../YamlDotNet.wiki/Samples." + fileName + ".md", samplePage);
sampleList
.AppendFormat("* *[{0}](Samples.{1})* \n", sample.Title, fileName)
.AppendFormat(" {0}\n", description.Replace("\n", "\n "));
}
var sampleIndexPage = TransformTextFile("YamlDotNet.Samples/build/SampleIndexTransform.md")
.WithToken("sampleList", sampleList.ToString())
.ToString();
System.IO.File.WriteAllText("../YamlDotNet.wiki/Samples.md", sampleIndexPage);
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
// .IsDependentOn("Document");
.IsDependentOn("Test");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
//////////////////////////////////////////////////////////////////////
// HELPERS
//////////////////////////////////////////////////////////////////////
string UnIndent(string text)
{
var lines = text
.Split('\n')
.Select(l => l.TrimEnd('\r', '\n'))
.SkipWhile(l => l.Trim(' ', '\t').Length == 0)
.ToList();
while (lines.Count > 0 && lines[lines.Count - 1].Trim(' ', '\t').Length == 0)
{
lines.RemoveAt(lines.Count - 1);
}
if (lines.Count > 0)
{
var indent = Regex.Match(lines[0], @"^(\s*)");
if (!indent.Success)
{
throw new ArgumentException("Invalid indentation");
}
lines = lines
.Select(l => l.Substring(indent.Groups[1].Length))
.ToList();
}
return string.Join("\n", lines.ToArray());
}
void BuildSolution(string solutionPath, string configuration, Verbosity verbosity)
{
Information("version: {0}", version);
Information("version.NuGetVersion: {0}", version.NuGetVersion);
DotNetCoreBuild(solutionPath, new DotNetCoreBuildSettings
{
Verbosity = (DotNetCoreVerbosity)(int)verbosity,
Configuration = configuration,
MSBuildSettings = new DotNetCoreMSBuildSettings
{
Properties =
{
{ "Version", new[] { version.NuGetVersion } }
}
}
});
}
IEnumerable<string> RunProcess(string processName, params string[] arguments)
{
var settings = new ProcessSettings()
.SetRedirectStandardOutput(true)
.WithArguments(a =>
{
foreach (var argument in arguments)
{
a.Append(argument);
}
});
using (var process = StartAndReturnProcess(processName, settings))
{
var output = new List<string>(process.GetStandardOutput());
process.WaitForExit();
var exitCode = process.GetExitCode();
if (exitCode != 0)
{
throw new Exception(string.Format("{0} failed with exit code {1}", processName, exitCode));
}
return output;
}
}