Popen()の応用

IDE等の内部から外部コマンドとしてgit commandを発行して、結果を得る

以前の記事で取り上げたPopen()の応用になります。

まずはフォームを示します。

TMemox1,TLabelx2,TEditx1をフォームに上図のような感じで配置します。Edit1の初期文字列は、”status”等で良いです。次にプロジェクトの構成は、

このようにして、popen.cppとpopen.hを含めておきます。それぞれのファイルは前記事から。さて、Unit1.cppは、

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <System.IOUtils.hpp>
#include <Clipbrd.hpp>
#include <iostream>
#include <sstream>
#include <System.StrUtils.hpp>
#include "popen.h"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
	AnsiString target;

	if( ParamCount() > 0 ){
		target = TPath::GetDirectoryName(ParamStr(1));
	}
	else
		target = GetCurrentDir();


	Label1->Caption = target;

	ChDir(target);
	Memo1->Lines->Clear();



}

void __fastcall TForm1::DoItClick(TObject *Sender)
{

	DWORD   retcode;
	String rtn;
	String command = "git";

	String args = Edit1->Text;

	rtn = Popen(command,args,retcode);
	Memo1->Lines->Clear();
	Label2->Caption = IntToStr((int)retcode);
	TStringDynArray array = SplitString(rtn,"\n");

   for (int i = 0; i < array.Length; ++i)
	Memo1->Lines->Add(array[i].c_str()); // OK

}
//---------------------------------------------------------------------------

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{

	if( Key == VK_RETURN ){
		//Button1Click(Sender);
		DoItClick(Sender);
		Key = 0;
	}



}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormShow(TObject *Sender)
{
 Edit1->SetFocus();
}
//---------------------------------------------------------------------------

buildして起動する前に、このプログラムはC++ BuilderのIDEやVisual StudioのIDEから外部ツールとして起動することを想定していますので、まず組み込み型を提示しておきます。まずbuildして出来たバイナリの場所を調べておきます。IDEのトップメニューから、

ツールの構成を選択。

ここで追加。

タイトル Git Commandを入れ、プログラムの場所、作業ディレクトリの場所を”参照”からたどり、パラメータは、マクロを開いて下図のように現在のプロジェクト名を選択後、挿入して、

こうした上で、”OK”をクリック。

ここで忘れずに、”閉じる”を選択。このように設定しておくと、IDEから

こうして起動した時に、起動コマンドラインに付加的にプロジェクトの場所がフルパスで指定されます。ので、

	AnsiString target;

	if( ParamCount() > 0 ){
		target = TPath::GetDirectoryName(ParamStr(1));
	}
	else
		target = GetCurrentDir();


	Label1->Caption = target;

	ChDir(target);

コンストラクタでChDir(target)します。このプログラムでは、git 云々の云々部分のみを入力しリターンを打つだけで、そのgit commandを実行して結果が表示されます。使ってみましょう。git initされているプロジェクトを開いて、

から、

ここでそのままリターンキーを叩くと、

これが普通の状態です。commit忘れとかあれば、そう表示されます。statusをremote -vとすると、

ここでリターンキー押すと、

remote repositoryが表示されます。同様な仕組みでremote repositoryのlist delete create migrateが可能なユーティリティー(remote repository manager)がありますので、随時紹介します。(復刻でした)

コメント