Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CloneFixture.cs « LibGit2Sharp.Tests - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7fb05048f7a27e7a029739d1110d547a703899bc (plain)
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp.Handlers;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;

namespace LibGit2Sharp.Tests
{
    public class CloneFixture : BaseFixture
    {
        [Theory]
        [InlineData("http://github.com/libgit2/TestGitRepository")]
        [InlineData("https://github.com/libgit2/TestGitRepository")]
        [InlineData("git://github.com/libgit2/TestGitRepository")]
        //[InlineData("git@github.com:libgit2/TestGitRepository")]
        public void CanClone(string url)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath);

            using (var repo = new Repository(clonedRepoPath))
            {
                string dir = repo.Info.Path;
                Assert.True(Path.IsPathRooted(dir));
                Assert.True(Directory.Exists(dir));

                Assert.NotNull(repo.Info.WorkingDirectory);
                Assert.Equal(Path.Combine(scd.RootedDirectoryPath, ".git" + Path.DirectorySeparatorChar), repo.Info.Path);
                Assert.False(repo.Info.IsBare);

                Assert.True(File.Exists(Path.Combine(scd.RootedDirectoryPath, "master.txt")));
                Assert.Equal(repo.Head.FriendlyName, "master");
                Assert.Equal(repo.Head.Tip.Id.ToString(), "49322bb17d3acc9146f98c97d078513228bbf3c0");
            }
        }

        [Theory]
        [InlineData("br2", "a4a7dce85cf63874e984719f4fdd239f5145052f")]
        [InlineData("packed", "41bc8c69075bbdb46c5c6f0566cc8cc5b46e8bd9")]
        [InlineData("test", "e90810b8df3e80c413d903f631643c716887138d")]
        public void CanCloneWithCheckoutBranchName(string branchName, string headTipId)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(BareTestRepoPath, scd.DirectoryPath, new CloneOptions { BranchName = branchName });

            using (var repo = new Repository(clonedRepoPath))
            {
                var head = repo.Head;

                Assert.Equal(branchName, head.FriendlyName);
                Assert.True(head.IsTracking);
                Assert.Equal(headTipId, head.Tip.Sha);
            }
        }

        private void AssertLocalClone(string url, string path = null, bool isCloningAnEmptyRepository = false)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath);

            using (var clonedRepo = new Repository(clonedRepoPath))
            using (var originalRepo = new Repository(path ?? url))
            {
                Assert.NotEqual(originalRepo.Info.Path, clonedRepo.Info.Path);
                Assert.Equal(originalRepo.Head, clonedRepo.Head);

                Assert.Equal(originalRepo.Branches.Count(), clonedRepo.Branches.Count(b => b.IsRemote));
                Assert.Equal(isCloningAnEmptyRepository ? 0 : 1, clonedRepo.Branches.Count(b => !b.IsRemote));

                Assert.Equal(originalRepo.Tags.Count(), clonedRepo.Tags.Count());
                Assert.Equal(1, clonedRepo.Network.Remotes.Count());
            }
        }

        [Fact]
        public void CanCloneALocalRepositoryFromALocalUri()
        {
            var uri = new Uri(Path.GetFullPath(BareTestRepoPath));
            AssertLocalClone(uri.AbsoluteUri, BareTestRepoPath);
        }

        [Fact]
        public void CanCloneALocalRepositoryFromAStandardPath()
        {
            AssertLocalClone(BareTestRepoPath);
        }

        [Fact]
        public void CanCloneALocalRepositoryFromANewlyCreatedTemporaryPath()
        {
            var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory(path);
            Repository.Init(scd.DirectoryPath);
            AssertLocalClone(scd.DirectoryPath, isCloningAnEmptyRepository: true);
        }

        [Theory]
        [InlineData("http://github.com/libgit2/TestGitRepository")]
        [InlineData("https://github.com/libgit2/TestGitRepository")]
        [InlineData("git://github.com/libgit2/TestGitRepository")]
        //[InlineData("git@github.com:libgit2/TestGitRepository")]
        public void CanCloneBarely(string url)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath, new CloneOptions
                {
                    IsBare = true
                });

            using (var repo = new Repository(clonedRepoPath))
            {
                string dir = repo.Info.Path;
                Assert.True(Path.IsPathRooted(dir));
                Assert.True(Directory.Exists(dir));

                Assert.Null(repo.Info.WorkingDirectory);
                Assert.Equal(scd.RootedDirectoryPath + Path.DirectorySeparatorChar, repo.Info.Path);
                Assert.True(repo.Info.IsBare);
            }
        }

        [Theory]
        [InlineData("git://github.com/libgit2/TestGitRepository")]
        public void WontCheckoutIfAskedNotTo(string url)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath, new CloneOptions()
            {
                Checkout = false
            });

            using (var repo = new Repository(clonedRepoPath))
            {
                Assert.False(File.Exists(Path.Combine(repo.Info.WorkingDirectory, "master.txt")));
            }
        }

        [Theory]
        [InlineData("git://github.com/libgit2/TestGitRepository")]
        public void CallsProgressCallbacks(string url)
        {
            bool transferWasCalled = false;
            bool progressWasCalled = false;
            bool updateTipsWasCalled = false;
            bool checkoutWasCalled = false;

            var scd = BuildSelfCleaningDirectory();

            Repository.Clone(url, scd.DirectoryPath, new CloneOptions()
            {
                OnTransferProgress = _ => { transferWasCalled = true; return true; },
                OnProgress = progress => { progressWasCalled = true; return true; },
                OnUpdateTips = (name, oldId, newId) => { updateTipsWasCalled = true; return true; },
                OnCheckoutProgress = (a, b, c) => checkoutWasCalled = true
            });

            Assert.True(transferWasCalled);
            Assert.True(progressWasCalled);
            Assert.True(updateTipsWasCalled);
            Assert.True(checkoutWasCalled);
        }

        [SkippableFact]
        public void CanCloneWithCredentials()
        {
            InconclusiveIf(() => string.IsNullOrEmpty(Constants.PrivateRepoUrl),
                "Populate Constants.PrivateRepo* to run this test");

            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(Constants.PrivateRepoUrl, scd.DirectoryPath,
                new CloneOptions()
                {
                    CredentialsProvider = Constants.PrivateRepoCredentials
                });


            using (var repo = new Repository(clonedRepoPath))
            {
                string dir = repo.Info.Path;
                Assert.True(Path.IsPathRooted(dir));
                Assert.True(Directory.Exists(dir));

                Assert.NotNull(repo.Info.WorkingDirectory);
                Assert.Equal(Path.Combine(scd.RootedDirectoryPath, ".git" + Path.DirectorySeparatorChar), repo.Info.Path);
                Assert.False(repo.Info.IsBare);
            }
        }

        [Theory]
        [InlineData("https://libgit2@bitbucket.org/libgit2/testgitrepository.git", "libgit3", "libgit3")]
        public void CanCloneFromBBWithCredentials(string url, string user, string pass)
        {
            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath, new CloneOptions()
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                {
                    Username = user,
                    Password = pass,
                }
            });

            using (var repo = new Repository(clonedRepoPath))
            {
                string dir = repo.Info.Path;
                Assert.True(Path.IsPathRooted(dir));
                Assert.True(Directory.Exists(dir));

                Assert.NotNull(repo.Info.WorkingDirectory);
                Assert.Equal(Path.Combine(scd.RootedDirectoryPath, ".git" + Path.DirectorySeparatorChar), repo.Info.Path);
                Assert.False(repo.Info.IsBare);
            }
        }

        [Fact]
        public void CloningAnUrlWithoutPathThrows()
        {
            var scd = BuildSelfCleaningDirectory();

            Assert.Throws<InvalidSpecificationException>(() => Repository.Clone("http://github.com", scd.DirectoryPath));
        }

        [Theory]
        [InlineData("git://github.com/libgit2/TestGitRepository")]
        public void CloningWithoutWorkdirPathThrows(string url)
        {
            Assert.Throws<ArgumentNullException>(() => Repository.Clone(url, null));
        }

        [Fact]
        public void CloningWithoutUrlThrows()
        {
            var scd = BuildSelfCleaningDirectory();

            Assert.Throws<ArgumentNullException>(() => Repository.Clone(null, scd.DirectoryPath));
        }

        /// <summary>
        /// Private helper to record the callbacks that were called as part of a clone.
        /// </summary>
        private class CloneCallbackInfo
        {
            /// <summary>
            /// Was checkout progress called.
            /// </summary>
            public bool CheckoutProgressCalled { get; set; }

            /// <summary>
            /// The reported remote URL.
            /// </summary>
            public string RemoteUrl { get; set; }

            /// <summary>
            /// Was remote ref update called.
            /// </summary>
            public bool RemoteRefUpdateCalled { get; set; }

            /// <summary>
            /// Was the transition callback called when starting
            /// work on this repository.
            /// </summary>
            public bool StartingWorkInRepositoryCalled { get; set; }

            /// <summary>
            /// Was the transition callback called when finishing
            /// work on this repository.
            /// </summary>
            public bool FinishedWorkInRepositoryCalled { get; set; }

            /// <summary>
            /// The reported recursion depth.
            /// </summary>
            public int RecursionDepth { get; set; }
        }

        [Fact]
        public void CanRecursivelyCloneSubmodules()
        {
            var uri = new Uri(Path.GetFullPath(SandboxSubmoduleSmallTestRepo()));
            var scd = BuildSelfCleaningDirectory();
            string relativeSubmodulePath = "submodule_target_wd";

            // Construct the expected URL the submodule will clone from.
            string expectedSubmoduleUrl = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath), relativeSubmodulePath);
            expectedSubmoduleUrl = expectedSubmoduleUrl.Replace('\\', '/');

            Dictionary<string, CloneCallbackInfo> callbacks = new Dictionary<string, CloneCallbackInfo>();

            CloneCallbackInfo currentEntry = null;
            bool unexpectedOrderOfCallbacks = false;

            CheckoutProgressHandler checkoutProgressHandler = (x, y, z) =>
                {
                    if (currentEntry != null)
                    {
                        currentEntry.CheckoutProgressCalled = true;
                    }
                    else
                    {
                        // Should not be called if there is not a current
                        // callbackInfo entry.
                        unexpectedOrderOfCallbacks = true;
                    }
                };

            UpdateTipsHandler remoteRefUpdated = (x, y, z) =>
            {
                if (currentEntry != null)
                {
                    currentEntry.RemoteRefUpdateCalled = true;
                }
                else
                {
                    // Should not be called if there is not a current
                    // callbackInfo entry.
                    unexpectedOrderOfCallbacks = true;
                }

                return true;
            };

            RepositoryOperationStarting repositoryOperationStarting = (x) =>
                {
                    if (currentEntry != null)
                    {
                        // Should not be called if there is a current
                        // callbackInfo entry.
                        unexpectedOrderOfCallbacks = true;
                    }

                    currentEntry = new CloneCallbackInfo();
                    currentEntry.StartingWorkInRepositoryCalled = true;
                    currentEntry.RecursionDepth = x.RecursionDepth;
                    currentEntry.RemoteUrl = x.RemoteUrl;
                    callbacks.Add(x.RepositoryPath, currentEntry);

                    return true;
                };

            RepositoryOperationCompleted repositoryOperationCompleted = (x) =>
                {
                    if (currentEntry != null)
                    {
                        currentEntry.FinishedWorkInRepositoryCalled = true;
                        currentEntry = null;
                    }
                    else
                    {
                        // Should not be called if there is not a current
                        // callbackInfo entry.
                        unexpectedOrderOfCallbacks = true;
                    }
                };

            CloneOptions options = new CloneOptions()
            {
                RecurseSubmodules = true,
                OnCheckoutProgress = checkoutProgressHandler,
                OnUpdateTips = remoteRefUpdated,
                RepositoryOperationStarting = repositoryOperationStarting,
                RepositoryOperationCompleted = repositoryOperationCompleted,
            };

            string clonedRepoPath = Repository.Clone(uri.AbsolutePath, scd.DirectoryPath, options);
            string workDirPath;

            using(Repository repo = new Repository(clonedRepoPath))
            {
                workDirPath = repo.Info.WorkingDirectory.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
            }

            // Verification:
            // Verify that no callbacks were called in an unexpected order.
            Assert.False(unexpectedOrderOfCallbacks);

            Dictionary<string, CloneCallbackInfo> expectedCallbackInfo = new Dictionary<string, CloneCallbackInfo>();
            expectedCallbackInfo.Add(workDirPath, new CloneCallbackInfo()
                {
                    RecursionDepth = 0,
                    RemoteUrl = uri.AbsolutePath,
                    StartingWorkInRepositoryCalled = true,
                    FinishedWorkInRepositoryCalled = true,
                    CheckoutProgressCalled = true,
                    RemoteRefUpdateCalled = true,
                });

            expectedCallbackInfo.Add(Path.Combine(workDirPath, relativeSubmodulePath), new CloneCallbackInfo()
            {
                RecursionDepth = 1,
                RemoteUrl = expectedSubmoduleUrl,
                StartingWorkInRepositoryCalled = true,
                FinishedWorkInRepositoryCalled = true,
                CheckoutProgressCalled = true,
                RemoteRefUpdateCalled = true,
            });

            // Callbacks for each expected repository that is cloned
            foreach (KeyValuePair<string, CloneCallbackInfo> kvp in expectedCallbackInfo)
            {
                CloneCallbackInfo entry = null;
                Assert.True(callbacks.TryGetValue(kvp.Key, out entry), string.Format("{0} was not found in callbacks.", kvp.Key));

                Assert.Equal(kvp.Value.RemoteUrl, entry.RemoteUrl);
                Assert.Equal(kvp.Value.RecursionDepth, entry.RecursionDepth);
                Assert.Equal(kvp.Value.StartingWorkInRepositoryCalled, entry.StartingWorkInRepositoryCalled);
                Assert.Equal(kvp.Value.FinishedWorkInRepositoryCalled, entry.FinishedWorkInRepositoryCalled);
                Assert.Equal(kvp.Value.CheckoutProgressCalled, entry.CheckoutProgressCalled);
                Assert.Equal(kvp.Value.RemoteRefUpdateCalled, entry.RemoteRefUpdateCalled);
            }

            // Verify the state of the submodule
            using(Repository repo = new Repository(clonedRepoPath))
            {
                var sm = repo.Submodules[relativeSubmodulePath];
                Assert.True(sm.RetrieveStatus().HasFlag(SubmoduleStatus.InWorkDir |
                                                        SubmoduleStatus.InConfig |
                                                        SubmoduleStatus.InIndex |
                                                        SubmoduleStatus.InHead));

                Assert.NotNull(sm.HeadCommitId);
                Assert.Equal("480095882d281ed676fe5b863569520e54a7d5c0", sm.HeadCommitId.Sha);

                Assert.False(repo.RetrieveStatus().IsDirty);
            }
        }

        [Fact]
        public void CanCancelRecursiveClone()
        {
            var uri = new Uri(Path.GetFullPath(SandboxSubmoduleSmallTestRepo()));
            var scd = BuildSelfCleaningDirectory();
            string relativeSubmodulePath = "submodule_target_wd";

            int cancelDepth = 0;

            RepositoryOperationStarting repositoryOperationStarting = (x) =>
            {
                return !(x.RecursionDepth >= cancelDepth);
            };

            CloneOptions options = new CloneOptions()
            {
                RecurseSubmodules = true,
                RepositoryOperationStarting = repositoryOperationStarting,
            };

            Assert.Throws<UserCancelledException>(() =>
                Repository.Clone(uri.AbsolutePath, scd.DirectoryPath, options));

            // Cancel after super repository is cloned, but before submodule is cloned.
            cancelDepth = 1;

            string clonedRepoPath = null;

            try
            {
                Repository.Clone(uri.AbsolutePath, scd.DirectoryPath, options);
            }
            catch(RecurseSubmodulesException ex)
            {
                Assert.NotNull(ex.InnerException);
                Assert.Equal(typeof(UserCancelledException), ex.InnerException.GetType());
                clonedRepoPath = ex.InitialRepositoryPath;
            }

            // Verify that the submodule was not initialized.
            using(Repository repo = new Repository(clonedRepoPath))
            {
                var submoduleStatus = repo.Submodules[relativeSubmodulePath].RetrieveStatus();
                Assert.Equal(SubmoduleStatus.InConfig | SubmoduleStatus.InHead | SubmoduleStatus.InIndex | SubmoduleStatus.WorkDirUninitialized,
                             submoduleStatus);

            }
        }
    }
}