Skip to main content
 首页 » 编程设计

c#之如何从 C# 应用程序检索 git 提交 ID

2024年02月13日16lovecherry

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

请您参考如下方法:

从 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 url (http://www.example.com/repo.git)
  • CI 服务器上的一个位置 (file:///C:/My%20Documents/repo.git)
  • 网络上的一个位置(file://server/repos/repo.git)