-
Notifications
You must be signed in to change notification settings - Fork 0
/
Build.cs
264 lines (230 loc) · 10.6 KB
/
Build.cs
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
using System;
using System.Linq;
using System.IO;
using System.IO.Compression;
using Nuke.Common;
using Nuke.Common.CI;
using Nuke.Common.Execution;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.Unity;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.EnvironmentInfo;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using System.Text.RegularExpressions;
using Serilog;
using Nuke.Common.Git;
using Nuke.Common.Tools.Git;
using Nuke.Common.Tools.GitHub;
using Octokit;
using _build;
using System.Collections.Generic;
using System.Net.Mime;
partial class Build : NukeBuild
{
private const string AppName = "GameMakersToolkitFlappyBirdTutorial";
private static readonly AbsolutePath _unityGameSrcDirectory = RootDirectory / "GameMakersToolkitFlappyBirdTutorial";
private static readonly AbsolutePath _buildsDirectory = RootDirectory / "Builds";
private static readonly AbsolutePath _winx64BuildDirectory = _buildsDirectory / "winx64";
private static readonly AbsolutePath _winx86BuildDirectory = _buildsDirectory / "winx86";
[GitRepository] readonly GitRepository Repository;
[Parameter("The version of the build taking place; Needs to be formatted in x.y.z, optionally post-fixes with -alpha or -beta")]
readonly string Version;
[Parameter("The 'Personal Access Token' used by the Build scripts for creating releases"), Secret]
readonly string GitHubPersonalAccessToken;
private readonly Dictionary<ReleaseTypes, AbsolutePath> _targetAppFileLocations = new();
private string _releaseVersion;
public static int Main() => Execute<Build>();
Target SetVersion => _ => _
.Requires(() => Version)
.Unlisted()
.Executes(() =>
{
Assert.True(GetValidVersionRegex().IsMatch(Version), "The 'Version' Parameter needs to be in the 'SemVer' fomat of x.y.z, with optionally -alpha or -beta postfix.");
var projectSettingsFile = _unityGameSrcDirectory / "ProjectSettings" / "ProjectSettings.asset";
// Match to ` bundleVersion: x.y.z-alpha` or ` bundleVersion: x.y.z-beta` or ` bundleVersion: x.y.z`:
Regex projectSettingsVersionRegex = GetProjectSettingsVersionRegex();
UpdateVersionTextInFileUsingRegex(Version!, projectSettingsFile, projectSettingsVersionRegex, "bundleVersion: <version>");
var mainMenuSceneFile = _unityGameSrcDirectory / "Assets" / "Scenes" / "MainMenuScene.unity";
// Match to ` m_Text: 'Version: x.y.z-alpha'` or ` m_Text: 'Version: x.y.z-beta'` or ` m_Text: 'Version: x.y.z'`:
var mainMenuSceneVersionTextValueRegex = GetMainMenuSceneVersionTextValueRegex();
UpdateVersionTextInFileUsingRegex(Version!, mainMenuSceneFile, mainMenuSceneVersionTextValueRegex, "m_Text: 'Version: <version>'");
});
Target BuildAppAsWin64bit => _ => _
.Executes(() =>
{
var targetAppFileLocation = _winx64BuildDirectory / $"{AppName}.exe";
BuildWin64BitInTargetDirectory(targetAppFileLocation);
});
Target BuildAppAsWin32bit => _ => _
.Executes(() =>
{
var targetAppFileLocation = _winx86BuildDirectory / $"{AppName}.exe";
BuildWin32BitInTargetDirectory(targetAppFileLocation);
});
Target BuildWin64BitReleaseBinaries => _ => _
.DependsOn(SetVersion)
.Unlisted()
.Executes(() =>
{
_releaseVersion = $"{AppName}_winx64_{Version}";
_targetAppFileLocations[ReleaseTypes.Windows64Bit] = _winx64BuildDirectory / _releaseVersion / $"{AppName}.exe";
BuildWin64BitInTargetDirectory(_targetAppFileLocations[ReleaseTypes.Windows64Bit], true);
});
Target BuildWin32BitReleaseBinaries => _ => _
.DependsOn(SetVersion)
.Unlisted()
.Executes(() =>
{
_releaseVersion = $"{AppName}_winx86_{Version}";
_targetAppFileLocations[ReleaseTypes.Windows32Bit] = _winx86BuildDirectory / _releaseVersion / $"{AppName}.exe";
BuildWin32BitInTargetDirectory(_targetAppFileLocations[ReleaseTypes.Windows32Bit], true);
});
Target BuildWin64BitReleaseZipFile => _ => _
.DependsOn(BuildWin64BitReleaseBinaries)
.Executes(() =>
{
ZipRelease(ReleaseTypes.Windows64Bit);
});
Target BuildWin32BitReleaseZipFile => _ => _
.DependsOn(BuildWin32BitReleaseBinaries)
.Executes(() =>
{
ZipRelease(ReleaseTypes.Windows32Bit);
});
Target CreateReleaseCommitAndPush => _ => _
.DependsOn(SetVersion)
.Requires(() => Repository.IsOnMainBranch()) // This project uses Trunk Based Development
.Executes(() =>
{
// Stage all side-effects of SetVersion Target:
GitTasks.Git("add .");
// Create release commit:
GitTasks.Git($"commit -m \"Build {Version}\"");
// Tag release commit:
GitTasks.Git($"tag -a {Version} -m \"Tag build {Version}\"");
// Push to origin:
GitTasks.Git("push origin --tags main:main");
});
Target CreateReleaseOnGithub => _ => _
.Requires(() => Version)
.Requires(() => GitHubPersonalAccessToken)
.DependsOn(CreateReleaseCommitAndPush)
.DependsOn(BuildWin64BitReleaseZipFile)
.DependsOn(BuildWin32BitReleaseZipFile)
.Executes(async () =>
{
string branchName = await GitHubTasks.GetDefaultBranch(Repository);
var productInformation = new ProductHeaderValue($"{AppName}-NukeBuildScript");
GitHubTasks.GitHubClient = new GitHubClient(productInformation)
{
Credentials = new Credentials(GitHubPersonalAccessToken)
};
bool isPrerelease = Version.EndsWith("alpha") || Version.EndsWith("beta");
string namePrefix = isPrerelease ? "Pre-release ": string.Empty;
var releaseData = new NewRelease(Version)
{
Prerelease = isPrerelease,
Body = "TODO",
Draft = true,
Name = $"{namePrefix}{Version}"
};
try
{
Release release = await GitHubTasks.GitHubClient.Repository.Release
.Create(Repository.GetGitHubOwner(), Repository.GetGitHubName(), releaseData);
foreach (ReleaseTypes releaseType in _targetAppFileLocations.Keys)
{
AbsolutePath releaseArtifact = GetReleaseZipFilePath(releaseType);
var upload = new ReleaseAssetUpload
{
ContentType = MediaTypeNames.Application.Zip,
FileName = Path.GetFileName(releaseArtifact),
RawData = File.OpenRead(releaseArtifact)
};
await GitHubTasks.GitHubClient.Repository.Release
.UploadAsset(release, upload);
}
}
catch (ApiException e)
{
Log.Debug("{@ExceptionData}", e);
Log.Error(e, "Failure during release creation towards Github");
}
});
private static void BuildWin64BitInTargetDirectory(AbsolutePath targetAppFileLocation, bool isReleaseBuild = false)
{
BuildInTargetDirectory(
unitySettings => _build.UnitySettingsExtensions.SetWindows64BitBuildTarget(unitySettings, targetAppFileLocation),
isReleaseBuild
);
}
private static void BuildWin32BitInTargetDirectory(AbsolutePath targetAppFileLocation, bool isReleaseBuild = false)
{
BuildInTargetDirectory(
unitySettings => _build.UnitySettingsExtensions.SetWindows32BitBuildTarget(unitySettings, targetAppFileLocation),
isReleaseBuild
);
}
private static void BuildInTargetDirectory(
Func<UnitySettings, UnitySettings> setBuildTarget,
bool isReleaseBuild = false)
{
UnityTasks.Unity(unitySettings =>
{
UnitySettings settings = unitySettings
.EnableQuit()
.EnableBatchMode()
.SetProjectPath(_unityGameSrcDirectory)
.SetLogFile(RootDirectory / "NukeBuild" / "unity.log");
settings = setBuildTarget(settings);
if (isReleaseBuild)
{
settings.AddCustomArguments("-releaseCodeOptimization");
}
return settings;
});
}
private static void UpdateVersionTextInFileUsingRegex(string versionText, AbsolutePath fileToBeUpdated, Regex regex, string expectedPattern)
{
Assert.FileExists(fileToBeUpdated);
string[] fileLines = fileToBeUpdated.ReadAllLines();
bool updatedVersion = false;
for (int i = 0; i < fileLines.Length; i++)
{
var line = fileLines[i];
var match = regex.Match(line);
if (match.Success)
{
Group currentVersionCaptureGroup = match.Groups["currentVersion"];
fileLines[i] = line.Replace(currentVersionCaptureGroup.Value, versionText);
updatedVersion = true;
break;
}
}
if (!updatedVersion)
{
Assert.Fail($"\"{expectedPattern}\" pattern missing from '{fileToBeUpdated}'.");
}
fileToBeUpdated.WriteAllLines(fileLines);
Log.Debug("Successfully updated {File} to {NewVersion}", fileToBeUpdated.ToString(), versionText);
}
private void ZipRelease(ReleaseTypes release)
{
AbsolutePath archiveFile = GetReleaseZipFilePath(release);
AbsolutePath releaseDirectory = _targetAppFileLocations[release].Parent;
releaseDirectory.ZipTo(
archiveFile,
compressionLevel: CompressionLevel.SmallestSize
);
}
private AbsolutePath GetReleaseZipFilePath(ReleaseTypes win64BitRelease) => _targetAppFileLocations[win64BitRelease].Parent + ".zip";
[GeneratedRegex("^\\s+bundleVersion:\\s+(?<currentVersion>\\d+\\.\\d+\\.\\d+(-(alpha|beta))?)$")]
private static partial Regex GetProjectSettingsVersionRegex();
[GeneratedRegex("^\\s+m_Text:\\s+'Version: (?<currentVersion>\\d+\\.\\d+\\.\\d+(-(alpha|beta))?)'$")]
private static partial Regex GetMainMenuSceneVersionTextValueRegex();
[GeneratedRegex("^\\d+\\.\\d+\\.\\d+(-(alpha|beta))?$")]
private static partial Regex GetValidVersionRegex();
}