Пример #1
0
        /// <inheritdoc />
        public TRepository Clone(string repository, ObjectId commitId = null, Func <OdbBackend> backend = null)
        {
            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }

            using (_logger.BeginScope("Cloning repository '{Repository}' from commit id '{CommitId}'.", repository, commitId))
            {
                // Clone & load in a temp folder to extract the repository id
                var tempPath            = System.IO.Path.Combine(System.IO.Path.GetTempPath(), UniqueId.CreateNew().ToString());
                var tempRepoDescription = new RepositoryDescription(tempPath, backend);
                var cloned = _repositoryLoader.Clone(this, repository, tempRepoDescription, commitId);

                // Evict temp repository from repo provider
                _repositoryProvider.Evict(tempRepoDescription);

                // Move to target path
                var path = System.IO.Path.Combine(Path, cloned.Id.ToString());
                Directory.Move(tempPath, path);

                var repositoryDescription = new RepositoryDescription(path, backend);
                return(ReloadRepository(repositoryDescription, cloned.CommitId));
            }
        }
Пример #2
0
        /// <inheritdoc />
        public AbstractObjectRepository LoadFrom(RepositoryDescription repositoryDescription, ObjectId commitId = null)
        {
            if (repositoryDescription == null)
            {
                throw new ArgumentNullException(nameof(repositoryDescription));
            }

            return(_repositoryProvider.Execute(repositoryDescription, repository =>
            {
                Commit currentCommit;
                if (commitId == null)
                {
                    currentCommit = repository.Head.Tip;
                    commitId = currentCommit.Id;
                }
                else
                {
                    currentCommit = repository.Lookup <Commit>(commitId);
                }

                var instance = (AbstractObjectRepository)LoadEntry(commitId, currentCommit[FileSystemStorage.DataFile], string.Empty);
                instance.SetRepositoryData(repositoryDescription, commitId);
                return instance;
            }));
        }
Пример #3
0
        private async Task <RepositoryDescription> GetRepositoryDescription(ServiceInvocationContext context)
        {
            // We use ConfigureAwait(false) to prevent .NET from trying to synchronize back to our current Sync Context (UI Thread/HttpContext/etc)
            // when continuing from await. We don't care about Sync Context, so this saves the perf hit of syncing back. Our caller will still
            // sync back to their current Sync Context when they await us, so this doesn't affect them.
            using (context.Trace.EnterExit())
            {
                try
                {
                    // Invoke the request
                    var url      = new Uri("/", UriKind.Relative);
                    var response = await context.GetAsync(url, context.CancellationToken)
                                   .ConfigureAwait(continueOnCapturedContext: false);

                    context.CancellationToken.ThrowIfCancellationRequested();
                    response.EnsureSuccessStatusCode();

                    // Parse the response as JSON
                    var json = JObject.Parse(await response.Content.ReadAsStringAsync()
                                             .ConfigureAwait(continueOnCapturedContext: false));

                    // Load the json in to a result
                    return(RepositoryDescription.FromJson(json, context.Trace, context.ResolveUrl(url)));
                }
                catch (Exception ex)
                {
                    context.Trace.Error(ex);
                    throw;
                }
            }
        }
        /// <inheritdoc />
        public ObjectId SaveInNewRepository(Signature signature, string message, RepositoryDescription repositoryDescription, bool isBare = false)
        {
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (repositoryDescription == null)
            {
                throw new ArgumentNullException(nameof(repositoryDescription));
            }

            LibGit2Sharp.Repository.Init(repositoryDescription.Path, isBare);

            return(_repositoryProvider.Execute(repositoryDescription, repository =>
            {
                var all = this.Flatten().Select(o => new MetadataTreeEntryChanges(o.GetDataPath(), ChangeKind.Added, @new: o));
                var changes = new MetadataTreeChanges(this, all.ToImmutableList());
                var result = repository.CommitChanges(changes, message, signature, signature, hooks: _hooks);

                if (result != null)
                {
                    SetRepositoryData(repositoryDescription, result.Id);
                }

                return result?.Id;
            }));
        }
Пример #5
0
        /// <inheritdoc />
        public TRepository AddRepository(TRepository repository, Signature signature, string message, Func <OdbBackend> backend = null, bool isBare = false)
        {
            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            using (_logger.BeginScope("Adding repository '{Repository}'.", repository.Id))
            {
                var repositoryDescription = new RepositoryDescription(System.IO.Path.Combine(Path, repository.Id.ToString()), backend);
                EnsureNewRepository(repository, repositoryDescription);
                LibGit2Sharp.Repository.Init(repositoryDescription.Path, isBare);

                return(_repositoryProvider.Execute(repositoryDescription, r =>
                {
                    var all = repository.Flatten().Select(o => new ObjectRepositoryEntryChanges(o.GetDataPath(), ChangeKind.Added, @new: o));
                    var changes = new ObjectRepositoryChangeCollection(repository, all.ToImmutableList());
                    var commit = r.CommitChanges(changes, _serializerFactory(), message, signature, signature, _hooks);
                    if (commit == null)
                    {
                        return null;
                    }
                    return ReloadRepository(repositoryDescription, commit.Id);
                }));
            }
        }
        void ReleaseDesignerOutlets()
        {
            if (ContentConstraint != null)
            {
                ContentConstraint.Dispose();
                ContentConstraint = null;
            }

            if (RepositoryDescription != null)
            {
                RepositoryDescription.Dispose();
                RepositoryDescription = null;
            }

            if (RepositoryImage != null)
            {
                RepositoryImage.Dispose();
                RepositoryImage = null;
            }

            if (RepositoryName != null)
            {
                RepositoryName.Dispose();
                RepositoryName = null;
            }

            if (RepositoryOwner != null)
            {
                RepositoryOwner.Dispose();
                RepositoryOwner = null;
            }
        }
Пример #7
0
 internal MigrationScaffolder(IObjectRepositoryContainer container, RepositoryDescription repositoryDescription,
                              IRepositoryProvider repositoryProvider, ObjectRepositorySerializerFactory repositorySerializerFactory)
 {
     _repositoryProvider          = repositoryProvider ?? throw new ArgumentNullException(nameof(repositoryProvider));
     _container                   = container ?? throw new ArgumentNullException(nameof(container));
     _repositoryDescription       = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));
     _repositorySerializerFactory = repositorySerializerFactory ?? throw new ArgumentNullException(nameof(repositorySerializerFactory));
 }
        public void RepositoryContextAttributesSet()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestOne>();

            IDictionary<DataLayerState, System.Type> result = desc.RepositoryContexts;

            Assert.IsNotNull(result, "The Repositories collection should not be null.");
            Assert.AreEqual(2, result.Count, "The number of registered repositories should be two.");
            Assert.AreEqual(typeof(short), result[DataLayerState.Live], "The type returned for the Live data layer state is not correct.");
            Assert.AreEqual(typeof(double), result[DataLayerState.Testing], "The type returned for the Testing data layer state is not correct.");
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MigrationScaffolder"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="repositoryDescription">The repository description.</param>
        /// <exception cref="ArgumentNullException">
        /// serviceProvider
        /// or
        /// repository
        /// </exception>
        public MigrationScaffolder(IServiceProvider serviceProvider, RepositoryDescription repositoryDescription)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _serializer            = serviceProvider.GetRequiredService <IObjectRepositoryLoader>().GetJsonSerializer();
            _repositoryProvider    = serviceProvider.GetRequiredService <IRepositoryProvider>();
            _repositoryDescription = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));
        }
Пример #10
0
 private void EnsureNewRepository(IObjectRepository repository, RepositoryDescription repositoryDescription)
 {
     if (Repositories.Any(r => r.Id == repository.Id))
     {
         throw new GitObjectDbException($"A repository with the same id already exists in the container repositories.");
     }
     if (Directory.Exists(repositoryDescription.Path))
     {
         throw new GitObjectDbException($"A repository with the target path already exists on the filesystem.");
     }
 }
Пример #11
0
        public ComputeTreeChanges(IObjectRepositoryContainer container, RepositoryDescription repositoryDescription,
                                  IModelDataAccessorProvider modelDataProvider, IObjectRepositoryLoader objectRepositoryLoader,
                                  IRepositoryProvider repositoryProvider, ILogger <ComputeTreeChanges> logger)
        {
            _container             = container ?? throw new ArgumentNullException(nameof(container));
            _repositoryDescription = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));

            _modelDataProvider      = modelDataProvider ?? throw new ArgumentNullException(nameof(modelDataProvider));
            _objectRepositoryLoader = objectRepositoryLoader ?? throw new ArgumentNullException(nameof(objectRepositoryLoader));
            _repositoryProvider     = repositoryProvider ?? throw new ArgumentNullException(nameof(repositoryProvider));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ComputeTreeChanges"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="repositoryDescription">The repository description.</param>
        /// <exception cref="ArgumentNullException">serviceProvider</exception>
        public ComputeTreeChanges(IServiceProvider serviceProvider, RepositoryDescription repositoryDescription)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _modelDataProvider = serviceProvider.GetRequiredService<IModelDataAccessorProvider>();
            _objectRepositoryLoader = serviceProvider.GetRequiredService<IObjectRepositoryLoader>();
            _repositoryProvider = serviceProvider.GetRequiredService<IRepositoryProvider>();

            _repositoryDescription = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));
        }
        /// <inheritdoc />
        public IObjectRepository LoadFrom(IObjectRepositoryContainer container, RepositoryDescription repositoryDescription, ObjectId commitId = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            if (repositoryDescription == null)
            {
                throw new ArgumentNullException(nameof(repositoryDescription));
            }

            return(_repositoryProvider.Execute(repositoryDescription, repository =>
                                               LoadFrom(container, repositoryDescription, repository, commitId)));
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MetadataTreeMerge"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="repositoryDescription">The repository description.</param>
        /// <param name="repository">The repository on which to apply the merge.</param>
        /// <param name="branchName">Name of the branch.</param>
        /// <exception cref="ArgumentNullException">
        /// serviceProvider
        /// or
        /// repositoryDescription
        /// or
        /// commitId
        /// or
        /// branchName
        /// or
        /// merger
        /// </exception>
        public MetadataTreeMerge(IServiceProvider serviceProvider, RepositoryDescription repositoryDescription, IObjectRepository repository, string branchName)
        {
            _serviceProvider       = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
            _repositoryDescription = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));
            Repository             = repository ?? throw new ArgumentNullException(nameof(repository));
            CommitId   = repository.CommitId ?? throw new NotSupportedException("Repository has no commit.");
            BranchName = branchName ?? throw new ArgumentNullException(nameof(branchName));

            _repositoryProvider         = serviceProvider.GetRequiredService <IRepositoryProvider>();
            _modelDataProvider          = serviceProvider.GetRequiredService <IModelDataAccessorProvider>();
            _migrationScaffolderFactory = serviceProvider.GetRequiredService <Func <RepositoryDescription, MigrationScaffolder> >();

            Initialize();
        }
Пример #15
0
        private IImmutableSet <TRepository> LoadRepositories()
        {
            var builder = ImmutableSortedSet.CreateBuilder(ObjectRepositoryIdComparer <TRepository> .Instance);

            foreach (var repositoryPath in Directory.EnumerateDirectories(Path))
            {
                if (Repository.IsValid(repositoryPath))
                {
                    var description = new RepositoryDescription(repositoryPath);
                    builder.Add(_repositoryLoader.LoadFrom(this, description));
                }
            }
            return(builder.ToImmutable());
        }
Пример #16
0
        public async Task CanSelectBranches()
        {
            var schedulers            = new TestSchedulers();
            var repositoryFactory     = new SimpleRepositoryFactoryMock();
            var repositoryDescription = new RepositoryDescription("Name", "PATH TO REPO");
            var res = await RepositoryViewModel.Create(
                schedulers,
                CancellationToken.None,
                repositoryFactory,
                new TestFileSystem(),
                repositoryDescription,
                Observable.Return(new CompareOptions()));

            Assert.IsTrue(res.Is <RepositoryViewModel>());
            using var repo = res.Get <RepositoryViewModel>();
            var refs = repo.References.Value;

            Assert.IsNotNull(refs);
            Assert.AreEqual(2, refs !.Branches.Refs.Count);
            var master = refs.Branches.Refs.Where(b => b.FriendlyName == "master").FirstOrDefault()
                         ?? throw new InvalidOperationException("Branch master not found.");
            var work = refs.Branches.Refs.Where(b => b.FriendlyName == "work").FirstOrDefault()
                       ?? throw new InvalidOperationException("Branch work not found.");

            Assert.IsTrue(master.Selected.Value, "Branch master (HEAD) should be selected.");
            Assert.IsFalse(work.Selected.Value, "Branch work should not be selected.");
            Assert.IsTrue(repo.Graph.LogGraphNodes.Value.VariantIndex == 0);
            var logGraphNodes = repo.Graph.LogGraphNodes.Value.First;

            using var _1 = repo.Graph.LogGraphNodes
                           .Subscribe(nodes => logGraphNodes = nodes.VariantIndex == 0
                        ? nodes.First : throw new InvalidOperationException(nodes.Second.Message));
            IList <RefSelection>?selectedBranches = null;

            refs         = repo.References.Value;
            using var _2 = refs !.Branches.SelectedRefs
                           .Subscribe(sb => selectedBranches = sb);
            Assert.AreEqual(1, selectedBranches.Where(b => b.Selected).Count());
            Assert.AreEqual(7, logGraphNodes.Count); // The mock doesn't filter unreachable commits.
            var nodesWithBranch = logGraphNodes.Where(c => c.Branches.Any());

            Assert.AreEqual(2, nodesWithBranch.Count());
            Assert.AreEqual("master", nodesWithBranch.First().Branches.First().FirendlyName);
            work.SelectCommand.Execute(true);
            Assert.AreEqual(2, logGraphNodes.Where(c => c.Branches.Any()).Count());
            _ = selectedBranches ?? throw new InvalidOperationException("Selected branches were not set.");
            Assert.AreEqual(2, selectedBranches.Where(b => b.Selected).Count());
        }
Пример #17
0
        public async Task CanCreateRepositoryViewModel()
        {
            var schedulers            = new TestSchedulers();
            var repositoryFactory     = new TestRepositoryFactory();
            var repositoryDescription = new RepositoryDescription("Name", "PATH TO REPO");
            var res = await RepositoryViewModel.Create(
                schedulers,
                CancellationToken.None,
                repositoryFactory,
                new TestFileSystem(),
                repositoryDescription,
                Observable.Return(new CompareOptions()));

            Assert.IsTrue(res.Is <RepositoryViewModel>());
            using var repo = res.Get <RepositoryViewModel>();
            Assert.AreEqual(repositoryDescription, repo.RepositoryDescription);
        }
Пример #18
0
        /// <inheritdoc />
        public AbstractObjectRepository Clone(string repository, RepositoryDescription repositoryDescription, ObjectId commitId = null)
        {
            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }

            if (repositoryDescription == null)
            {
                throw new ArgumentNullException(nameof(repositoryDescription));
            }

            Repository.Clone(repository, repositoryDescription.Path, new CloneOptions {
                Checkout = false
            });
            return(LoadFrom(repositoryDescription, commitId));
        }
        private IObjectRepository LoadFrom(IObjectRepositoryContainer container, RepositoryDescription repositoryDescription, IRepository repository, ObjectId commitId = null)
        {
            Commit currentCommit;

            if (commitId == null)
            {
                currentCommit = repository.Head.Tip;
                commitId      = currentCommit.Id;
            }
            else
            {
                currentCommit = repository.Lookup <Commit>(commitId);
            }

            var instance = (IObjectRepository)LoadEntry(container, commitId, currentCommit[FileSystemStorage.DataFile], string.Empty,
                                                        relativePath => (currentCommit[relativePath]?.Target as Blob)?.GetContentText() ?? string.Empty);

            instance.SetRepositoryData(repositoryDescription, commitId);
            return(instance);
        }
Пример #20
0
        public void Should_Parse_Repo_Url(
            string repoUrl,
            string serverUrl,
            string collectionName,
            string collectionurl,
            string projectName,
            string repositoryName,
            string repositoryUrl)
        {
            // Given / When
            var repositoryDescription = new RepositoryDescription(new Uri(repoUrl));

            // Then
            repositoryDescription.ServerUrl.ShouldBe(new Uri(serverUrl));
            repositoryDescription.CollectionName.ShouldBe(collectionName);
            repositoryDescription.CollectionUrl.ShouldBe(new Uri(collectionurl));
            repositoryDescription.ProjectName.ShouldBe(projectName);
            repositoryDescription.RepositoryName.ShouldBe(repositoryName);
            repositoryDescription.RepositoryUrl.ShouldBe(new Uri(repositoryUrl));
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MetadataTreeMergeProcessor"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="repositoryDescription">The repository description.</param>
        /// <param name="metadataTreeMerge">The metadata tree merge.</param>
        /// <exception cref="ArgumentNullException">
        /// serviceProvider
        /// or
        /// repositoryDescription
        /// </exception>
        internal MetadataTreeMergeProcessor(IServiceProvider serviceProvider, RepositoryDescription repositoryDescription, MetadataTreeMerge metadataTreeMerge)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _repositoryDescription = repositoryDescription ?? throw new ArgumentNullException(nameof(repositoryDescription));
            _metadataTreeMerge     = metadataTreeMerge ?? throw new ArgumentNullException(nameof(metadataTreeMerge));

            _repositoryProvider        = serviceProvider.GetRequiredService <IRepositoryProvider>();
            _computeTreeChangesFactory = serviceProvider.GetRequiredService <Func <RepositoryDescription, IComputeTreeChanges> >();
            _serializer = new Lazy <JsonSerializer>(() => serviceProvider.GetRequiredService <IObjectRepositoryLoader>().GetJsonSerializer());
            _hooks      = serviceProvider.GetRequiredService <GitHooks>();
            _changes    = _metadataTreeMerge.ModifiedChunks.ToLookup(c => c.Path, StringComparer.OrdinalIgnoreCase);

            Guid tempGuid;

            _forceVisit = new HashSet <Guid>(from path in _metadataTreeMerge.AllImpactedPaths
                                             from part in path.Split('/')
                                             where Guid.TryParse(part, out tempGuid)
                                             let guid = tempGuid
                                                        select guid);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureDevOpsPullRequest"/> class.
        /// </summary>
        /// <param name="log">The Cake log context.</param>
        /// <param name="settings">Settings for accessing AzureDevOps.</param>
        /// <param name="gitClientFactory">A factory to communicate with Git client.</param>
        /// <exception cref="AzureDevOpsPullRequestNotFoundException">If <see cref="AzureDevOpsPullRequestSettings.ThrowExceptionIfPullRequestCouldNotBeFound"/>
        /// is set to <c>true</c> and no pull request could be found.</exception>
        internal AzureDevOpsPullRequest(ICakeLog log, AzureDevOpsPullRequestSettings settings, IGitClientFactory gitClientFactory)
        {
            log.NotNull(nameof(log));
            settings.NotNull(nameof(settings));
            gitClientFactory.NotNull(nameof(gitClientFactory));

            this.log = log;
            this.gitClientFactory = gitClientFactory;
            this.credentials      = settings.Credentials;
            this.throwExceptionIfPullRequestCouldNotBeFound = settings.ThrowExceptionIfPullRequestCouldNotBeFound;

            this.repositoryDescription = new RepositoryDescription(settings.RepositoryUrl);

            this.log.Verbose(
                "Repository information:\n  CollectionName: {0}\n  CollectionUrl: {1}\n  ProjectName: {2}\n  RepositoryName: {3}",
                this.repositoryDescription.CollectionName,
                this.repositoryDescription.CollectionUrl,
                this.repositoryDescription.ProjectName,
                this.repositoryDescription.RepositoryName);

            using (var gitClient = this.gitClientFactory.CreateGitClient(this.repositoryDescription.CollectionUrl, settings.Credentials, out var authorizedIdenity))
            {
                this.log.Verbose(
                    "Authorized Identity:\n  Id: {0}\n  DisplayName: {1}",
                    authorizedIdenity.Id,
                    authorizedIdenity.DisplayName);

                if (settings.PullRequestId.HasValue)
                {
                    this.log.Verbose("Read pull request with ID {0}", settings.PullRequestId.Value);
                    this.pullRequest =
                        gitClient
                        .GetPullRequestAsync(
                            this.repositoryDescription.ProjectName,
                            this.repositoryDescription.RepositoryName,
                            settings.PullRequestId.Value)
                        .ConfigureAwait(false)
                        .GetAwaiter()
                        .GetResult();
                }
                else if (!string.IsNullOrWhiteSpace(settings.SourceRefName))
                {
                    this.log.Verbose("Read pull request for branch {0}", settings.SourceRefName);

                    var pullRequestSearchCriteria =
                        new GitPullRequestSearchCriteria()
                    {
                        Status        = Microsoft.TeamFoundation.SourceControl.WebApi.PullRequestStatus.Active,
                        SourceRefName = settings.SourceRefName,
                    };

                    this.pullRequest =
                        gitClient
                        .GetPullRequestsAsync(
                            this.repositoryDescription.ProjectName,
                            this.repositoryDescription.RepositoryName,
                            pullRequestSearchCriteria,
                            top: 1)
                        .ConfigureAwait(false)
                        .GetAwaiter()
                        .GetResult()
                        .SingleOrDefault();
                }
                else
                {
                    throw new ArgumentOutOfRangeException(
                              nameof(settings),
                              "Either PullRequestId or SourceRefName needs to be set");
                }
            }

            if (this.pullRequest == null)
            {
                if (this.throwExceptionIfPullRequestCouldNotBeFound)
                {
                    throw new AzureDevOpsPullRequestNotFoundException("Pull request not found");
                }

                this.log.Warning("Could not find pull request");
                return;
            }

            this.log.Verbose(
                "Pull request information:\n  PullRequestId: {0}\n  RepositoryId: {1}\n  RepositoryName: {2}\n  SourceRefName: {3}",
                this.pullRequest.PullRequestId,
                this.pullRequest.Repository.Id,
                this.pullRequest.Repository.Name,
                this.pullRequest.SourceRefName);
        }
Пример #23
0
 /// <inheritdoc />
 public TInstance LoadFrom <TInstance>(RepositoryDescription repositoryDescription, ObjectId commitId = null)
     where TInstance : AbstractObjectRepository
 {
     return((TInstance)LoadFrom(repositoryDescription, commitId));
 }
 /// <summary>
 /// Sets the repository data.
 /// </summary>
 /// <param name="repositoryDescription">The repository description.</param>
 /// <param name="commitId">The commit getter.</param>
 internal void SetRepositoryData(RepositoryDescription repositoryDescription, ObjectId commitId)
 {
     _repositoryDescription = repositoryDescription;
     CommitId = commitId;
 }
        public void ServiceTypeSet()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestOne>();

            Assert.AreEqual(typeof(string), desc.ServiceType, "The ServiceType property was not set correctly.");
        }
        public void ServicePath_NullWhenNotRegistered()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestThree>();

            Assert.IsNull(desc.ServicePath, @"
            The ServicePath property should be null if the RepositoryServicePathAttribute is not registered on the repository.
            ");
        }
        public void ServicePathSet_Again()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestTwo>();

            Assert.AreEqual("TestRepositoryPathAgain", desc.ServicePath, "The ServicePath property was not set correctly.");
        }
 /// <inheritdoc />
 public TRepository Clone <TRepository>(IObjectRepositoryContainer <TRepository> container, string repository, RepositoryDescription repositoryDescription, ObjectId commitId = null)
     where TRepository : class, IObjectRepository
 {
     return((TRepository)Clone((IObjectRepositoryContainer)container, repository, repositoryDescription, commitId));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="TfsPullRequestSystem"/> class.
        /// Connects to the TFS server using NTLM authentication.
        /// </summary>
        /// <param name="log">The Cake log context.</param>
        /// <param name="settings">Settings for accessing TFS.</param>
        public TfsPullRequestSystem(ICakeLog log, TfsPullRequestSettings settings)
            : base(log)
        {
            settings.NotNull(nameof(settings));

            this.settings = settings;

            this.repositoryDescription = new RepositoryDescription(settings.RepositoryUrl);

            this.Log.Verbose(
                "Repository information:\n  CollectionName: {0}\n  CollectionUrl: {1}\n  ProjectName: {2}\n  RepositoryName: {3}",
                this.repositoryDescription.CollectionName,
                this.repositoryDescription.CollectionUrl,
                this.repositoryDescription.ProjectName,
                this.repositoryDescription.RepositoryName);

            Identity authorizedIdenity;

            using (var gitClient = this.CreateGitClient(out authorizedIdenity))
            {
                this.Log.Verbose(
                    "Authorized Identity:\n  Id: {0}\n  DisplayName: {1}",
                    authorizedIdenity.Id,
                    authorizedIdenity.DisplayName);

                if (settings.PullRequestId.HasValue)
                {
                    this.Log.Verbose("Read pull request with ID {0}", settings.PullRequestId.Value);
                    this.pullRequest =
                        gitClient.GetPullRequestAsync(
                            this.repositoryDescription.ProjectName,
                            this.repositoryDescription.RepositoryName,
                            settings.PullRequestId.Value).Result;
                }
                else if (!string.IsNullOrWhiteSpace(settings.SourceBranch))
                {
                    this.Log.Verbose("Read pull request for branch {0}", settings.SourceBranch);

                    var pullRequestSearchCriteria =
                        new GitPullRequestSearchCriteria()
                    {
                        Status        = PullRequestStatus.Active,
                        SourceRefName = settings.SourceBranch
                    };

                    this.pullRequest =
                        gitClient.GetPullRequestsAsync(
                            this.repositoryDescription.ProjectName,
                            this.repositoryDescription.RepositoryName,
                            pullRequestSearchCriteria,
                            top: 1).Result.SingleOrDefault();
                }
                else
                {
                    throw new ArgumentOutOfRangeException(
                              nameof(settings),
                              "Either PullRequestId or SourceBranch needs to be set");
                }
            }

            if (this.pullRequest == null)
            {
                if (this.settings.ThrowExceptionIfPullRequestDoesNotExist)
                {
                    throw new PrcaException("Could not find pull request");
                }

                this.Log.Warning("Could not find pull request");
                return;
            }

            this.Log.Verbose(
                "Pull request information:\n  PullRequestId: {0}\n  RepositoryId: {1}\n  RepositoryName: {2}\n  SourceRefName: {3}",
                this.pullRequest.PullRequestId,
                this.pullRequest.Repository.Id,
                this.pullRequest.Repository.Name,
                this.pullRequest.SourceRefName);
        }
        public void ServiceTypeSet_Again()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestTwo>();

            Assert.AreEqual(typeof(System.IDisposable), desc.ServiceType, "The ServiceType property was not set correctly.");
        }
Пример #31
0
 public RepositoryError(string message, RepositoryDescription repositoryDescription)
     : base(message)
     => RepositoryDescription = repositoryDescription;
Пример #32
0
        private TRepository ReloadRepository(RepositoryDescription repositoryDescription, ObjectId commit = null)
        {
            var result = _repositoryLoader.LoadFrom(this, repositoryDescription, commit);

            return(AddOrReplace(result));
        }
        /// <summary>
        /// Create a pull request.
        /// </summary>
        /// <param name="log">The Cake log context.</param>
        /// <param name="gitClientFactory">Git client factory.</param>
        /// <param name="settings">Settings for accessing AzureDevOps.</param>
        /// <returns>Instance of the created pull request.</returns>
        internal static AzureDevOpsPullRequest Create(ICakeLog log, IGitClientFactory gitClientFactory, AzureDevOpsCreatePullRequestSettings settings)
        {
            log.NotNull(nameof(log));
            gitClientFactory.NotNull(nameof(gitClientFactory));
            settings.NotNull(nameof(settings));

            var repositoryDescription = new RepositoryDescription(settings.RepositoryUrl);

            using (var gitClient = gitClientFactory.CreateGitClient(repositoryDescription.CollectionUrl, settings.Credentials))
            {
                var repository =
                    gitClient
                    .GetRepositoryAsync(repositoryDescription.ProjectName, repositoryDescription.RepositoryName)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();

                if (repository == null)
                {
                    throw new AzureDevOpsException("Could not read repository.");
                }

                var targetBranchName = settings.TargetRefName;
                if (targetBranchName == null)
                {
                    targetBranchName = repository.DefaultBranch;
                }

                var refs =
                    gitClient
                    .GetRefsAsync(
                        repositoryDescription.ProjectName,
                        repositoryDescription.RepositoryName,
                        filter: targetBranchName.Replace("refs/", string.Empty))
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();

                if (refs == null)
                {
                    throw new AzureDevOpsBranchNotFoundException(targetBranchName);
                }

                var targetBranch = refs.SingleOrDefault();

                if (targetBranch == null)
                {
                    throw new AzureDevOpsBranchNotFoundException(targetBranchName);
                }

                var pullRequest = new GitPullRequest()
                {
                    SourceRefName = settings.SourceRefName,
                    TargetRefName = targetBranch.Name,
                    Title         = settings.Title,
                    Description   = settings.Description,
                };

                var createdPullRequest =
                    gitClient
                    .CreatePullRequestAsync(
                        pullRequest,
                        repositoryDescription.ProjectName,
                        repositoryDescription.RepositoryName)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();

                var pullRequestReadSettings =
                    new AzureDevOpsPullRequestSettings(
                        settings.RepositoryUrl,
                        createdPullRequest.PullRequestId,
                        settings.Credentials);

                return(new AzureDevOpsPullRequest(log, pullRequestReadSettings, gitClientFactory));
            }
        }
        public void RepositoryTypeSet()
        {
            IRepositoryDescription desc = new RepositoryDescription<ITestOne>();

            Assert.AreEqual(typeof(ITestOne), desc.RepositoryType, "The RepositoryType property was not set.");
        }
        /// <inheritdoc />
        public IObjectRepository Clone(IObjectRepositoryContainer container, string repository, RepositoryDescription repositoryDescription, ObjectId commitId = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }
            if (repositoryDescription == null)
            {
                throw new ArgumentNullException(nameof(repositoryDescription));
            }

            Repository.Init(repositoryDescription.Path);
            return(_repositoryProvider.Execute(repositoryDescription, r =>
            {
                Clone(repository, r, commitId);
                return LoadFrom(container, repositoryDescription, r, commitId);
            }));
        }
 /// <inheritdoc />
 public TRepository LoadFrom <TRepository>(IObjectRepositoryContainer <TRepository> container, RepositoryDescription repositoryDescription, ObjectId commitId = null)
     where TRepository : class, IObjectRepository
 {
     return((TRepository)LoadFrom((IObjectRepositoryContainer)container, repositoryDescription, commitId));
 }