-
Notifications
You must be signed in to change notification settings - Fork 891
/
Repository.cs
1796 lines (1538 loc) · 73.7 KB
/
Repository.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
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// A Repository is the primary interface into a git repository
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public sealed class Repository : IRepository
{
private readonly bool isBare;
private readonly BranchCollection branches;
private readonly CommitLog commits;
private readonly Lazy<Configuration> config;
private readonly RepositoryHandle handle;
private readonly Lazy<Index> index;
private readonly ReferenceCollection refs;
private readonly TagCollection tags;
private readonly StashCollection stashes;
private readonly Lazy<RepositoryInformation> info;
private readonly Diff diff;
private readonly NoteCollection notes;
private readonly Lazy<ObjectDatabase> odb;
private readonly Lazy<Network> network;
private readonly Lazy<Rebase> rebaseOperation;
private readonly Stack<IDisposable> toCleanup = new Stack<IDisposable>();
private readonly Ignore ignore;
private readonly SubmoduleCollection submodules;
private readonly WorktreeCollection worktrees;
private readonly Lazy<PathCase> pathCase;
[Flags]
private enum RepositoryRequiredParameter
{
None = 0,
Path = 1,
Options = 2,
}
/// <summary>
/// Initializes a new instance of the <see cref="Repository"/> class
/// that does not point to an on-disk Git repository. This is
/// suitable only for custom, in-memory Git repositories that are
/// configured with custom object database, reference database and/or
/// configuration backends.
/// </summary>
public Repository()
: this(null, null, RepositoryRequiredParameter.None)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Repository"/> class.
/// <para>For a standard repository, <paramref name="path"/> should either point to the ".git" folder or to the working directory. For a bare repository, <paramref name="path"/> should directly point to the repository folder.</para>
/// </summary>
/// <param name="path">
/// The path to the git repository to open, can be either the path to the git directory (for non-bare repositories this
/// would be the ".git" folder inside the working directory) or the path to the working directory.
/// </param>
public Repository(string path)
: this(path, null, RepositoryRequiredParameter.Path)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="Repository"/> class,
/// providing optional behavioral overrides through the
/// <paramref name="options"/> parameter.
/// <para>For a standard repository, <paramref name="path"/> may
/// either point to the ".git" folder or to the working directory.
/// For a bare repository, <paramref name="path"/> should directly
/// point to the repository folder.</para>
/// </summary>
/// <param name="path">
/// The path to the git repository to open, can be either the
/// path to the git directory (for non-bare repositories this
/// would be the ".git" folder inside the working directory)
/// or the path to the working directory.
/// </param>
/// <param name="options">
/// Overrides to the way a repository is opened.
/// </param>
public Repository(string path, RepositoryOptions options) :
this(path, options, RepositoryRequiredParameter.Path | RepositoryRequiredParameter.Options)
{
}
internal Repository(WorktreeHandle worktreeHandle)
{
try
{
handle = Proxy.git_repository_open_from_worktree(worktreeHandle);
RegisterForCleanup(handle);
RegisterForCleanup(worktreeHandle);
isBare = Proxy.git_repository_is_bare(handle);
Func<Index> indexBuilder = () => new Index(this);
string configurationGlobalFilePath = null;
string configurationXDGFilePath = null;
string configurationSystemFilePath = null;
if (!isBare)
{
index = new Lazy<Index>(() => indexBuilder());
}
commits = new CommitLog(this);
refs = new ReferenceCollection(this);
branches = new BranchCollection(this);
tags = new TagCollection(this);
stashes = new StashCollection(this);
info = new Lazy<RepositoryInformation>(() => new RepositoryInformation(this, isBare));
config = new Lazy<Configuration>(() => RegisterForCleanup(new Configuration(this,
null,
configurationGlobalFilePath,
configurationXDGFilePath,
configurationSystemFilePath)));
odb = new Lazy<ObjectDatabase>(() => new ObjectDatabase(this));
diff = new Diff(this);
notes = new NoteCollection(this);
ignore = new Ignore(this);
network = new Lazy<Network>(() => new Network(this));
rebaseOperation = new Lazy<Rebase>(() => new Rebase(this));
pathCase = new Lazy<PathCase>(() => new PathCase(this));
submodules = new SubmoduleCollection(this);
worktrees = new WorktreeCollection(this);
}
catch
{
CleanupDisposableDependencies();
throw;
}
}
private Repository(string path, RepositoryOptions options, RepositoryRequiredParameter requiredParameter)
{
if ((requiredParameter & RepositoryRequiredParameter.Path) == RepositoryRequiredParameter.Path)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
}
if ((requiredParameter & RepositoryRequiredParameter.Options) == RepositoryRequiredParameter.Options)
{
Ensure.ArgumentNotNull(options, "options");
}
try
{
handle = (path != null) ? Proxy.git_repository_open(path) : Proxy.git_repository_new();
RegisterForCleanup(handle);
isBare = Proxy.git_repository_is_bare(handle);
/* TODO: bug in libgit2, update when fixed by
* https://github.com/libgit2/libgit2/pull/2970
*/
if (path == null)
{
isBare = true;
}
Func<Index> indexBuilder = () => new Index(this);
string configurationGlobalFilePath = null;
string configurationXDGFilePath = null;
string configurationSystemFilePath = null;
if (options != null)
{
bool isWorkDirNull = string.IsNullOrEmpty(options.WorkingDirectoryPath);
bool isIndexNull = string.IsNullOrEmpty(options.IndexPath);
if (isBare && (isWorkDirNull ^ isIndexNull))
{
throw new ArgumentException("When overriding the opening of a bare repository, both RepositoryOptions.WorkingDirectoryPath an RepositoryOptions.IndexPath have to be provided.");
}
if (!isWorkDirNull)
{
isBare = false;
}
if (!isIndexNull)
{
indexBuilder = () => new Index(this, options.IndexPath);
}
if (!isWorkDirNull)
{
Proxy.git_repository_set_workdir(handle, options.WorkingDirectoryPath);
}
if (options.Identity != null)
{
Proxy.git_repository_set_ident(handle, options.Identity.Name, options.Identity.Email);
}
}
if (!isBare)
{
index = new Lazy<Index>(() => indexBuilder());
}
commits = new CommitLog(this);
refs = new ReferenceCollection(this);
branches = new BranchCollection(this);
tags = new TagCollection(this);
stashes = new StashCollection(this);
info = new Lazy<RepositoryInformation>(() => new RepositoryInformation(this, isBare));
config = new Lazy<Configuration>(() => RegisterForCleanup(new Configuration(this,
null,
configurationGlobalFilePath,
configurationXDGFilePath,
configurationSystemFilePath)));
odb = new Lazy<ObjectDatabase>(() => new ObjectDatabase(this));
diff = new Diff(this);
notes = new NoteCollection(this);
ignore = new Ignore(this);
network = new Lazy<Network>(() => new Network(this));
rebaseOperation = new Lazy<Rebase>(() => new Rebase(this));
pathCase = new Lazy<PathCase>(() => new PathCase(this));
submodules = new SubmoduleCollection(this);
worktrees = new WorktreeCollection(this);
EagerlyLoadComponentsWithSpecifiedPaths(options);
}
catch
{
CleanupDisposableDependencies();
throw;
}
}
/// <summary>
/// Check if parameter <paramref name="path"/> leads to a valid git repository.
/// </summary>
/// <param name="path">
/// The path to the git repository to check, can be either the path to the git directory (for non-bare repositories this
/// would be the ".git" folder inside the working directory) or the path to the working directory.
/// </param>
/// <returns>True if a repository can be resolved through this path; false otherwise</returns>
static public bool IsValid(string path)
{
Ensure.ArgumentNotNull(path, "path");
if (string.IsNullOrWhiteSpace(path))
{
return false;
}
try
{
Proxy.git_repository_open_ext(path, RepositoryOpenFlags.NoSearch, null);
}
catch (RepositoryNotFoundException)
{
return false;
}
return true;
}
private void EagerlyLoadComponentsWithSpecifiedPaths(RepositoryOptions options)
{
if (options == null)
{
return;
}
if (!string.IsNullOrEmpty(options.IndexPath))
{
// Another dirty hack to avoid warnings
if (Index.Count < 0)
{
throw new InvalidOperationException("Unexpected state.");
}
}
}
internal RepositoryHandle Handle
{
get { return handle; }
}
/// <summary>
/// Shortcut to return the branch pointed to by HEAD
/// </summary>
public Branch Head
{
get
{
Reference reference = Refs.Head;
if (reference == null)
{
throw new LibGit2SharpException("Corrupt repository. The 'HEAD' reference is missing.");
}
if (reference is SymbolicReference)
{
return new Branch(this, reference);
}
return new DetachedHead(this, reference);
}
}
/// <summary>
/// Provides access to the configuration settings for this repository.
/// </summary>
public Configuration Config
{
get { return config.Value; }
}
/// <summary>
/// Gets the index.
/// </summary>
public Index Index
{
get
{
if (isBare)
{
throw new BareRepositoryException("Index is not available in a bare repository.");
}
return index != null ? index.Value : null;
}
}
/// <summary>
/// Manipulate the currently ignored files.
/// </summary>
public Ignore Ignore
{
get { return ignore; }
}
/// <summary>
/// Provides access to network functionality for a repository.
/// </summary>
public Network Network
{
get { return network.Value; }
}
/// <summary>
/// Provides access to rebase functionality for a repository.
/// </summary>
public Rebase Rebase
{
get
{
return rebaseOperation.Value;
}
}
/// <summary>
/// Gets the database.
/// </summary>
public ObjectDatabase ObjectDatabase
{
get { return odb.Value; }
}
/// <summary>
/// Lookup and enumerate references in the repository.
/// </summary>
public ReferenceCollection Refs
{
get { return refs; }
}
/// <summary>
/// Lookup and enumerate commits in the repository.
/// Iterating this collection directly starts walking from the HEAD.
/// </summary>
public IQueryableCommitLog Commits
{
get { return commits; }
}
/// <summary>
/// Lookup and enumerate branches in the repository.
/// </summary>
public BranchCollection Branches
{
get { return branches; }
}
/// <summary>
/// Lookup and enumerate tags in the repository.
/// </summary>
public TagCollection Tags
{
get { return tags; }
}
///<summary>
/// Lookup and enumerate stashes in the repository.
///</summary>
public StashCollection Stashes
{
get { return stashes; }
}
/// <summary>
/// Provides high level information about this repository.
/// </summary>
public RepositoryInformation Info
{
get { return info.Value; }
}
/// <summary>
/// Provides access to diffing functionalities to show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
/// </summary>
public Diff Diff
{
get { return diff; }
}
/// <summary>
/// Lookup notes in the repository.
/// </summary>
public NoteCollection Notes
{
get { return notes; }
}
/// <summary>
/// Submodules in the repository.
/// </summary>
public SubmoduleCollection Submodules
{
get { return submodules; }
}
/// <summary>
/// Worktrees in the repository.
/// </summary>
public WorktreeCollection Worktrees
{
get { return worktrees; }
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
private void Dispose(bool disposing)
{
CleanupDisposableDependencies();
}
#endregion
/// <summary>
/// Initialize a repository at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to the working folder when initializing a standard ".git" repository. Otherwise, when initializing a bare repository, the path to the expected location of this later.</param>
/// <returns>The path to the created repository.</returns>
public static string Init(string path)
{
return Init(path, false);
}
/// <summary>
/// Initialize a repository at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to the working folder when initializing a standard ".git" repository. Otherwise, when initializing a bare repository, the path to the expected location of this later.</param>
/// <param name="isBare">true to initialize a bare repository. False otherwise, to initialize a standard ".git" repository.</param>
/// <returns>The path to the created repository.</returns>
public static string Init(string path, bool isBare)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
using (RepositoryHandle repo = Proxy.git_repository_init_ext(null, path, isBare))
{
FilePath repoPath = Proxy.git_repository_path(repo);
return repoPath.Native;
}
}
/// <summary>
/// Initialize a repository by explictly setting the path to both the working directory and the git directory.
/// </summary>
/// <param name="workingDirectoryPath">The path to the working directory.</param>
/// <param name="gitDirectoryPath">The path to the git repository to be created.</param>
/// <returns>The path to the created repository.</returns>
public static string Init(string workingDirectoryPath, string gitDirectoryPath)
{
Ensure.ArgumentNotNullOrEmptyString(workingDirectoryPath, "workingDirectoryPath");
Ensure.ArgumentNotNullOrEmptyString(gitDirectoryPath, "gitDirectoryPath");
// When being passed a relative workdir path, libgit2 will evaluate it from the
// path to the repository. We pass a fully rooted path in order for the LibGit2Sharp caller
// to pass a path relatively to his current directory.
string wd = Path.GetFullPath(workingDirectoryPath);
// TODO: Shouldn't we ensure that the working folder isn't under the gitDir?
using (RepositoryHandle repo = Proxy.git_repository_init_ext(wd, gitDirectoryPath, false))
{
FilePath repoPath = Proxy.git_repository_path(repo);
return repoPath.Native;
}
}
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
public GitObject Lookup(ObjectId id)
{
return LookupInternal(id, GitObjectType.Any, null);
}
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
public GitObject Lookup(string objectish)
{
return Lookup(objectish, GitObjectType.Any, LookUpOptions.None);
}
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/> and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <param name="type">The kind of GitObject being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
public GitObject Lookup(ObjectId id, ObjectType type)
{
return LookupInternal(id, type.ToGitObjectType(), null);
}
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <param name="type">The kind of <see cref="GitObject"/> being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
public GitObject Lookup(string objectish, ObjectType type)
{
return Lookup(objectish, type.ToGitObjectType(), LookUpOptions.None);
}
internal GitObject LookupInternal(ObjectId id, GitObjectType type, string knownPath)
{
Ensure.ArgumentNotNull(id, "id");
using (ObjectHandle obj = Proxy.git_object_lookup(handle, id, type))
{
if (obj == null || obj.IsInvalid)
{
return null;
}
return GitObject.BuildFrom(this, id, Proxy.git_object_type(obj), knownPath);
}
}
private static string PathFromRevparseSpec(string spec)
{
if (spec.StartsWith(":/", StringComparison.Ordinal))
{
return null;
}
if (Regex.IsMatch(spec, @"^:.*:"))
{
return null;
}
var m = Regex.Match(spec, @"[^@^ ]*:(.*)");
return (m.Groups.Count > 1) ? m.Groups[1].Value : null;
}
internal GitObject Lookup(string objectish, GitObjectType type, LookUpOptions lookUpOptions)
{
Ensure.ArgumentNotNullOrEmptyString(objectish, "objectish");
GitObject obj;
using (ObjectHandle sh = Proxy.git_revparse_single(handle, objectish))
{
if (sh == null)
{
if (lookUpOptions.HasFlag(LookUpOptions.ThrowWhenNoGitObjectHasBeenFound))
{
Ensure.GitObjectIsNotNull(null, objectish);
}
return null;
}
GitObjectType objType = Proxy.git_object_type(sh);
if (type != GitObjectType.Any && objType != type)
{
return null;
}
obj = GitObject.BuildFrom(this, Proxy.git_object_id(sh), objType, PathFromRevparseSpec(objectish));
}
if (lookUpOptions.HasFlag(LookUpOptions.DereferenceResultToCommit))
{
return obj.Peel<Commit>(lookUpOptions.HasFlag(LookUpOptions.ThrowWhenCanNotBeDereferencedToACommit));
}
return obj;
}
internal Commit LookupCommit(string committish)
{
return (Commit)Lookup(committish,
GitObjectType.Any,
LookUpOptions.ThrowWhenNoGitObjectHasBeenFound |
LookUpOptions.DereferenceResultToCommit |
LookUpOptions.ThrowWhenCanNotBeDereferencedToACommit);
}
/// <summary>
/// Lists the Remote Repository References.
/// </summary>
/// <para>
/// Does not require a local Repository. The retrieved
/// <see cref="IBelongToARepository.Repository"/>
/// throws <see cref="InvalidOperationException"/> in this case.
/// </para>
/// <param name="url">The url to list from.</param>
/// <returns>The references in the remote repository.</returns>
public static IEnumerable<Reference> ListRemoteReferences(string url)
{
return ListRemoteReferences(url, null, new ProxyOptions());
}
/// <summary>
/// Lists the Remote Repository References.
/// </summary>
/// <param name="url">The url to list from.</param>
/// <param name="proxyOptions">Options for connecting through a proxy.</param>
/// <returns>The references in the remote repository.</returns>
public static IEnumerable<Reference> ListRemoteReferences(string url, ProxyOptions proxyOptions)
{
return ListRemoteReferences(url, null, proxyOptions);
}
/// <summary>
/// Lists the Remote Repository References.
/// </summary>
/// <para>
/// Does not require a local Repository. The retrieved
/// <see cref="IBelongToARepository.Repository"/>
/// throws <see cref="InvalidOperationException"/> in this case.
/// </para>
/// <param name="url">The url to list from.</param>
/// <param name="credentialsProvider">The <see cref="Func{Credentials}"/> used to connect to remote repository.</param>
/// <returns>The references in the remote repository.</returns>
public static IEnumerable<Reference> ListRemoteReferences(string url, CredentialsHandler credentialsProvider)
{
return ListRemoteReferences(url, credentialsProvider, new ProxyOptions());
}
/// <summary>
/// Lists the Remote Repository References.
/// </summary>
/// <para>
/// Does not require a local Repository. The retrieved
/// <see cref="IBelongToARepository.Repository"/>
/// throws <see cref="InvalidOperationException"/> in this case.
/// </para>
/// <param name="url">The url to list from.</param>
/// <param name="credentialsProvider">The <see cref="Func{Credentials}"/> used to connect to remote repository.</param>
/// <param name="proxyOptions">Options for connecting through a proxy.</param>
/// <returns>The references in the remote repository.</returns>
public static IEnumerable<Reference> ListRemoteReferences(string url, CredentialsHandler credentialsProvider, ProxyOptions proxyOptions)
{
Ensure.ArgumentNotNull(url, "url");
proxyOptions ??= new();
using RepositoryHandle repositoryHandle = Proxy.git_repository_new();
using RemoteHandle remoteHandle = Proxy.git_remote_create_anonymous(repositoryHandle, url);
using var proxyOptionsWrapper = new GitProxyOptionsWrapper(proxyOptions.CreateGitProxyOptions());
var gitCallbacks = new GitRemoteCallbacks { version = 1 };
if (credentialsProvider != null)
{
var callbacks = new RemoteCallbacks(credentialsProvider);
gitCallbacks = callbacks.GenerateCallbacks();
}
var gitProxyOptions = proxyOptionsWrapper.Options;
Proxy.git_remote_connect(remoteHandle, GitDirection.Fetch, ref gitCallbacks, ref gitProxyOptions);
return Proxy.git_remote_ls(null, remoteHandle);
}
/// <summary>
/// Probe for a git repository.
/// <para>The lookup start from <paramref name="startingPath"/> and walk upward parent directories if nothing has been found.</para>
/// </summary>
/// <param name="startingPath">The base path where the lookup starts.</param>
/// <returns>The path to the git repository, or null if no repository was found.</returns>
public static string Discover(string startingPath)
{
FilePath discoveredPath = Proxy.git_repository_discover(startingPath);
if (discoveredPath == null)
{
return null;
}
return discoveredPath.Native;
}
/// <summary>
/// Clone using default options.
/// </summary>
/// <exception cref="RecurseSubmodulesException">This exception is thrown when there
/// is an error is encountered while recursively cloning submodules. The inner exception
/// will contain the original exception. The initially cloned repository would
/// be reported through the <see cref="RecurseSubmodulesException.InitialRepositoryPath"/>
/// property.</exception>"
/// <exception cref="UserCancelledException">Exception thrown when the cancelling
/// the clone of the initial repository.</exception>"
/// <param name="sourceUrl">URI for the remote repository</param>
/// <param name="workdirPath">Local path to clone into</param>
/// <returns>The path to the created repository.</returns>
public static string Clone(string sourceUrl, string workdirPath)
{
return Clone(sourceUrl, workdirPath, null);
}
/// <summary>
/// Clone with specified options.
/// </summary>
/// <exception cref="RecurseSubmodulesException">This exception is thrown when there
/// is an error is encountered while recursively cloning submodules. The inner exception
/// will contain the original exception. The initially cloned repository would
/// be reported through the <see cref="RecurseSubmodulesException.InitialRepositoryPath"/>
/// property.</exception>"
/// <exception cref="UserCancelledException">Exception thrown when the cancelling
/// the clone of the initial repository.</exception>"
/// <param name="sourceUrl">URI for the remote repository</param>
/// <param name="workdirPath">Local path to clone into</param>
/// <param name="options"><see cref="CloneOptions"/> controlling clone behavior</param>
/// <returns>The path to the created repository.</returns>
public static string Clone(string sourceUrl, string workdirPath, CloneOptions options)
{
Ensure.ArgumentNotNull(sourceUrl, "sourceUrl");
Ensure.ArgumentNotNull(workdirPath, "workdirPath");
options ??= new CloneOptions();
// context variable that contains information on the repository that
// we are cloning.
var context = new RepositoryOperationContext(Path.GetFullPath(workdirPath), sourceUrl);
// Notify caller that we are starting to work with the current repository.
bool continueOperation = OnRepositoryOperationStarting(options.FetchOptions.RepositoryOperationStarting, context);
if (!continueOperation)
{
throw new UserCancelledException("Clone cancelled by the user.");
}
using (var checkoutOptionsWrapper = new GitCheckoutOptsWrapper(options))
using (var fetchOptionsWrapper = new GitFetchOptionsWrapper())
{
var gitCheckoutOptions = checkoutOptionsWrapper.Options;
var gitFetchOptions = fetchOptionsWrapper.Options;
gitFetchOptions.Depth = options.FetchOptions.Depth;
gitFetchOptions.ProxyOptions = options.FetchOptions.ProxyOptions.CreateGitProxyOptions();
gitFetchOptions.RemoteCallbacks = new RemoteCallbacks(options.FetchOptions).GenerateCallbacks();
if (options.FetchOptions != null && options.FetchOptions.CustomHeaders != null)
{
gitFetchOptions.CustomHeaders = GitStrArrayManaged.BuildFrom(options.FetchOptions.CustomHeaders);
}
var cloneOpts = new GitCloneOptions
{
Version = 1,
Bare = options.IsBare ? 1 : 0,
CheckoutOpts = gitCheckoutOptions,
FetchOpts = gitFetchOptions,
};
string clonedRepoPath;
try
{
cloneOpts.CheckoutBranch = StrictUtf8Marshaler.FromManaged(options.BranchName);
using (RepositoryHandle repo = Proxy.git_clone(sourceUrl, workdirPath, ref cloneOpts))
{
clonedRepoPath = Proxy.git_repository_path(repo).Native;
}
}
finally
{
EncodingMarshaler.Cleanup(cloneOpts.CheckoutBranch);
}
// Notify caller that we are done with the current repository.
OnRepositoryOperationCompleted(options.FetchOptions.RepositoryOperationCompleted, context);
// Recursively clone submodules if requested.
try
{
RecursivelyCloneSubmodules(options, clonedRepoPath, 1);
}
catch (Exception ex)
{
throw new RecurseSubmodulesException("The top level repository was cloned, but there was an error cloning its submodules.", ex, clonedRepoPath);
}
return clonedRepoPath;
}
}
/// <summary>
/// Recursively clone submodules if directed to do so by the clone options.
/// </summary>
/// <param name="options">Options controlling clone behavior.</param>
/// <param name="repoPath">Path of the parent repository.</param>
/// <param name="recursionDepth">The current depth of the recursion.</param>
private static void RecursivelyCloneSubmodules(CloneOptions options, string repoPath, int recursionDepth)
{
if (options.RecurseSubmodules)
{
List<string> submodules = new List<string>();
using (Repository repo = new Repository(repoPath))
{
var updateOptions = new SubmoduleUpdateOptions()
{
Init = true,
OnCheckoutProgress = options.OnCheckoutProgress,
FetchOptions = options.FetchOptions
};
string parentRepoWorkDir = repo.Info.WorkingDirectory;
// Iterate through the submodules (where the submodule is in the index),
// and clone them.
foreach (var sm in repo.Submodules.Where(sm => sm.RetrieveStatus().HasFlag(SubmoduleStatus.InIndex)))
{
string fullSubmodulePath = Path.Combine(parentRepoWorkDir, sm.Path);
// Resolve the URL in the .gitmodule file to the one actually used
// to clone
string resolvedUrl = Proxy.git_submodule_resolve_url(repo.Handle, sm.Url);
var context = new RepositoryOperationContext(fullSubmodulePath,
resolvedUrl,
parentRepoWorkDir,
sm.Name,
recursionDepth);
bool continueOperation = OnRepositoryOperationStarting(options.FetchOptions.RepositoryOperationStarting,
context);
if (!continueOperation)
{
throw new UserCancelledException("Recursive clone of submodules was cancelled.");
}
repo.Submodules.Update(sm.Name, updateOptions);
OnRepositoryOperationCompleted(options.FetchOptions.RepositoryOperationCompleted,
context);
submodules.Add(Path.Combine(repo.Info.WorkingDirectory, sm.Path));
}
}
// If we are continuing the recursive operation, then
// recurse into nested submodules.
// Check submodules to see if they have their own submodules.
foreach (string submodule in submodules)
{
RecursivelyCloneSubmodules(options, submodule, recursionDepth + 1);
}
}
}
/// <summary>
/// If a callback has been provided to notify callers that we are
/// either starting to work on a repository.
/// </summary>
/// <param name="repositoryChangedCallback">The callback to notify change.</param>
/// <param name="context">Context of the repository this operation affects.</param>
/// <returns>true to continue the operation, false to cancel.</returns>
private static bool OnRepositoryOperationStarting(
RepositoryOperationStarting repositoryChangedCallback,
RepositoryOperationContext context)
{
bool continueOperation = true;
if (repositoryChangedCallback != null)
{
continueOperation = repositoryChangedCallback(context);
}
return continueOperation;
}
private static void OnRepositoryOperationCompleted(
RepositoryOperationCompleted repositoryChangedCallback,
RepositoryOperationContext context)
{
if (repositoryChangedCallback != null)
{
repositoryChangedCallback(context);
}
}
/// <summary>
/// Find where each line of a file originated.
/// </summary>
/// <param name="path">Path of the file to blame.</param>
/// <param name="options">Specifies optional parameters; if null, the defaults are used.</param>
/// <returns>The blame for the file.</returns>
public BlameHunkCollection Blame(string path, BlameOptions options)
{
return new BlameHunkCollection(this, Handle, path, options ?? new BlameOptions());
}
/// <summary>
/// Checkout the specified tree.
/// </summary>
/// <param name="tree">The <see cref="Tree"/> to checkout.</param>
/// <param name="paths">The paths to checkout.</param>
/// <param name="options">Collection of parameters controlling checkout behavior.</param>
public void Checkout(Tree tree, IEnumerable<string> paths, CheckoutOptions options)
{
CheckoutTree(tree, paths != null ? paths.ToList() : null, options);
}
/// <summary>
/// Checkout the specified tree.
/// </summary>
/// <param name="tree">The <see cref="Tree"/> to checkout.</param>
/// <param name="paths">The paths to checkout.</param>
/// <param name="opts">Collection of parameters controlling checkout behavior.</param>
private void CheckoutTree(Tree tree, IList<string> paths, IConvertableToGitCheckoutOpts opts)
{
using (GitCheckoutOptsWrapper checkoutOptionsWrapper = new GitCheckoutOptsWrapper(opts, ToFilePaths(paths)))
{
var options = checkoutOptionsWrapper.Options;
Proxy.git_checkout_tree(Handle, tree.Id, ref options);
}
}
/// <summary>
/// Sets the current <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and
/// the content of the working tree to match.
/// </summary>
/// <param name="resetMode">Flavor of reset operation to perform.</param>
/// <param name="commit">The target commit object.</param>
public void Reset(ResetMode resetMode, Commit commit)
{
Reset(resetMode, commit, new CheckoutOptions());
}
/// <summary>
/// Sets <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and
/// the content of the working tree to match.
/// </summary>
/// <param name="resetMode">Flavor of reset operation to perform.</param>
/// <param name="commit">The target commit object.</param>