Using ChatGPT API To Generate Git Commit Messages With Powershell

Git commit messages introduce a little bit of friction when I’m writing code. I tend to get stuck trying to come up with the perfect message, similar to the character creation screen in an RPG. So armed with an OpenAI account and API access, I decided to test handing over the work to ChatGPT.

Below is a small PowerShell function that I have in my $Profile file, it creates a prompt asking for a commit message to be generated, along with git status and git diff output. This is sent to ChatGPT, and the returned commit message is used in git commit and then pushed.

function AICommit {
    
    git add -A
    $Prompt = @("Please make a succinct git commit message for the changes below. I have included output from git status and git diff. Technical answers preferred", (git status), (git diff --cached))
    $Prompt = ($Prompt | % { $_ -join [System.Environment]::NewLine }) -join [System.Environment]::NewLine
    

    $OpenAIApiUrl = "https://api.openai.com/v1/chat/completions"
    $Headers = @{
        "Authorization" = "Bearer $env:OpenAIKey"
        "Content-Type"  = "application/json"
    }

    $MaxTokens = 150
    
    $Body = @{
        model      = "gpt-4"
        messages   = @(@{role = "user"; content = $Prompt })
        max_tokens = $MaxTokens
    } | ConvertTo-Json

    $Response = Invoke-RestMethod -Uri $OpenAIApiUrl -Method POST -Headers $Headers -Body $Body
    $CommitMessage = $response.choices[0].message.content
    Write-host "Commit Message is: $CommitMessage"

    git commit -am "$CommitMessage"
    git push
}

A few notes and caveats

  • This is probably not suitable for use at work unless you’re certain your employer is ok with code being sent to OpenAI.
  • It requires a Premium OpenAI account with API access
  • The OpenAI API Key is stored in the $env:OpenAIKey environmental variable

Example usage

This is the AI generated commit message for this blog post.

PS C:\Code\xkln.net> AICommit

Commit Message is: "Added new blog post draft on using ChatGPT API with PowerShell"

[master e34232e] "Added new blog post draft on using ChatGPT API with PowerShell"
 1 file changed, 51 insertions(+)
 create mode 100644 content/drafts/using-chatgpt-api-to-generate-git-commit-messages-with-powershell/index.md
Enumerating objects: 9, done.
Counting objects: 100% (9/9), done.
Delta compression using up to 24 threads
Compressing objects: 100% (5/5), done.
Writing objects: 100% (6/6), 1.63 KiB | 1.63 MiB/s, done.
Total 6 (delta 3), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (3/3), completed with 3 local objects.
To https://github.com/mdjx/xkln.net.git
   a3b979e..e34232e  master -> master

If you enjoyed this post consider sharing it on , , , or , and .