/// <summary>
        /// Gives the complete repository status
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="repository">The name of repository</param>
        /// <returns>The repository status</returns>
        public RepoStatus RepositoryStatus(string org, string repository)
        {
            RepoStatus repoStatus = new RepoStatus();

            repoStatus.ContentStatus = new List <RepositoryContent>();
            string localServiceRepoFolder = _settings.GetServicePath(org, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext));

            using (var repo = new LibGit2Sharp.Repository(localServiceRepoFolder))
            {
                RepositoryStatus status = repo.RetrieveStatus(new LibGit2Sharp.StatusOptions());
                foreach (StatusEntry item in status)
                {
                    RepositoryContent content = new RepositoryContent();
                    content.FilePath   = item.FilePath;
                    content.FileStatus = (Altinn.Studio.Designer.Enums.FileStatus)(int) item.State;
                    if (content.FileStatus == Enums.FileStatus.Conflicted)
                    {
                        repoStatus.RepositoryStatus = Enums.RepositoryStatus.MergeConflict;
                        repoStatus.HasMergeConflict = true;
                    }

                    repoStatus.ContentStatus.Add(content);
                }

                LibGit2Sharp.Branch branch = repo.Branches.FirstOrDefault(b => b.IsTracking == true);
                if (branch != null)
                {
                    repoStatus.AheadBy  = branch.TrackingDetails.AheadBy;
                    repoStatus.BehindBy = branch.TrackingDetails.BehindBy;
                }
            }

            return(repoStatus);
        }
        public void Pull(Octokit.Repository rep)
        {
            string reppath = Path.Combine(_account.TempRepPath, rep.Name);

            if (!Repository.IsValid(reppath))
            {
                Repository.Clone(rep.CloneUrl, reppath);
                using (var repo = new Repository(reppath))
                {
                    var upstream = repo.Network.Remotes.Add("upstream", rep.Parent.CloneUrl);
                    Commands.Fetch(repo, "upstream", new List <string>()
                    {
                    }, new FetchOptions(), null);
                    Branch upstreamMaster = repo.Branches["upstream/master"];
                    Branch localMaster    = repo.Branches["master"];
                    repo.Branches.Update(localMaster, b => b.TrackedBranch = upstreamMaster.CanonicalName);
                    var sign = new LibGit2Sharp.Signature(_account.UserName, _account.Email, new DateTimeOffset(DateTime.Now));
                    Commands.Pull(repo, sign, new PullOptions());
                }
            }
            else
            {
                using (var repo = new Repository(reppath))
                {
                    var branchMaster = repo.Branches["master"];

                    Commands.Checkout(repo, branchMaster);
                    var sign = new LibGit2Sharp.Signature(_account.UserName, _account.Email, new DateTimeOffset(DateTime.Now));
                    Commands.Pull(repo, sign, new PullOptions());
                }
            }
        }
        public void CreateChangesBranch(string changesBranch)
        {
            // need to make sure that the changes branch name is unique both locally and remote
            // if branch name is taken we'll try branchname-2, branchname-3 etc
            var    branchName = changesBranch;
            Branch localBranch;
            Branch trackedBranch;

            var i = 0;

            do
            {
                i++;
                branchName    = $"{changesBranch}{(i == 1 ? string.Empty : "-" + i)}";
                localBranch   = _repository.Branches[branchName];
                trackedBranch = _repository.Branches[$"origin/{branchName}"];
            }while (localBranch != null || trackedBranch != null);

            if (i != 1)
            {
                Console.WriteLine($"Branch name {changesBranch} was in use, checked out {changesBranch}-{i} instead.");
            }

            localBranch = _repository.CreateBranch(branchName);
            _repository.Branches.Update(localBranch, b => b.UpstreamBranch = $"refs/heads/{branchName}");

            Commands.Checkout(_repository, _repository.Branches[branchName]);
            _changesBranch = localBranch;
        }
        public void PullAndRebaseAndPush(PullRequest pr)
        {
            string reppath = Path.Combine(_account.TempRepPath, pr.Base.Repository.Name);

            using (var repo = new Repository(reppath))
            {
                var branchMaster  = repo.Branches["master"];
                var masterCommits = branchMaster.Commits.First();
                var orgin         = repo.Network.Remotes["orgin"];

                var branchname = pr.Head.Ref;
                repo.Branches.Remove(branchname);

                Branch orginBranch = repo.Branches[$"refs/remotes/origin/{branchname}"];

                Branch localBranch = repo.CreateBranch(branchname, orginBranch.Tip);
                localBranch = Commands.Checkout(repo, localBranch);

                if (!localBranch.Commits.Contains(masterCommits))
                {
                    Console.WriteLine(branchname);
                    var rebaseOptions = new RebaseOptions();
                    var rb            = repo.Rebase.Start(localBranch, branchMaster, null, _identity, rebaseOptions);
                    if (rb.Status != RebaseStatus.Complete)
                    {
                        repo.Rebase.Abort();
                        return;
                    }
                    Commands.Checkout(repo, branchname);
                    repo.Network.Push(orgin, $"+refs/heads/{branchname}:refs/heads/{branchname}", _pushOptions);
                }
            }
        }
Esempio n. 5
0
        public List <Branch> GetBranches(string repositoryPath)
        {
            List <Branch> branches = new List <Branch>();

            using (GitRepository gitRepositoryInfo = new GitRepository(repositoryPath))
            {
                GitBranch headBranch = null;
                gitRepositoryInfo.Branches.ForEach(branch =>
                {
                    if (branch.IsRemote)
                    {
                        return;
                    }
                    if (headBranch == null || headBranch.Commits.Count() < branch.Commits.Count())
                    {
                        headBranch = branch;
                    }
                });

                List <Commit> commits = GetCommits(headBranch, repositoryPath);

                gitRepositoryInfo.Branches.ForEach(branch =>
                {
                    if (branch.IsRemote)
                    {
                        return;
                    }
                    Branch branchInstance = new Branch()
                    {
                        Name = branch.FriendlyName
                    };

                    var uniqueCommits = branch.Commits.Where(c => commits.All(c1 => c1.Revision != c.Sha));
                    var enumerable    = uniqueCommits as IList <GitCommit> ?? uniqueCommits.ToList();
                    if (enumerable.Any())
                    {
                        enumerable.ForEach(uCommit =>
                        {
                            var newCommit = GetCommitFromGitCommit(uCommit, repositoryPath);
                            branchInstance.AddCommit(newCommit);
                        });
                    }

                    commits.ForEach(commit =>
                    {
                        if (branch.Commits.Any(c => c.Sha == commit.Revision))
                        {
                            branchInstance.AddCommit(commit);
                        }
                    });
                    branches.Add(branchInstance);
                });
            }
            return(branches);
        }
Esempio n. 6
0
        public List <Commit> GetCommits(GitBranch branch, string repositoryPath)
        {
            List <Commit> commits = new List <Commit>();

            foreach (GitCommit gitCommitInfo in branch.Commits)
            {
                Commit commit = GetCommitFromGitCommit(gitCommitInfo, repositoryPath);
                commits.Add(commit);
            }
            return(commits);
        }
        /// <summary>
        /// Gets the number of commits the local repository is behind the remote
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="repository">The name of the repository</param>
        /// <returns>The number of commits behind</returns>
        public int?CheckRemoteUpdates(string org, string repository)
        {
            using (var repo = new LibGit2Sharp.Repository(FindLocalRepoLocation(org, repository)))
            {
                LibGit2Sharp.Branch branch = repo.Branches["master"];
                if (branch == null)
                {
                    return(null);
                }

                return(branch.TrackingDetails.BehindBy);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Gives the complete repository status
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="repository">The name of repository</param>
        /// <returns>The repository status</returns>
        public RepoStatus RepositoryStatus(string org, string repository)
        {
            RepoStatus repoStatus = new RepoStatus();

            repoStatus.ContentStatus = new List <RepositoryContent>();
            string localServiceRepoFolder = _settings.GetServicePath(org, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext));

            using (var repo = new LibGit2Sharp.Repository(localServiceRepoFolder))
            {
                var watch = System.Diagnostics.Stopwatch.StartNew();
                RepositoryStatus status = repo.RetrieveStatus(new LibGit2Sharp.StatusOptions());
                watch.Stop();
                _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "retrieverepostatusentries - {0} ", watch.ElapsedMilliseconds);

                watch = System.Diagnostics.Stopwatch.StartNew();
                foreach (StatusEntry item in status)
                {
                    RepositoryContent content = new RepositoryContent();
                    content.FilePath   = item.FilePath;
                    content.FileStatus = (Altinn.Studio.Designer.Enums.FileStatus)(int) item.State;
                    if (content.FileStatus == Enums.FileStatus.Conflicted)
                    {
                        repoStatus.RepositoryStatus = Enums.RepositoryStatus.MergeConflict;
                        repoStatus.HasMergeConflict = true;
                    }

                    repoStatus.ContentStatus.Add(content);
                }

                watch.Stop();
                _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "parsestatusentries - {0}", watch.ElapsedMilliseconds);

                watch = System.Diagnostics.Stopwatch.StartNew();
                LibGit2Sharp.Branch branch = repo.Branches.FirstOrDefault(b => b.IsTracking == true);
                if (branch != null)
                {
                    repoStatus.AheadBy  = branch.TrackingDetails.AheadBy;
                    repoStatus.BehindBy = branch.TrackingDetails.BehindBy;
                }

                watch.Stop();
                _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "branch details - {0}", watch.ElapsedMilliseconds);
            }

            return(repoStatus);
        }
        public RepositoryProcessor(Uri repositoryUrl, UsernamePasswordCredentials credentials)
        {
            _repositoryUrl = repositoryUrl;
            _credentials   = credentials;

            Console.WriteLine($"Cloning {_repositoryUrl}");

            _clonePath = Path.Combine(".", _repositoryUrl.ToString().Split("/").Last(x => !string.IsNullOrWhiteSpace(x)));
            var repoPath = Repository.Clone(
                _repositoryUrl.ToString(),
                _clonePath,
                new CloneOptions {
                CredentialsProvider = (x, y, z) => _credentials
            });

            _repository = new Repository(repoPath);
            _baseBranch = _repository.Branches[_repository.Head.FriendlyName];
        }
Esempio n. 10
0
        public Branch Checkout(string branchName)
        {
            if (string.IsNullOrEmpty(branchName))
            {
                throw new ArgumentNullException(nameof(branchName));
            }


            var branch = _repository.Branches[branchName];

            if (branch == null)
            {
                return(null);
            }

            LibGit2Sharp.Branch currentBranch = Commands.Checkout(_repository, branch);
            return(new Branch(currentBranch.FriendlyName, currentBranch.IsRemote, currentBranch.IsCurrentRepositoryHead, currentBranch.Tip.Sha));
        }
        public void CheckoutBaseBranch(string branchName)
        {
            var localBranch = _repository.Branches[branchName];

            if (localBranch == null)
            {
                // Probably a remote branch
                Branch trackedBranch = _repository.Branches[$"origin/{branchName}"];

                if (trackedBranch == null)
                {
                    throw new Exception($"Branch {branchName} not found locally or on origin.");
                }

                localBranch = _repository.CreateBranch(branchName, trackedBranch.Tip);
                _repository.Branches.Update(localBranch, b => b.UpstreamBranch = $"refs/heads/{branchName}");
            }

            Commands.Checkout(_repository, _repository.Branches[branchName]);
            _baseBranch    = localBranch;
            _changesBranch = localBranch;
        }
Esempio n. 12
0
 /// <summary>
 /// Checkout the tip commit of the specified <see cref="Branch"/> object. If this commit is the
 /// current tip of the branch, will checkout the named branch. Otherwise, will checkout the tip commit
 /// as a detached HEAD.
 /// </summary>
 /// <param name="repository">The repository to act on</param>
 /// <param name="branch">The <see cref="Branch"/> to check out.</param>
 /// <returns>The <see cref="Branch"/> that was checked out.</returns>
 public static Branch Checkout(IRepository repository, Branch branch)
 {
     return(Checkout(repository, branch, new CheckoutOptions()));
 }
Esempio n. 13
0
 private void LogCheckout(string previousHeadName, Branch newHead)
 {
     LogCheckout(previousHeadName, newHead.Tip.Id, newHead.Name);
 }
Esempio n. 14
0
 /// <summary>
 ///   Determines whether the specified <see cref = "Branch" /> is equal to the current <see cref = "Branch" />.
 /// </summary>
 /// <param name = "other">The <see cref = "Branch" /> to compare with the current <see cref = "Branch" />.</param>
 /// <returns>True if the specified <see cref = "Branch" /> is equal to the current <see cref = "Branch" />; otherwise, false.</returns>
 public bool Equals(Branch other)
 {
     return(equalityHelper.Equals(this, other));
 }