aicommit2: 利用Ollama 生成 git message的工具

一个可以在本地利用 Ollama 的工具
更新于: 2025-01-18 20:47:46

安装

# 可以使用yarn安装
npm install -g aicommit2

# aicommit2 或者 aic2

启动 ollama

ollama run llama3.2 # model you want use. ex) codellama, deepseek-coder

配置

这个配置会保存在 ~/.aicommit2 下面。

# 基本
aicommit2 config set OLLAMA.host=<your host>
aicommit2 config set OLLAMA.model=<your model>
aicommit2 config set OLLAMA.numCtx=4096

# 一些忽略的文件
aicommit2 config set exclude="*.ts"
aicommit2 config set exclude="*.ts,*.json"
aicommit2 config set type="conventional"

# 实际
aicommit2 config set OLLAMA.host=http://localhost:11434
aicommit2 config set OLLAMA.model=llama3.2
aicommit2 config set OLLAMA.numCtx=4096
aicommit2 config set type="conventional"

使用

生成 message
提交到 github 效果
git add <files...>
aicommit2

# 或者
aic2 --type conventional
# 添加 + 不需要确认,再结合 git push 就可以完全自动提交了
aic2 --all -y

利用 git hook

添加 hooks
aicommit2 hook install

原理

#!/usr/bin/env sh

# .git/hooks/prepare-commit-msg
# Make this file executable: chmod +x .git/hooks/prepare-commit-msg
echo "Running prepare-commit-msg hook"
COMMIT_MSG_FILE="$1"

# Get the staged diff
DIFF=$(git diff --cached)

# Generate a summary with ollama CLI and phi4 model

SUMMARY=$(
  ollama run phi4 <<EOF
Generate a raw text commit message for the following diff.
Keep commit message concise and to the point.
Make the first line the title (100 characters max) and the rest the body:
$DIFF
EOF
)

if [ -f "$COMMIT_MSG_FILE" ]; then
  # Save the AI generated summary to the commit message file
  echo "$SUMMARY" >"$COMMIT_MSG_FILE"
  # Append existing message if it exists
  if [ -n "$EXISTING_MSG" ]; then
    echo "" >>"$COMMIT_MSG_FILE"
    echo "$EXISTING_MSG" >>"$COMMIT_MSG_FILE"
  fi
fi

效果如下