forked from doubleespressobro/WheresMyPluginsAt-PoE2
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGitUpdater.cs
More file actions
697 lines (594 loc) · 25.8 KB
/
GitUpdater.cs
File metadata and controls
697 lines (594 loc) · 25.8 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExileCore2;
using ExileCore2.Shared;
using LibGit2Sharp;
using LibGit2Sharp.Handlers;
namespace PluginUpdater
{
public class PluginInfo
{
public required string Name { get; set; }
public required string Path { get; set; }
public string CurrentCommit { get; set; } = "";
public string LatestCommit { get; set; } = "";
public string BehindAhead { get; set; } = "";
public int BehindBy { get; set; } = 0;
public int AheadBy { get; set; } = 0;
public string LastMessage { get; set; } = "";
public string LatestCommitMessage { get; set; }
public string PreviousCommit { get; set; }
public int UncommittedChangeCount { get; set; }
public List<string> AvailableBranches { get; set; } = new();
public string CurrentBranch { get; set; }
public string Error { get; set; }
}
public class GitUpdater : IDisposable
{
private readonly PluginManager _pluginManager;
private readonly string _pluginFolder;
private readonly ConcurrentDictionary<string, PluginInfo> _pluginInfo = new(StringComparer.OrdinalIgnoreCase);
private CancellationTokenSource _updateCts;
private Task _updateTask;
public event Action<int, int> ProgressChanged;
private void ReportProgress(int current, int total) => ProgressChanged?.Invoke(current, total);
private IEnumerable<PluginInfo> GetGitPlugins() =>
Directory.GetDirectories(_pluginFolder).Select(x =>
{
var resolvedPath = PluginManager.ResolvePluginDirectory(x);
var gitPath = Path.Join(resolvedPath, ".git");
if (Directory.Exists(gitPath) || File.Exists(gitPath))
{
return CreatePluginInfo(Path.GetFileName(x), resolvedPath);
}
return null;
}).Where(p => p != null);
public IEnumerable<PluginInfo> GetManualPlugins() =>
Directory.GetDirectories(_pluginFolder).Select(x =>
{
var resolvedPath = PluginManager.ResolvePluginDirectory(x);
var gitPath = Path.Join(resolvedPath, ".git");
if (!Directory.Exists(gitPath) && !File.Exists(gitPath))
{
return CreatePluginInfo(Path.GetFileName(x), resolvedPath);
}
return null;
}).Where(p => p != null);
public GitUpdater(PluginManager pluginManager)
{
_pluginManager = pluginManager;
_pluginFolder = pluginManager.SourcePluginDirectoryPath;
UpdateLocal();
}
private static PluginInfo CreatePluginInfo(string name, string folder)
{
return new PluginInfo { Name = name, Path = folder };
}
public void UpdateLocal()
{
_pluginInfo.Clear();
var folders = GetGitPlugins().ToList();
foreach (var pluginInfo in folders)
{
try
{
using var repo = new Repository(pluginInfo.Path);
SetPluginInfo(pluginInfo, repo);
_pluginInfo[pluginInfo.Name] = pluginInfo;
}
catch (Exception e)
{
DebugWindow.LogError($"Error processing {pluginInfo.Path}: {e}");
}
}
}
public async Task UpdateGitInfoAsync()
{
if (_updateTask != null && !_updateTask.IsCompleted)
{
var result = MessageBox.Show(
"Update in progress, do you want to restart?",
"Update in progress",
MessageBoxButtons.YesNo);
if (result == DialogResult.No)
return;
_updateCts?.Cancel();
try
{
await Task.WhenAny(_updateTask, Task.Delay(5000));
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
DebugWindow.LogError($"Error during task cancellation: {ex.Message}");
}
}
_updateCts = new CancellationTokenSource();
try
{
_updateTask = UpdateGitInfoInternalAsync(_updateCts.Token);
await _updateTask;
}
catch (OperationCanceledException)
{
DebugWindow.LogMsg("Git update operation was cancelled");
}
catch (Exception ex)
{
DebugWindow.LogError($"Error during git update: {ex.Message}");
throw;
}
}
private void SetPluginInfo(PluginInfo plugin, Repository repository)
{
SetBranchInfo(plugin, repository);
plugin.CurrentCommit = repository.Head.Tip.Sha[..7];
plugin.UncommittedChangeCount = repository.Diff.Compare<TreeChanges>().Count;
var trackingBranch = repository.Head.TrackedBranch;
if (trackingBranch != null)
{
plugin.LatestCommit = trackingBranch.Tip.Sha[..7];
plugin.LatestCommitMessage = trackingBranch.Tip.MessageShort;
if (plugin.CurrentCommit != plugin.LatestCommit)
{
var ahead = repository.Head.TrackingDetails.AheadBy ?? 0;
var behind = repository.Head.TrackingDetails.BehindBy ?? 0;
plugin.BehindAhead = $"{behind} behind, {ahead} ahead";
plugin.BehindBy = behind;
plugin.AheadBy = ahead;
}
else
{
plugin.BehindBy = 0;
plugin.AheadBy = 0;
plugin.BehindAhead = "";
}
}
else
{
plugin.LatestCommit = plugin.CurrentCommit;
plugin.LatestCommitMessage = null;
plugin.BehindAhead = "";
}
var previousCommit = repository.Head.Tip.Parents.FirstOrDefault();
plugin.PreviousCommit = previousCommit != null
? $"{previousCommit.Sha[..7]} {previousCommit.MessageShort}"
: null;
}
private void SetBranchInfo(PluginInfo plugin, Repository repository)
{
// Get all local branches
var localBranches = repository.Branches
.Where(b => !b.IsRemote)
.Where(b => b.FriendlyName != "HEAD")
.ToList();
var trackedBranches = localBranches
.Select(x => GetTrackedBranchSafe(repository, x))
.Where(x => x != null)
.ToHashSet();
// Get all remote branches
var remoteBranches = repository.Branches
.Where(b => b.IsRemote)
.Where(b => !b.FriendlyName.EndsWith("/HEAD"))
.Except(trackedBranches)
.Distinct();
// Combine and deduplicate branches
plugin.AvailableBranches = localBranches
.Union(remoteBranches)
.Select(b => b.FriendlyName)
.Order()
.ToList();
plugin.CurrentBranch = repository.Head.FriendlyName;
}
private static Branch GetTrackedBranchSafe(Repository repository, Branch x)
{
return x.RemoteName == null ||
x.RemoteName.EndsWith(".git", StringComparison.OrdinalIgnoreCase) ||
repository.Network.Remotes[x.RemoteName] == null
? null
: x.TrackedBranch;
}
private async Task UpdateGitInfoInternalAsync(CancellationToken cancellationToken)
{
_pluginInfo.Clear();
var folders = GetGitPlugins().ToList();
var totalFolders = folders.Count;
var currentFolder = 0;
ReportProgress(0, totalFolders);
foreach (var pluginInfo in folders)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
await Task.Run(() =>
{
using var repo = new Repository(pluginInfo.Path);
SetPluginInfo(pluginInfo, repo);
_pluginInfo[pluginInfo.Name] = pluginInfo;
var fetchOptions = new FetchOptions
{
CredentialsProvider = _credentialsHandler,
};
var branchName = repo.Head.FriendlyName;
var trackingBranch = repo.Head.TrackedBranch;
var remote = GetHeadRemote(repo, false);
var refSpecs = remote.FetchRefSpecs.Select(r => r.Specification);
Commands.Fetch(repo, remote.Name, refSpecs, fetchOptions, null);
if (trackingBranch == null)
{
var remoteBranch = repo.Branches[$"origin/{branchName}"];
if (remoteBranch != null)
{
repo.Branches.Update(repo.Head,
b => b.TrackedBranch = remoteBranch.CanonicalName);
}
}
SetPluginInfo(pluginInfo, repo);
}, cancellationToken);
_pluginInfo[pluginInfo.Name] = pluginInfo;
}
catch (Exception e)
{
DebugWindow.LogError($"Error processing {pluginInfo.Path}: {e}");
pluginInfo.Error = e.Message;
if (_pluginInfo.ContainsKey(pluginInfo.Name))
{
_pluginInfo[pluginInfo.Name] = pluginInfo;
}
else
{
using var repo = new Repository(pluginInfo.Path);
SetPluginInfo(pluginInfo, repo);
_pluginInfo.TryAdd(pluginInfo.Name, pluginInfo);
}
}
finally
{
currentFolder++;
ReportProgress(currentFolder, totalFolders);
}
}
}
public async Task RevertPluginAsync(string pluginName)
{
var folder = GetGitPlugins().FirstOrDefault(f => f.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase));
if (folder == null) return;
var plugin = _pluginInfo.GetValueOrDefault(pluginName);
if (plugin == null) return;
await Task.Run(() =>
{
try
{
using var repo = new Repository(folder.Path);
var parent = repo.Head.Tip.Parents.FirstOrDefault() ?? throw new Exception("Cannot revert: no parent commit found");
repo.Reset(ResetMode.Hard, parent);
plugin.LastMessage = $"Reset to parent commit {parent.Sha[..7]}";
SetPluginInfo(plugin, repo);
DebugWindow.LogMsg($"{folder.Path} reverted to {plugin.CurrentCommit}");
DebugWindow.LogMsg(plugin.LastMessage);
}
catch (Exception ex)
{
var errorMsg = $"Error reverting plugin {pluginName}: {ex}";
DebugWindow.LogError(errorMsg);
throw;
}
});
}
public async Task UpdatePluginAsync(string pluginName)
{
var folder = GetGitPlugins().FirstOrDefault(f => f.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase));
if (folder == null) return;
var plugin = _pluginInfo.GetValueOrDefault(pluginName);
if (plugin == null) return;
await Task.Run(() =>
{
try
{
using var repo = new Repository(folder.Path);
var remote = GetHeadRemote(repo);
var refSpecs = remote.FetchRefSpecs.Select(r => r.Specification);
Commands.Fetch(repo, remote.Name, refSpecs, new FetchOptions
{
CredentialsProvider = _credentialsHandler,
}, null);
var mergeResult = Commands.Pull(
repo,
new Signature("Plugin Updater", "updater@local", DateTimeOffset.Now),
new PullOptions());
plugin.LastMessage = mergeResult.Status == MergeStatus.UpToDate
? "Already up to date"
: $"Updated to {mergeResult.Commit.Id.Sha[..7]}";
SetPluginInfo(plugin, repo);
DebugWindow.LogMsg($"{folder.Path} updated to {plugin.CurrentCommit}");
DebugWindow.LogMsg(plugin.LastMessage);
}
catch (Exception ex)
{
DebugWindow.LogError($"Error updating plugin {pluginName}: {ex}");
throw;
}
});
}
public async Task ForceUpdatePluginAsync(string pluginName)
{
var folder = GetGitPlugins().FirstOrDefault(f => f.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase));
if (folder == null) return;
var plugin = _pluginInfo.GetValueOrDefault(pluginName);
if (plugin == null) return;
await Task.Run(() =>
{
try
{
using var repo = new Repository(folder.Path);
var remote = GetHeadRemote(repo);
var refSpecs = remote.FetchRefSpecs.Select(r => r.Specification);
Commands.Fetch(repo, remote.Name, refSpecs, new FetchOptions
{
CredentialsProvider = _credentialsHandler,
}, null);
var trackedBranch = repo.Head.TrackedBranch;
if (repo.Head.Tip != trackedBranch.Tip)
{
repo.Reset(ResetMode.Hard, trackedBranch.Tip);
plugin.LastMessage = $"Force updated to {trackedBranch.Tip.Id.Sha[..7]}";
}
else
{
plugin.LastMessage = "Already up to date";
}
SetPluginInfo(plugin, repo);
DebugWindow.LogMsg($"{folder.Path} updated to {plugin.CurrentCommit}");
DebugWindow.LogMsg(plugin.LastMessage);
}
catch (Exception ex)
{
DebugWindow.LogError($"Error updating plugin {pluginName}: {ex}");
throw;
}
});
}
private static Remote GetHeadRemote(Repository repo, bool throwOnNoTracking = true)
{
var headTrackedBranch = repo.Head.TrackedBranch;
if (throwOnNoTracking && headTrackedBranch is null)
{
throw new Exception("No tracking branch found");
}
return (headTrackedBranch, repo.Head) switch
{
({ RemoteName: { } remoteName }, _) => repo.Network.Remotes[remoteName],
(_, { RemoteName: { } remoteName }) => repo.Network.Remotes[remoteName],
_ => repo.Network.Remotes["updater_remote"] ?? repo.Network.Remotes["origin"] ?? repo.Network.Remotes.Single(),
};
}
private static string ExtractRepoNameAndBranch(string repoUrl, out string branch)
{
branch = null;
var treeIndex = repoUrl.IndexOf("/tree/", StringComparison.OrdinalIgnoreCase);
if (treeIndex != -1)
{
branch = repoUrl[(treeIndex + 6)..];
repoUrl = repoUrl[..treeIndex];
}
var repoName = Path.GetFileNameWithoutExtension(repoUrl.TrimEnd('/'));
if (string.IsNullOrEmpty(repoName))
repoName = repoUrl.Split('/').Last().Replace(".git", "");
return repoName;
}
public async Task CloneRepositoryAsync(string repoUrl)
{
var repoName = ExtractRepoNameAndBranch(repoUrl, out var branch);
var targetPath = Path.Combine(_pluginFolder, repoName);
if (Directory.Exists(targetPath))
throw new InvalidOperationException($"A plugin with the name {repoName} already exists");
await Task.Run(() =>
{
try
{
var fetchOptions = new FetchOptions
{
CredentialsProvider = _credentialsHandler,
};
var cloneOptions = new CloneOptions
{
IsBare = false,
Checkout = true,
};
cloneOptions.FetchOptions.CredentialsProvider = fetchOptions.CredentialsProvider;
var cleanUrl = repoUrl;
var treeIndex = cleanUrl.IndexOf("/tree/", StringComparison.OrdinalIgnoreCase);
if (treeIndex != -1)
{
cleanUrl = cleanUrl[..treeIndex];
if (!cleanUrl.EndsWith(".git"))
cleanUrl += ".git";
}
Repository.Clone(cleanUrl, targetPath, cloneOptions);
if (!string.IsNullOrEmpty(branch))
{
using var branchRepo = new Repository(targetPath);
var targetBranch = branchRepo.Branches[$"origin/{branch}"] ?? throw new Exception($"Branch '{branch}' not found in repository");
var localBranch = branchRepo.CreateBranch(branch, targetBranch.Tip);
branchRepo.Branches.Update(localBranch,
b => b.TrackedBranch = targetBranch.CanonicalName);
Commands.Checkout(branchRepo, localBranch);
}
using var finalRepo = new Repository(targetPath);
var pluginInfo = new PluginInfo
{
Name = repoName,
Path = targetPath,
};
SetPluginInfo(pluginInfo, finalRepo);
var trackingBranch = finalRepo.Head.TrackedBranch;
if (trackingBranch != null)
pluginInfo.LatestCommit = trackingBranch.Tip.Sha[..7];
_pluginInfo[pluginInfo.Name] = pluginInfo;
}
catch (Exception)
{
if (Directory.Exists(targetPath))
{
try
{
Directory.Delete(targetPath, true);
}
catch (Exception ex)
{
DebugWindow.LogError($"Unable to delete {targetPath}: {ex}");
}
}
throw;
}
});
}
public void DeletePlugin(string pluginName)
{
var pluginPath = Path.Combine(_pluginFolder, pluginName);
if (!Directory.Exists(pluginPath))
throw new DirectoryNotFoundException($"Plugin directory not found: {pluginPath}");
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
using (var repo = new Repository(pluginPath)) { }
foreach (var file in Directory.GetFiles(pluginPath, "*.*", SearchOption.AllDirectories))
File.SetAttributes(file, FileAttributes.Normal);
foreach (var dir in Directory.GetDirectories(pluginPath, "*", SearchOption.AllDirectories))
File.SetAttributes(dir, FileAttributes.Normal);
Directory.Delete(pluginPath, true);
_pluginInfo.TryRemove(pluginName, out _);
}
catch (Exception ex)
{
throw new Exception($"Failed to delete plugin: {ex.Message}", ex);
}
}
public List<PluginInfo> GetPluginInfo()
{
return _pluginInfo.Values.ToList();
}
public void Dispose()
{
_updateCts?.Cancel();
_updateCts?.Dispose();
GC.SuppressFinalize(this);
}
private readonly CredentialsHandler _credentialsHandler = (url, usernameFromUrl, types) =>
{
string username = null;
string password = null;
try
{
var startInfo = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = "credential fill",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var process = new Process
{
StartInfo = startInfo
};
process.Start();
var uri = new Uri(url);
process.StandardInput.NewLine = "\n";
process.StandardInput.WriteLine($"protocol={uri.Scheme}");
process.StandardInput.WriteLine($"host={uri.Host}");
process.StandardInput.WriteLine($"path={uri.AbsolutePath}");
process.StandardInput.WriteLine();
while (process.StandardOutput.ReadLine() is { } line)
{
var details = line.Split('=');
if (details[0] == "username")
{
username = details[1];
}
else if (details[0] == "password")
{
password = details[1];
}
}
}
catch (Exception ex)
{
DebugWindow.LogError($"Unable to retrieve credentials for {url}: {ex}");
return new DefaultCredentials();
}
if (username == null || password == null)
{
DebugWindow.LogError($"Unable to retrieve credentials for {url}");
return new DefaultCredentials();
}
return new UsernamePasswordCredentials
{
Username = username,
Password = password,
};
};
public async Task ChangeBranchAsync(PluginInfo plugin, string branchName)
{
var pluginPath = plugin.Path;
await Task.Run(() =>
{
using var repo = new Repository(pluginPath);
Branch branch;
foreach (var remote in repo.Network.Remotes)
{
Commands.Fetch(repo, remote.Name, remote.FetchRefSpecs.Select(r => r.Specification),
new FetchOptions { CredentialsProvider = _credentialsHandler }, null);
}
// Try to get local branch first
if (repo.Branches[branchName] is {} literalBranch)
{
if (literalBranch.IsRemote)
{
branch = repo.Branches.FirstOrDefault(x => GetTrackedBranchSafe(repo, x) == literalBranch);
if (branch == null)
{
var nameParts = literalBranch.FriendlyName.Split("/", 2);
var branchNameCandidate = nameParts.Length == 2 ? nameParts[1] : (nameParts[0] + "_local");
if (repo.Branches[branchNameCandidate] != null)
{
branchNameCandidate = literalBranch.FriendlyName.Replace('/', '_');
}
branch = repo.CreateBranch(branchNameCandidate, literalBranch.Tip);
repo.Branches.Update(branch, b => b.TrackedBranch = literalBranch.CanonicalName);
}
}
else
{
branch = literalBranch;
}
}
// If local branch doesn't exist, try to create it from remote
else if (repo.Branches[$"{GetHeadRemote(repo, false).Name}/{branchName}"] is { } remoteBranch)
{
branch = repo.CreateBranch(branchName, remoteBranch.Tip);
// Set up tracking
repo.Branches.Update(branch,
b => b.TrackedBranch = remoteBranch.CanonicalName);
}
else
{
throw new Exception($"Branch {branchName} not found locally or remotely");
}
Commands.Checkout(repo, branch);
SetPluginInfo(plugin, repo);
});
}
}
}