程会玩 | 在.NET Core里操作Git
點擊上方藍(lán)字關(guān)注“汪宇杰博客”
Git是很多程序員的首選源代碼版本控制工具,我最近也從TFVC切換到了Git,受益匪淺。今天我就來帶大家看看如何在.NET Core里操作Git。
為啥要這么做
首先,這件事情的意義,并不是閑的蛋疼。我們確實有很多不錯的Git客戶端,如GitHub for Windows、VS/VS Code,Git GUI等,都相當(dāng)成熟,沒有必要自己再去用.NET/C#重新發(fā)明輪子。但在服務(wù)器上,可能你需要管理一個Git倉庫,有自己的業(yè)務(wù)邏輯,Git倉庫需要和其他系統(tǒng)流程整合,甚至想用ASP.NET寫一個自己的GitHub出來,那么用.NET Core來操作Git就勢在必行了。
LibGit2Sharp
我們不需要從零開始研究Git的原理,強大的.NET社區(qū)已經(jīng)有了一個操作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 遠(yuǎn)程倉庫
Repository.Clone() 方法可以拉取一個遠(yuǎn)程倉庫到本地,等同于 git clone 命令。
Repository.Clone("https://github.com/EdiWang/EnvSetup.git", @"D:\EnvSetup");
創(chuàng)建本地倉庫
Repository.Init() 方法可以在指定路徑創(chuàng)建一個新的Git倉庫,等同于 git init 命令。
Repository.Init(@"D:\GitRocks");
打開本地Git倉庫
LibGit2Sharp.Repository 類型代表一個Git倉庫,它可以只在內(nèi)存中,也可以從一個本地路徑加載,即包含".git"文件夾的目錄。如我的博客項目 D:\GitHub\Moonglade
由于它實現(xiàn)了?IDisposable 接口,所以推薦使用using語句把對Repository的操作包裝起來,以便于釋放資源。
打開本地Git倉庫很簡單,將路徑傳給Repository的構(gòu)造函數(shù),就搞定了:
using (var repo = new Repository(@"D:\GitHub\Moonglade"))
{
}
檢索 Branch
Repository.Branches 屬性包含了當(dāng)前倉庫所有的分支信息。比如,我們要輸出當(dāng)前倉庫有哪些本地和遠(yuǎn)程branch,就可以這么做:
using (var repo = new Repository(@"D:\GitHub\Moonglade"))
{
? ? var branches = repo.Branches;
? ? foreach (var b in branches)
? ? {
? ? ? ? Console.WriteLine(b.FriendlyName);
? ? }
}
當(dāng)然,除了分支的名稱,還包括該分支底下的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<Commit>()方法:
var commit = repo.Lookup<Commit>("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類似,標(biāo)簽信息可以通過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
總結(jié)
以上是生活随笔為你收集整理的程会玩 | 在.NET Core里操作Git的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Core 3.0 Previe
- 下一篇: asp.net ajax控件工具集 Au