1

我希望能够在 repo 中收集按提交日期排序的文件。

File       Committed
abc.bat    Dec 1 2013
bar.txt    Jan 1 2010
baz.cmd    Nov 8 2010
cru.zip    Feb 9 2012

如何使用 LibGit2Sharp 执行此操作,以便我可以按提交日期订购?

我需要这样做的原因是 LibGit2Sharp 不允许您这样做.Pull(),从而合并更改。如果是这种情况,我会System.IO.DirectoryInfo在 Windows 中按修改日期进行查询。似乎我们只有.Clone(),它不会在文件系统中维护这些日期。

4

1 回答 1

1

唔。没有什么开箱即用的东西可以满足这种需求。

但是,通过向后追溯修订历史并识别添加和修改,可以收集正在检查的提交中存在的每个文件的最新更改日期。

这个怎么样?

public void LetUsTryThis()
{
    using (var repo = new Repository(StandardTestRepoPath))
    {
        var referenceCommit = repo.Head.Tip;

        IEnumerable<KeyValuePair<string, DateTimeOffset>> res = LatestChanges(repo, referenceCommit);

        foreach (KeyValuePair<string, DateTimeOffset> kvp in res)
        {
            Console.WriteLine(string.Format("{0} - {1}", kvp.Key, kvp.Value));
        }
    }
}

private IEnumerable<KeyValuePair<string, DateTimeOffset>> LatestChanges(Repository repo, Commit referenceCommit)
{
    IDictionary<string, DateTimeOffset> dic = new Dictionary<string, DateTimeOffset>();

    var commitLog = repo.Commits.QueryBy(new CommitFilter { Since = referenceCommit })
                        .Concat(new[] { default(Commit) })
                        .Skip(1);

    var mostRecent = referenceCommit;

    foreach (Commit current in commitLog)
    {
        IEnumerable<KeyValuePair<string, DateTimeOffset>> res = ExtractAdditionsAndModifications(repo, mostRecent, current);
        AddLatest(dic, res);

        mostRecent = current;
    }

    return dic.OrderByDescending(kvp => kvp.Value);
}

private IEnumerable<KeyValuePair<string, DateTimeOffset>> ExtractAdditionsAndModifications(Repository repo, Commit next, Commit current)
{
    IDictionary<string, DateTimeOffset> dic = new Dictionary<string, DateTimeOffset>();

    var tc = repo.Diff.Compare(current == null ? null : current.Tree, next.Tree);

    foreach (TreeEntryChanges treeEntryChanges in tc.Added)
    {
        dic.Add(treeEntryChanges.Path, next.Committer.When);
    }

    foreach (TreeEntryChanges treeEntryChanges in tc.Modified)
    {
        dic.Add(treeEntryChanges.Path, next.Committer.When);
    }

    return dic;
}

private void AddLatest(IDictionary<string, DateTimeOffset> main, IEnumerable<KeyValuePair<string, DateTimeOffset>> latest)
{
    foreach (var kvp in latest)
    {
        if (main.ContainsKey(kvp.Key))
        {
            continue;
        }

        main.Add(kvp);
    }
}
于 2013-08-05T21:59:36.740 回答