-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBuildContext.cs
More file actions
283 lines (246 loc) · 11.5 KB
/
Copy pathBuildContext.cs
File metadata and controls
283 lines (246 loc) · 11.5 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
using System.Formats.Tar;
using System.IO.Compression;
using System.Runtime.InteropServices;
using Cake.Common;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
using Cake.Frosting;
using Path = System.IO.Path;
namespace LadybugDB.Build;
/// <summary>
/// Shared state and paths for the packaging pipeline. Resolves the binding root from the running
/// assembly (independent of the caller's working directory) and stages prebuilt engine libraries.
/// </summary>
public sealed class BuildContext : FrostingContext
{
/// <summary>RID -> (release asset name, canonical native library file name).</summary>
public static readonly IReadOnlyDictionary<string, (string Asset, string Library)> NativeAssets =
new Dictionary<string, (string, string)>(StringComparer.Ordinal)
{
["win-x64"] = ("liblbug-windows-x86_64.zip", "lbug_shared.dll"),
["linux-x64"] = ("liblbug-linux-x86_64.tar.gz", "liblbug.so"),
["linux-arm64"] = ("liblbug-linux-aarch64.tar.gz", "liblbug.so"),
["osx-x64"] = ("liblbug-osx-x86_64.tar.gz", "liblbug.dylib"),
["osx-arm64"] = ("liblbug-osx-arm64.tar.gz", "liblbug.dylib"),
};
public BuildContext(ICakeContext context) : base(context)
{
BuildConfiguration = context.Argument("configuration", "Release");
Commit = context.Argument("commit", Environment.GetEnvironmentVariable("GITHUB_SHA") ?? string.Empty);
Root = FindBindingRoot();
// version.txt at the binding root is the single source of truth for the package family version
// (e.g. "0.17.0.1"). The first three numeric segments identify the upstream engine release
// (v0.17.0), while an optional fourth segment identifies a binding-only package revision.
// Overrides: --engine-version / ENGINE_VERSION pick a different engine release; --prerelease
// can add or replace a prerelease suffix; --package-version sets the package version verbatim
// (the release workflow passes the git tag). 'version' is reserved by the Cake host.
string fileVersion = ReadVersion(Root);
string versionBase = StripVersionSuffixes(fileVersion);
string filePrerelease = GetPrereleaseSuffix(fileVersion);
string prerelease = context.Argument("prerelease", filePrerelease);
Version = context.HasArgument("package-version")
? context.Argument<string>("package-version")
: prerelease.Length == 0 ? versionBase : $"{versionBase}-{prerelease}";
EngineVersion = context.Argument("engine-version",
Environment.GetEnvironmentVariable("ENGINE_VERSION") ?? $"v{DeriveEngineVersion(Version)}");
ManagedProject = Path.Combine(Root, "src", "LadybugDB", "LadybugDB.csproj");
TestProject = Path.Combine(Root, "test", "LadybugDB.Tests", "LadybugDB.Tests.csproj");
Solution = Path.Combine(Root, "LadybugDB.slnx");
NativeDir = Path.Combine(Root, "cake", "native");
RuntimeProject = Path.Combine(NativeDir, "LadybugDB.Native.Runtime.csproj");
MetaProject = Path.Combine(NativeDir, "LadybugDB.Native.Meta.csproj");
MetaNuspecTemplate = Path.Combine(NativeDir, "LadybugDB.Native.nuspec");
RuntimesStageDir = Path.Combine(Root, "lib", "runtimes");
ArtifactsDir = Path.Combine(Root, "artifacts");
DownloadDir = Path.Combine(Root, "download");
}
public string BuildConfiguration { get; }
public string Version { get; }
public string Commit { get; }
public string EngineVersion { get; }
public string Root { get; }
public string ManagedProject { get; }
public string TestProject { get; }
public string Solution { get; }
public string NativeDir { get; }
public string RuntimeProject { get; }
public string MetaProject { get; }
public string MetaNuspecTemplate { get; }
public string RuntimesStageDir { get; }
public string ArtifactsDir { get; }
public string DownloadDir { get; }
public IReadOnlyList<string> AllRids { get; } = [.. NativeAssets.Keys];
public string HostRid { get; } =
(OperatingSystem.IsWindows() ? "win" : OperatingSystem.IsMacOS() ? "osx" : "linux")
+ "-"
+ (RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64");
/// <summary>Absolute path the native library for <paramref name="rid"/> is staged to.</summary>
public string StagedLibraryPath(string rid) =>
Path.Combine(RuntimesStageDir, rid, "native", NativeAssets[rid].Library);
/// <summary>
/// Ensure the prebuilt engine library for <paramref name="rid"/> sits under
/// lib/runtimes/{rid}/native. No-op when it is already present (e.g. built from source locally);
/// otherwise downloads the pinned engine release asset and extracts the canonical library out of it.
/// </summary>
public void EnsureNativeStaged(string rid)
{
if (!NativeAssets.TryGetValue(rid, out (string Asset, string Library) info))
{
throw new CakeException($"Unknown RID '{rid}'. Known: {string.Join(", ", AllRids)}.");
}
string dest = StagedLibraryPath(rid);
if (File.Exists(dest))
{
Log.Information($"native already staged for {rid}: {dest}");
return;
}
string asset = Path.Combine(DownloadDir, info.Asset);
if (!File.Exists(asset))
{
DownloadEngineAsset(info.Asset);
}
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
if (info.Asset.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
ExtractFromZip(asset, info.Library, dest);
}
else
{
ExtractFromTarGz(asset, dest);
}
Log.Information($"staged {rid} -> {dest}");
}
private void DownloadEngineAsset(string asset)
{
Directory.CreateDirectory(DownloadDir);
Log.Information($"downloading {asset} from LadybugDB/ladybug@{EngineVersion}");
var args = new ProcessArgumentBuilder()
.Append("release").Append("download").AppendQuoted(EngineVersion)
.Append("--repo").Append("LadybugDB/ladybug")
.Append("--dir").AppendQuoted(DownloadDir)
.Append("--pattern").AppendQuoted(asset);
int exit;
try
{
exit = this.StartProcess("gh", new ProcessSettings { Arguments = args });
}
catch (Exception ex)
{
throw new CakeException(
$"Could not run 'gh' to download '{asset}'. Install the GitHub CLI and authenticate, " +
$"or stage the native library under lib/runtimes/<rid>/native/ manually. ({ex.Message})");
}
if (exit != 0 || !File.Exists(Path.Combine(DownloadDir, asset)))
{
throw new CakeException($"gh release download failed for '{asset}' (exit {exit}).");
}
}
private static void ExtractFromZip(string archive, string library, string dest)
{
using ZipArchive zip = ZipFile.OpenRead(archive);
ZipArchiveEntry entry = zip.Entries.FirstOrDefault(e =>
string.Equals(Path.GetFileName(e.FullName), library,
StringComparison.OrdinalIgnoreCase))
?? throw new CakeException($"'{library}' not found in '{Path.GetFileName(archive)}'.");
entry.ExtractToFile(dest, overwrite: true);
}
// The Linux/macOS tarballs ship a symlink chain (liblbug.so -> .so.0 -> .so.0.x.y). NuGet does not
// preserve symlinks and the binding loads by path, so copy the real shared object out under the
// canonical name: the largest regular file in the "liblbug" family with the platform extension.
private static void ExtractFromTarGz(string archive, string dest)
{
string ext = dest.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) ? ".dylib" : ".so";
long bestLength = -1;
byte[]? best = null;
using FileStream fs = File.OpenRead(archive);
using GZipStream gz = new(fs, CompressionMode.Decompress);
using TarReader tar = new(gz);
while (tar.GetNextEntry() is { } entry)
{
if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile) ||
entry.DataStream is null)
{
continue;
}
string name = Path.GetFileName(entry.Name);
if (!name.StartsWith("liblbug", StringComparison.OrdinalIgnoreCase) ||
!name.Contains(ext, StringComparison.OrdinalIgnoreCase))
{
continue;
}
using MemoryStream ms = new();
entry.DataStream.CopyTo(ms);
if (ms.Length > bestLength)
{
bestLength = ms.Length;
best = ms.ToArray();
}
}
if (best is null)
{
throw new CakeException($"No 'liblbug*{ext}' regular file found in '{Path.GetFileName(archive)}'.");
}
File.WriteAllBytes(dest, best);
}
/// <summary>
/// Reads the binding package-family version from <c>version.txt</c> at the root. The first three
/// numeric segments track the native engine release, and an optional fourth segment tracks a
/// binding-only package revision.
/// </summary>
private static string ReadVersion(string root)
{
string path = Path.Combine(root, "version.txt");
if (!File.Exists(path))
{
throw new CakeException(
$"Version file not found at '{path}'. " +
$"It is the single source of truth for the package version (e.g. 0.17.0.1).");
}
return File.ReadAllText(path).Trim();
}
private static string DeriveEngineVersion(string packageVersion)
{
string baseVersion = StripVersionSuffixes(packageVersion);
string[] parts = baseVersion.Split('.');
if (parts.Length < 3 || parts.Take(3).Any(p => p.Length == 0 || !p.All(char.IsDigit)))
{
throw new CakeException(
$"Package version '{packageVersion}' must start with three numeric engine segments, " +
"for example 0.17.0 or 0.17.0.1.");
}
return string.Join(".", parts.Take(3));
}
private static string StripVersionSuffixes(string version)
{
int dash = version.IndexOf('-');
int plus = version.IndexOf('+');
int suffix = dash < 0 ? plus : plus < 0 ? dash : Math.Min(dash, plus);
return suffix < 0 ? version : version[..suffix];
}
private static string GetPrereleaseSuffix(string version)
{
int dash = version.IndexOf('-');
if (dash < 0)
{
return string.Empty;
}
int plus = version.IndexOf('+', dash + 1);
return plus < 0 ? version[(dash + 1)..] : version[(dash + 1)..plus];
}
private static string FindBindingRoot()
{
for (DirectoryInfo? dir = new(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "LadybugDB.slnx")))
{
return dir.FullName;
}
}
throw new CakeException("Could not locate the binding root (no LadybugDB.slnx found above the build output).");
}
/// <summary>Console entry point. Cake resolves the task graph and constructs this context via DI.</summary>
public static int Main(string[] args) => new CakeHost()
.UseContext<BuildContext>()
.Run(args);
}