-
Notifications
You must be signed in to change notification settings - Fork 45
/
Pr.cs
316 lines (290 loc) · 15.7 KB
/
Pr.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
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CompatApiClient.Utils;
using CompatBot.Commands.Attributes;
using CompatBot.Utils;
using CompatBot.Utils.Extensions;
using CompatBot.Utils.ResultFormatters;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.TeamFoundation.Build.WebApi;
using BuildStatus = Microsoft.TeamFoundation.Build.WebApi.BuildStatus;
namespace CompatBot.Commands;
[Group("pr"), TriggersTyping]
[Description("Commands to list opened pull requests information")]
internal sealed class Pr: BaseCommandModuleCustom
{
private static readonly GithubClient.Client GithubClient = new(Config.GithubToken);
private static readonly CompatApiClient.Client CompatApiClient = new();
[GroupCommand]
public Task List(CommandContext ctx, [Description("Get information for specific PR number")] int pr) => LinkPrBuild(ctx.Client, ctx.Message, pr);
[GroupCommand]
public async Task List(CommandContext ctx, [Description("Get information for PRs with specified text in description. First word might be an author"), RemainingText] string? searchStr = null)
{
var openPrList = await GithubClient.GetOpenPrsAsync(Config.Cts.Token).ConfigureAwait(false);
if (openPrList == null)
{
await ctx.ReactWithAsync(Config.Reactions.Failure, "Couldn't retrieve open pull requests list, try again later").ConfigureAwait(false);
return;
}
if (openPrList.Count == 0)
{
await ctx.Channel.SendMessageAsync("It looks like there are no open pull requests at the moment 🎉").ConfigureAwait(false);
return;
}
if (!string.IsNullOrEmpty(searchStr))
{
var filteredList = openPrList.Where(
pr => pr.Title?.Contains(searchStr, StringComparison.InvariantCultureIgnoreCase) is true
|| pr.User?.Login?.Contains(searchStr, StringComparison.InvariantCultureIgnoreCase) is true
).ToList();
if (filteredList.Count == 0)
{
var searchParts = searchStr.Split(' ', 2);
if (searchParts.Length == 2)
{
var author = searchParts[0].Trim();
var substr = searchParts[1].Trim();
openPrList = openPrList.Where(
pr => pr.User?.Login?.Contains(author, StringComparison.InvariantCultureIgnoreCase) is true
&& pr.Title?.Contains(substr, StringComparison.InvariantCultureIgnoreCase) is true
).ToList();
}
else
openPrList = filteredList;
}
else
openPrList = filteredList;
}
if (openPrList.Count == 0)
{
await ctx.Channel.SendMessageAsync("No open pull requests were found for specified filter").ConfigureAwait(false);
return;
}
if (openPrList.Count == 1)
{
await LinkPrBuild(ctx.Client, ctx.Message, openPrList[0].Number).ConfigureAwait(false);
return;
}
var responseChannel = await ctx.GetChannelForSpamAsync().ConfigureAwait(false);
const int maxTitleLength = 80;
var maxNum = openPrList.Max(pr => pr.Number).ToString().Length + 1;
var maxAuthor = openPrList.Max(pr => (pr.User?.Login).GetVisibleLength());
var maxTitle = Math.Min(openPrList.Max(pr => pr.Title.GetVisibleLength()), maxTitleLength);
var result = new StringBuilder($"There are {openPrList.Count} open pull requests:\n");
foreach (var pr in openPrList)
result.Append('`').Append($"{("#" + pr.Number).PadLeft(maxNum)} by {pr.User?.Login?.PadRightVisible(maxAuthor)}: {pr.Title?.Trim(maxTitleLength).PadRightVisible(maxTitle)}".FixSpaces()).AppendLine($"` <{pr.HtmlUrl}>");
await responseChannel.SendAutosplitMessageAsync(result, blockStart: null, blockEnd: null).ConfigureAwait(false);
}
[Command("link"), Aliases("old")]
[Description("Links to the official binary builds produced after specified PR was merged")]
public Task Link(CommandContext ctx, [Description("PR number")] int pr) => LinkPrBuild(ctx.Client, ctx.Message, pr, true);
#if DEBUG
[Command("stats"), RequiresBotModRole]
public async Task Stats(CommandContext ctx)
{
var azureClient = Config.GetAzureDevOpsClient();
var duration = await azureClient.GetPipelineDurationAsync(Config.Cts.Token).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(
$"Expected pipeline duration (using {duration.BuildCount} builds): \n" +
$"95%: {duration.Percentile95} ({duration.Percentile95.TotalMinutes})\n" +
$"90%: {duration.Percentile90} ({duration.Percentile90.TotalMinutes})\n" +
$"85%: {duration.Percentile85} ({duration.Percentile85.TotalMinutes})\n" +
$"80%: {duration.Percentile80} ({duration.Percentile80.TotalMinutes})\n" +
$"Avg: {duration.Mean} ({duration.Mean.TotalMinutes})\n" +
$"Dev: {duration.StdDev} ({duration.StdDev.TotalMinutes})"
).ConfigureAwait(false);
}
#endif
public static async Task LinkPrBuild(DiscordClient client, DiscordMessage message, int pr, bool linkOld = false)
{
var prInfo = await GithubClient.GetPrInfoAsync(pr, Config.Cts.Token).ConfigureAwait(false);
if (prInfo is null or {Number: 0})
{
await message.ReactWithAsync(Config.Reactions.Failure, prInfo?.Title ?? "PR not found").ConfigureAwait(false);
return;
}
var (state, _) = prInfo.GetState();
var embed = prInfo.AsEmbed();
var azureClient = Config.GetAzureDevOpsClient();
if (state is "Open" or "Closed")
{
var windowsDownloadHeader = "Windows PR Build";
var linuxDownloadHeader = "Linux PR Build";
var macDownloadHeader = "Mac PR Build";
string? windowsDownloadText = null;
string? linuxDownloadText = null;
string? macDownloadText = null;
string? buildTime = null;
if (azureClient != null && prInfo.Head?.Sha is string commit)
try
{
windowsDownloadText = "⏳ Pending...";
linuxDownloadText = "⏳ Pending...";
macDownloadText = "⏳ Pending...";
var latestBuild = await azureClient.GetPrBuildInfoAsync(commit, prInfo.MergedAt?.DateTime, pr, Config.Cts.Token).ConfigureAwait(false);
if (latestBuild == null)
{
if (state == "Open")
{
embed.WithFooter($"Opened on {prInfo.CreatedAt:u} ({(DateTime.UtcNow - prInfo.CreatedAt).AsTimeDeltaDescription()} ago)");
}
windowsDownloadText = null;
linuxDownloadText = null;
macDownloadText = null;
}
else
{
bool shouldHaveArtifacts = false;
if (latestBuild is
{
Status: BuildStatus.Completed,
Result: BuildResult.Succeeded or BuildResult.PartiallySucceeded,
FinishTime: not null
})
{
buildTime = $"Built on {latestBuild.FinishTime:u} ({(DateTime.UtcNow - latestBuild.FinishTime.Value).AsTimeDeltaDescription()} ago)";
shouldHaveArtifacts = true;
}
// Check for subtask errors (win/lin/mac)
if (latestBuild.Result is BuildResult.Failed or BuildResult.Canceled)
{
windowsDownloadText = $"❌ {latestBuild.Result}";
}
/*
if (latestBuild.LinuxBuild?.Status is TaskStatus.Aborted or TaskStatus.Failed or TaskStatus.Skipped)
{
linuxDownloadText = $"❌ {latestBuild.LinuxBuild?.Status}";
}
if (latestBuild.MacBuild?.Status is TaskStatus.Aborted or TaskStatus.Failed or TaskStatus.Skipped)
{
macDownloadText = $"❌ {latestBuild.MacBuild?.Status}";
}
*/
// Check estimated time for pending builds
if (latestBuild is { Status: BuildStatus.InProgress, StartTime: not null })
{
var estimatedCompletionTime = latestBuild.StartTime.Value + (await azureClient.GetPipelineDurationAsync(Config.Cts.Token).ConfigureAwait(false)).Mean;
var estimatedTime = TimeSpan.FromMinutes(1);
if (estimatedCompletionTime > DateTime.UtcNow)
estimatedTime = estimatedCompletionTime - DateTime.UtcNow;
windowsDownloadText = $"⏳ Pending in {estimatedTime.AsTimeDeltaDescription()}...";
linuxDownloadText = windowsDownloadText;
macDownloadText = windowsDownloadText;
/*
if (latestBuild.WindowsBuild?.Status is TaskStatus.Executing)
{
windowsDownloadText = $"⏳ Pending in {estimatedTime.AsTimeDeltaDescription()}...";
}
if (latestBuild.LinuxBuild?.Status is TaskStatus.Executing)
{
linuxDownloadText = $"⏳ Pending in {estimatedTime.AsTimeDeltaDescription()}...";
}
if (latestBuild.MacBuild?.Status is TaskStatus.Executing)
{
macDownloadText = $"⏳ Pending in {estimatedTime.AsTimeDeltaDescription()}...";
}
*/
}
// windows build
var name = latestBuild.WindowsFilename ?? "Windows PR Build";
name = name.Replace("rpcs3-", "").Replace("_win64", "");
if (!string.IsNullOrEmpty(latestBuild.WindowsBuildDownloadLink))
windowsDownloadText = $"[⏬ {name}]({latestBuild.WindowsBuildDownloadLink})";
else if (shouldHaveArtifacts)
{
if (latestBuild.FinishTime.HasValue && (DateTime.UtcNow - latestBuild.FinishTime.Value).TotalDays > 30)
windowsDownloadText = "No longer available";
}
// linux build
name = latestBuild.LinuxFilename ?? "Linux PR Build";
name = name.Replace("rpcs3-", "").Replace("_linux64", "");
if (!string.IsNullOrEmpty(latestBuild.LinuxBuildDownloadLink))
linuxDownloadText = $"[⏬ {name}]({latestBuild.LinuxBuildDownloadLink})";
else if (shouldHaveArtifacts)
{
if (latestBuild.FinishTime.HasValue && (DateTime.UtcNow - latestBuild.FinishTime.Value).TotalDays > 30)
linuxDownloadText = "No longer available";
}
// mac build
name = latestBuild.MacFilename ?? "Mac PR Build";
name = name.Replace("rpcs3-", "").Replace("_macos", "");
if (!string.IsNullOrEmpty(latestBuild.MacBuildDownloadLink))
macDownloadText = $"[⏬ {name}]({latestBuild.MacBuildDownloadLink})";
else if (shouldHaveArtifacts)
{
if (latestBuild.FinishTime.HasValue && (DateTime.UtcNow - latestBuild.FinishTime.Value).TotalDays > 30)
macDownloadText = "No longer available";
}
// Neatify PR's with missing builders
/*if (latestBuild.WindowsBuild?.Status is null)
{
windowsDownloadText = null;
}
if (latestBuild.LinuxBuild?.Status is null)
{
linuxDownloadText = null;
}
if (latestBuild.MacBuild?.Status is null)
{
macDownloadText = null;
}*/
}
}
catch (Exception e)
{
Config.Log.Error(e, "Failed to get CI build info");
windowsDownloadText = null; // probably due to expired access token
linuxDownloadText = null;
macDownloadText = null;
}
if (!string.IsNullOrEmpty(windowsDownloadText))
embed.AddField(windowsDownloadHeader, windowsDownloadText, true);
if (!string.IsNullOrEmpty(linuxDownloadText))
embed.AddField(linuxDownloadHeader, linuxDownloadText, true);
if (!string.IsNullOrEmpty (macDownloadText))
embed.AddField(macDownloadHeader, macDownloadText, true);
if (!string.IsNullOrEmpty(buildTime))
embed.WithFooter(buildTime);
}
else if (state is "Merged" && azureClient is not null)
{
var mergeTime = prInfo.MergedAt.GetValueOrDefault();
var now = DateTime.UtcNow;
var updateInfo = await CompatApiClient.GetUpdateAsync(Config.Cts.Token, linkOld ? prInfo.MergeCommitSha : null).ConfigureAwait(false);
if (updateInfo is not null)
{
if (DateTime.TryParse(updateInfo.LatestBuild?.Datetime, out var masterBuildTime) && masterBuildTime.Ticks >= mergeTime.Ticks)
embed = await updateInfo.AsEmbedAsync(client, false, embed, prInfo, linkOld).ConfigureAwait(false);
else
{
var waitTime = TimeSpan.FromMinutes(5);
var avgBuildTime = (await azureClient.GetPipelineDurationAsync(Config.Cts.Token).ConfigureAwait(false)).Mean;
if (now < mergeTime + avgBuildTime)
waitTime = mergeTime + avgBuildTime - now;
embed.AddField("Latest master build", $"""
This pull request has been merged, and will be part of `master` very soon.
Please check again in {waitTime.AsTimeDeltaDescription()}.
""");
}
}
}
await message.Channel.SendMessageAsync(embed: embed).ConfigureAwait(false);
}
public static async Task LinkIssue(DiscordClient client, DiscordMessage message, int issue)
{
var issueInfo = await GithubClient.GetIssueInfoAsync(issue, Config.Cts.Token).ConfigureAwait(false);
if (issueInfo is null or {Number: 0})
return;
if (issueInfo.PullRequest != null)
{
await LinkPrBuild(client, message, issue).ConfigureAwait(false);
return;
}
await message.Channel.SendMessageAsync(embed: issueInfo.AsEmbed()).ConfigureAwait(false);
}
}