.NET Core operating Git, to automatically submit code GitHub

.NET Core 3.0 preview release is already better time, the park also has blog for a production environment, we can see .NET Core matures

Return to the topic you want to cover building? GitHub you want a green home? Today take her play automatically submit code to GitHub.

Installation Project Templates

dotnet new --install "Microsoft.DotNet.Web.ProjectTemplates.3.0"
dotnet new worker

Create a project

Direct use .NET CLI project to create a Work Service

dotnet new worker -o AutomaticPush

Open a Visual Studio 2019 project you can see the following code

// 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>();
            });
}
  • Starting from 3.0 Host WebHost been replaced
  • CreateHostBuilderHost and create ConfigureServicescall.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 inherited BackgroundService, completion code automatically submitted override ExecuteAsync method

Git operations need to use a library under the .NET LibGit2Sharp, supports both .NET Framework and .NET Core

Install and use in your project

Install-Package LibGit2Sharp

LibGit2Sharp simple to use

  • Repository.Init(@"D:\Work") Create a new Git repository at the specified path, the equivalent of git init

  • Repository.Clone("https://github.com/Meowv/Blog.git", @"D:\Work") Pull a remote repository to local, equivalent to git clone

  • using (var repo = new Repository(@"D:\Blog")){} Open the existing local Git repository

  • Gets Branch

    using (var repo = new Repository(@"D:\Blog"))
    {
        var branches = repo.Branches;
    
        foreach (var item in branches)
        {
        }
    }
  • Get Commits

    using (var repo = new Repository(@"D:\Blog"))
    {
        foreach (var commit in repo.Commits)
        {
        }
    }
  • Gets Tags

    using (var repo = new Repository(@"D:\Blog"))
    {
        foreach (var commit in repo.Tags)
        {
        }
    }
  • More Actions venue https://github.com/libgit2/libgit2sharp

Automatic Push cover building codes

With the above basis, it can automatically generate a file, push the code to GitHub up.

Create a new profile, warehouse and store our GitHub account passwords and other important information

{
  "repository": "本地git仓库绝对路径",
  "username": "GitHub账号",
  "password": "GitHub密码",
  "name": "提交人",
  "email": "邮箱"
}

Reads the configuration file information in 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 will automatically detect file changes, so I have to create the .log files by date automatically and continuously generate and submit content

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);
}

At this point, the entire coding portion of the end, the project is released can choose sc.exe registered as a Windows service, here are recommended nssm (a service wrapper), well, cover the building quickly go ~~

Guess you like

Origin www.cnblogs.com/meowv/p/11389175.html