This repository has been archived by the owner on Jun 21, 2023. It is now read-only.
/
PullRequestSession.cs
430 lines (374 loc) · 13.5 KB
/
PullRequestSession.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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GitHub.Extensions;
using GitHub.InlineReviews.Models;
using GitHub.Models;
using GitHub.Services;
using ReactiveUI;
using System.Threading;
using System.Reactive.Subjects;
using static System.FormattableString;
using GitHub.Primitives;
namespace GitHub.InlineReviews.Services
{
/// <summary>
/// A pull request session used to display inline reviews.
/// </summary>
/// <remarks>
/// A pull request session represents the real-time state of a pull request in the IDE.
/// It takes the pull request model and updates according to the current state of the
/// repository on disk and in the editor.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "PullRequestSession is shared and shouldn't be disposed")]
public class PullRequestSession : ReactiveObject, IPullRequestSession
{
readonly IPullRequestSessionService service;
readonly Dictionary<string, PullRequestSessionFile> fileIndex = new Dictionary<string, PullRequestSessionFile>();
readonly SemaphoreSlim getFilesLock = new SemaphoreSlim(1);
bool isCheckedOut;
string mergeBase;
IReadOnlyList<IPullRequestSessionFile> files;
PullRequestDetailModel pullRequest;
string pullRequestNodeId;
Subject<PullRequestDetailModel> pullRequestChanged = new Subject<PullRequestDetailModel>();
bool hasPendingReview;
public PullRequestSession(
IPullRequestSessionService service,
ActorModel user,
PullRequestDetailModel pullRequest,
ILocalRepositoryModel localRepository,
string repositoryOwner,
bool isCheckedOut)
{
Guard.ArgumentNotNull(service, nameof(service));
Guard.ArgumentNotNull(user, nameof(user));
Guard.ArgumentNotNull(pullRequest, nameof(pullRequest));
Guard.ArgumentNotNull(localRepository, nameof(localRepository));
this.service = service;
this.isCheckedOut = isCheckedOut;
this.pullRequest = pullRequest;
User = user;
LocalRepository = localRepository;
RepositoryOwner = repositoryOwner;
UpdatePendingReview();
}
/// <inheritdoc/>
public async Task<IReadOnlyList<IPullRequestSessionFile>> GetAllFiles()
{
if (files == null)
{
files = await CreateAllFiles();
}
return files;
}
/// <inheritdoc/>
public async Task<IPullRequestSessionFile> GetFile(
string relativePath,
string commitSha = "HEAD")
{
await getFilesLock.WaitAsync();
try
{
PullRequestSessionFile file;
var normalizedPath = relativePath.Replace("\\", "/");
var key = normalizedPath + '@' + commitSha;
if (!fileIndex.TryGetValue(key, out file))
{
file = new PullRequestSessionFile(normalizedPath, commitSha);
await UpdateFile(file);
fileIndex.Add(key, file);
}
return file;
}
finally
{
getFilesLock.Release();
}
}
/// <inheritdoc/>
public async Task<string> GetMergeBase()
{
if (mergeBase == null)
{
mergeBase = await service.GetPullRequestMergeBase(LocalRepository, PullRequest);
}
return mergeBase;
}
/// <inheritdoc/>
public string GetRelativePath(string path)
{
if (Path.IsPathRooted(path))
{
var basePath = LocalRepository.LocalPath;
if (path.StartsWith(basePath, StringComparison.OrdinalIgnoreCase) && path.Length > basePath.Length + 1)
{
return path.Substring(basePath.Length + 1);
}
}
return null;
}
/// <inheritdoc/>
public async Task PostReviewComment(
string body,
string commitId,
string path,
IReadOnlyList<DiffChunk> diff,
int position)
{
if (!HasPendingReview)
{
var model = await service.PostStandaloneReviewComment(
LocalRepository,
PullRequest.Id,
body,
commitId,
path,
position);
await Update(model);
}
else
{
var model = await service.PostPendingReviewComment(
LocalRepository,
PendingReviewId,
body,
commitId,
path,
position);
await Update(model);
}
}
/// <inheritdoc/>
public async Task DeleteComment(int pullRequestId, int commentDatabaseId)
{
var model = await service.DeleteComment(
LocalRepository,
RepositoryOwner,
pullRequestId,
commentDatabaseId);
await Update(model);
}
/// <inheritdoc/>
public async Task EditComment(string commentNodeId, string body)
{
var model = await service.EditComment(
LocalRepository,
RepositoryOwner,
commentNodeId,
body);
await Update(model);
}
/// <inheritdoc/>
public async Task PostReviewComment(
string body,
string inReplyTo)
{
if (!HasPendingReview)
{
var model = await service.PostStandaloneReviewCommentReply(
LocalRepository,
PullRequest.Id,
body,
inReplyTo);
await Update(model);
}
else
{
var model = await service.PostPendingReviewCommentReply(
LocalRepository,
PendingReviewId,
body,
inReplyTo);
await Update(model);
}
}
/// <inheritdoc/>
public async Task StartReview()
{
if (HasPendingReview)
{
throw new InvalidOperationException("A pending review is already underway.");
}
var model = await service.CreatePendingReview(
LocalRepository,
await GetPullRequestNodeId());
await Update(model);
}
/// <inheritdoc/>
public async Task CancelReview()
{
if (!HasPendingReview)
{
throw new InvalidOperationException("There is no pending review to cancel.");
}
await service.CancelPendingReview(LocalRepository, PendingReviewId);
PullRequest.Reviews = PullRequest.Reviews
.Where(x => x.Id != PendingReviewId)
.ToList();
await Update(PullRequest);
}
/// <inheritdoc/>
public async Task PostReview(string body, Octokit.PullRequestReviewEvent e)
{
PullRequestDetailModel model;
if (PendingReviewId == null)
{
model = await service.PostReview(
LocalRepository,
PullRequest.Id,
PullRequest.HeadRefSha,
body,
e);
}
else
{
model = await service.SubmitPendingReview(
LocalRepository,
PendingReviewId,
body,
e);
}
await Update(model);
}
/// <inheritdoc/>
public async Task Refresh()
{
var address = HostAddress.Create(LocalRepository.CloneUrl);
var model = await service.ReadPullRequestDetail(
address,
RepositoryOwner,
LocalRepository.Name,
PullRequest.Number);
await Update(model);
}
/// <inheritdoc/>
async Task Update(PullRequestDetailModel pullRequestModel)
{
PullRequest = pullRequestModel;
mergeBase = null;
foreach (var file in this.fileIndex.Values.ToList())
{
await UpdateFile(file);
}
UpdatePendingReview();
pullRequestChanged.OnNext(pullRequestModel);
}
async Task AddComment(PullRequestReviewCommentModel comment)
{
var review = PullRequest.Reviews.FirstOrDefault(x => x.Id == PendingReviewId);
if (review == null)
{
throw new KeyNotFoundException("Could not find pending review.");
}
review.Comments = review.Comments
.Concat(new[] { comment })
.ToList();
await Update(PullRequest);
}
async Task UpdateFile(PullRequestSessionFile file)
{
await Task.Delay(0);
var mergeBaseSha = await GetMergeBase();
file.BaseSha = PullRequest.BaseRefSha;
file.CommitSha = file.IsTrackingHead ? PullRequest.HeadRefSha : file.CommitSha;
file.Diff = await service.Diff(LocalRepository, mergeBaseSha, file.CommitSha, file.RelativePath);
file.InlineCommentThreads = service.BuildCommentThreads(PullRequest, file.RelativePath, file.Diff, file.CommitSha);
}
void UpdatePendingReview()
{
var pendingReview = PullRequest.Reviews
.FirstOrDefault(x => x.State == PullRequestReviewState.Pending && x.Author.Login == User.Login);
if (pendingReview != null)
{
HasPendingReview = true;
PendingReviewId = pendingReview.Id;
}
else
{
HasPendingReview = false;
PendingReviewId = null;
}
}
async Task<IReadOnlyList<IPullRequestSessionFile>> CreateAllFiles()
{
var result = new List<IPullRequestSessionFile>();
foreach (var path in FilePaths)
{
var file = await GetFile(path);
result.Add(file);
}
return result;
}
string GetFullPath(string relativePath)
{
return Path.Combine(LocalRepository.LocalPath, relativePath);
}
async Task<string> GetPullRequestNodeId()
{
if (pullRequestNodeId == null)
{
pullRequestNodeId = await service.GetGraphQLPullRequestId(
LocalRepository,
RepositoryOwner,
PullRequest.Number);
}
return pullRequestNodeId;
}
static string BuildDiffHunk(IReadOnlyList<DiffChunk> diff, int position)
{
var lines = diff.SelectMany(x => x.Lines).Reverse();
var context = lines.SkipWhile(x => x.DiffLineNumber != position).Take(5).Reverse().ToList();
var oldLineNumber = context.Select(x => x.OldLineNumber).Where(x => x != -1).FirstOrDefault();
var newLineNumber = context.Select(x => x.NewLineNumber).Where(x => x != -1).FirstOrDefault();
var header = Invariant($"@@ -{oldLineNumber},5 +{newLineNumber},5 @@");
return header + '\n' + string.Join("\n", context);
}
/// <inheritdoc/>
public bool IsCheckedOut
{
get { return isCheckedOut; }
internal set { this.RaiseAndSetIfChanged(ref isCheckedOut, value); }
}
/// <inheritdoc/>
public ActorModel User { get; }
/// <inheritdoc/>
public PullRequestDetailModel PullRequest
{
get { return pullRequest; }
private set
{
// PullRequestModel overrides Equals such that two PRs with the same number are
// considered equal. This was causing the PullRequest not to be updated on refresh:
// we need to use ReferenceEquals.
if (!ReferenceEquals(pullRequest, value))
{
this.RaisePropertyChanging(nameof(PullRequest));
pullRequest = value;
this.RaisePropertyChanged(nameof(PullRequest));
}
}
}
/// <inheritdoc/>
public IObservable<PullRequestDetailModel> PullRequestChanged => pullRequestChanged;
/// <inheritdoc/>
public ILocalRepositoryModel LocalRepository { get; }
/// <inheritdoc/>
public string RepositoryOwner { get; }
/// <inheritdoc/>
public bool HasPendingReview
{
get { return hasPendingReview; }
private set { this.RaiseAndSetIfChanged(ref hasPendingReview, value); }
}
/// <inheritdoc/>
public string PendingReviewId { get; private set; }
IEnumerable<string> FilePaths
{
get { return PullRequest.ChangedFiles.Select(x => x.FileName); }
}
}
}