-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathLibGit2Service.cs
More file actions
543 lines (449 loc) · 14.7 KB
/
Copy pathLibGit2Service.cs
File metadata and controls
543 lines (449 loc) · 14.7 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
using LibGit2Sharp;
using Microsoft.Extensions.Logging;
using Sentry;
using System.Text;
using System.Text.RegularExpressions;
namespace Files.App.Services.Git;
internal sealed partial class LibGit2Service // : IVersionControl
{
private const string GIT_RESOURCE_NAME = "Files:https://github.com";
private const string GIT_RESOURCE_USERNAME = "Personal Access Token";
private const string CLIENT_ID_SECRET = Constants.AutomatedWorkflowInjectionKeys.GitHubClientId;
private const int END_OF_ORIGIN_PREFIX = 7;
private const int MAX_NUMBER_OF_BRANCHES = 30;
private static readonly SemaphoreSlim GitOperationSemaphore = new(1, 1);
private static readonly FetchOptions _fetchOptions = new() { Prune = true };
private static readonly PullOptions _pullOptions = new();
private static readonly string _clientId = AppLifecycleHelper.AppEnvironment is AppEnvironment.Dev
? string.Empty
: CLIENT_ID_SECRET;
private bool _isExecutingGitAction;
private static readonly StatusCenterViewModel StatusCenterViewModel = Ioc.Default.GetRequiredService<StatusCenterViewModel>();
private static readonly ILogger _logger = Ioc.Default.GetRequiredService<ILogger<App>>();
private static readonly IDialogService _dialogService = Ioc.Default.GetRequiredService<IDialogService>();
public bool IsExecutingGitAction
{
get => _isExecutingGitAction;
internal set // TODO: Make set method private again when move finished
{
if (_isExecutingGitAction != value)
{
_isExecutingGitAction = value;
IsExecutingGitActionChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsExecutingGitAction)));
}
}
}
public event PropertyChangedEventHandler? IsExecutingGitActionChanged;
public event EventHandler? GitFetchCompleted;
public string? GetGitRepositoryPath(string? path, string? root)
{
if (string.IsNullOrEmpty(root))
return null;
if (root.EndsWith('\\'))
root = root.Substring(0, root.Length - 1);
if (string.IsNullOrWhiteSpace(path) ||
path.Equals(root, StringComparison.OrdinalIgnoreCase) ||
path.Equals("Home", StringComparison.OrdinalIgnoreCase) ||
ShellStorageFolder.IsShellPath(path))
{
return null;
}
try
{
if (IsRepoValid(path))
return path;
else
{
var parentDir = PathNormalization.GetParentDir(path);
if (parentDir == path)
return null;
else
return GetGitRepositoryPath(parentDir, root);
}
}
catch (Exception ex) when (ex is LibGit2SharpException or EncoderFallbackException)
{
_logger.LogWarning(ex.Message);
return null;
}
}
public string GetOriginRepositoryName(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !IsRepoValid(path))
return string.Empty;
using var repository = new Repository(path);
var repositoryUrl = repository.Network.Remotes.FirstOrDefault()?.Url;
if (string.IsNullOrEmpty(repositoryUrl))
return string.Empty;
var repositoryName = repositoryUrl.Split('/').Last();
return repositoryName[..repositoryName.LastIndexOf(".git")];
}
public async Task<BranchItem[]> GetBranchNames(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !IsRepoValid(path))
return [];
var (result, returnValue) = await DoGitOperationAsync<(GitOperationResult, BranchItem[])>(() =>
{
var branches = Array.Empty<BranchItem>();
var result = GitOperationResult.Success;
try
{
using var repository = new Repository(path);
branches = GetValidBranches(repository.Branches)
.OrderByDescending(b => b.Tip?.Committer.When)
.GroupBy(b => b.IsRemote)
.SelectMany(g => g.Take(MAX_NUMBER_OF_BRANCHES))
.OrderByDescending(b => b.IsCurrentRepositoryHead)
.Select(b => new BranchItem(b.FriendlyName, b.IsCurrentRepositoryHead, b.IsRemote, TryGetTrackingDetails(b)?.AheadBy ?? 0, TryGetTrackingDetails(b)?.BehindBy ?? 0))
.ToArray();
}
catch (Exception)
{
result = GitOperationResult.GenericError;
}
return (result, branches);
});
return returnValue;
}
public async Task<BranchItem?> GetRepositoryHead(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !IsRepoValid(path))
return null;
var (_, returnValue) = await DoGitOperationAsync<(GitOperationResult, BranchItem?)>(() =>
{
BranchItem? head = null;
try
{
using var repository = new Repository(path);
var branch = repository.Head;
if (branch?.Tip is not null)
{
var trackingDetails = TryGetTrackingDetails(branch);
head = new BranchItem(
branch.FriendlyName,
true,
branch.IsRemote,
trackingDetails?.AheadBy ?? 0,
trackingDetails?.BehindBy ?? 0
);
}
}
catch
{
return (GitOperationResult.GenericError, head);
}
return (GitOperationResult.Success, head);
}, true);
return returnValue;
}
public Task<string?> GetRepositoryHeadName(string? path)
{
if (string.IsNullOrWhiteSpace(path))
return Task.FromResult<string?>(null);
return Task.Run(() =>
{
try
{
using var repository = new Repository(path);
var branch = repository.Head;
return branch?.Tip is null ? null : branch.FriendlyName;
}
// The repository may have been removed or corrupted after discovery returned its path
catch (LibGit2SharpException)
{
return null;
}
});
}
public async Task<bool> Checkout(string? repositoryPath, string? branch)
{
SentrySdk.Metrics.EmitCounter("Triggered git checkout", 1);
if (string.IsNullOrWhiteSpace(repositoryPath) || !IsRepoValid(repositoryPath))
return false;
using var repository = new Repository(repositoryPath);
var checkoutBranch = repository.Branches[branch];
if (checkoutBranch is null)
return false;
var options = new CheckoutOptions();
var isBringingChanges = false;
IsExecutingGitAction = true;
if (repository.Index.Conflicts.Any())
{
var dialog = DynamicDialogFactory.GetFor_GitMergeConflicts(checkoutBranch.FriendlyName, repository.Head.FriendlyName);
await dialog.ShowAsync();
var resolveConflictOption = dialog.ViewModel.AdditionalData is GitCheckoutOptions option
? option
: GitCheckoutOptions.None;
switch (resolveConflictOption)
{
case GitCheckoutOptions.None:
IsExecutingGitAction = false;
return false;
case GitCheckoutOptions.AbortMerge:
repository.Reset(ResetMode.Hard);
break;
}
}
else if (repository.RetrieveStatus().IsDirty)
{
var dialog = DynamicDialogFactory.GetFor_GitCheckoutConflicts(checkoutBranch.FriendlyName, repository.Head.FriendlyName);
await dialog.ShowAsync();
var resolveConflictOption = dialog.ViewModel.AdditionalData is GitCheckoutOptions option
? option
: GitCheckoutOptions.None;
switch (resolveConflictOption)
{
case GitCheckoutOptions.None:
IsExecutingGitAction = false;
return false;
case GitCheckoutOptions.DiscardChanges:
options.CheckoutModifiers = CheckoutModifiers.Force;
break;
case GitCheckoutOptions.BringChanges:
case GitCheckoutOptions.StashChanges:
var signature = repository.Config.BuildSignature(DateTimeOffset.Now);
if (signature is null)
{
IsExecutingGitAction = false;
return false;
}
repository.Stashes.Add(signature);
isBringingChanges = resolveConflictOption is GitCheckoutOptions.BringChanges;
break;
}
}
var result = await DoGitOperationAsync<GitOperationResult>(() =>
{
try
{
if (checkoutBranch.IsRemote)
CheckoutRemoteBranch(repository, checkoutBranch);
else
LibGit2Sharp.Commands.Checkout(repository, checkoutBranch, options);
if (isBringingChanges)
{
var lastStashIndex = repository.Stashes.Count() - 1;
repository.Stashes.Pop(lastStashIndex, new StashApplyOptions());
}
}
catch (Exception)
{
return GitOperationResult.GenericError;
}
return GitOperationResult.Success;
});
IsExecutingGitAction = false;
return result is GitOperationResult.Success;
}
public async Task CreateNewBranchAsync(string repositoryPath, string activeBranch)
{
SentrySdk.Metrics.EmitCounter("Triggered create git branch", 1);
var viewModel = new AddBranchDialogViewModel(repositoryPath, activeBranch);
var loadBranchesTask = viewModel.LoadBranches();
var dialog = _dialogService.GetDialog(viewModel);
await loadBranchesTask;
var result = await dialog.TryShowAsync();
if (result != DialogResult.Primary)
return;
using var repository = new Repository(repositoryPath);
IsExecutingGitAction = true;
if (repository.Head.FriendlyName.Equals(viewModel.NewBranchName) ||
await Checkout(repositoryPath, viewModel.BasedOn))
{
repository.CreateBranch(viewModel.NewBranchName);
if (viewModel.Checkout)
await Checkout(repositoryPath, viewModel.NewBranchName);
}
IsExecutingGitAction = false;
}
public async Task DeleteBranchAsync(string? repositoryPath, string? activeBranch, string? branchToDelete)
{
SentrySdk.Metrics.EmitCounter("Triggered delete git branch", 1);
if (string.IsNullOrWhiteSpace(repositoryPath) ||
string.IsNullOrWhiteSpace(activeBranch) ||
string.IsNullOrWhiteSpace(branchToDelete) ||
activeBranch.Equals(branchToDelete, StringComparison.OrdinalIgnoreCase) ||
!IsRepoValid(repositoryPath))
{
return;
}
var dialog = DynamicDialogFactory.GetFor_DeleteGitBranchConfirmation(branchToDelete);
await dialog.TryShowAsync();
if (!(dialog.ViewModel.AdditionalData as bool? ?? false))
return;
IsExecutingGitAction = true;
await DoGitOperationAsync<GitOperationResult>(() =>
{
try
{
using var repository = new Repository(repositoryPath);
repository.Branches.Remove(branchToDelete);
}
catch (Exception)
{
return GitOperationResult.GenericError;
}
return GitOperationResult.Success;
});
IsExecutingGitAction = false;
}
public bool ValidateBranchNameForRepository(string branchName, string repositoryPath)
{
if (string.IsNullOrEmpty(branchName) || !IsRepoValid(repositoryPath))
return false;
var nameValidator = RegexHelpers.GitBranchName();
if (!nameValidator.IsMatch(branchName))
return false;
using var repository = new Repository(repositoryPath);
return !repository.Branches.Any(branch =>
branch.FriendlyName.Equals(branchName, StringComparison.OrdinalIgnoreCase));
}
public async void FetchOrigin(string? repositoryPath, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(repositoryPath))
return;
using var repository = new Repository(repositoryPath);
var signature = repository.Config.BuildSignature(DateTimeOffset.Now);
var token = CredentialsHelpers.GetPassword(GIT_RESOURCE_NAME, GIT_RESOURCE_USERNAME);
if (signature is not null && !string.IsNullOrWhiteSpace(token))
{
_fetchOptions.CredentialsProvider = (url, user, cred)
=> new UsernamePasswordCredentials
{
Username = signature.Name,
Password = token
};
}
MainWindow.Instance.DispatcherQueue.TryEnqueue(() =>
{
IsExecutingGitAction = true;
});
await DoGitOperationAsync<GitOperationResult>(() =>
{
var result = GitOperationResult.Success;
foreach (var remote in repository.Network.Remotes)
{
if (cancellationToken.IsCancellationRequested)
return result;
try
{
LibGit2Sharp.Commands.Fetch(
repository,
remote.Name,
remote.FetchRefSpecs.Select(rs => rs.Specification),
_fetchOptions,
"git fetch updated a ref");
}
catch (Exception ex)
{
// An unreachable remote (e.g. a deleted fork answering 401) must not prevent fetching the remaining remotes
_logger.LogWarning(ex, "Failed to fetch remote {RemoteName} in {RepositoryPath}", remote.Name, LogPathHelper.RedactPath(repositoryPath));
if (IsAuthorizationException(ex))
result = GitOperationResult.AuthorizationError;
}
}
return result;
});
MainWindow.Instance.DispatcherQueue.TryEnqueue(() =>
{
if (cancellationToken.IsCancellationRequested)
// Do nothing because the operation was cancelled and another fetch may be in progress
return;
IsExecutingGitAction = false;
GitFetchCompleted?.Invoke(null, EventArgs.Empty);
});
}
private static bool IsRepoValid(string path)
{
return SafetyExtensions.IgnoreExceptions(() => Repository.IsValid(path));
}
private static IEnumerable<Branch> GetValidBranches(BranchCollection branches)
{
foreach (var branch in branches)
{
try
{
_ = branch.IsCurrentRepositoryHead;
}
catch (LibGit2SharpException)
{
continue;
}
yield return branch;
}
}
private static BranchTrackingDetails? TryGetTrackingDetails(Branch branch)
{
try
{
return branch.TrackingDetails;
}
catch (LibGit2SharpException)
{
return null;
}
}
private static Commit? GetLastCommitForFile(Repository repository, string currentPath)
{
foreach (var currentCommit in repository.Commits)
{
var currentTreeEntry = currentCommit.Tree[currentPath];
if (currentTreeEntry == null)
return null;
var parentCount = currentCommit.Parents.Take(2).Count();
if (parentCount == 0)
{
return currentCommit;
}
else if (parentCount == 1)
{
var parentCommit = currentCommit.Parents.Single();
// Does not consider renames
var parentPath = currentPath;
var parentTreeEntry = parentCommit.Tree[parentPath];
if (parentTreeEntry == null ||
parentTreeEntry.Target.Id != currentTreeEntry.Target.Id ||
parentPath != currentPath)
{
return currentCommit;
}
}
}
return null;
}
private static void CheckoutRemoteBranch(Repository repository, Branch branch)
{
var uniqueName = branch.FriendlyName.Substring(END_OF_ORIGIN_PREFIX);
// TODO: This is a temp fix to avoid an issue where Files would create many branches in a loop
if (repository.Branches.Any(b => !b.IsRemote && b.FriendlyName == uniqueName))
return;
//var discriminator = 0;
//while (repository.Branches.Any(b => !b.IsRemote && b.FriendlyName == uniqueName))
// uniqueName = $"{branch.FriendlyName}_{++discriminator}";
var newBranch = repository.CreateBranch(uniqueName, branch.Tip);
repository.Branches.Update(newBranch, b => b.TrackedBranch = branch.CanonicalName);
LibGit2Sharp.Commands.Checkout(repository, newBranch);
}
private static bool IsAuthorizationException(Exception ex)
{
return
ex.Message.Contains("status code: 401", StringComparison.OrdinalIgnoreCase) ||
ex.Message.Contains("authentication replays", StringComparison.OrdinalIgnoreCase);
}
private static async Task<T?> DoGitOperationAsync<T>(Func<object> payload, bool useSemaphore = false)
{
if (useSemaphore)
await GitOperationSemaphore.WaitAsync();
try
{
return (T)await Task.Run(payload);
}
finally
{
if (useSemaphore)
GitOperationSemaphore.Release();
}
}
[GeneratedRegex(@"^(?:https?:\/\/)?(?:www\.)?(?<domain>github|gitlab)\.com\/(?<user>[^\/]+)\/(?<repo>[^\/]+?)(?=\.git|\/|$)(?:\.git)?(?:\/)?", RegexOptions.IgnoreCase)]
private static partial Regex GitHubRepositoryRegex();
}