forked from rubberduck-vba/Rubberduck
-
Notifications
You must be signed in to change notification settings - Fork 12
/
GitProvider.cs
619 lines (543 loc) · 21.2 KB
/
GitProvider.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using Rubberduck.VBEditor.SafeComWrappers.Abstract;
namespace Rubberduck.SourceControl
{
public class GitProvider : SourceControlProviderBase, IDisposable
{
private readonly LibGit2Sharp.Repository _repo;
private readonly LibGit2Sharp.Credentials _credentials;
private readonly CredentialsHandler _credentialsHandler;
private List<ICommit> _unsyncedLocalCommits;
private List<ICommit> _unsyncedRemoteCommits;
public GitProvider(IVBProject project)
: base(project)
{
_unsyncedLocalCommits = new List<ICommit>();
_unsyncedRemoteCommits = new List<ICommit>();
}
public GitProvider(IVBProject project, IRepository repository)
: base(project, repository)
{
_unsyncedLocalCommits = new List<ICommit>();
_unsyncedRemoteCommits = new List<ICommit>();
try
{
_repo = new LibGit2Sharp.Repository(CurrentRepository.LocalLocation);
}
catch (RepositoryNotFoundException ex)
{
throw new SourceControlException(SourceControlText.GitRepoNotFound, ex);
}
}
public GitProvider(IVBProject project, IRepository repository, string userName, string passWord)
: this(project, repository)
{
_credentials = new UsernamePasswordCredentials()
{
Username = userName,
Password = passWord
};
_credentialsHandler = (url, user, cred) => _credentials;
}
public GitProvider(IVBProject project, IRepository repository, ICredentials<SecureString> secureCredentials)
: this(project, repository)
{
_credentials = new SecureUsernamePasswordCredentials()
{
Username = secureCredentials.Username,
Password = secureCredentials.Password
};
_credentialsHandler = (url, user, cred) => _credentials;
}
public void Dispose()
{
if (_repo != null)
{
_repo.Dispose();
}
}
public override IBranch CurrentBranch
{
get
{
return Branches.FirstOrDefault(b => !b.IsRemote && b.IsCurrentHead);
}
}
public override IEnumerable<IBranch> Branches
{
get
{
//note: consider doing this once and refreshing if necessary
return _repo.Branches.Select(b => new Branch(b));
}
}
public override IList<ICommit> UnsyncedLocalCommits
{
get { return _unsyncedLocalCommits; }
}
public override IList<ICommit> UnsyncedRemoteCommits
{
get { return _unsyncedRemoteCommits; }
}
public override IRepository Clone(string remotePathOrUrl, string workingDirectory, SecureCredentials credentials = null)
{
try
{
var name = GetProjectNameFromDirectory(remotePathOrUrl);
if (credentials == null)
{
LibGit2Sharp.Repository.Clone(remotePathOrUrl, workingDirectory);
}
else
{
var credentialsHandler = new CredentialsHandler((url, usernameFromUrl, types) => new SecureUsernamePasswordCredentials
{
Username = credentials.Username,
Password = credentials.Password
});
var options = new CloneOptions {CredentialsProvider = credentialsHandler};
LibGit2Sharp.Repository.Clone(remotePathOrUrl, workingDirectory, options);
}
return new Repository(name, workingDirectory, remotePathOrUrl);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitRepoNotCloned, ex);
}
}
public override IRepository Init(string directory, bool bare = false)
{
try
{
var workingDir = (bare) ? string.Empty : directory;
LibGit2Sharp.Repository.Init(directory, bare);
return new Repository(Project.HelpFile, workingDir, directory);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitNotInit, ex);
}
}
public override void AddOrigin(string path, string trackingBranchName)
{
try
{
if (_repo.Network.Remotes.Any(r => r.Name == "origin"))
{
_repo.Network.Remotes.Remove("origin"); // todo prompt that remote is already taken
}
_repo.Network.Remotes.Add("origin", path);
_repo.Branches.Update(_repo.Branches[CurrentBranch.Name], c => c.Remote = "origin",
c => c.UpstreamBranch = "refs/heads/" + trackingBranchName);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException("Failed to add remote location.", ex);
}
}
public override bool HasCredentials()
{
return _credentials != null;
}
/// <summary>
/// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo.
/// </summary>
/// <param name="directory">Local file path of the directory where the new repository will be created.</param>
/// <returns>Newly initialized repository.</returns>
public override IRepository InitVBAProject(string directory)
{
var repository = base.InitVBAProject(directory);
Init(repository.LocalLocation);
//add a master branch to newly created repo
using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation))
{
var status = repo.RetrieveStatus(new StatusOptions {DetectRenamesInWorkDir = true});
foreach (var stat in status.Untracked)
{
LibGit2Sharp.Commands.Stage(repo, stat.FilePath);
}
try
{
//The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found,
// but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead.
// so we pass a signature that won't throw along to the commit.
repo.Commit("Initial Commit", author: GetSignature(repo), committer: GetSignature(repo));
}
catch(LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitNoInitialCommit, ex);
}
}
return repository;
}
public override void Push()
{
try
{
//Only use credentials if we've been given credentials to use in the constructor.
PushOptions options = null;
if (_credentials != null)
{
options = new PushOptions()
{
CredentialsProvider = _credentialsHandler
};
}
var branch = _repo.Branches[CurrentBranch.Name];
_repo.Network.Push(branch, options);
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitPushFailed, ex);
}
}
/// <summary>
/// Fetches the specified remote for tracking.
/// If not argument is supplied, fetches the "origin" remote.
/// </summary>
public override void Fetch([Optional] string remoteName)
{
if (remoteName == null)
{
remoteName = "origin";
}
try
{
var remote = _repo.Network.Remotes[remoteName];
if (remote != null)
{
// FIXME: hardcoded string
IEnumerable<string> refSpec = new List<string>() {"+refs/heads/*:refs/remotes/origin/*"};
LibGit2Sharp.Commands.Fetch(_repo, remoteName, refSpec, null,"");
}
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitFetchFailed, ex);
}
}
public override void Pull()
{
try
{
var options = new PullOptions()
{
MergeOptions = new MergeOptions()
{
FastForwardStrategy = FastForwardStrategy.Default
}
};
var signature = GetSignature();
LibGit2Sharp.Commands.Pull(_repo, signature, options);
base.Pull();
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitPullFailed, ex);
}
}
public override void Commit(string message)
{
try
{
//The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found,
// but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead.
// so we pass a signature that won't throw along to the commit.
_repo.Commit(message, author: GetSignature(), committer: GetSignature());
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitCommitFailed, ex);
}
}
public override void Stage(string filePath)
{
try
{
LibGit2Sharp.Commands.Stage(_repo, filePath);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitFileStageFailed, ex);
}
}
public override void Stage(IEnumerable<string> filePaths)
{
try
{
LibGit2Sharp.Commands.Stage(_repo, filePaths);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitFileStageFailed, ex);
}
}
public override void Merge(string sourceBranch, string destinationBranch)
{
Checkout(destinationBranch);
var oldHeadCommit = _repo.Head.Tip;
var signature = GetSignature();
var result = _repo.Merge(_repo.Branches[sourceBranch], signature);
switch (result.Status)
{
case MergeStatus.Conflicts:
//abort the merge by resetting to the state prior to the merge
_repo.Reset(ResetMode.Hard, oldHeadCommit);
break;
case MergeStatus.NonFastForward:
//https://help.github.com/articles/dealing-with-non-fast-forward-errors/
Pull();
Merge(sourceBranch, destinationBranch); //a little leary about this. Could stack overflow if I'm wrong.
break;
}
base.Merge(sourceBranch, destinationBranch);
}
public override void Checkout(string branch)
{
try
{
LibGit2Sharp.Commands.Checkout(_repo, branch);
base.Checkout(branch);
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitCheckoutFailed, ex);
}
}
public override void CreateBranch(string branch)
{
try
{
_repo.CreateBranch(branch);
LibGit2Sharp.Commands.Checkout(_repo,branch);
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitNewBranchFailed, ex);
}
}
public override void CreateBranch(string sourceBranch, string branch)
{
try
{
_repo.CreateBranch(branch, _repo.Branches[sourceBranch].Commits.Last());
LibGit2Sharp.Commands.Checkout(_repo, branch);
RequeryUnsyncedCommits();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitNewBranchFailed, ex);
}
}
public override void Publish(string branch)
{
try
{
_repo.Branches.Update(_repo.Branches[branch], b => b.Remote = _repo.Network.Remotes["origin"].Name,
b => b.UpstreamBranch = _repo.Branches[branch].CanonicalName);
PushOptions options = null;
if (_credentials != null)
{
options = new PushOptions
{
CredentialsProvider = _credentialsHandler
};
}
_repo.Network.Push(_repo.Branches[branch], options);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitPublishFailed, ex);
}
}
public override void Unpublish(string branch)
{
try
{
var remote = _repo.Network.Remotes[branch];
_repo.Branches.Update(_repo.Branches[branch], b => b.Remote = remote.Name,
b => b.TrackedBranch = null, b => b.UpstreamBranch = null);
PushOptions options = null;
if (_credentials != null)
{
options = new PushOptions
{
CredentialsProvider = _credentialsHandler
};
}
_repo.Network.Push(remote, ":" + _repo.Branches[branch].UpstreamBranchCanonicalName, options);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitUnpublishFailed, ex);
}
}
public override void Revert()
{
try
{
var results = _repo.Revert(_repo.Head.Tip, GetSignature());
if (results.Status == RevertStatus.Conflicts)
{
throw new SourceControlException(SourceControlText.GitRevertConflict);
}
base.Revert();
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitRevertFailed, ex);
}
}
public override void AddFile(string filePath)
{
try
{
LibGit2Sharp.Commands.Stage(_repo, filePath);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(string.Format(SourceControlText.GitFileStageFailedMsg, filePath), ex);
}
}
/// <summary>
/// Removes file from staging area.
/// </summary>
/// <param name="filePath"></param>
/// <param name="removeFromWorkingDirectory"></param>
public override void RemoveFile(string filePath, bool removeFromWorkingDirectory)
{
try
{
NotifyExternalFileChanges = false;
LibGit2Sharp.Commands.Remove(_repo, filePath, removeFromWorkingDirectory);
NotifyExternalFileChanges = true;
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(string.Format(SourceControlText.GitFileStageFailedMsg, filePath), ex);
}
}
public override IEnumerable<IFileStatusEntry> Status()
{
try
{
base.Status();
return _repo.RetrieveStatus(new StatusOptions {IncludeUnaltered = true, DetectRenamesInWorkDir = true})
.Select(item => new FileStatusEntry(item));
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitRepoStatusFailed, ex);
}
catch (SEHException ex)
{
throw new SourceControlException(SourceControlText.GitRepoStatusFailed + " (SEH Code " + ex.ErrorCode + ")", ex);
}
}
public override IEnumerable<IFileStatusEntry> LastKnownStatus()
{
try
{
return _repo.RetrieveStatus(new StatusOptions { IncludeUnaltered = true, DetectRenamesInWorkDir = true})
.Select(item => new FileStatusEntry(item));
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitRepoStatusFailed, ex);
}
}
public override void Undo(string filePath)
{
try
{
var tip = _repo.Branches.First(b => !b.IsRemote && b.IsCurrentRepositoryHead).Tip;
var options = new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force };
_repo.CheckoutPaths(tip.Sha, new List<string> { filePath }, options);
base.Undo(filePath);
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitUndoFailed, ex);
}
}
public override void DeleteBranch(string branchName)
{
try
{
var branch = _repo.Branches.FirstOrDefault(b => b.FriendlyName == branchName);
if (branch != null)
{
if (branch.TrackedBranch != null && branch.TrackedBranch.Tip != null) // check if the branch exists on the remote repo
{
PushOptions options = null;
if (_credentials != null)
{
options = new PushOptions
{
CredentialsProvider = _credentialsHandler
};
}
_repo.Network.Push(_repo.Network.Remotes[branchName], ":" + _repo.Branches[branchName].UpstreamBranchCanonicalName, options);
}
// remote local repo
_repo.Branches.Remove(branch);
}
}
catch(LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitBranchDeleteFailed, ex);
}
}
public override bool RepoHasRemoteOrigin()
{
try
{
return _repo.Network.Remotes.Any(a => a.Name == "origin");
}
catch (LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitPublishFailed, ex);
}
}
private Signature GetSignature(LibGit2Sharp.IRepository repo)
{
return repo.Config.BuildSignature(DateTimeOffset.Now);
}
private Signature GetSignature()
{
return _repo.Config.BuildSignature(DateTimeOffset.Now);
}
private void RequeryUnsyncedCommits()
{
var currentBranch = _repo.Branches[CurrentBranch.Name];
var local = currentBranch.Commits;
if (currentBranch.TrackedBranch == null)
{
_unsyncedLocalCommits = local.Select(c => new Commit(c) as ICommit)
.ToList();
_unsyncedRemoteCommits = new List<ICommit>();
}
else
{
var remote = currentBranch.TrackedBranch.Commits;
_unsyncedLocalCommits = local.Where(c => !remote.Contains(c))
.Select(c => new Commit(c) as ICommit)
.ToList();
_unsyncedRemoteCommits = remote.Where(c => !local.Contains(c))
.Select(c => new Commit(c) as ICommit)
.ToList();
}
}
}
}