Simplify Your Git Workflow: Introducing Git-ChatGPT, a Command Line Tool Empowered by ChatGPT

Introduction

Chat GPT stands for Chat Generative Pre-Trained Transformer and was developed by an AI research company, Open AI. It is an artificial intelligence (AI) chatbot technology that can process our natural human language and generate a response. Simply put — you can ask Chat GPT a question, and it will give you an answer.

ChatGPT is an example of how AI is used to improve human-computer interaction and make it more intuitive and efficient.

ChatGpt

What is Git-ChatGPT?

Git-ChatGPT is a program designed to implement a natural language user interface for Git. This approach enables users to communicate with Git in plain language simply by telling GitChat what they want to do.

Git-ChatGPT will utilize the ChatGPT API to interpret users’ natural language input and translate it into Git command line format. Once the command line is generated, GitChat will execute it, enabling users to carry out their desired action in Git.

The primary objective of creating Git-ChatGPT is to simplify the Git workflow and make it more accessible to those who are new to Git or unfamiliar with Git command lines.

Git-ChatGPT is C# .NET 7 console application that uses the OpenAI API.

Before we start, you need to “Create a new secret key” from the OpenAI API key. Once you get the secret key, copy it, and store it.

Initially, the program loads the Open-AI APIKey from an appsettings.json, which enters a loop that continually prompts the user for input. Using the GPT-3 API, the program generates a Git command line based on the user’s input. Subsequently, the program requests confirmation from the user on whether to execute the command or not.

var config = new ConfigurationBuilder()
      .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .AddEnvironmentVariables()
      .Build();

   var apiKey = config.GetSection("apiKey").Get<string>();

while (true)
   {
    Console.Write(">");
    string userInput = Console.ReadLine()?.ToLowerInvariant() ?? "";
    string response = string.Empty;

    var _openAIService = new OpenAIService(new OpenAiOptions()
    {
     ApiKey = apiKey
    });

    var _completionResult = await _openAIService.Completions.CreateCompletion(new CompletionCreateRequest()
    {
     Prompt = $"[SYSTEM]: Outpupt a git command only from the following instructions, no explanation or other text \n --- \n Instructions: {userInput} \n Git Command:",
     Model = Models.TextDavinciV2,
     Temperature = 0.5F,
     MaxTokens = 100,
     N = 1
    });

    if (_completionResult.Successful)
    {
     response = _completionResult.Choices[0].Text;
    }
    else
    {
     if (_completionResult.Error == null)
     {
      throw new Exception("Unknown Error");
     }
     Console.WriteLine($"{_completionResult.Error.Code}: {_completionResult.Error.Message}");
    }

    var gitCommands = response.Trim(' ', '\r', '\n')
            .Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

    if (gitCommands == null)
    {
     Console.WriteLine(response);
     continue;
    }
    foreach (var cmd in gitCommands)
    {
     string gitCommand = cmd.Trim().ToLowerInvariant();
     if (gitCommand.StartsWith("git "))
     {
      Console.Write($"{gitCommand} (y/n)");
      var confirm = Console.ReadLine()?.ToLower();
      if ((confirm == "y") || (confirm == ""))
      {
       ExecuteCommand(gitCommand);
      }
      Console.WriteLine("");
     }
     else
     {
      Console.Write($"{gitCommand}");
     }
    }
   }

The ExecuteCommand method is used to execute the Git command line.

 static void ExecuteCommand(string command)
  {
   Process process = new Process();

   process.StartInfo.FileName = "cmd.exe";
   process.StartInfo.Arguments = "/c " + command;
   process.StartInfo.UseShellExecute = false;
   process.StartInfo.RedirectStandardOutput = true;
   process.StartInfo.RedirectStandardError = true;
   process.StartInfo.CreateNoWindow = false;

   var ret = process.Start();
   if (ret)
   {
    process.WaitForExit();
    var output = process.StandardOutput.ReadToEnd();
    if (!string.IsNullOrEmpty(output))
     Console.WriteLine(output);
    var error = process.StandardError.ReadToEnd();
    if (!string.IsNullOrEmpty(error))
     Console.WriteLine(error);
   }
   else
   {
    Console.WriteLine("failed to run..");
   }
  }

Exploring Git-ChatGPT

In order to activate the command line tool Git-ChatGPT with Git Bash, we need to add Git-ChatGPT.exe and the appsettings.json in C:\Program Files\Git\usr\bin (Release v1.0.0)

Here is a screenshot of it running in Git Bash on Windows:

One conversation can accommodate multiple Git commands with ease.

The source code is available on the following repository.

Summary

I hope this article helps you understand the use of the Git-ChatGPT command line tool.

It is important to recognize that GitChat is a trial program and should be handled accordingly. The Git-ChatGPT program might not always produce the accurate Git command line or may necessitate further input from the user to guarantee the correct command is carried out.

Thank you for reading; please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.

Happy Documenting!