繁体   English   中英

如何从C#应用程序中检索git Commit Id?

[英]How to retrieve git Commit Id from a C# Application?

我正在研究CI构建自动化任务,我想使用Git Commit Id命名我的构建。 我打算写一个C#程序来做这件事。 我可以使用哪些库从C#调用Git存储库? 我能够调用本地存储库克隆并使用git.exe(Windows)或libgit2sharp检索此信息,但我不知道如何在远程源上执行此操作

我已经使用LibGit2Sharp很长一段时间了,这很好。

下面是一个示例,它将遍历您urlcommits

注意:我必须做一个clone ,不确定是否有更好的方法:

string url = "http://github.com/libgit2/TestGitRepository";

using (Repository repo = Repository.Clone(url, @"C:\Users\Documents\test"))
{
    foreach (var commit in repo.Commits)
    {
        var commitId = commit.Id;
        var commitRawId = commitId.RawId;
        var commitSha = commitId.Sha; //0ab936416fa3bec6f1bf3d25001d18a00ee694b8
        var commitAuthorName = commit.Author.Name;

        commits.Add(commit);
    }
}

从CI的角度来看,您可能愿意建立一个特定的分支。

以下代码演示了这一点。

using (Repository repo = Repository.Clone(url, localPath))
{
    // Retrieve the branch to build
    var branchToBuild = repo.Branches["vNext"];

    // Updates the content of the working directory with the content of the branch
    branchToBuild.Checkout();

    // Perform your build magic here ;-)
    Build();

    // Retrieve the commit sha of the branch that has just been built
    string sha = branchToBuild.Tip.Sha;

    // Package your build artifacts using the sha to name the package
    Package(sha);
}

注意: url可以指向:

  • 远程http网址( http://www.example.com/repo.git
  • CI服务器上的位置( file:///C:/My%20Documents/repo.git
  • 网络上的位置( file://server/repos/repo.git

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM