在软件开发过程中,编写清晰且符合规范的 Git 提交信息至关重要。为了提高效率和规范性,可以利用 Ollama 和 PowerShell 脚本自动生成提交信息。本文将介绍如何实现这一功能。

前置条件

  • git
  • ollama,并 pull model , 比如这里使用 codegeex4:latest

1. 添加 PowerShell 函数

执行notepad $PROFILE 添加加以下内容,其中 model codegeex4:latest,你可以改成其它 model (qwen2.5-coderdeepseek-coder-v2),请参考https://ollama.com/library?q=code :

function gco {
    # Function to generate commit message
    function Generate-CommitMessage {
        $diff = git diff --cached
        $message = $diff | & ollama run codegeex4:latest "
Below is a diff of all staged changes, coming from the command:
\`\`\`
git diff --cached
\`\`\`
Please generate a concise, one-line commit message for these changes, conforming to the Conventional Commits specification."
        return $message
    }

    # Function to read user input
    function Read-Input {
        param (
            [string]$Prompt
        )
        Write-Host -NoNewline $Prompt
        return Read-Host
    }

    # Main script
    Write-Host "Generating..."
    $commitMessage = Generate-CommitMessage

    while ($true) {
        Write-Host "`nProposed commit message:"
        Write-Host $commitMessage

        $choice = Read-Input "Do you want to (a)ccept, (e)dit, (r)egenerate, or (c)ancel? "

        switch ($choice.ToLower()) {
            'a' {
                if ($commitMessage) {
                    git commit -m "$commitMessage"
                    if ($?) {
                        Write-Host "Changes committed successfully!"
                        return 0
                    } else {
                        Write-Host "Commit failed. Please check your changes and try again."
                        return 1
                    }
                } else {
                    Write-Host "Commit message cannot be empty. Please try again."
                }
            }
            'e' {
                $commitMessage = Read-Input "Enter your commit message: "
                if ($commitMessage) {
                    git commit -m "$commitMessage"
                    if ($?) {
                        Write-Host "Changes committed successfully with your message!"
                        return 0
                    } else {
                        Write-Host "Commit failed. Please check your message and try again."
                        return 1
                    }
                } else {
                    Write-Host "Commit message cannot be empty. Please try again."
                }
            }
            'r' {
                Write-Host "Regenerating commit message..."
                $commitMessage = Generate-CommitMessage
            }
            'c' {
                Write-Host "Commit cancelled."
                return 1
            }
            default {
                Write-Host "Invalid choice. Please try again."
            }
        }
    }
}

2. 执行,生成 git commit message

在 PowerShell 执行. $PROFILE 重新加载配置文件,在项目目录执行 gco