簡體   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