简体   繁体   中英

Run git commands from a C# function

How can my C# code run git commands when it detects changes in tracked file? I am writing a VisualStudio/C# console project for this purpose.

I am new to the the .NET environment and currently working on integrating automated GIT commits to a folder. I need to automatically commit any change/add/delete on a known folder and push that to a git remote. Any guidance appreciated. Thank you.

Here is what I have and the last one is the one I need some guidance with:

  1. Git repository initially set up on folder with proper ignore file (done).
  2. I am using C# FileSystemWatcher to catch any changes on said folder (done).
  3. Once my project detects a change it needs to commit and push those changes (pending).

Tentative commands the project needs to run:

git add -A
git commit "explanations_of_changes"
git push our_remote

NOTE: This code (with no user interaction) will be the only entity committing to this repo so I am not worried about conflicts and believe this flow will work.

I realize this is an old question but I wanted to add the solution I recently came across to help those in the future.

The PowerShell class provides an easy way to interact with git. This is part of the System.Management.Automation namespace in .NET. Note that System.Management.Automation.dll is available via NuGet.

string directory = ""; // directory of the git repository

using (PowerShell powershell = PowerShell.Create()) {
    // this changes from the user folder that PowerShell starts up with to your git repository
    powershell.AddScript($"cd {directory}");

    powershell.AddScript(@"git init");
    powershell.AddScript(@"git add *");
    powershell.AddScript(@"git commit -m 'git commit from PowerShell in C#'");
    powershell.AddScript(@"git push");

    Collection<PSObject> results = powershell.Invoke();
}

In my opinion this is cleaner and nicer than using the Process.Start() approach. You can modify this to your specfic needs by editing the scripts that are added to the powershell object.

As commented by @ArtemIllarionov, powershell.Invoke() does not return errors but the Streams property has output information. Specifically powerShell.Streams.Error for errors.

If you want to do it in C#, you can call the external git command by Process.Start when you detect file change

string gitCommand = "git";
string gitAddArgument = @"add -A";
string gitCommitArgument = @"commit ""explanations_of_changes""";
string gitPushArgument = @"push our_remote";

Process.Start(gitCommand, gitAddArgument);
Process.Start(gitCommand, gitCommitArgument);
Process.Start(gitCommand, gitPushArgument);

Not the best solution but it works in C#

    //Console.WriteLine(CommandOutput("git status"));

    public static string CommandOutput(string command,
                                       string workingDirectory = null)
    {
        try
        {
            ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);

            procStartInfo.RedirectStandardError = procStartInfo.RedirectStandardInput = procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;
            if (null != workingDirectory)
            {
                procStartInfo.WorkingDirectory = workingDirectory;
            }

            Process proc = new Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            StringBuilder sb = new StringBuilder();
            proc.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
            {
                sb.AppendLine(e.Data);
            };
            proc.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e)
            {
                sb.AppendLine(e.Data);
            };

            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();
            proc.WaitForExit();
            return sb.ToString();
        }
        catch (Exception objException)
        {
            return $"Error in command: {command}, {objException.Message}";
        }
    }

Try LibGit2Sharp, a native implementation of git for .NET:

https://github.com/libgit2/libgit2sharp/

One alternative would be to setup Grunt and TaskRunner with your project.

Grunt should be able to provide the automation of detecting changes to a folder(or folders) in your project and execute the appropriate git commands to commit it.

Task Runner allows you to initialize and run Grunt from within Visual Studio.

The Visual Studio team has indicated that Task Runner is going to become integrated into future releases of Visual Studio, so this could be a long term solution.

Note: It has been mentioned in the comments, but I feel it worth mentioning again that auto-commiting anytime a file is saved to the repository isn't best practice. You want functional / atomic code changes to get pushed in, not simple text changes. Auto-Commit at your own risk.

The Package Manager Console is Powershell console. So you can run your git commands from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM