如何更改 Git 提交的编码 header?

How to change a Git commit's encoding header?

Git 中是否有重写 commit encoding header 的方法?我有一些带有 author name 的提交,它具有 ISO-8859-1 编码名称,但提交编码 header 是空的,默认为 UTF-8。这会导致一些应用程序在解码提交时出错(例如 Gitlab)。这同样适用于一些提交消息。

一些想法?

测试(使用 git 2.2.0)表明,每当您使用 [=12= 进行新提交时,git commit 都会将 encoding <blah> 添加到提交 headers ].这包括 "amended" 提交——它们只是 parent(s) is/are HEAD 的 parent(s) 的新提交——因此,给定一个现有提交您希望将其标记为 HEAD,只需 运行 git commit --amend 并退出编辑器以编写一个新的(不同的)HEAD 提交并附加 header行。

我没有测试 git rebase -i 但因为 运行 实际 cherry-pick 操作,并且 edit 模式允许您使用 git commit --amend 来制作新 HEAD 提交,它肯定会起作用。机械师可能不是最漂亮的。

要查看原始提交(包括其编码行),请使用 git cat-file -p HEAD(或其他 commit-ID 代替 HEAD)。

(如 eis 所述 in a comment,首先使用 UTF-8 可能更好。您当然可以在修改过程中执行此操作,尽管它可能会或可能不会很棘手,具体取决于在你的编辑器上。)

这样解决的:

$ git filter-branch -f --commit-filter '
author_type=$( echo $GIT_AUTHOR_NAME | file -b --mime-encoding - )
author=$( echo $GIT_AUTHOR_NAME | iconv -f $author_type -t UTF-8 )
GIT_AUTHOR_NAME=$author

committer_type=$( echo $GIT_COMMITTER_NAME | file -b --mime-encoding - )
committer=$( echo $GIT_COMMITTER_NAME | iconv -f $committer_type -t UTF-8 )
GIT_COMMITTER_NAME=$committer

git commit-tree "$@";' --msg-filter '
cat > .commitmsg
type=$(cat .commitmsg|file -b --mime-encoding -)
cat .commitmsg|iconv -f $type -t UTF-8
' HEAD

$ rm -f .commitmsg

如果提交消息真的一团糟并且 Sascha 的解决方案不起作用(因为 file -b --mime-encoding - 没有说实话),可以使用以下方法删除提交消息中的每个字符不是 ASCII:

git filter-branch --msg-filter '
  perl -pe 's/[^[:ascii:]]//g;'
  ' HEAD

显然,这远非完美,因为它会杀死各种非英语字符,如变音符号,但在某些情况下(即 git-repo 是从旧的 cvs-repo 产生的,编码非常糟糕提交消息)它可能是唯一的自动解决方案。