-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
227 lines (178 loc) · 7.88 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
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using DragonFruit.OnionFruit.Deploy.Build;
using Microsoft.Extensions.Configuration;
using Octokit;
using Serilog;
using Serilog.Sinks.SystemConsole.Themes;
namespace DragonFruit.OnionFruit.Deploy;
public static class Program
{
private static readonly IConfiguration Config;
public static string ReleasesDirectory { get; } = Path.Combine(Environment.CurrentDirectory, "releases");
public static string StagingDirectory { get; } = Path.Combine(Environment.CurrentDirectory, "staging");
internal static string SolutionName => Config["SolutionName"] ?? throw new InvalidOperationException("SolutionName not set in app.config");
internal static string GitHubRepoUser => Config["GitHub:User"] ?? string.Empty;
internal static string GitHubRepoName => Config["GitHub:Repo"] ?? string.Empty;
internal static string GitHubAccessToken => Config["GitHub:Token"] ?? string.Empty;
internal static string GitHubRepoUrl => CanUseGitHub ? $"https://github.com/{GitHubRepoUser}/{GitHubRepoName}" : string.Empty;
internal static bool CanUseGitHub => !string.IsNullOrEmpty(GitHubAccessToken) && !string.IsNullOrEmpty(GitHubRepoName) && !string.IsNullOrEmpty(GitHubRepoUser);
internal static string VelopackId => Config["Velopack:PackageId"] ?? string.Empty;
internal static string VelopackIcon => Config["Velopack:PackageIcon"] ?? string.Empty;
internal static string VelopackIconPath => Path.GetFullPath(Path.Combine(SolutionPath, VelopackIcon));
internal static string CodeSignCert => Config["CodeSign:Certificate"] ?? string.Empty;
internal static string CodeSignCertPassword => Config["CodeSign:Password"] ?? string.Empty;
public static GitHubClient? GitHubClient { get; private set; }
internal static string ProjectLocation { get; private set; } = null!;
internal static string SolutionPath { get; private set; } = null!;
static Program()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.With(new ProcessAgeEnricher())
.WriteTo.Console(outputTemplate: "> [{ProcessAge} {Level}]: {Message}{NewLine}", theme: AnsiConsoleTheme.Literate)
.CreateLogger();
Config = new ConfigurationBuilder()
.AddXmlFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "oniondeploy.xml"), optional: true)
.AddEnvironmentVariables("ONIONDEPLOY_")
.Build();
}
public static async Task<int> Main(string[] args)
{
if (args.Length < 2)
{
Log.Information("Usage: [csproj file location] [runtime identifier] [version]");
return -1;
}
if (CanUseGitHub)
{
GitHubClient = new GitHubClient(new ProductHeaderValue("OnionFruit-Deploy"))
{
Credentials = new Credentials(GitHubAccessToken)
};
}
ProjectLocation = GetArg(0) ?? string.Empty;
if (Path.GetExtension(ProjectLocation) != ".csproj" || !File.Exists(ProjectLocation))
{
Log.Error("Invalid project file");
return -1;
}
var fullProjectDir = Path.IsPathRooted(ProjectLocation) ? ProjectLocation : Path.Combine(Environment.CurrentDirectory, ProjectLocation);
FindSolutionPath(Path.GetDirectoryName(fullProjectDir)!);
var version = GetArg(2) ?? await GetVersionFromPublicReleasesAsync();
Log.Information("OnionFruit Deploy v{version:l} building {appVersion:l}", Assembly.GetExecutingAssembly().GetName().Version!.ToString(3), version);
ProgramBuilder builder;
switch (GetArg(1))
{
case "win-x64":
builder = new WindowsProgramBuilder(version, Architecture.X64);
break;
case "win-arm64":
builder = new WindowsProgramBuilder(version, Architecture.Arm64);
break;
default:
Log.Error("Unsupported platform {platform}", GetArg(1));
return -1;
}
var distributor = builder.CreateBuildDistributor();
if (Config["SkipBuild"]?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)
{
if (!File.Exists(Path.Combine(StagingDirectory, builder.ExecutableName)))
{
Log.Error("Build was skipped but no executable was found in the staging directory");
return -1;
}
Log.Information("Build skipped, restoring and publishing only...");
}
else
{
Log.Information("Performing build...");
await builder.BuildAsync();
}
Log.Information("Restoring build...");
await distributor.RestoreBuild();
Log.Information("Pack n' Publishing build...");
await distributor.PublishBuild(version);
if (CanUseGitHub)
{
Process.Start(new ProcessStartInfo($"{GitHubRepoUrl}/releases")
{
UseShellExecute = true,
Verb = "open"
});
}
Log.Information("Build complete");
return 0;
}
public static async Task<bool> RunCommand(string command, string args, bool useSolutionPath = true, bool throwOnError = true)
{
var psi = new ProcessStartInfo(command, args)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
WorkingDirectory = useSolutionPath ? SolutionPath : Environment.CurrentDirectory
};
using var process = Process.Start(psi);
Debug.Assert(process != null);
process.ErrorDataReceived += (_, err) => Log.Error(err.Data!);
process.OutputDataReceived += (_, output) => Log.Debug(output.Data!);
process.BeginErrorReadLine();
process.BeginOutputReadLine();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
{
Log.Error("Command {command:l} failed with exit code {exitCode}", $"{process.StartInfo.FileName} {process.StartInfo.Arguments}", process.ExitCode);
if (throwOnError)
{
throw new InvalidOperationException($"Command {command} failed with exit code {process.ExitCode}");
}
return false;
}
return true;
}
private static string? GetArg(int index)
{
var args = Environment.GetCommandLineArgs();
return args.Length > ++index ? args[index] : null;
}
private static void FindSolutionPath(string path)
{
while (true)
{
if (File.Exists(Path.Combine(path, SolutionName)))
break;
path = Path.GetFullPath(Path.Combine(path, ".."));
}
SolutionPath = path;
}
private static async Task<string> GetVersionFromPublicReleasesAsync()
{
Release? latestRelease = null;
if (CanUseGitHub)
{
var latestReleases = await GitHubClient!.Repository.Release.GetAll(GitHubRepoUser, GitHubRepoName, new ApiOptions
{
PageSize = 1
});
latestRelease = latestReleases.SingleOrDefault();
}
// get latest release for incrementing
var version = DateTime.Now.ToString("yyyy.Mdd.");
if (latestRelease?.Draft == false && latestRelease.TagName.StartsWith(version, StringComparison.InvariantCulture))
{
version += int.Parse(latestRelease.TagName.Split('.')[2]) + 1;
}
else
{
version += "0";
}
return version;
}
}