Ejemplo n.º 1
0
        public static bool ValidateGitHashes(string path, string oldest, string newest)
        {
            using (var repo = new Repository(path))
            {
                Commit oldestCommit = repo.Lookup <Commit> (oldest);
                if (oldestCommit == null)
                {
                    Console.Error.WriteLine($"Unable to find starting hash {oldest} in repo.");
                    return(false);
                }
                Commit newestCommit = repo.Lookup <Commit> (newest);
                if (newestCommit == null)
                {
                    Console.Error.WriteLine($"Unable to find ending hash {newest} in repo.");
                    return(false);
                }

                var filter = new CommitFilter
                {
                    ExcludeReachableFrom = oldest,
                    IncludeReachableFrom = newest
                };

                if (!repo.Commits.QueryBy(filter).Any())
                {
                    Console.Error.WriteLine($"Unable to find any commit in range {oldest} to {newest}. Is the order reversed?");
                    return(false);
                }

                return(true);
            }
        }
Ejemplo n.º 2
0
        public Task <IEnumerable <Commit> > GetLatestCommitsBetweenTagsAsync(string startingTagName, string endingTagName, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(startingTagName))
            {
                throw new ArgumentNullException(nameof(startingTagName));
            }

            if (string.IsNullOrEmpty(endingTagName))
            {
                throw new ArgumentNullException(nameof(endingTagName));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var startingCommitsWithTags = GetCommitsWithTags(startingTagName);
            var endingCommitsWithTags   = GetCommitsWithTags(endingTagName);
            var startingCommit          = startingCommitsWithTags
                                          .LastOrDefault();
            var endingCommit = endingCommitsWithTags
                               .LastOrDefault();

            var filter = new CommitFilter
            {
                ExcludeReachableFrom = startingCommit,
                IncludeReachableFrom = endingCommit,
                SortBy = CommitSortStrategies.Reverse
            };

            return(Task.FromResult(
                       (IEnumerable <Commit>)_repository.Commits.QueryBy(filter)));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Returns the list of SQL scripts for packaging.
        /// </summary>
        /// <param name="settings">Settings.</param>
        /// <returns>The list of files.</returns>
        public virtual List <string> GetFiles(SqlServerPackagerSettings settings)
        {
            if (string.IsNullOrWhiteSpace(settings.Tag) && string.IsNullOrWhiteSpace(settings.Commit))
            {
                throw new InvalidOperationException("You should provide Tag or Commit to load changes from Git");
            }

            using (var git = new Repository(settings.ScriptsFolder))
            {
                var files      = new List <string>();
                var lastCommit = FindCommit(git, settings);
                if (string.IsNullOrWhiteSpace(lastCommit))
                {
                    throw new InvalidOperationException("Tag and Commit are not found");
                }

                Logger.Log($"Processing changes till {lastCommit}");
                var filter = new CommitFilter {
                    ExcludeReachableFrom = lastCommit
                };
                var commits = git.Commits.QueryBy(filter).ToArray();
                if (commits.Length == 0)
                {
                    return(files);
                }
                else if (commits.Length == 1)
                {
                    var newCommit = commits.First();
                    var changes   = git.Diff.Compare <TreeChanges>(newCommit.Parents.First().Tree, newCommit.Tree);
                    files.AddRange(ProcessTreeChanges(changes, settings));
                }
                else
                {
                    var newCommit = commits[0];
                    for (int i = 1; i < commits.Length; i++)
                    {
                        var oldCommit = commits[i];
                        if (settings.ExcludedChagesets.Contains(oldCommit.Sha))
                        {
                            // Skip the change completely
                            i++;
                            if (i == commits.Length)
                            {
                                // It was the last commit which we're going to skip.
                                break;
                            }

                            newCommit = commits[i];
                            continue;
                        }

                        var changes = git.Diff.Compare <TreeChanges>(oldCommit.Tree, newCommit.Tree);
                        files.AddRange(ProcessTreeChanges(changes, settings));
                        newCommit = oldCommit;
                    }
                }

                return(files.Distinct().ToList());
            }
        }
Ejemplo n.º 4
0
        public Task <IReadOnlyCollection <string> > GetNewCommitMessages(string baseBranchName, string headBranchName)
        {
            return(Task.Run(() =>
            {
                if (!BranchExists(baseBranchName))
                {
                    throw new NuKeeperException(
                        $"Git Cannot compare branches: the branch named '{baseBranchName}' doesn't exist");
                }
                if (!BranchExists(headBranchName))
                {
                    throw new NuKeeperException(
                        $"Git Cannot compare branches: the branch named '{headBranchName}' doesn't exist");
                }

                using (var repo = MakeRepo())
                {
                    var baseBranch = repo.Branches[baseBranchName];
                    var headBranch = repo.Branches[headBranchName];

                    var filter = new CommitFilter
                    {
                        SortBy = CommitSortStrategies.Time,
                        ExcludeReachableFrom = baseBranch,
                        IncludeReachableFrom = headBranch
                    };
                    return (IReadOnlyCollection <string>)repo.Commits.QueryBy(filter).Select(c => c.MessageShort.TrimEnd(new[] { '\r', '\n' })).ToList().AsReadOnly();
                }
            }));
        }
Ejemplo n.º 5
0
        public Task <IReadOnlyList <CommitMessage> > GetMessagesForUniqueCommits(
            IRepository repo,
            string baseBranch,
            string compareBranch,
            int maxCommits)
        {
            return(Task.Factory.StartNew(() =>
            {
                var baseCommit = repo.Lookup <Commit>(baseBranch);
                var compareCommit = repo.Lookup <Commit>(compareBranch);
                if (baseCommit == null || compareCommit == null)
                {
                    var missingBranch = baseCommit == null ? baseBranch : compareBranch;
                    throw new NotFoundException(missingBranch);
                }

                var mergeCommit = repo.ObjectDatabase.FindMergeBase(baseCommit, compareCommit);
                var commitFilter = new CommitFilter
                {
                    IncludeReachableFrom = baseCommit,
                    ExcludeReachableFrom = mergeCommit,
                };

                var commits = repo.Commits
                              .QueryBy(commitFilter)
                              .Take(maxCommits)
                              .Select(c => new CommitMessage(c.Message))
                              .ToList();

                return (IReadOnlyList <CommitMessage>)commits;
            }));
        }
Ejemplo n.º 6
0
        public void CanRetrieveChildrenOfASpecificCommit()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";

                var filter = new CommitFilter
                {
                    /* Revwalk from all the refs (git log --all) ... */
                    IncludeReachableFrom = repo.Refs,

                    /* ... and stop when the parent is reached */
                    ExcludeReachableFrom = parentSha
                };

                var commits = repo.Commits.QueryBy(filter);

                var children = from c in commits
                               from p in c.Parents
                               let pId = p.Id
                                         where pId.Sha == parentSha
                                         select c;

                var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
                                               "4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };

                Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
            }
        }
Ejemplo n.º 7
0
        private static List <CommitItem> GetCommitsForDate(Repository repository, DateTimeOffset since)
        {
            var filter    = new CommitFilter();
            var commitLog = repository.Commits.QueryBy(filter);
            var commits   = commitLog
                            .Where(c => c.Committer.When.Date == since)
                            .Select(x => new CommitItem
            {
                Message = x.Message,
                Date    = x.Committer.When,
                Author  = x.Committer.Name
            }).ToList();

            if (repository.Submodules.Any())
            {
                Console.WriteLine($"Lookup submodules ({repository.Submodules.Count()})...");
            }

            foreach (var sub in repository.Submodules)
            {
                using (var subRep = new Repository(sub.Path))
                {
                    Console.WriteLine($"Submodule {sub.Name} opened");
                    commits.AddRange(GetCommitsForDate(subRep, since));
                }
            }
            return(commits);
        }
Ejemplo n.º 8
0
 public string ObterVersao(CommitFilter filter = null)
 {
     if (filter == null)
     {
         filter = new CommitFilter {
             IncludeReachableFrom = _branch.CanonicalName
         }
     }
     ;
     try
     {
         var lastCommit = _repositorio.Commits.QueryBy(_arquivoVersao, filter).First();
         var blob       = lastCommit.Commit[_arquivoVersao].Target as Blob;
         if (blob == null)
         {
             return("");
         }
         using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
         {
             var parser = new FileIniDataParser();
             var data   = parser.ReadData(content);
             return($"{data["versaoinfo"]["MajorVersion"]}.{data["versaoinfo"]["MinorVersion"]}.{data["versaoinfo"]["Release"]}");
         }
     }
     catch (Exception)
     {
         return("");
     }
 }
Ejemplo n.º 9
0
 private void CarregarDependencias()
 {
     try
     {
         var filter = new CommitFilter {
             IncludeReachableFrom = _branch.CanonicalName
         };
         var lastCommit = _repositorio.Commits.QueryBy(_arquivoManifesto, filter).First();
         var blob       = lastCommit.Commit[_arquivoManifesto].Target as Blob;
         if (blob == null)
         {
             return;
         }
         using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
         {
             var manifestoJson = JObject.Parse(content.ReadToEnd());
             var d             = manifestoJson["dependencias"];
             if (d == null)
             {
                 return;
             }
             foreach (var dependencia in d.Children())
             {
                 var projeto = dependencia.Path.Substring(dependencia.Path.LastIndexOf('.') + 1);
                 var versao  = dependencia.Values <string>().First();
                 Dependencias.Add(new Dependencia(projeto, versao, this));
             }
         }
     }
     catch {
     }
 }
Ejemplo n.º 10
0
        public Data.Commit[] ExtractCommitsFromBranch(string branchName = "master")
        {
            Ensure.ArgumentNotNullOrEmptyString(branchName, nameof(branchName));

            var branch = _gitRepo.Branches[branchName];

            if (branch == null)
            {
                throw new Exception($"No branch with name {branchName}");
            }

            var filter = new CommitFilter
            {
                SortBy = CommitSortStrategies.Topological
                         | CommitSortStrategies.Time
                         | CommitSortStrategies.Reverse,
                IncludeReachableFrom = branch
            };

            _logger.LogInformation("{datetime}: getting commits from git.", DateTime.Now);

            var commits = _gitRepo.Commits.QueryBy(filter).ToArray();

            return(Mapper.Map <Data.Commit[]>(commits));
        }
Ejemplo n.º 11
0
        public static ICollection <GitCommit> GitLog(
            this ICakeContext context,
            DirectoryPath repositoryDirectoryPath,
            CommitFilter filter
            )
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

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

            return(context.UseRepository(
                       repositoryDirectoryPath,
                       repository => repository.Commits
                       .QueryBy(filter)
                       .Select(commit => new GitCommit(commit))
                       .ToList()
                       ));
        }
Ejemplo n.º 12
0
        public void Execute()
        {
            var success = false;

            try
            {
                // Find out which refs lead to at least one the commits
                var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList();

                var filter = new CommitFilter
                {
                    Since  = refsToRewrite,
                    SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological
                };

                var commits = repo.Commits.QueryBy(filter);
                foreach (var commit in commits)
                {
                    RewriteCommit(commit);
                }

                // Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten
                // before A.
                foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth))
                {
                    // TODO: Check how rewriting of notes actually behaves

                    RewriteReference(reference);
                }

                success = true;
                if (options.OnSucceeding != null)
                {
                    options.OnSucceeding();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (!success && options.OnError != null)
                    {
                        options.OnError(ex);
                    }
                }
                finally
                {
                    foreach (var action in rollbackActions)
                    {
                        action();
                    }
                }

                throw;
            }
            finally
            {
                rollbackActions.Clear();
            }
        }
Ejemplo n.º 13
0
        private IEnumerable <Commit> FetchCommits(int count)
        {
            if (this.repo == null)
            {
                return(new List <Commit>());
            }

            if (this.targetPath.Length == 0)
            {
                return(this.branches[this.currentBranchIndex].Commits.Where(c => CommitHasOneParent(c)).Take(count));
            }
            else
            {
                string relPath  = this.targetPath;
                var    segments = relPath.Split(PathSeparators, StringSplitOptions.RemoveEmptyEntries);
                // Without the filter libgit2sharp/FileHistory will throw KeyNotFoundException
                // on certain history e.g. containing merges.
                var filter = new CommitFilter()
                {
                    SortBy = CommitSortStrategies.Topological,
                    //FirstParentOnly = true,
                };

                return(this.branches[this.currentBranchIndex].Commits.Where(c => CommitHasOneParent(c) && CommitTouchedPath(c, segments)).Take(count));
            }
        }
Ejemplo n.º 14
0
        public static IEnumerable <CommitInfo> ParseHashRange(string path, SearchOptions options, string oldest, string newest)
        {
            var filter = new CommitFilter {
                ExcludeReachableFrom = oldest, IncludeReachableFrom = newest
            };

            return(ParseWithFilter(path, options, filter));
        }
Ejemplo n.º 15
0
        public static IEnumerable <CommitInfo> ParseSpecificRange(string path, string oldest, string newest)
        {
            var filter = new CommitFilter {
                ExcludeReachableFrom = oldest, IncludeReachableFrom = newest
            };

            return(ParseWithFilter(path, filter));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Finds the latest pushed commit of a file and returns the sha of that commit. Returns null when no commits have
        /// been found in any remote branches or the current local branch.
        /// </summary>
        /// <param name="path">The local path of a repository or a file inside a repository. This cannot be null.</param>
        /// <param name="remote">The remote name to look for</param>
        /// <returns></returns>
        public Task <string> GetLatestPushedSha(string path, string remote = "origin")
        {
            Guard.ArgumentNotNull(path, nameof(path));

            return(Task.Run(() =>
            {
                using (var repo = GetRepository(path))
                {
                    if (repo != null)
                    {
                        // This is the common case where HEAD is tracking a remote branch
                        var commonAncestor = repo.Head.TrackingDetails.CommonAncestor;
                        if (commonAncestor != null)
                        {
                            return commonAncestor.Sha;
                        }

                        // This is the common case where a branch was forked from a local branch.
                        // Use CommonAncestor because we don't want to search for a commit that only exists
                        // locally or that has been added to the remote tracking branch since the fork.
                        var commonAncestorShas = repo.Branches
                                                 .Where(b => b.IsTracking)
                                                 .Select(b => b.TrackingDetails.CommonAncestor?.Sha)
                                                 .Where(s => s != null)
                                                 .ToArray();

                        var sortByTopological = new CommitFilter {
                            SortBy = CommitSortStrategies.Topological
                        };
                        foreach (var commit in repo.Commits.QueryBy(sortByTopological))
                        {
                            if (commonAncestorShas.Contains(commit.Sha))
                            {
                                return commit.Sha;
                            }
                        }

                        // This is a less common case where a branch was forked from a branch
                        // which has since had new commits added to it.
                        var nearestCommonAncestor = repo.Branches
                                                    .Where(b => b.IsRemote)
                                                    .Select(b => b.Tip)
                                                    .Distinct()
                                                    .Select(c => repo.ObjectDatabase.CalculateHistoryDivergence(c, repo.Head.Tip))
                                                    .Where(hd => hd.AheadBy != null)
                                                    .OrderBy(hd => hd.BehindBy)
                                                    .Select(hd => hd.CommonAncestor)
                                                    .FirstOrDefault();
                        if (nearestCommonAncestor != null)
                        {
                            return nearestCommonAncestor.Sha;
                        }
                    }

                    return null;
                }
            }));
        }
Ejemplo n.º 17
0
        public static IEnumerable <CommitInfo> Parse(string path, SearchRange range)
        {
            var filter = new CommitFilter();

            range.Oldest.MatchSome(v => filter.ExcludeReachableFrom = v + (range.IncludeOldest ? "~" : ""));
            range.Newest.MatchSome(v => filter.IncludeReachableFrom = v);

            return(ParseWithFilter(path, filter));
        }
    private IEnumerable <ICommit> GetCommitsReacheableFrom(IGitObject commit, IBranch branch)
    {
        var filter = new CommitFilter {
            IncludeReachableFrom = branch
        };
        var commitCollection = this.repository.Commits.QueryBy(filter);

        return(commitCollection.Where(c => c.Sha == commit.Sha));
    }
Ejemplo n.º 19
0
 private static ICommitLog GetNewCommitsFrom(Repository repo, string branch)
 {
     var filter = new CommitFilter
     {
         IncludeReachableFrom = repo.Branches[string.Format("origin/{0}", branch)],
         ExcludeReachableFrom = repo.Branches["origin/master"]
     };
     var commits = repo.Commits.QueryBy(filter);
     return commits;
 }
Ejemplo n.º 20
0
        /// <inheritdoc />
        protected override string[] GetCommitMessages()
        {
            var repositoryPath = Repository.Discover(this.SourcePath) ?? throw new InvalidOperationException($"Could not find repository for '{this.SourcePath}'");
            var commonPath     = GetVersion.GetCommonPath(repositoryPath,
                                                          this.SourcePath) ?? throw new InvalidOperationException($"'{this.SourcePath}' has no common path with '{repositoryPath}'");

            string relativePath;

            try
            {
                relativePath = this.SourcePath.Substring(commonPath.Length);
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Could not get {nameof(relativePath)}",
                                                    exception);
            }

            if (!string.IsNullOrEmpty(relativePath))
            {
                relativePath = relativePath.Replace("\\",
                                                    "/");
            }

            string[] result;
            using (var repository = new Repository(repositoryPath))
            {
                // Unfortunately, CommitSortStrategies.Time | CommitSortStrategies.Reverse is not
                // supported, hence we are ordering the LINQ-way afterwards ... #smh
                var commitFilter = new CommitFilter
                {
                    IncludeReachableFrom = repository.Head,
                    ExcludeReachableFrom = this.BaseRevision,
                    SortBy = CommitSortStrategies.Time
                };

                IEnumerable <Commit> commits;
                if (string.IsNullOrEmpty(relativePath))
                {
                    commits = repository.Commits.QueryBy(commitFilter);
                }
                else
                {
                    commits = repository.Commits.QueryBy(relativePath,
                                                         commitFilter)
                              .Select(arg => arg.Commit);
                }

                result = commits.OrderBy(arg => arg.Author.When)
                         .Select(arg => arg.Message)
                         .ToArray();
            }

            return(result);
        }
Ejemplo n.º 21
0
 public GitClient(string path)
 {
     RootPathToRepository = Repository
                            .Discover(path)
                            .Replace(".git/", string.Empty);
     this.repository   = new Repository(RootPathToRepository);
     this.commitFilter = new CommitFilter
     {
         FirstParentOnly = true
     };
 }
Ejemplo n.º 22
0
        private static IEnumerable <Commit> GetReachableCommits(IRepository repo)
        {
            var filter = new CommitFilter
            {
                FirstParentOnly      = true,
                IncludeReachableFrom = repo.Head,
                SortBy = CommitSortStrategies.Reverse
            };

            return(repo.Commits.QueryBy(filter).Reverse());
        }
        private ICommitLog GetPullRequestCommits(PullRequestDto pullRequestDto)
        {
            var filter = new CommitFilter
            {
                Since           = pullRequestDto.MergeCommitSha,
                Until           = pullRequestDto.BaseCommitSha,
                FirstParentOnly = true
            };

            return(_programArgs.LocalGitRepository.Commits.QueryBy(filter));
        }
Ejemplo n.º 24
0
        private IEnumerable <Commit> GetReachableCommits()
        {
            var filter = new CommitFilter
            {
                FirstParentOnly      = true,
                IncludeReachableFrom = _repo.Head,
                SortBy = CommitSortStrategies.Topological
            };

            return(_repo.Commits.QueryBy(filter));
        }
        private static int CountCommitsSinceVersionTag(Repository repository, Commit lastTaggedCommit)
        {
            var query = new CommitFilter
            {
                Since  = repository.Head.Tip,
                Until  = lastTaggedCommit,
                SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time
            };

            return(repository.Commits.QueryBy(query).Count());
        }
Ejemplo n.º 26
0
        private Commit GetRootCommit(Commit commit)
        {
            var filter = new CommitFilter
            {
                IncludeReachableFrom = commit,
                SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Time
            };

            return(this.Repository.Commits.QueryBy(filter)
                   .Where(c => !c.Parents.Any()).FirstOrDefault());
        }
Ejemplo n.º 27
0
        public static List <GitCommit> GetCommitBetweenTags(ChangelogSettings settings, string versionName, string from, string to)
        {
            using (var repo = new Repository(settings.GitRepoLocation))
            {
                object fromTag = null;
                object toTag   = null;

                if (string.IsNullOrEmpty(from))
                {
                    fromTag = repo.Branches[settings.LatestCodeBranch];
                }
                else
                {
                    fromTag = repo.Tags[from];
                }

                if (string.IsNullOrEmpty(to))
                {
                    toTag = repo.Branches[settings.LatestCodeBranch];
                }
                else
                {
                    toTag = repo.Tags[to];
                }

                if (fromTag == null || toTag == null)
                {
                    throw new Exception($"Failed to find tags - from: {fromTag}  to: {toTag}");
                }

                CommitFilter filter = null;

                if (string.IsNullOrEmpty(from))
                {
                    filter = new CommitFilter
                    {
                        IncludeReachableFrom = toTag
                    };
                }
                else
                {
                    filter = new CommitFilter
                    {
                        ExcludeReachableFrom = fromTag,
                        IncludeReachableFrom = toTag
                    };
                }

                var commits = repo.Commits.QueryBy(filter);

                return(commits.Select(c => GitCommit.Create(versionName, c)).ToList());
            }
        }
Ejemplo n.º 28
0
        public static List <Commit> GetCommitsReacheableFromHead(this IRepository repository, Commit headCommit)
        {
            var filter = new CommitFilter
            {
                IncludeReachableFrom = headCommit,
                SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Reverse
            };

            var commitCache = repository.Commits.QueryBy(filter).ToList();

            return(commitCache);
        }
Ejemplo n.º 29
0
        public static bool GetMatchingCommitBranch(this IRepository repository, Commit baseVersionSource, Branch branch, Commit firstMatchingCommit)
        {
            var filter = new CommitFilter
            {
                IncludeReachableFrom = branch,
                ExcludeReachableFrom = baseVersionSource,
                FirstParentOnly      = true,
            };
            var query = repository.Commits.QueryBy(filter);

            return(query.Contains(firstMatchingCommit));
        }
Ejemplo n.º 30
0
        private int countCommitsBetween(object tag, object now, bool firstParentOnly = false)
        {
            var filter = new CommitFilter()
            {
                SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Time,
                ExcludeReachableFrom = tag,
                IncludeReachableFrom = now,
                FirstParentOnly      = firstParentOnly
            };

            return(repo.Commits.QueryBy(filter).Count());
        }
Ejemplo n.º 31
0
        public void Execute()
        {
            // Find out which refs lead to at least one the commits
            var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList();

            var filter = new CommitFilter
                             {
                                 Since = refsToRewrite,
                                 SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological
                             };

            var commits = repo.Commits.QueryBy(filter);
            foreach (var commit in commits)
            {
                RewriteCommit(commit);
            }

            var rollbackActions = new Queue<Action>();

            try
            {
                // Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten
                // before A.
                foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth))
                {
                    // TODO: Check how rewriting of notes actually behaves

                    var dref = reference as DirectReference;
                    if (dref == null)
                    {
                        // TODO: Handle a cornercase where a symbolic reference
                        //       points to a Tag which name has been rewritten
                        continue;
                    }

                    var newTarget = RewriteTarget(dref.Target);

                    RewriteReference(dref, newTarget, backupRefsNamespace, rollbackActions);
                }
            }
            catch (Exception)
            {
                foreach (var action in rollbackActions)
                {
                    action();
                }

                throw;
            }
        }
Ejemplo n.º 32
0
        public void CanTellComplexCommitHistory()
        {
            var repoPath = CreateEmptyRepository();
            const string path1 = "Test1.txt";
            const string path2 = "Test2.txt";

            using (var repo = new Repository(repoPath))
            {
                // Make initial changes.
                var commit1 = MakeAndCommitChange(repo, repoPath, path1, "Hello World");
                MakeAndCommitChange(repo, repoPath, path2, "Second file's contents");
                var commit2 = MakeAndCommitChange(repo, repoPath, path1, "Hello World again");

                // Move the first file to a new directory.
                var newPath1 = Path.Combine(SubFolderPath1, path1);
                Commands.Move(repo, path1, newPath1);
                var commit3 = repo.Commit("Moved " + path1 + " to " + newPath1,
                    Constants.Signature, Constants.Signature);

                // Make further changes.
                MakeAndCommitChange(repo, repoPath, path2, "Changed second file's contents");
                var commit4 = MakeAndCommitChange(repo, repoPath, newPath1, "I have done it again!");

                // Perform tests.
                var commitFilter = new CommitFilter () { SortBy = CommitSortStrategies.Topological };
                var fileHistoryEntries = repo.Commits.QueryBy(newPath1, commitFilter).ToList();
                var changedBlobs = fileHistoryEntries.Blobs().Distinct().ToList();

                Assert.Equal(4, fileHistoryEntries.Count());
                Assert.Equal(3, changedBlobs.Count());

                Assert.Equal(2, fileHistoryEntries.Count(e => e.Path == newPath1));
                Assert.Equal(2, fileHistoryEntries.Count(e => e.Path == path1));

                Assert.Equal(commit4, fileHistoryEntries[0].Commit);
                Assert.Equal(commit3, fileHistoryEntries[1].Commit);
                Assert.Equal(commit2, fileHistoryEntries[2].Commit);
                Assert.Equal(commit1, fileHistoryEntries[3].Commit);

                Assert.Equal(commit4.Tree[newPath1].Target, changedBlobs[0]);
                Assert.Equal(commit2.Tree[path1].Target, changedBlobs[1]);
                Assert.Equal(commit1.Tree[path1].Target, changedBlobs[2]);
            }
        }
        public IList<Commit> GetHistory(Repository repository, Branch branch, string relativePath, object since, object until, int maxCount, GitHistoryOptions options = GitHistoryOptions.None)
        {
            List<Commit> list = new List<Commit>();
            //bool flag1 = (options & GitHistoryOptions.IncludeChanges) != GitHistoryOptions.None;
            string str = relativePath;
            bool hasRelativePath = !string.IsNullOrEmpty(str);
            bool excludeUnnecessaryCommits = hasRelativePath && (options & GitHistoryOptions.ExcludeUnnecessaryCommits) != GitHistoryOptions.None;
            HashSet<ObjectId> necessaryObjectIds = new HashSet<ObjectId>();
            if (since == null)
            {
                if (branch != null && branch.Tip != null)
                    since = (object)branch.Tip.Id.Sha;
                if (since == null)
                    since = (object)repository.Head;
            }
            CommitSortStrategies commitSortStrategies = CommitSortStrategies.Time;
            if ((options & GitHistoryOptions.TopologicalTimeSort) != GitHistoryOptions.None)
                commitSortStrategies |= CommitSortStrategies.Topological;
            CommitFilter filter = new CommitFilter()
            {
                Since = since,
                Until = until,
                SortBy = commitSortStrategies
            };
            foreach (Commit commit in (IEnumerable<Commit>)repository.Commits.QueryBy(filter))
            {
                string renameSourcePath = (string)null;
                ChangeKind? changeKind = new ChangeKind?();
                if (hasRelativePath)
                {
                    if (excludeUnnecessaryCommits && necessaryObjectIds.Count == 0)
                    {
                        TreeEntry treeEntry = commit.Tree[relativePath];
                        if (treeEntry != (TreeEntry)null)
                            necessaryObjectIds.Add(treeEntry.Target.Id);
                    }
                    changeKind = this.CommitContainsFile(repository, commit, str, options, necessaryObjectIds, out renameSourcePath);
                    if (!changeKind.HasValue || changeKind.Value == ChangeKind.Unmodified)
                    {
                        //trace "GitRepository.GetHistory Skipping commit {0} because it doesn't contain the file", commit.Id != (ObjectId)null ? (object)GitId.GetShortId(commit.Id.Sha) : (object)(string)null);
                        continue;
                    }
                }

                //trace "GitRepository.GetHistory Adding commit {0}", commit.Id != (ObjectId)null ? (object)GitId.GetShortId(commit.Id.Sha) : (object)(string)null);
                list.Add(commit);
                if (hasRelativePath && excludeUnnecessaryCommits && (changeKind.HasValue && changeKind.Value == ChangeKind.Added) && string.IsNullOrEmpty(renameSourcePath))
                {
                    //trace "GitRepository.GetHistory Breaking after finding changeKind={0}", changeKind.HasValue ? (object)changeKind.Value.ToString() : (object)"null");
                    break;
                }
                if (list.Count >= maxCount)
                {
                    //trace "GitRepository.GetHistory Breaking after reaching the commit maxCount={0}", (object)maxCount);
                    break;
                }
                if (!string.IsNullOrEmpty(renameSourcePath))
                    str = renameSourcePath;
            }
            //trace "GitRepository.GetHistory Found {0} commits", (object)list.Count);
            return (IList<Commit>)list.AsReadOnly();
        }
Ejemplo n.º 34
0
        public void CanRetrieveChildrenOfASpecificCommit()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";

                var filter = new CommitFilter
                                 {
                                     /* Revwalk from all the refs (git log --all) ... */
                                     Since = repo.Refs,

                                     /* ... and stop when the parent is reached */
                                     Until = parentSha
                                 };

                var commits = repo.Commits.QueryBy(filter);

                var children = from c in commits
                            from p in c.Parents
                            let pId = p.Id
                            where pId.Sha == parentSha
                            select c;

                var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
                                                "4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };

                Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
            }
        }