C#/.NET uses the GIT command line to operate the GIT repository method example

Time:2019-9-5

We can manipulate git on the command line, but as a programmer, it would be foolish to knock on the command line manually when there is a lot of repetition.

This paper introduces how to write a. NET program using C # to operate the GIT warehouse automatically using the GIT command line.

This is a very basic introductory article.

The simplest code to run the GIT command

In. NET, running a command requires only the use ofProcess.StartJust start a subprocess. So run onegitOrders, we only need this sentence enough:


Process.Start("git", "status");

Of course, it can be abbreviated directly.gitBecausegit.exeIn my environment variables, the general developer will automatically add this command to the environment variables when installing the Git client. If not, you need to use the full pathC:\Program Files\Git\mingw64\bin\git.exeIt’s just that everyone’s paths may be different, so it’s unreliable.

Allow command output

For what was written in the previous sectionProcess.StartYou can see at a glance that this is completely useless code. becausegit statusThe command is just to get the current state of the warehouse. This command does not affect the warehouse at all, just to see the state.

So it’s better for commands to get output.

To get output, you need to useProcessStartInfoTo specify how to start a process.


var info = new ProcessStartInfo(ExecutablePath, arguments)
{
 CreateNoWindow = true,
 RedirectStandardOutput = true,
 UseShellExecute = false,
 WorkingDirectory = WorkingDirectory,
};

At least four properties need to be set:

  • CreateNoWindowIndicates that you do not create a console window for this command alone

In fact, if the program using this code is also a console program, this sentence is not necessary, because the child process will share the console window of the parent process; but for GUI programs, this sentence is important, which can avoid accidental pop-up of a black console window during the execution of commands. 。

  • RedirectStandardOutputRedirecting output

This must be set totrueBecause we want to get the output of the command.

  • WorkingDirectorySetting up working paths

Originally this was an optional setting, but forgitCommands generally operate on an existing git repository, so of course a reasonable git repository should be specified.

  • UseShellExecuteSet tofalseIndicate not to useShellExecuteFunction creation process

Detailed description of this property,

The default value of UseShellExecute istrue

If you have the following requirements, it is recommended to set this valuefalse

  • A known procedure needs to be explicitly executed
  • Need to redirect input and output

If you have the following requirements, it is recommended to set this value to true or to keep the default:

  • Documents, media, web pages, etc. need to be opened
  • Need to open Url
  • Need to open script execution
  • Need to open the program in the path of the environment variable on the computer

Here we have to specifyfalseBecause to redirect the output, this is the only valid value. By the way, if this property is not set, the default value istrue

CommandRunner

For convenience, I encapsulated all the code that ran a command into oneCommandRunnerAmong the classes.


using System;
using System.Diagnostics;
using System.IO;

namespace Walterlv.GitDemo
{
 public class CommandRunner
 {
  public string ExecutablePath { get; }
  public string WorkingDirectory { get; }

  public CommandRunner(string executablePath, string workingDirectory = null)
  {
   ExecutablePath = executablePath ?? throw new ArgumentNullException(nameof(executablePath));
   WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(executablePath);
  }

  public string Run(string arguments)
  {
   var info = new ProcessStartInfo(ExecutablePath, arguments)
   {
    CreateNoWindow = true,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    WorkingDirectory = WorkingDirectory,
   };
   var process = new Process
   {
    StartInfo = info,
   };
   process.Start();
   return process.StandardOutput.ReadToEnd();
  }
 }
}

Tests and results

AboveCommandRunnerThe use of commands is very simple.newWhen it comes out, you get an instance that you can use to execute the command, and then each time you execute the callRunThe method can pass in the parameters.

var git = new CommandRunner("git", @"D:\Developments\Blogs\walterlv.github.io");
git.Run("add .");
Git. Run (@ "commit-m", "this is automatically submitted");

If you need to get the execution result of the command, use it directlyRunThe return value of the method is sufficient.

For example, I posted the followingMainThe complete code of the function can output the current state of my warehouse:

using System;

namespace Walterlv.GitDemo
{
 class Program
 {
  static void Main(string[] args)
  {
   Console. WriteLine ("walterlv's automatic git command");

   var git = new CommandRunner("git", @"D:\Developments\Blogs\walterlv.github.io");
   var status = git.Run("status");

   Console.WriteLine(status);
   Console. WriteLine ("Exit the program by Enter... "";
   Console.ReadLine();
  }
 }
}

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.