-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
executable file
·335 lines (267 loc) · 10.5 KB
/
Program.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
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
using System.Buffers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
const string releaseIndexUrl = "https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json";
const string intelRuntimeId = "osx-x64";
const string armRuntimeId = "osx-arm64";
const string macOsPkgExt = ".pkg";
const string stateFile = "state.json";
const string changesSummaryFile = "changes-summary.txt";
const int hashBufferLength = 4096;
await using var changesSummaryWriter = new StreamWriter(File.OpenWrite(changesSummaryFile));
var stateJsonOpts = new JsonSerializerOptions { WriteIndented = true };
var state = await LoadState();
using var client = new HttpClient();
var releasesIndex = await client.GetFromJsonAsync<ReleaseIndexList>(releaseIndexUrl)
?? throw new Exception("Could not fetch release index list");
await changesSummaryWriter.WriteLineAsync("Updating formulas");
await changesSummaryWriter.WriteLineAsync();
Log("processing releases after " + state.LatestReleaseDate);
foreach (var releaseIndex in releasesIndex.ReleasesIndex.Where(x => x.LatestReleaseDate > state.LatestReleaseDate))
{
var releases = await client.GetFromJsonAsync<ReleaseList>(releaseIndex.ReleasesUrl)
?? throw new Exception("Could not fetch releases");
foreach (var release in releases.Releases.Where(x => x.ReleaseDate > state.LatestReleaseDate))
{
if (!state.KnownSdkVersions.Add(release.Sdk.Version))
continue;
var sdkFiles = release.Sdk.Files
.Where(x => x.Rid is armRuntimeId or intelRuntimeId && x.Name.EndsWith(macOsPkgExt, StringComparison.Ordinal))
.GroupBy(x => x.Rid)
.ToDictionary(x => x.Key, x => x.First());
var hasIntelSdk = sdkFiles.TryGetValue(intelRuntimeId, out var intelSdkFile);
var hasArmSdk = sdkFiles.TryGetValue(armRuntimeId, out var armSdkFile);
if (!hasIntelSdk && !hasArmSdk)
continue;
Log($"processing {release.Sdk.Version}");
var formula = new Formula
{
Product = releaseIndex.Product,
ReleaseVersion = release.ReleaseVersion,
SdkVersion = release.Sdk.Version,
IntelVariant = hasIntelSdk ? await BuildVariant(client, release, intelSdkFile!) : null,
ArmVariant = hasArmSdk ? await BuildVariant(client, release, armSdkFile!) : null,
};
await StoreFormula(changesSummaryWriter, formula);
if (release.Sdk.Version.Equals(releases.LatestSdk))
{
formula.Channel = releases.ChannelVersion;
await StoreFormula(changesSummaryWriter, formula);
}
}
}
state.LatestReleaseDate = releasesIndex.ReleasesIndex.Max(x => x.LatestReleaseDate);
await StoreState(state);
async Task<State> LoadState()
{
if (!File.Exists(stateFile))
return new State();
await using var stream = File.OpenRead(stateFile);
return await JsonSerializer.DeserializeAsync<State>(stream)
?? new State();
}
async Task StoreState(State stateToStore)
{
await using var stream = File.Create(stateFile);
await JsonSerializer.SerializeAsync(stream, stateToStore, stateJsonOpts);
}
void Log(string msg) => Console.WriteLine(msg);
async Task<FormulaVariant> BuildVariant(HttpClient httpClient, Release release, ReleaseFile sdkFile)
{
// we cannot use the provided hash since its sha512
// but homebrew requires sha256
var (sha256, sha512) = await ComputeHash(httpClient, sdkFile.Url);
if (!string.Equals(sha512, sdkFile.Hash))
throw new Exception($"Hash verification of {sdkFile.Url} failed");
return new FormulaVariant
{
PkgName = sdkFile.Url.Split("/").Last(),
Sha256 = sha256,
DownloadUrl = sdkFile.Url,
DownloadUrlWithVersionPlaceholder = sdkFile.Url.Replace(release.Sdk.Version, "#{version.before_comma}"),
};
}
async Task<(string Sha256, string Sha512)> ComputeHash(HttpClient httpClient, string url)
{
await using var fileStream = await httpClient.GetStreamAsync(url);
using var sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
using var sha512 = IncrementalHash.CreateHash(HashAlgorithmName.SHA512);
var buffer = ArrayPool<byte>.Shared.Rent(hashBufferLength);
while (true)
{
var bufferReadLength = await fileStream.ReadAsync(buffer);
if (bufferReadLength <= 0)
break;
sha256.AppendData(buffer, 0, bufferReadLength);
sha512.AppendData(buffer, 0, bufferReadLength);
}
ArrayPool<byte>.Shared.Return(buffer);
return (
HashAsHex(sha256.GetCurrentHash()),
HashAsHex(sha512.GetCurrentHash()));
}
string HashAsHex(IReadOnlyCollection<byte> hash)
{
var sb = new StringBuilder(hash.Count * 2);
foreach (var hashByte in hash)
{
sb.Append(hashByte.ToString("x2"));
}
return sb.ToString();
}
async Task StoreFormula(TextWriter changesWriter, Formula formula)
{
if (File.Exists(formula.FilePath))
{
Log($"writing updated formula {formula.Id}");
await changesWriter.WriteLineAsync("* Updated " + formula.ReleaseVersion);
}
else
{
Log($"adding formula {formula.Id}");
await changesWriter.WriteLineAsync("* Added " + formula.ReleaseVersion);
}
var formulaStr = BuildFormula(formula);
Directory.CreateDirectory(Path.GetDirectoryName(formula.FilePath)!);
await File.WriteAllTextAsync(formula.FilePath, formulaStr);
}
string BuildFormula(Formula formula)
{
return $$"""
cask "{{formula.Id}}" do
version "{{formula.SdkVersion}},{{formula.ReleaseVersion}}"
{{BuildFormulaVariants(formula)}}
name "{{formula.Product}} SDK {{formula.SdkVersion}},{{formula.ReleaseVersion}}"
desc "Developer platform"
homepage "https://www.microsoft.com/net/core#macos"
conflicts_with cask: [
"dotnet-sdk",
"homebrew/cask-versions/dotnet-preview",
"homebrew/cask-versions/dotnet-sdk-preview",
]
uninstall pkgutil: [
"com.microsoft.dotnet.*.#{version.after_comma}.*",
"com.microsoft.netstandard.pack.targeting.*.#{version.after_comma}.*",
"com.microsoft.dotnet.*.#{version.before_comma}.*",
"com.microsoft.netstandard.pack.targeting.*.#{version.before_comma}.*",
]
zap trash: ["~/.dotnet", "~/.nuget", "/etc/paths.d/dotnet", "/etc/paths.d/dotnet-cli-tools"]
end
""";
}
string BuildFormulaVariants(Formula formula)
{
if (formula is { IntelVariant: not null, ArmVariant: not null })
{
return $"""
if Hardware::CPU.intel?
{BuildFormulaVariant(formula.IntelVariant, 2)}
else
{BuildFormulaVariant(formula.ArmVariant, 2)}
end
""";
}
return BuildFormulaVariant((formula.IntelVariant ?? formula.ArmVariant)!, 1);
}
string BuildFormulaVariant(FormulaVariant formulaVariant, int indentLevel)
{
var indention = string.Join("", Enumerable.Repeat(" ", indentLevel * 4));
return $"""
url "{formulaVariant.DownloadUrlWithVersionPlaceholder}"
{indention}sha256 "{formulaVariant.Sha256}"
{indention}pkg "{formulaVariant.PkgName}"
""";
}
class State
{
[JsonIgnore]
public HashSet<string> KnownSdkVersions { get; set; } = [];
[JsonPropertyName(nameof(KnownSdkVersions))]
public IEnumerable<string> SortedKnownSdkVersions
{
get => KnownSdkVersions.OrderBy(x => x);
init => KnownSdkVersions = [..value];
}
public DateOnly LatestReleaseDate { get; set; }
}
class Formula
{
public string Id => $"dotnet-sdk-{ChannelOrSdkVersion.Replace(".", "-")}";
public string FilePath => Path.GetFullPath(Path.Combine(".", "Casks", Id + ".rb"));
public string ChannelOrSdkVersion => Channel ?? SdkVersion;
public string? Channel { get; set; }
public string SdkVersion { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the release version.
/// </summary>
public string ReleaseVersion { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the product.
/// <example>.NET</example>
/// <example>.NET Core</example>
/// </summary>
public string Product { get; set; } = string.Empty;
public FormulaVariant? IntelVariant { get; set; }
public FormulaVariant? ArmVariant { get; set; }
}
class FormulaVariant
{
/// <summary>
/// Gets or sets the name of the installer incl. the extension.
/// <example>dotnet-sdk-5.0.300-osx-x64.pkg</example>
/// </summary>
public required string PkgName { get; init; }
/// <summary>
/// Gets or sets the sha256 as a hex string.
/// </summary>
public required string Sha256 { get; init; }
public required string DownloadUrl { get; init; }
public required string DownloadUrlWithVersionPlaceholder { get; init; }
}
class ReleaseIndexList
{
[JsonPropertyName("releases-index")]
public required List<ReleaseIndex> ReleasesIndex { get; init; }
}
class ReleaseIndex
{
public required string Product { get; init; }
[JsonPropertyName("latest-release-date")]
public required DateOnly LatestReleaseDate { get; init; }
[JsonPropertyName("releases.json")]
public required string ReleasesUrl { get; init; }
}
class ReleaseList
{
[JsonPropertyName("channel-version")]
public required string ChannelVersion { get; init; }
[JsonPropertyName("latest-sdk")]
public required string LatestSdk { get; init; }
public required List<Release> Releases { get; init; }
}
class Release
{
[JsonPropertyName("release-date")]
public required DateOnly ReleaseDate { get; init; }
[JsonPropertyName("release-version")]
public required string ReleaseVersion { get; init; }
public required SdkRelease Sdk { get; init; }
}
class SdkRelease
{
public required string Version { get; init; }
public required List<ReleaseFile> Files { get; init; }
}
class ReleaseFile
{
public required string Name { get; init; }
public required string Rid { get; init; }
public required string Url { get; init; }
/// <summary>
/// SHA512
/// </summary>
public required string Hash { get; init; }
}