UnityのC#からGitを叩く
UnityのC#のEditor拡張スクリプトからGitコマンドを叩く機会があったので、忘れないうちにまとめます。
サンプルコマンド
今回、例として、UnityのC#から以下のコマンドを叩いてみます。
git config core.autocrlf
改行コードを自動で変換する機能が有効になっているか確認できるコマンドです。
サンプルコード
以下がサンプルコードです。外部から GetAutocrlf
を叩けばコマンドが実行されます。
usingSystem;usingSystem.Diagnostics;usingSystem.IO;usingUnityEditor;usingUnityEngine;usingDebug=UnityEngine.Debug;publicclassGitCommandPractice{/// <summary>/// Gitのautocrlfを確認する。/// </summary>publicvoidGetAutocrlf(){// gitのパスを取得する。stringgitPath=GetGitPath();// gitのコマンドを設定する。stringgitCommand="config core.autocrlf";// コマンドを実行して標準出力を取得する。stringautocrlf=GetStandardOutputFromProcess(gitPath,gitCommand).Trim();Debug.Log(autocrlf);}/// <summary>/// Gitの実行ファイルのパスを取得する。/// </summary>/// <returns>Gitのパス</returns>privatestringGetGitPath(){// Macのときif(Application.platform==RuntimePlatform.OSXEditor){// パスの候補string[]exePaths={"/usr/local/bin/git","/usr/bin/git"};// 存在するパスで最初に見つかったものreturnexePaths.FirstOrDefault(exePath=>File.Exists(exePath));}// Windowsはこれだけで十分return"git";}/// <summary>/// コマンドを実行して標準出力を取得する。/// </summary>/// <param name="exePath">実行ファイルのパス</param>/// <param name="arguments">コマンドライン引数</param>/// <returns>標準出力</returns>privatestringGetStandardOutputFromProcess(stringexePath,stringarguments){// プロセスの起動条件を設定する。ProcessStartInfostartInfo=newProcessStartInfo(){FileName=exePath,Arguments=arguments,WindowStyle=ProcessWindowStyle.Hidden,UseShellExecute=false,RedirectStandardOutput=true,};// プロセスを起動する。using(Processprocess=Process.Start(startInfo)){// 標準出力を取得する。stringoutput=process.StandardOutput.ReadToEnd();// プロセスが終了するかタイムアウトするまで待つ。process.WaitForExit(TimeoutPeriod);returnoutput;}}}
解説
C# の Prosess
を使って、Gitコマンドを叩き、その標準出力を読み取るという仕組みです。
GetGitPath()
では、Gitの実行ファイルのパスを取得しています。
Gitの実行ファイルのパスは、環境変数Pathに登録されていることが一般的だと思うので、単に git
と記述してもほとんどの場合、問題ないと思います。
ただし、私のMac環境ではそれではうまく行かなかったので、 /usr/local/bin/git
と usr/bin/git
の2種類を明示的にハードコーディングし、どちらか見つかった方を実行ファイルとして利用するようにしました。
さいごに
本記事作成にあたり、以下を参考にしました。ありがとうございました。