LoginSignup
5
5

More than 5 years have passed since last update.

ソースコード修正時にファイルエンコーディングがBOM付きUTF-8かどうかをチェックする

Last updated at Posted at 2014-07-30

どうやら OS X の MonoDevelop でリファクタリング機能を使うと、BOM付きUTF-8がBOM無しで保存されるらしい。
そのままの状態でプロジェクトのリポジトリにコミットしてしまうとWindowsな人から苦情が来るのでコミット前にチェックできるようにしてみた。(ほんとはSVNサーバ側Hookしてコミットさせないのが良いんでしょうね...)

AssetPostprocessorでソースコードの変更を監視して、BOM無しでソースコードが保存された場合にダイアログボックスを表示するエディタ拡張を作ってみた。

SourceFileEncodingChecker.cs
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;

public class SourceFileEcodingChecker : AssetPostprocessor {
    static Regex m_SourceFilePattern;

    static SourceFileEcodingChecker() {
        m_SourceFilePattern = new Regex(@".+\.cs");
    }

    static void OnPostprocessAllAssets(
        string[] importedAssets,
        string[] deletedAssets,
        string[] movedAssets,
        string[] movedFromAssetPaths) {

        var invalidFiles = new List<string>();

        foreach (var importedAsset in importedAssets) {
            if (m_SourceFilePattern.IsMatch(importedAsset)) {
                var dataPath = Application.dataPath;
                dataPath = dataPath.Substring(0, dataPath.Length - 7);

                var path = System.IO.Path.Combine(dataPath, importedAsset);

                Debug.Log ("*** import: " + path);

                using(FileStream fs = File.OpenRead(path)) {
                    var head = new byte[3];
                    fs.Read (head, 0, 3);
                    var headStr = System.BitConverter.ToString(head);
                    Debug.Log (headStr);
                    if (headStr != "EF-BB-BF") {
                        invalidFiles.Add(path);
                    }
                    fs.Close ();
                }
            }
        }

        if (invalidFiles.Count > 0) {
            EditorUtility.DisplayDialog(
                "File encoding check error", 
                string.Join ("\n",invalidFiles.ToArray ()),
                "OK"
            );
        }
    }
}

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5