Skip to content

Latest commit

 

History

History
112 lines (66 loc) · 2.87 KB

File metadata and controls

112 lines (66 loc) · 2.87 KB

Git Commit Message 乱码问题解决方案

问题原因

在 Windows 系统上,PowerShell 默认使用 GB2312/GBK 编码,而 GitHub 使用 UTF-8 编码。当 commit message 包含中文时,如果 Git 没有正确配置编码,会导致在 GitHub 上显示为乱码。

解决方案

1. 配置 Git 使用 UTF-8 编码

# 设置 commit message 编码为 UTF-8
git config --global i18n.commitencoding utf-8

# 设置 log 输出编码为 UTF-8
git config --global i18n.logoutputencoding utf-8

# 禁用路径引用(避免中文路径显示为转义序列)
git config --global core.quotepath false

2. 配置 PowerShell 使用 UTF-8(可选但推荐)

在 PowerShell 中执行:

# 设置控制台输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 或者添加到 PowerShell 配置文件(永久生效)
# 编辑 $PROFILE 文件,添加:
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

3. 验证配置

# 检查 Git 编码配置
git config --global --get i18n.commitencoding
git config --global --get i18n.logoutputencoding
git config --global --get core.quotepath

# 应该输出:
# utf-8
# utf-8
# false

修复已存在的乱码 commit

如果已经提交了乱码的 commit message,可以使用以下方法修复:

方法1:修改最近一次 commit message

git commit --amend -m "新的正确的中文 commit message"
git push --force  # 注意:如果已经 push 到远程,需要使用 force push

方法2:使用交互式 rebase 修改多个 commit

# 修改最近 3 个 commit
git rebase -i HEAD~3

# 在编辑器中,将要修改的 commit 前的 "pick" 改为 "reword"
# 保存后,Git 会逐个提示修改 commit message

方法3:使用 filter-branch(不推荐,复杂)

对于大量 commit 需要修改的情况,可以使用 git filter-branch,但操作复杂,建议谨慎使用。

预防措施

  1. 使用 UTF-8 编码的编辑器:确保你的代码编辑器(如 VS Code)使用 UTF-8 编码保存文件
  2. 设置 Git 编辑器编码:如果使用自定义编辑器,确保编辑器也使用 UTF-8
  3. 检查 .gitattributes:可以在项目中添加 .gitattributes 文件,指定文件编码:
*.txt text encoding=utf-8
*.md text encoding=utf-8
*.c text encoding=utf-8
*.h text encoding=utf-8

注意事项

  • 修改已 push 的 commit message 需要使用 --force push,这会影响其他协作者
  • 如果是团队项目,修改 commit message 前应该与团队沟通
  • 建议在项目开始时就配置好编码设置,避免后续问题

相关链接