c# - 如何使用 libgit2 连接到 GitHub 存储库?

标签 c# git github libgit2 libgit2sharp

我正在尝试连接到一个存储库:

using(var Git = new Repository(
    Repository.Clone("https://github.com/wikimedia/mediawiki-core", "tmp")
)){
    foreach(var Commit in Git.Commits)
    {
        MessageBox.Show(Commit.Author.Name);
    }
}

它连接正常(例如,如果我更改 URL,我会得到预期的异常),但没有显示 MessageBoxes - 为什么?这应该很简单。

最佳答案

关于您的问题需要考虑的几点:

  • 不能“连接”到远程存储库并通过 git 协议(protocol)动态检索一个文件。通常,需要检索本地副本(通过 Repository.Clone()),然后针对本地存储库执行一些工作。
  • Mediawiki-core 是一个相当大的存储库。它包含超过 10000 个提交。因此,克隆可能需要相当长的时间。通过为 Clone() 方法提供传输进度处理程序,可以深入了解克隆的进度。
  • @CarlosMartínNieto 是对的。如果您只需要一个文件(而不是存储库的整个历史记录),则依赖 GitHub API 确实会更有效率。请注意,此 API 的使用受一些 rate limitations 的约束。 您可能需要考虑,具体取决于预见的用途。

下面的代码(极大地启发自您自己的代码)克隆一个远程存储库,将当前克隆进度输出到控制台,并枚举可从 HEAD 访问的提交。

它已经成功地针对 LibGit2Sharp v0.14.1 NuGet 包进行了测试。

public void CloneAndEnumerateCommitsFromHead()
{
    var tmp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

    string path = Repository.Clone(
        "https://github.com/nulltoken/TestGitRepository", 
        tmp,
        onTransferProgress: ProgressHandler);

    using (var Git = new Repository(path))
    {
        foreach (var Commit in Git.Commits)
        {
            Console.WriteLine("{0} by {1}",
                Commit.Id.ToString(7),
                Commit.Author.Name);
        }
    }
}

private int ProgressHandler(TransferProgress progress)
{
    Console.WriteLine("{0}/{1}", progress.IndexedObjects, progress.TotalObjects);
    return 0;
}

运行时输出如下

0/70
1/70
2/70
2/70
...snipped for brevity...
68/70
69/70
70/70
70/70
49322bb by A U Thor
d0114ab by A U Thor
f73b956 by A U Thor
6e14752 by A U Thor
1203b03 by A U Thor
bab66b4 by A U Thor
83834a7 by A U Thor
6462e7d by A U Thor
42e4e7c by A U Thor
7f82283 by A U Thor
59706a1 by A U Thor
c070ad8 by A U Thor
d31f5a6 by A U Thor
83d2f04 by A U Thor
6db9c2e by A U Thor
d86a2aa by A U Thor
0966a43 by A U Thor
2c34933 by A U Thor
ac7e7e4 by A U Thor
58be465 by A U Thor
6c8b137 by A U Thor

关于c# - 如何使用 libgit2 连接到 GitHub 存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185412/

相关文章:

c# - UserStore 每个 HttpRequest 的 Unity IoC 生命周期

c# - 使用Linq查找满足特定条件的矩阵的所有索引

git - 从当前分支开始一个新的 git repo

github - 在我的博客中添加github gist的问题(使用Google博客)

ruby - 如何将项目 readme.md 读入 user.github.com 站点?

c# - SQL Server 和 C# : get last inserted id

c# - Json.Net 可以处理 List<object> 吗?

git - Perforce p4 相当于 git 中的交换

git - 使用 git hash-object 构建 git commit 对象?

git - 使用 Github 接口(interface)进行单个提交 pull 请求