forked from ppy/osu-deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
770 lines (605 loc) · 31.6 KB
/
Program.cs
File metadata and controls
770 lines (605 loc) · 31.6 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;
using osu.Framework;
using osu.Framework.Extensions;
using osu.Framework.IO.Network;
namespace osu.Desktop.Deploy
{
internal static class Program
{
private static string packages => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
private static string nugetPath => getToolPath("NuGet.CommandLine", "NuGet.exe");
private static string squirrelPath => getToolPath("Clowd.Squirrel", "Squirrel.exe");
private const string staging_folder = "staging";
private const string templates_folder = "templates";
private const string releases_folder = "releases";
/// <summary>
/// How many previous build deltas we want to keep when publishing.
/// </summary>
private const int keep_delta_count = 4;
public static string? GitHubAccessToken = ConfigurationManager.AppSettings["GitHubAccessToken"];
public static bool GitHubUpload = bool.Parse(ConfigurationManager.AppSettings["GitHubUpload"] ?? "false");
public static string? GitHubUsername = ConfigurationManager.AppSettings["GitHubUsername"];
public static string? GitHubRepoName = ConfigurationManager.AppSettings["GitHubRepoName"];
public static string? SolutionName = ConfigurationManager.AppSettings["SolutionName"];
public static string? ProjectName = ConfigurationManager.AppSettings["ProjectName"];
public static string? NuSpecName = ConfigurationManager.AppSettings["NuSpecName"];
public static bool IncrementVersion = bool.Parse(ConfigurationManager.AppSettings["IncrementVersion"] ?? "true");
public static string? PackageName = ConfigurationManager.AppSettings["PackageName"];
public static string? IconName = ConfigurationManager.AppSettings["IconName"];
public static string? CodeSigningCertificate = ConfigurationManager.AppSettings["CodeSigningCertificate"];
public static string GitHubApiEndpoint => $"https://api.github.com/repos/{GitHubUsername}/{GitHubRepoName}/releases";
private static string? solutionPath;
private static string stagingPath => Path.Combine(Environment.CurrentDirectory, staging_folder);
private static string templatesPath => Path.Combine(Environment.CurrentDirectory, templates_folder);
private static string releasesPath => Path.Combine(Environment.CurrentDirectory, releases_folder);
private static string iconPath
{
get
{
Debug.Assert(solutionPath != null);
Debug.Assert(ProjectName != null);
Debug.Assert(IconName != null);
return Path.Combine(solutionPath, ProjectName, IconName);
}
}
private static string splashImagePath
{
get
{
Debug.Assert(solutionPath != null);
return Path.Combine(solutionPath, "assets\\lazer-nuget.png");
}
}
private static readonly Stopwatch stopwatch = new Stopwatch();
private static bool interactive;
/// <summary>
/// args[0]: code signing passphrase
/// args[1]: version
/// args[2]: platform
/// args[3]: arch
/// </summary>
public static void Main(string[] args)
{
interactive = args.Length == 0;
displayHeader();
findSolutionPath();
if (!Directory.Exists(releases_folder))
{
write("WARNING: No release directory found. Make sure you want this!", ConsoleColor.Yellow);
Directory.CreateDirectory(releases_folder);
}
GitHubRelease? lastRelease = null;
if (canGitHub)
{
write("Checking GitHub releases...");
lastRelease = getLastGithubRelease();
write(lastRelease == null
? "This is the first GitHub release"
: $"Last GitHub release was {lastRelease.Name}.");
}
//increment build number until we have a unique one.
string verBase = DateTime.Now.ToString("yyyy.Mdd.");
int increment = 0;
if (lastRelease?.TagName.StartsWith(verBase, StringComparison.InvariantCulture) ?? false)
increment = int.Parse(lastRelease.TagName.Split('.')[2]) + (IncrementVersion ? 1 : 0);
string version = $"{verBase}{increment}";
var targetPlatform = RuntimeInfo.OS;
if (args.Length > 1 && !string.IsNullOrEmpty(args[1]))
version = args[1];
if (args.Length > 2 && !string.IsNullOrEmpty(args[2]))
Enum.TryParse(args[2], true, out targetPlatform);
Console.ResetColor();
Console.WriteLine($"Increment Version: {IncrementVersion}");
Console.WriteLine($"Signing Certificate: {CodeSigningCertificate}");
Console.WriteLine($"Upload to GitHub: {GitHubUpload}");
Console.WriteLine();
Console.Write($"Ready to deploy version {version} on platform {targetPlatform}!");
pauseIfInteractive();
stopwatch.Start();
refreshDirectory(staging_folder);
updateAppveyorVersion(version);
Debug.Assert(solutionPath != null);
write("Running build process...");
switch (targetPlatform)
{
case RuntimeInfo.Platform.Windows:
if (lastRelease != null)
getAssetsFromRelease(lastRelease);
runCommand("dotnet", $"publish -f net6.0 -r win-x64 {ProjectName} -o {stagingPath} --configuration Release /p:Version={version}");
// add icon to dotnet stub
runCommand("tools/rcedit-x64.exe", $"\"{stagingPath}\\osu!.exe\" --set-icon \"{iconPath}\"");
write("Creating NuGet deployment package...");
runCommand(nugetPath, $"pack {NuSpecName} -Version {version} -Properties Configuration=Deploy -OutputDirectory {stagingPath} -BasePath {stagingPath}");
// prune once before checking for files so we can avoid erroring on files which aren't even needed for this build.
pruneReleases();
checkReleaseFiles();
write("Running squirrel build...");
string codeSigningCmd = string.Empty;
if (!string.IsNullOrEmpty(CodeSigningCertificate))
{
string? codeSigningPassword;
if (args.Length > 0)
{
codeSigningPassword = args[0];
}
else
{
Console.Write("Enter code signing password: ");
codeSigningPassword = readLineMasked();
}
codeSigningCmd = string.IsNullOrEmpty(codeSigningPassword)
? ""
: $"--signParams=\"/td sha256 /fd sha256 /f {CodeSigningCertificate} /p {codeSigningPassword} /tr http://timestamp.comodoca.com\"";
}
string nupkgFilename = $"{PackageName}.{version}.nupkg";
runCommand(squirrelPath,
$"releasify --package={stagingPath}\\{nupkgFilename} --releaseDir={releasesPath} --icon={iconPath} --appIcon={iconPath} --splashImage={splashImagePath} {codeSigningCmd}");
// prune again to clean up before upload.
pruneReleases();
// rename setup to install.
File.Copy(Path.Combine(releases_folder, "osulazerSetup.exe"), Path.Combine(releases_folder, "install.exe"), true);
File.Delete(Path.Combine(releases_folder, "osulazerSetup.exe"));
break;
case RuntimeInfo.Platform.macOS:
string targetArch = "";
if (args.Length > 3)
{
targetArch = args[3];
}
else if (interactive)
{
Console.Write("Build for which architecture? [x64/arm64]: ");
targetArch = Console.ReadLine() ?? string.Empty;
}
if (targetArch != "x64" && targetArch != "arm64")
error($"Invalid Architecture: {targetArch}");
buildForMac(targetArch, version);
break;
case RuntimeInfo.Platform.Android:
string codeSigningArguments = string.Empty;
if (!string.IsNullOrEmpty(CodeSigningCertificate))
{
string? codeSigningPassword;
if (args.Length > 0)
{
codeSigningPassword = args[0];
}
else
{
Console.Write("Enter code signing password: ");
codeSigningPassword = readLineMasked();
}
codeSigningArguments += " -p:AndroidKeyStore=true"
+ $" -p:AndroidSigningKeyStore={CodeSigningCertificate}"
+ $" -p:AndroidSigningKeyAlias={Path.GetFileNameWithoutExtension(CodeSigningCertificate)}"
+ $" -p:AndroidSigningKeyPass={codeSigningPassword}"
+ $" -p:AndroidSigningStorePass={codeSigningPassword}";
}
string[] versionParts = version.Split('.');
string appVersion = string.Join
(
separator: string.Empty,
versionParts[0].PadLeft(4, '0'),
versionParts[1].PadLeft(4, '0'),
versionParts[2].PadLeft(1, '0')
);
runCommand("dotnet", "publish"
+ " -f net6.0-android"
+ " -r android-arm64"
+ " -c Release"
+ $" -o {stagingPath}"
+ $" -p:Version={version}"
+ $" -p:ApplicationVersion={appVersion}"
+ codeSigningArguments
+ " --self-contained"
+ " osu.Android/osu.Android.csproj");
// copy update information
File.Move(Path.Combine(stagingPath, "sh.ppy.osulazer-Signed.apk"), Path.Combine(releasesPath, "sh.ppy.osulazer.apk"), true);
break;
case RuntimeInfo.Platform.iOS:
runCommand("dotnet", "publish"
+ " -f net6.0-ios"
+ " -r ios-arm64"
+ " -c Release"
+ $" -o {stagingPath}"
+ $" -p:Version={version}"
+ $" -p:ApplicationDisplayVersion=1.0"
+ " --self-contained"
+ " osu.iOS/osu.iOS.csproj");
// copy update information
File.Move(Path.Combine(stagingPath, "osu.iOS.ipa"), Path.Combine(releasesPath, "osu.iOS.ipa"), true);
break;
case RuntimeInfo.Platform.Linux:
const string app_dir = "osu!.AppDir";
string stagingTarget = Path.Combine(stagingPath, app_dir);
if (Directory.Exists(stagingTarget))
Directory.Delete(stagingTarget, true);
Directory.CreateDirectory(stagingTarget);
foreach (var file in Directory.GetFiles(Path.Combine(templatesPath, app_dir)))
new FileInfo(file).CopyTo(Path.Combine(stagingTarget, Path.GetFileName(file)));
// mark AppRun as executable, as zip does not contains executable information
runCommand("chmod", $"+x {stagingTarget}/AppRun");
runCommand("dotnet", $"publish -f net6.0 -r linux-x64 {ProjectName} -o {stagingTarget}/usr/bin/ --configuration Release /p:Version={version} --self-contained");
// mark output as executable
runCommand("chmod", $"+x {stagingTarget}/usr/bin/osu!");
// copy png icon (for desktop file)
File.Copy(Path.Combine(solutionPath, "assets/lazer.png"), $"{stagingTarget}/osu!.png");
// download appimagetool
string appImageToolPath = $"{stagingPath}/appimagetool.AppImage";
using (var client = new HttpClient())
{
using (var stream = client.GetStreamAsync("https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage").GetResultSafely())
using (var fileStream = new FileStream(appImageToolPath, FileMode.CreateNew))
{
stream.CopyToAsync(fileStream).WaitSafely();
}
}
// mark appimagetool as executable
runCommand("chmod", $"a+x {appImageToolPath}");
// create AppImage itself
// gh-releases-zsync stands here for GitHub Releases ZSync, that is a way to check for updates
// ppy|osu|latest stands for https://github.com/ppy/osu and get the latest release
// osu.AppImage.zsync is AppImage update information file, that is generated by the tool
// more information there https://docs.appimage.org/packaging-guide/optional/updates.html?highlight=update#using-appimagetool
runCommand(appImageToolPath,
$"\"{stagingTarget}\" -u \"gh-releases-zsync|ppy|osu|latest|osu.AppImage.zsync\" \"{Path.Combine(Environment.CurrentDirectory, "releases")}/osu.AppImage\" --sign", false);
// mark finally the osu! AppImage as executable -> Don't compress it.
runCommand("chmod", $"+x \"{Path.Combine(Environment.CurrentDirectory, "releases")}/osu.AppImage\"");
// copy update information
File.Move(Path.Combine(Environment.CurrentDirectory, "osu.AppImage.zsync"), $"{releases_folder}/osu.AppImage.zsync", true);
break;
}
if (GitHubUpload)
uploadBuild(version);
write("Done!");
pauseIfInteractive();
}
private static void displayHeader()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine(" Please note that OSU! and PPY are registered trademarks and as such covered by trademark law.");
Console.WriteLine(" Do not distribute builds of this project publicly that make use of these.");
Console.ResetColor();
Console.WriteLine();
}
private static void buildForMac(string arch, string version)
{
// unzip the template app, with all structure existing except for dotnet published content.
runCommand("unzip", $"\"osu!.app-template.zip\" -d {stagingPath}", false);
// without touching the app bundle itself, changes to file associations / icons / etc. will be cached at a macOS level and not updated.
runCommand("touch", $"\"{Path.Combine(stagingPath, "osu!.app")}\" {stagingPath}", false);
runCommand("dotnet", $"publish -r osx-{arch} {ProjectName} --configuration Release -o {stagingPath}/osu!.app/Contents/MacOS /p:Version={version}");
string stagingApp = $"{stagingPath}/osu!.app";
string archLabel = arch == "x64" ? "Intel" : "Apple Silicon";
string zippedApp = $"{releasesPath}/osu!.app ({archLabel}).zip";
// correct permissions post-build. dotnet outputs 644 by default; we want 755.
runCommand("chmod", $"-R 755 {stagingApp}");
if (!string.IsNullOrEmpty(CodeSigningCertificate))
{
// sign using apple codesign
runCommand("codesign",
$"--deep --force --verify --keychain app-signing --entitlements {Path.Combine(Environment.CurrentDirectory, "osu.entitlements")} -o runtime --verbose --sign \"{CodeSigningCertificate}\" {stagingApp}");
// check codesign was successful
runCommand("spctl", $"--assess -vvvv {stagingApp}");
}
// package for distribution
runCommand("ditto", $"-ck --rsrc --keepParent --sequesterRsrc {stagingApp} \"{zippedApp}\"");
string notarisationUsername = ConfigurationManager.AppSettings["AppleUsername"] ?? string.Empty;
if (!string.IsNullOrEmpty(notarisationUsername))
{
// upload for notarisation
runCommand("xcrun",
$"altool --notarize-app --primary-bundle-id \"sh.ppy.osu.lazer\" --username \"{notarisationUsername}\" --password \"{ConfigurationManager.AppSettings["ApplePassword"]}\" --file \"{zippedApp}\"");
// TODO: make this actually wait properly
write("Waiting for notarisation to complete..");
Thread.Sleep(60000 * 5);
// staple notarisation result
runCommand("xcrun", $"stapler staple {stagingApp}");
}
File.Delete(zippedApp);
// repackage for distribution
runCommand("ditto", $"-ck --rsrc --keepParent --sequesterRsrc {stagingApp} \"{zippedApp}\"");
}
/// <summary>
/// Ensure we have all the files in the release directory which are expected to be there.
/// This should have been accounted for in earlier steps, and just serves as a verification step.
/// </summary>
private static void checkReleaseFiles()
{
if (!canGitHub) return;
var releaseLines = getReleaseLines();
//ensure we have all files necessary
foreach (var l in releaseLines)
if (!File.Exists(Path.Combine(releases_folder, l.Filename)))
error($"Local file missing {l.Filename}");
}
private static IEnumerable<ReleaseLine> getReleaseLines()
{
return File.ReadAllLines(Path.Combine(releases_folder, "RELEASES")).Select(l => new ReleaseLine(l));
}
private static void pruneReleases()
{
if (!canGitHub) return;
write("Pruning RELEASES...");
var releaseLines = getReleaseLines().ToList();
var fulls = releaseLines.Where(l => l.Filename.Contains("-full")).Reverse().Skip(1);
//remove any FULL releases (except most recent)
foreach (var l in fulls)
{
write($"- Removing old release {l.Filename}", ConsoleColor.Yellow);
File.Delete(Path.Combine(releases_folder, l.Filename));
releaseLines.Remove(l);
}
//remove excess deltas
var deltas = releaseLines.Where(l => l.Filename.Contains("-delta")).ToArray();
if (deltas.Length > keep_delta_count)
{
foreach (var l in deltas.Take(deltas.Length - keep_delta_count))
{
write($"- Removing old delta {l.Filename}", ConsoleColor.Yellow);
File.Delete(Path.Combine(releases_folder, l.Filename));
releaseLines.Remove(l);
}
}
var lines = new List<string>();
releaseLines.ForEach(l => lines.Add(l.ToString()));
File.WriteAllLines(Path.Combine(releases_folder, "RELEASES"), lines);
}
private static void uploadBuild(string version)
{
if (!canGitHub || string.IsNullOrEmpty(CodeSigningCertificate))
return;
write("Publishing to GitHub...");
var req = new JsonWebRequest<GitHubRelease>($"{GitHubApiEndpoint}")
{
Method = HttpMethod.Post,
};
GitHubRelease? targetRelease = getLastGithubRelease(true);
if (targetRelease == null || targetRelease.TagName != version)
{
write($"- Creating release {version}...", ConsoleColor.Yellow);
req.AddRaw(JsonConvert.SerializeObject(new GitHubRelease
{
Name = version,
Draft = true,
}));
req.AuthenticatedBlockingPerform();
targetRelease = req.ResponseObject;
}
else
{
write($"- Adding to existing release {version}...", ConsoleColor.Yellow);
}
Debug.Assert(targetRelease.UploadUrl != null);
var assetUploadUrl = targetRelease.UploadUrl.Replace("{?name,label}", "?name={0}");
foreach (var a in Directory.GetFiles(releases_folder).Reverse()) //reverse to upload RELEASES first.
{
if (Path.GetFileName(a).StartsWith('.'))
continue;
write($"- Adding asset {a}...", ConsoleColor.Yellow);
var upload = new WebRequest(assetUploadUrl, Path.GetFileName(a))
{
Method = HttpMethod.Post,
Timeout = 240000,
ContentType = "application/octet-stream",
};
upload.AddRaw(File.ReadAllBytes(a));
upload.AuthenticatedBlockingPerform();
}
openGitHubReleasePage();
}
private static void openGitHubReleasePage()
{
Process.Start(new ProcessStartInfo
{
FileName = $"https://github.com/{GitHubUsername}/{GitHubRepoName}/releases",
UseShellExecute = true //see https://github.com/dotnet/corefx/issues/10361
});
}
private static bool canGitHub => !string.IsNullOrEmpty(GitHubAccessToken);
private static GitHubRelease? getLastGithubRelease(bool includeDrafts = false)
{
var req = new JsonWebRequest<List<GitHubRelease>>($"{GitHubApiEndpoint}");
req.AuthenticatedBlockingPerform();
return req.ResponseObject.FirstOrDefault(r => includeDrafts || !r.Draft);
}
/// <summary>
/// Download assets from a previous release into the releases folder.
/// </summary>
/// <param name="release"></param>
private static void getAssetsFromRelease(GitHubRelease release)
{
if (!canGitHub) return;
//there's a previous release for this project.
var assetReq = new JsonWebRequest<List<GitHubObject>>($"{GitHubApiEndpoint}/{release.Id}/assets");
assetReq.AuthenticatedBlockingPerform();
var assets = assetReq.ResponseObject;
//make sure our RELEASES file is the same as the last build on the server.
var releaseAsset = assets.FirstOrDefault(a => a.Name == "RELEASES");
//if we don't have a RELEASES asset then the previous release likely wasn't a Squirrel one.
if (releaseAsset == null) return;
bool requireDownload = false;
if (!File.Exists(Path.Combine(releases_folder, $"{PackageName}-{release.Name}-full.nupkg")))
{
write("Last version's package not found locally.", ConsoleColor.Red);
requireDownload = true;
}
else
{
var lastReleases = new RawFileWebRequest($"{GitHubApiEndpoint}/assets/{releaseAsset.Id}");
lastReleases.AuthenticatedBlockingPerform();
if (File.ReadAllText(Path.Combine(releases_folder, "RELEASES")) != lastReleases.GetResponseString())
{
write("Server's RELEASES differed from ours.", ConsoleColor.Red);
requireDownload = true;
}
}
if (!requireDownload) return;
write("Refreshing local releases directory...");
refreshDirectory(releases_folder);
foreach (var a in assets)
{
if (a.Name != "RELEASES" && !a.Name.EndsWith(".nupkg", StringComparison.InvariantCulture)) continue;
write($"- Downloading {a.Name}...", ConsoleColor.Yellow);
new FileWebRequest(Path.Combine(releases_folder, a.Name), $"{GitHubApiEndpoint}/assets/{a.Id}").AuthenticatedBlockingPerform();
}
}
private static void refreshDirectory(string directory)
{
if (Directory.Exists(directory))
Directory.Delete(directory, true);
Directory.CreateDirectory(directory);
}
/// <summary>
/// Find the base path of the active solution (git checkout location)
/// </summary>
private static void findSolutionPath()
{
string? path = Path.GetDirectoryName(Environment.CommandLine.Replace("\"", "").Trim());
if (string.IsNullOrEmpty(path))
path = Environment.CurrentDirectory;
while (true)
{
if (File.Exists(Path.Combine(path, $"{SolutionName}.sln")))
break;
if (Directory.Exists(Path.Combine(path, "osu")) && File.Exists(Path.Combine(path, "osu", $"{SolutionName}.sln")))
{
path = Path.Combine(path, "osu");
break;
}
path = path.Remove(path.LastIndexOf(Path.DirectorySeparatorChar));
}
path += Path.DirectorySeparatorChar;
solutionPath = path;
}
private static bool runCommand(string command, string args, bool useSolutionPath = true)
{
write($"Running {command} {args}...");
var psi = new ProcessStartInfo(command, args)
{
WorkingDirectory = useSolutionPath ? solutionPath : Environment.CurrentDirectory,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
};
Process? p = Process.Start(psi);
if (p == null) return false;
string output = p.StandardOutput.ReadToEnd();
output += p.StandardError.ReadToEnd();
p.WaitForExit();
if (p.ExitCode == 0) return true;
write(output);
error($"Command {command} {args} failed!");
return false;
}
private static string? readLineMasked()
{
var fg = Console.ForegroundColor;
Console.ForegroundColor = Console.BackgroundColor;
var ret = Console.ReadLine();
Console.ForegroundColor = fg;
return ret;
}
private static string getToolPath(string packageName, string toolExecutable)
{
var process = Process.Start(new ProcessStartInfo("dotnet", "list osu.Desktop.Deploy.csproj package")
{
RedirectStandardOutput = true
});
Debug.Assert(process != null);
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
var match = Regex.Matches(output, $@"(?m){packageName.Replace(".", "\\.")}.*\s(\d{{1,3}}\.\d{{1,3}}\.\d.*?)$");
if (match.Count == 0)
throw new InvalidOperationException($"Missing tool for {toolExecutable}");
var toolPath = Path.Combine(packages, packageName.ToLowerInvariant(), match[0].Groups[1].Value.Trim(), "tools", toolExecutable);
return toolPath;
}
private static void error(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"FATAL ERROR: {message}");
pauseIfInteractive();
Environment.Exit(-1);
}
private static void pauseIfInteractive()
{
if (interactive)
Console.ReadLine();
else
Console.WriteLine();
}
private static bool updateAppveyorVersion(string version)
{
try
{
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript($"Update-AppveyorBuild -Version \"{version}\"");
ps.Invoke();
}
return true;
}
catch
{
// we don't have appveyor and don't care
}
return false;
}
private static void write(string message, ConsoleColor col = ConsoleColor.Gray)
{
if (stopwatch.ElapsedMilliseconds > 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(stopwatch.ElapsedMilliseconds.ToString().PadRight(8));
}
Console.ForegroundColor = col;
Console.WriteLine(message);
}
public static void AuthenticatedBlockingPerform(this WebRequest r)
{
r.AddHeader("Authorization", $"token {GitHubAccessToken}");
r.Perform();
}
}
internal class RawFileWebRequest : WebRequest
{
public RawFileWebRequest(string url)
: base(url)
{
}
protected override string Accept => "application/octet-stream";
}
internal class ReleaseLine
{
public string Hash;
public string Filename;
public int Filesize;
public ReleaseLine(string line)
{
var split = line.Split(' ');
Hash = split[0];
Filename = split[1];
Filesize = int.Parse(split[2]);
}
public override string ToString()
{
return $"{Hash} {Filename} {Filesize}";
}
}
}