前言
git log
命令,提取仓库下的提交日志。实践经过
git log
默认的输出格式是下面这个样子:git log --shortstat
来输出变更的行数,如下图所示。git log --all --pretty="%x40%h%x2C%an%x2C%ad%x2C%x22%s%x22%x2C" --shortstat | tr "\n" " " | tr "@" "\n"
然而这种方式始终不够优雅,命令中额外使用了 tr
对字符串进行处理,这意味着在目标机器上也要有这个工具,否则无法运行,而 windows 上只能通过安装第三方工具实现。
另外一点是扩展性问题,命令行对于csv这种简单的格式处理还好说,如果要输出JSON格式的话,就不好办了,而且命令行的配置项几乎没人能看懂,以后维护起来免不了要996。
基于上述痛点,阿捷又在网上搜寻了一番,最终在MVP大佬的一篇博客(https://edi.wang/post/2019/3/26/operate-git-with-net-core)中找到了蛛丝马迹。根据博客中的内容来看,可以通过一款名为libgit2sharp(https://github.com/libgit2/libgit2sharp)的类库,实现我们的需求。
libgit2sharp内部嵌套了一个基于C语言实现的Git内核,它自身对外提供一系列和Git操作相关的接口,并且它的上游核心仓库libgit2(https://github.com/libgit2/),提供了对包括Python,PHP,C#在内的多种语言的支持。而且项目是开源的,由社区进行维护。
阿捷经过简单上手,觉得提供的API可以满足需要,然后快速制作出了一个简易的命令行程序。核心代码如下:
using (var repo = new Repository(workdir))
{
Console.WriteLine("all commit count:" + repo.Commits.Count());
foreach (Commit commit in repo.Commits)
{
var commitDto = new GitCommitLogDto
{
CommitHash = commit.Sha,
AuthorName = commit.Author.Name,
AuthorEmail = commit.Author.Email,
MessageShort = commit.MessageShort,
AuthorDate = commit.Author.When.DateTime,
};
var patch = GetPatchInfo(repo, commit);
if (patch != null)
{
commitDto.LinesAdded = patch.LinesAdded;
commitDto.LinesDeleted = patch.LinesDeleted;
};
Console.WriteLine(commitDto.ToString());
list.Add(commitDto);
}
}
# publish win-x64
dotnet publish -c Release -o publish/win-x64 -r win-x64 /p:PublishSingleFile=true /p:IncludeSymbolsInSingleFile=true /p:PublishTrimmed=true
#publish linux-x64
dotnet publish -c Release -o publish/linux-x64 -r linux-x64 /p:PublishSingleFile=true /p:IncludeSymbolsInSingleFile=true /p:PublishTrimmed=true
后记