點選上方藍字關註“汪宇傑部落格”

Git是很多程式員的首選原始碼版本控制工具,我最近也從TFVC切換到了Git,受益匪淺。今天我就來帶大家看看如何在.NET Core裡操作Git。
為啥要這麼做
首先,這件事情的意義,並不是閑的蛋疼。我們確實有很多不錯的Git客戶端,如GitHub for Windows、VS/VS Code,Git GUI等,都相當成熟,沒有必要自己再去用.NET/C#重新發明輪子。但在伺服器上,可能你需要管理一個Git倉庫,有自己的業務邏輯,Git倉庫需要和其他系統流程整合,甚至想用ASP.NET寫一個自己的GitHub出來,那麼用.NET Core來操作Git就勢在必行了。

LibGit2Sharp
我們不需要從零開始研究Git的原理,強大的.NET社群已經有了一個操作Git的庫:LibGit2Sharp。它同時支援.NET Framework及.NET Core,我們需要用的就是它!
傳送門:https://github.com/libgit2/libgit2sharp
這個庫也能在NuGet上直接安裝:
https://www.nuget.org/packages/LibGit2Sharp
首先,我們將它引入.NET Core工程
NuGet Package Manager (Visual Studio)
Install-Package LibGit2Sharp
.NET Core CLI
dotnet add package LibGit2Sharp

Clone 遠端倉庫
Repository.Clone() 方法可以拉取一個遠端倉庫到本地,等同於 git clone 命令。
Repository.Clone(“https://github.com/EdiWang/EnvSetup.git”, @”D:\EnvSetup”);
建立本地倉庫
Repository.Init() 方法可以在指定路徑建立一個新的Git倉庫,等同於 git init 命令。
Repository.Init(@”D:\GitRocks”);
開啟本地Git倉庫
LibGit2Sharp.Repository 型別代表一個Git倉庫,它可以只在記憶體中,也可以從一個本地路徑載入,即包含”.git”檔案夾的目錄。如我的部落格專案 D:\GitHub\Moonglade

由於它實現了 IDisposable 介面,所以推薦使用using陳述句把對Repository的操作包裝起來,以便於釋放資源。
開啟本地Git倉庫很簡單,將路徑傳給Repository的建構式,就搞定了:
using (var repo = new Repository(@”D:\GitHub\Moonglade”))
{
}
檢索 Branch
Repository.Branches 屬性包含了當前倉庫所有的分支資訊。比如,我們要輸出當前倉庫有哪些本地和遠端branch,就可以這麼做:
using (var repo = new Repository(@”D:\GitHub\Moonglade”))
{
var branches = repo.Branches;
foreach (var b in branches)
{
Console.WriteLine(b.FriendlyName);
}
}

當然,除了分支的名稱,還包括該分支底下的Commits等其他資訊。

檢索 Commits
透過遍歷Branch.Commits,或Repository.Commits,可以獲得完整的Commits歷史記錄資訊:
foreach (var commit in repo.Commits)
{
Console.WriteLine(
$”{commit.Id.ToString().Substring(0, 7)} ” +
$”{commit.Author.When.ToLocalTime()} ” +
$”{commit.MessageShort} ” +
$”{commit.Author.Name}”);
}

要查詢具體某一個Commit,可以使用Repository.Lookup()方法:
var commit = repo.Lookup(“9fddbbf”);
Console.WriteLine($”Commit Full ID: {commit.Id}”);
Console.WriteLine($”Message: {commit.MessageShort}”);
Console.WriteLine($”Author: {commit.Author.Name}”);
Console.WriteLine($”Time: {commit.Author.When.ToLocalTime()}”);

想要獲取最新的Commit,訪問Repository.Head.Tip即可。
var commit = repo.Head.Tip;
Console.WriteLine($”Commit Full ID: {commit.Id}”);
Console.WriteLine($”Message: {commit.MessageShort}”);
Console.WriteLine($”Author: {commit.Author.Name}”);
Console.WriteLine($”Time: {commit.Author.When.ToLocalTime()}”);

檢索 Tags
和Branch類似,標簽資訊可以透過Repository.Tags屬性得到:
foreach (var item in repo.Tags)
{
Console.WriteLine($”{item.FriendlyName} – {item.Target.Id}”);
}

其他操作
以上例子演示了最常用的Git倉庫資訊檢索操作,還有很多其他操作,如透過Repository.Ignore讀寫忽略檔案,寫入Commit、對比更改等,本文就不再一一贅述啦,大家可以自己探索~

參考:http://www.woodwardweb.com/git/getting_started_2.html
朋友會在“發現-看一看”看到你“在看”的內容