Gitでチェックアウトする

最近は前置きが長かったので、今回はサッサとチェックアウトのコードを示します。

textBox1: 対象のプロジェクトのディレクトリ
textBox2: チェックアウトするハッシュ
listBox1: 実行結果を表示するリストボックス
button1: ログを表示表示する
button2: 指定されたハッシュにチェックアウトする

チェックアウトに成功しても UNIX 的にダンマリですので、なにも listBox1 に表示されません。それが正しい成功動作です。button2 押した直後に button1 を押してチェックアウトされたか確認してください。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace aaa
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load( object sender, EventArgs e )
		{

			// ここをあなたの環境にあわせてください.
			textBox1.Text = "c:/develop/the_project";

			// ハッシュの初期値.
			textBox2.Text = "abcd012";

			button1.Text = "log";
			button2.Text = "checkout";

		}

		private void button1_Click( object sender, EventArgs e )
		{

			String dir_working = textBox1.Text.Trim();

			const String ARGV = "log --pretty=format:\"%h %ad %s\" --date=format:\"%Y/%m/%d_%H:%M:%S\"";
			// const String ARGV = "log --oneline"; // 日付まで不要ならこちらでもいい.

			List<String> retout = ExecGitCommand( ARGV, dir_working );

			listBox1.Items.Clear();

			for ( int k = 0; k < retout.Count; k++ )
			{
				listBox1.Items.Add( retout[k] );
			}

		}

		private void button2_Click( object sender, EventArgs e )
		{


			String hash = textBox2.Text.Trim();

			if ( hash.Length < 4 )
			{
				StringBuilder sb = new StringBuilder();
				sb.AppendLine( "ハッシュの文字数は最低4文字以上必要です." );
				sb.AppendLine( "(履歴でハッシュの重複がある場合はそれ以上の文字数が必要です)" );
				MessageBox.Show( sb.ToString().Trim() );
				return; // warning.
			}

			// チェックアウトを実行する.
			String argv = $"checkout {hash}";
			String dir_working = textBox1.Text.Trim();
			List<String> retout = ExecGitCommand( argv, dir_working );

			listBox1.Items.Clear();

			for ( int k = 0; k < retout.Count; k++ )
			{
				listBox1.Items.Add( retout[k] );
			}

		}

		private List<string> ExecGitCommand( string arguments, string working_directory )
		{

			ProcessStartInfo psi = new ProcessStartInfo();
			psi.FileName               = "git";
			psi.Arguments              = arguments;
			psi.WorkingDirectory       = working_directory;
			psi.RedirectStandardOutput = true;
			psi.RedirectStandardError  = true;
			psi.StandardOutputEncoding = Encoding.UTF8; // ここを指定しないと日本語は文字化けする.
			psi.StandardErrorEncoding  = Encoding.UTF8; // ここを指定しないと日本語は文字化けする.
			psi.UseShellExecute        = false;
			psi.CreateNoWindow         = true;

			List<String> output = new List<string>();

			try
			{

				using ( Process proc = Process.Start( psi ) )
				{

					while ( !proc.StandardOutput.EndOfStream )
					{
						output.Add( proc.StandardOutput.ReadLine() );
					}

					string err = proc.StandardError.ReadToEnd();
					proc.WaitForExit();

					if ( proc.ExitCode != 0 )
					{
						throw new Exception( err );
					}

				}

			}
			catch ( Exception excp )
			{
				output.Add( excp.Message );
			}

			return output;

		}
	}
}