.NET Core下操作Git,自动提交代码到 GitHub
.net core 3.0 预览版发布已经好些时日了,博客园也已将其用于生产环境中,可见 .net core 日趋成熟
回归正题,你想盖大楼吗?想 github 首页一片绿吗?今天拿她玩玩自动提交代码至 github。
安装项目模板
dotnet new --install "microsoft.dotnet.web.projecttemplates.3.0" dotnet new worker
创建项目
直接使用 .net cli 创建一个 work service 的项目
dotnet new worker -o automaticpush
用 visual studio 2019 打开项目可以看到以下代码
// program.cs public class program { public static void main(string[] args) { createhostbuilder(args).build().run(); } public static ihostbuilder createhostbuilder(string[] args) => host.createdefaultbuilder(args) .configureservices((hostcontext, services) => { services.addhostedservice<worker>(); }); }
- 从 3.0 起 webhost 被 host 取代了
-
createhostbuilder
创建 host 并在configureservices
中调用.addhostedservice<worker>()
// worker.cs public class worker : backgroundservice { private readonly ilogger<worker> _logger; public worker(ilogger<worker> logger) { _logger = logger; } protected override async task executeasync(cancellationtoken stoppingtoken) { while (!stoppingtoken.iscancellationrequested) { _logger.loginformation("worker running at: {time}", datetimeoffset.now); await task.delay(1000, stoppingtoken); } } }
worker 继承了 backgroundservice,在 override executeasync 方法中完成自动提交的代码
.net 下操作 git 需要用到一个库 libgit2sharp
,同时支持 .net framework 及 .net core
在项目中安装使用
install-package libgit2sharp
libgit2sharp 简单使用
repository.init(@"d:\work")
在指定路径创建一个新的 git 仓库,相当于git init
repository.clone("https://github.com/meowv/blog.git", @"d:\work")
拉取一个远程仓库到本地,相当于git clone
using (var repo = new repository(@"d:\blog")){}
打开本地存在的 git 仓库-
获取 branch
using (var repo = new repository(@"d:\blog")) { var branches = repo.branches; foreach (var item in branches) { } }
-
获取 commits
using (var repo = new repository(@"d:\blog")) { foreach (var commit in repo.commits) { } }
-
获取 tags
using (var repo = new repository(@"d:\blog")) { foreach (var commit in repo.tags) { } }
更多操作请移步 https://github.com/libgit2/libgit2sharp
自动 push 代码盖大楼
有了以上基础,就可以实现自动生成文件,push 代码到 github 了。
新建一个配置文件,存放我们 github 仓库以及账号密码等重要信息
{ "repository": "本地git仓库绝对路径", "username": "github账号", "password": "github密码", "name": "提交人", "email": "邮箱" }
在executeasync中读取配置文件信息
var configurationroot = new configurationbuilder().addjsonfile("config.json").build(); var path = configurationroot["repository"]; var username = configurationroot["username"]; var password = configurationroot["password"]; var name = configurationroot["name"]; var email = configurationroot["email"];
git会自动检测文件变化,所以就先自动按日期创建.log文件,不断生成内容然后提交
while (!stoppingtoken.iscancellationrequested) { var filename = $"{datetime.now.tostring("dd")}.log"; var content = datetime.now.tostring("yyyy-mm-dd hh:mm:ss"); // 写入内容 writetext(path, filename, content); using (var repo = new repository(path)) { // stage the file commands.stage(repo, "*"); // create the committer's signature and commit var author = new signature(name, email, datetime.now); var committer = author; // commit to the repository var commit = repo.commit(content, author, committer); // git push var options = new pushoptions { credentialsprovider = new credentialshandler((url, usernamefromurl, types) => { return new usernamepasswordcredentials() { username = username, password = password }; }) }; repo.network.push(repo.branches["master"], options); } console.writeline(content); // 等待60秒继续执行... await task.delay(60000, stoppingtoken); } private static void writetext(string path, string filename, string content) { path = path.combine(path, datetime.now.tostring(@"yyyy\\mm")); if (!directory.exists(path)) { directory.createdirectory(path); } var filepath = path.combine(path, filename); using var fs = new filestream(filepath, filemode.append); using var sw = new streamwriter(fs); sw.writeline(content); }
至此,整个代码编写部分结束,项目发布后可以选择sc.exe注册为windows服务,在这里推荐使用nssm(一个服务封装程序),好了,赶紧盖大楼去吧~~
上一篇: 目录结构导致无法通过新闻源审核