LoginSignup
2
0

More than 3 years have passed since last update.

UnityのC#からGitを叩く

Last updated at Posted at 2020-08-05

UnityのC#からGitを叩く

UnityのC#のEditor拡張スクリプトからGitコマンドを叩く機会があったので、忘れない内にまとめます。

サンプルコマンド

今回、例として、UnityのC#から以下のコマンドを叩いてみます。

git config core.autocrlf

改行コードを自動で変換する機能が有効になっているか確認できるコマンドです。

サンプルコード

以下がサンプルコードです。外部から GetAutocrlf を叩けばコマンドが実行されます。

using System;
using System.Diagnostics;
using System.IO;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class GitCommandPractice
{
    /// <summary>
    /// Gitのautocrlfを確認する。
    /// </summary>
    public void GetAutocrlf()
    {
        // gitのパスを取得する。
        string gitPath = GetGitPath();

        // gitのコマンドを設定する。
        string gitCommand = "config core.autocrlf";

        // コマンドを実行して標準出力を取得する。
        string autocrlf = GetStandardOutputFromProcess(gitPath, gitCommand).Trim();

        Debug.Log(autocrlf);
    }

    /// <summary>
    /// Gitの実行ファイルのパスを取得する。
    /// </summary>
    /// <returns>Gitのパス</returns>
    private string GetGitPath()
    {
        // Macのとき
        if (Application.platform == RuntimePlatform.OSXEditor)
        {
            // パスの候補
            string[] exePaths =
            {
                "/usr/local/bin/git",
                "/usr/bin/git"
            };

            // 存在するパスで最初に見つかったもの
            return exePaths.FirstOrDefault(exePath => File.Exists(exePath));
        }

        // Windowsはこれだけで十分
        return "git";
    }

    /// <summary>
    /// コマンドを実行して標準出力を取得する。
    /// </summary>
    /// <param name="exePath">実行ファイルのパス</param>
    /// <param name="arguments">コマンドライン引数</param>
    /// <returns>標準出力</returns>
    private string GetStandardOutputFromProcess(string exePath, string arguments)
    {
        // プロセスの起動条件を設定する。
        ProcessStartInfo startInfo = new ProcessStartInfo()
        {
            FileName = exePath,
            Arguments = arguments,
            WindowStyle = ProcessWindowStyle.Hidden,
            UseShellExecute = false,
            RedirectStandardOutput = true,
        };

        // プロセスを起動する。
        using (Process process = Process.Start(startInfo))
        {
            // 標準出力を取得する。
            string output = process.StandardOutput.ReadToEnd();

            // プロセスが終了するかタイムアウトするまで待つ。
            process.WaitForExit(TimeoutPeriod);

            return output;
        }
    }
}

解説

C# の Prosess を使って、Gitコマンドを叩き、その標準出力を読み取るという仕組みです。

GetGitPath() では、Gitの実行ファイルのパスを取得しています。

Gitの実行ファイルのパスは、環境変数Pathに登録されていることが一般的だと思うので、単に git と記述してもほとんどの場合、問題ないと思います。

ただし、私のMac環境ではそれではうまく行かなかったので、 /usr/local/bin/gitusr/bin/git の2種類を明示的にハードコーディングし、どちらか見つかった方を実行ファイルとして利用するようにしました。

さいごに

本記事作成にあたり、以下を参考にしました。ありがとうございました。

2
0
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
2
0