Gitで現在のブランチ一覧を表示する
最近グダグダと前置きが長いので、さらっと解説します。
ブランチを列挙する場合は
git branch コマンドです。
現在のカレントブランチを得るには
git rev-parse --abbrev-ref HEAD コマンドです。
下記のコントロールを Form1 に配置してください
textBox1: git コマンドを実行するディレクトリを指定
listBox1: git の実行結果を表示
button1: ブランチを列挙する
button2: カレントブランチ(アクティブブランチ)を表示する
using System;
using System.Collections.Generic;
using System.Diagnostics;
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/my_project";
button1.Text = "branch all";
button2.Text = "branch current";
}
private void button1_Click( object sender, EventArgs e )
{
// ブランチコマンドで列挙する.
const String ARGV = "branch";
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 void button2_Click( object sender, EventArgs e )
{
// カレントブランチだけ表示する.
const String ARGV = "rev-parse --abbrev-ref HEAD";
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;
}
}
}