Open1

UTF-8以外の文字コードのファイルでgit diffを出したい

catatsuycatatsuy

未だにUTF-8をまともに扱えないOSがあるので、そういうOSを触る時のtipsです。

日本語に限定すればnkfが自動で文字コードを判定できるので以下のようなスクリプトを実行する。

generate_gitattributes_nkf.sh
#!/bin/bash

# 出力先の .gitattributes ファイルを初期化
echo "# Auto-generated .gitattributes based on file encoding" > .gitattributes

# リポジトリ内のすべてのファイルを走査
for file in $(git ls-files); do
    # ファイルのエンコーディングを判別 (nkf --guess を使用)
    encoding=$(nkf --guess "$file")

    # エンコーディングに応じて .gitattributes に追加
    if echo "$encoding" | grep -q 'Shift_JIS'; then
        echo "$file diff=sjis" >> .gitattributes
    fi
done

echo ".gitattributes generated successfully!"

そうすると.gitattributesに色々書き込まれるので、以下の設定をする。

git config diff.sjis.textconv "iconv -f sjis"

もちろんnkfでも良いが、iconvなら大抵プリインストールされているのでiconvの方が便利。

これでgit diffの時にiconvで文字コードを変換できる。