DoboWiki
Top
> .NETプログラミング研究/110 をテンプレートにして作成
.NETプログラミング研究/110 をテンプレートにして作成
開始行:
*Command Line Parser Libraryを使ってコマンドライン引数を...
前々回、前回と、コマンドライン引数を解析する機能を提供す...
**解析できなかった時や「--help」オプションが指定された時...
コマンドライン引数の解析に失敗した時、自動的に指定したメ...
さらにこのメッセージは、アプリケーションに「--help」オプ...
例えばOptionsクラスに以下のようなGetUsageメソッドを追加す...
#code(vbnet){{
'オプションをプロパティに持つクラス
Public Class Options
<CommandLine.Option("o"c)> _
Public Property OutputFile As String
<CommandLine.Option("v"c)> _
Public Property Overwrite As Boolean
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Return "コマンドラインオプションの記述が正しくあ...
End Function
End Class
}}
#code(csharp){{
//オプションをプロパティに持つクラス
public class Options
{
[CommandLine.Option('o')]
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v')]
public bool Overwrite
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
return "コマンドラインオプションの記述が正しくあ...
}
}
}}
#column(注意){{
前述したように、新しく作成したParserオブジェクトを使って...
}}
#column(補足){{
GetUsageメソッドがなくても、解析に失敗した時(あるいは「-...
さらにParseArgumentsStrictメソッドは、3番目の引数がない場...
}}
**オプションの説明文を作成する [#g46c36e2]
通常のコンソールアプリケーションでは、「/?」のようなオプ...
そのための準備として、Option属性のHelpTextプロパティを使...
このようにしておけば、HelpTextクラスのAddOptionsメソッド...
このようにして、使用法とオプションの説明を表示する例を示...
#code(vbnet){{
Public Class Options
<CommandLine.Option("o"c, "output", Required:=True, _
HelpText:="出力先のファイル名", MetaValue:="ファ...
Public Property OutputFile As String
<CommandLine.Option("v"c, HelpText:="ファイルを上書き...
Public Property Overwrite As Boolean
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Dim help = New CommandLine.Text.HelpText()
'オプションの前にダッシュをつける(これがないとダ...
help.AddDashesToOption = True
'オプションの説明の前に表示する文字列を追加
help.AddPreOptionsLine("使用法: TestApp -o ファイ...
help.AddPreOptionsLine("")
help.AddPreOptionsLine("オプション:")
'オプションの説明を追加。"[必須]"を省略すると、
' 必須オプションの説明の前に付く文字列が"Require...
help.AddOptions(Me, "[必須]")
'オプションの説明の後に表示する文字列を追加
help.AddPostOptionsLine("詳しくは、ヘルプをご覧く...
help.AddPostOptionsLine("")
Return help
End Function
End Class
}}
#code(csharp){{
public class Options
{
[CommandLine.Option('o', "output", Required = true,
HelpText = "出力先のファイル名", MetaValue = "フ...
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v', HelpText="ファイルを上書き保...
public bool Overwrite
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
var help = new CommandLine.Text.HelpText();
//オプションの前にダッシュをつける(これがないと...
help.AddDashesToOption = true;
//オプションの説明の前に表示する文字列を追加
help.AddPreOptionsLine("使用法: TestApp -o ファイ...
help.AddPreOptionsLine("");
help.AddPreOptionsLine("オプション:");
//オプションの説明を追加。"[必須]"を省略すると、
// 必須オプションの説明の前に付く文字列が"Requir...
help.AddOptions(this, "[必須]");
//オプションの説明の後に表示する文字列を追加
help.AddPostOptionsLine("詳しくは、ヘルプをご覧く...
help.AddPostOptionsLine("");
return help;
}
}
}}
このようにすると、解析に失敗した時、以下のように表示され...
#pre{{
使用法: TestApp -o ファイル [-v]
オプション:
-o ファイル, --output=ファイル [必須] 出力先のファイ...
-v ファイルを上書き保存する
--help Display this help screen.
詳しくは、ヘルプをご覧ください。
}}
**ヘルプを表示するオプションを「--help」以外にする [#p48b...
「--help」というオプションによってもGetUsageが返すメッセ...
さらに、HelpOptionもHelpTextプロパティによって、「--help...
例えばGetUsageメソッドに適用するHelpOption属性を次のよう...
#code(vbnet){{
<CommandLine.HelpOption("?"c, HelpText:="この説明画面を表...
Public Function GetUsage() As String
}}
#code(csharp){{
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption('?' , HelpText="この説明画面を表...
public string GetUsage()
}}
するとメッセージは「-?」で表示できて「--help」では表示で...
#pre{{
使用法: TestApp -o ファイル [-v]
オプション:
-o ファイル, --output=ファイル [必須] 出力先のファイ...
-v ファイルを上書き保存する
-? この説明画面を表示します
詳しくは、ヘルプをご覧ください。
}}
**エラーの理由によって表示するメッセージを変える [#ib905b...
Optionsクラスに、ParserState属性を適用したIParserStateの...
さらに、エラーがあった時は、HelpText.RenderParsingErrorsT...
これらを使用した例を以下に示します。
#code(vbnet){{
'オプションをプロパティに持つクラス
Public Class Options
<CommandLine.Option("o"c, "output", Required:=True, _
HelpText:="出力先のファイル名", MetaValue:="ファ...
Public Property OutputFile As String
<CommandLine.Option("v"c, HelpText:="ファイルを上書き...
Public Property Overwrite As Boolean
<CommandLine.Option("s"c, HelpText:="出力するファイル...
MetaValue:="サイズ")> _
Public Property Size As Integer
<CommandLine.ParserState> _
Public Property LastParserState As CommandLine.IParse...
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Dim help = New CommandLine.Text.HelpText()
help.AddDashesToOption = True
If Me.LastParserState Is Nothing Then
'--help オプションで表示される時?
help.AddPreOptionsLine("使用できるオプション...
ElseIf Me.LastParserState.Errors IsNot Nothing An...
Me.LastParserState.Errors.Count > 0 Then
'エラーがあった時
'エラーメッセージを取得する。インデントは2と...
Dim errMsg As String = help.RenderParsingErro...
help.AddPreOptionsLine(errMsg)
Else
'不明なオプションが指定されている時?
help.AddPreOptionsLine("理解できないオプショ...
help.AddPreOptionsLine("以下に使用できるオプ...
End If
'オプションの説明を追加
help.AddOptions(Me)
'オプションの説明の後に改行を入れる
help.AddPostOptionsLine("")
Return help
End Function
End Class
}}
#code(csharp){{
//オプションをプロパティに持つクラス
public class Options
{
[CommandLine.Option('o', "output", Required = true,
HelpText = "出力先のファイル名", MetaValue = "フ...
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v', HelpText = "ファイルを上書き...
public bool Overwrite
{
get;
set;
}
[CommandLine.Option('s',
HelpText = "出力するファイルのサイズ", MetaValue ...
public int Size
{
get;
set;
}
[CommandLine.ParserState]
public CommandLine.IParserState LastParserState
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
var help = new CommandLine.Text.HelpText();
help.AddDashesToOption = true;
if (this.LastParserState == null)
{
//--help オプションで表示される時?
help.AddPreOptionsLine("使用できるオプション...
}
else if (this.LastParserState.Errors != null &&
this.LastParserState.Errors.Count > 0)
{
//エラーがあった時
//エラーメッセージを取得する。インデントは2と...
string errMsg = help.RenderParsingErrorsText(...
help.AddPreOptionsLine(errMsg);
}
else
{
//不明なオプションが指定されている時?
help.AddPreOptionsLine("理解できないオプショ...
help.AddPreOptionsLine("以下に使用できるオプ...
}
//オプションの説明を追加
help.AddOptions(this);
//オプションの説明の後に改行を入れる
help.AddPostOptionsLine("");
return help;
}
}
}}
上記のコードで、必須オプションの欠落とフォーマットのエラ...
#pre{{
-s option violates format.
-o/--output required option is missing.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
さらに説明を補足します。上記の例では、エラーの原因が「thi...
「this.LastParserState.Errors」はParsingErrorオブジェクト...
また、ParsingErrorオブジェクトのBadOptionプロパティによっ...
これらを駆使してエラーメッセージを自分で作成することがで...
**自動でメッセージを作成する最も簡単な方法 [#j05d9e29]
HelpText.AutoBuildとHelpText.DefaultParsingErrorsHandler...
#code(vbnet){{
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
'メッセージを自動的に作成する
Return CommandLine.Text.HelpText.AutoBuild(Me, _
Sub(current) CommandLine.Text.HelpText.DefaultPar...
Me, current))
End Function
}}
#code(csharp){{
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
//メッセージを自動的に作成する
return CommandLine.Text.HelpText.AutoBuild(this, curr...
CommandLine.Text.HelpText.DefaultParsingErrorsHan...
}
}}
このようにした時に表示されるメッセージは、例えば次によう...
#pre{{
TestApplication 1.0.0.0
Copyright c 2013 DOBON!
ERROR(S):
-s option violates format.
-o/--output required option is missing.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
この中で、「TestApplication」というのはアプリケーションの...
#column(補足){{
このようなアプリケーションのタイトルとバージョンの説明はH...
}}
さらに、「AssemblyInfo.cs」(VB.NETでは「AssemblyInfo.vb...
例えばAssemblyInfo.csに次のような記述を追加したとします。
#code(vbnet){{
<Assembly: CommandLine.AssemblyLicense( _
"このアプリケーションは、MITライセンスで公開します。"...
"The MIT License (MIT) <http://opensource.org/license...
<Assembly: CommandLine.AssemblyUsage( _
"使用法: TestApp -o ファイル [-v] [-s サイズ]", _
" TestApp --output=ファイル")>
}}
#code(csharp){{
[assembly: CommandLine.AssemblyLicense(
"このアプリケーションは、MITライセンスで公開します。",
"The MIT License (MIT) <http://opensource.org/license...
[assembly: CommandLine.AssemblyUsage(
"使用法: TestApp -o ファイル [-v] [-s サイズ]",
" TestApp --output=ファイル")]
}}
するとエラーメッセージは、次のように変わります。
#pre{{
TestApplication 1.0.0.0
Copyright c 2013 DOBON!
ERROR(S):
-s option violates format.
-o/--output required option is missing.
このアプリケーションは、MITライセンスで公開します。
The MIT License (MIT) <http://opensource.org/licenses/mit...
使用法: TestApp -o ファイル [-v] [-s サイズ]
TestApp --output=ファイル
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
**エラーメッセージを日本語にする [#n1c08a14]
RenderParsingErrorsTextやAutoBuild(DefaultParsingErrorsH...
まず以下のようなBaseSentenceBuilderの派生クラス「Japanese...
#code(vbnet){{
Public Class JapaneseSentenceBuilder
Inherits CommandLine.Text.BaseSentenceBuilder
Public Overrides ReadOnly Property AndWord() As String
Get
Return "且つ"
End Get
End Property
Public Overrides ReadOnly Property ErrorsHeadingText(...
Get
Return "エラー:"
End Get
End Property
Public Overrides ReadOnly Property OptionWord() As St...
Get
Return "オプション"
End Get
End Property
Public Overrides ReadOnly Property RequiredOptionMiss...
Get
Return "必須のオプションが指定されていません"
End Get
End Property
Public Overrides ReadOnly Property ViolatesFormatText...
Get
Return "書式が正しくありません"
End Get
End Property
Public Overrides ReadOnly Property ViolatesMutualExcl...
Get
Return "一緒に使用できないオプションが使われ...
End Get
End Property
End Class
}}
#code(csharp){{
public class JapaneseSentenceBuilder : CommandLine.Text.B...
{
public override string AndWord
{
get { return "且つ"; }
}
public override string ErrorsHeadingText
{
get { return "エラー:"; }
}
public override string OptionWord
{
get { return "オプション"; }
}
public override string RequiredOptionMissingText
{
get { return "必須のオプションが指定されていませ...
}
public override string ViolatesFormatText
{
get { return "書式が正しくありません"; }
}
public override string ViolatesMutualExclusivenessText
{
get { return "一緒に使用できないオプションが使わ...
}
}
}}
このクラスを使えば、RenderParsingErrorsTextやDefaultParsi...
それでもあえてAutoBuildを使う場合は、例えば以下のような方...
#code(vbnet){{
<CommandLine.HelpOption> _
Public Function GetUsage() As String
'エラーメッセージのないメッセージを作成
Dim help = CommandLine.Text.HelpText.AutoBuild(Me)
'日本語のエラーメッセージを作成
Dim jhelp = New CommandLine.Text.HelpText(New Japanes...
CommandLine.Text.HelpText.DefaultParsingErrorsHandler...
'日本語のエラーメッセージを追加
help.AddPreOptionsLine(jhelp)
Return help
End Function
}}
#code(csharp){{
[CommandLine.HelpOption]
public string GetUsage()
{
//エラーメッセージのないメッセージを作成
var help = CommandLine.Text.HelpText.AutoBuild(this);
//日本語のエラーメッセージを作成
var jhelp = new CommandLine.Text.HelpText(new Japanes...
CommandLine.Text.HelpText.DefaultParsingErrorsHandler...
//日本語のエラーメッセージを追加
help.AddPreOptionsLine(jhelp);
return help;
}
}}
すると、エラーメッセージは以下のようになります。
#pre{{
TestApplication 1.0.0.0
Copyright c 2013
このアプリケーションは、MITライセンスで公開します。
The MIT License (MIT) <http://opensource.org/licenses/mit...
使用法: TestApp -o ファイル [-v] [-s サイズ]
TestApp --output=ファイル
エラー:
-s オプション 書式が正しくありません.
-o/--output 必須のオプションが指定されていません.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
エラーメッセージが表示される位置が変わりましたが、エラー...
**メッセージをコンソール以外に表示する [#u623bf1d]
前に触れましたが、ParserクラスのHelpWriterプロパティによ...
Parser.DefaultのHelpWriterはConsole.Errorなので、標準エラ...
コンソールアプリケーションであれば標準エラー出力ストリー...
以下にその例を示します。
#code(vbnet){{
Module Module1
'エントリポイント
Sub Main(args As String())
'Optionsクラスのインスタンスを作成
Dim opts = New Options()
'メッセージを書き込むStringWriterを作成
Dim sw = New System.IO.StringWriter()
'Parserを作成して、HelpWriterをStringWriterに変更
Dim p = New CommandLine.Parser(Sub(w) w.HelpWrite...
'コマンドライン引数を解析する
Dim isSuccess As Boolean = p.ParseArguments(args,...
'メッセージを取得する
sw.Close()
Dim helpMsg As String = sw.ToString()
'メッセージがある時は、表示する
If Not String.IsNullOrEmpty(helpMsg) Then
Console.WriteLine(helpMsg)
End If
Console.ReadLine()
End Sub
End Module
}}
#code(csharp){{
//エントリポイント
static void Main(string[] args)
{
//Optionsクラスのインスタンスを作成
var opts = new Options();
//メッセージを書き込むStringWriterを作成
var sw = new System.IO.StringWriter();
//Parserを作成して、HelpWriterをStringWriterに変更
var p = new CommandLine.Parser(with => with.HelpWrite...
//コマンドライン引数を解析する
bool isSuccess = p.ParseArguments(args, opts);
//メッセージを取得する
sw.Close();
string helpMsg = sw.ToString();
//メッセージがある時は、表示する
if (!string.IsNullOrEmpty(helpMsg))
{
Console.WriteLine(helpMsg);
}
Console.ReadLine();
}
}}
**最後に [#m74d80ce]
Command Line Parser Libraryについて長々と説明してきました...
//これより下は編集しないでください
#pageinfo(,2013-04-22 (月) 01:36:11,DOBON!,2013-04-22 (月...
終了行:
*Command Line Parser Libraryを使ってコマンドライン引数を...
前々回、前回と、コマンドライン引数を解析する機能を提供す...
**解析できなかった時や「--help」オプションが指定された時...
コマンドライン引数の解析に失敗した時、自動的に指定したメ...
さらにこのメッセージは、アプリケーションに「--help」オプ...
例えばOptionsクラスに以下のようなGetUsageメソッドを追加す...
#code(vbnet){{
'オプションをプロパティに持つクラス
Public Class Options
<CommandLine.Option("o"c)> _
Public Property OutputFile As String
<CommandLine.Option("v"c)> _
Public Property Overwrite As Boolean
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Return "コマンドラインオプションの記述が正しくあ...
End Function
End Class
}}
#code(csharp){{
//オプションをプロパティに持つクラス
public class Options
{
[CommandLine.Option('o')]
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v')]
public bool Overwrite
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
return "コマンドラインオプションの記述が正しくあ...
}
}
}}
#column(注意){{
前述したように、新しく作成したParserオブジェクトを使って...
}}
#column(補足){{
GetUsageメソッドがなくても、解析に失敗した時(あるいは「-...
さらにParseArgumentsStrictメソッドは、3番目の引数がない場...
}}
**オプションの説明文を作成する [#g46c36e2]
通常のコンソールアプリケーションでは、「/?」のようなオプ...
そのための準備として、Option属性のHelpTextプロパティを使...
このようにしておけば、HelpTextクラスのAddOptionsメソッド...
このようにして、使用法とオプションの説明を表示する例を示...
#code(vbnet){{
Public Class Options
<CommandLine.Option("o"c, "output", Required:=True, _
HelpText:="出力先のファイル名", MetaValue:="ファ...
Public Property OutputFile As String
<CommandLine.Option("v"c, HelpText:="ファイルを上書き...
Public Property Overwrite As Boolean
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Dim help = New CommandLine.Text.HelpText()
'オプションの前にダッシュをつける(これがないとダ...
help.AddDashesToOption = True
'オプションの説明の前に表示する文字列を追加
help.AddPreOptionsLine("使用法: TestApp -o ファイ...
help.AddPreOptionsLine("")
help.AddPreOptionsLine("オプション:")
'オプションの説明を追加。"[必須]"を省略すると、
' 必須オプションの説明の前に付く文字列が"Require...
help.AddOptions(Me, "[必須]")
'オプションの説明の後に表示する文字列を追加
help.AddPostOptionsLine("詳しくは、ヘルプをご覧く...
help.AddPostOptionsLine("")
Return help
End Function
End Class
}}
#code(csharp){{
public class Options
{
[CommandLine.Option('o', "output", Required = true,
HelpText = "出力先のファイル名", MetaValue = "フ...
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v', HelpText="ファイルを上書き保...
public bool Overwrite
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
var help = new CommandLine.Text.HelpText();
//オプションの前にダッシュをつける(これがないと...
help.AddDashesToOption = true;
//オプションの説明の前に表示する文字列を追加
help.AddPreOptionsLine("使用法: TestApp -o ファイ...
help.AddPreOptionsLine("");
help.AddPreOptionsLine("オプション:");
//オプションの説明を追加。"[必須]"を省略すると、
// 必須オプションの説明の前に付く文字列が"Requir...
help.AddOptions(this, "[必須]");
//オプションの説明の後に表示する文字列を追加
help.AddPostOptionsLine("詳しくは、ヘルプをご覧く...
help.AddPostOptionsLine("");
return help;
}
}
}}
このようにすると、解析に失敗した時、以下のように表示され...
#pre{{
使用法: TestApp -o ファイル [-v]
オプション:
-o ファイル, --output=ファイル [必須] 出力先のファイ...
-v ファイルを上書き保存する
--help Display this help screen.
詳しくは、ヘルプをご覧ください。
}}
**ヘルプを表示するオプションを「--help」以外にする [#p48b...
「--help」というオプションによってもGetUsageが返すメッセ...
さらに、HelpOptionもHelpTextプロパティによって、「--help...
例えばGetUsageメソッドに適用するHelpOption属性を次のよう...
#code(vbnet){{
<CommandLine.HelpOption("?"c, HelpText:="この説明画面を表...
Public Function GetUsage() As String
}}
#code(csharp){{
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption('?' , HelpText="この説明画面を表...
public string GetUsage()
}}
するとメッセージは「-?」で表示できて「--help」では表示で...
#pre{{
使用法: TestApp -o ファイル [-v]
オプション:
-o ファイル, --output=ファイル [必須] 出力先のファイ...
-v ファイルを上書き保存する
-? この説明画面を表示します
詳しくは、ヘルプをご覧ください。
}}
**エラーの理由によって表示するメッセージを変える [#ib905b...
Optionsクラスに、ParserState属性を適用したIParserStateの...
さらに、エラーがあった時は、HelpText.RenderParsingErrorsT...
これらを使用した例を以下に示します。
#code(vbnet){{
'オプションをプロパティに持つクラス
Public Class Options
<CommandLine.Option("o"c, "output", Required:=True, _
HelpText:="出力先のファイル名", MetaValue:="ファ...
Public Property OutputFile As String
<CommandLine.Option("v"c, HelpText:="ファイルを上書き...
Public Property Overwrite As Boolean
<CommandLine.Option("s"c, HelpText:="出力するファイル...
MetaValue:="サイズ")> _
Public Property Size As Integer
<CommandLine.ParserState> _
Public Property LastParserState As CommandLine.IParse...
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
Dim help = New CommandLine.Text.HelpText()
help.AddDashesToOption = True
If Me.LastParserState Is Nothing Then
'--help オプションで表示される時?
help.AddPreOptionsLine("使用できるオプション...
ElseIf Me.LastParserState.Errors IsNot Nothing An...
Me.LastParserState.Errors.Count > 0 Then
'エラーがあった時
'エラーメッセージを取得する。インデントは2と...
Dim errMsg As String = help.RenderParsingErro...
help.AddPreOptionsLine(errMsg)
Else
'不明なオプションが指定されている時?
help.AddPreOptionsLine("理解できないオプショ...
help.AddPreOptionsLine("以下に使用できるオプ...
End If
'オプションの説明を追加
help.AddOptions(Me)
'オプションの説明の後に改行を入れる
help.AddPostOptionsLine("")
Return help
End Function
End Class
}}
#code(csharp){{
//オプションをプロパティに持つクラス
public class Options
{
[CommandLine.Option('o', "output", Required = true,
HelpText = "出力先のファイル名", MetaValue = "フ...
public string OutputFile
{
get;
set;
}
[CommandLine.Option('v', HelpText = "ファイルを上書き...
public bool Overwrite
{
get;
set;
}
[CommandLine.Option('s',
HelpText = "出力するファイルのサイズ", MetaValue ...
public int Size
{
get;
set;
}
[CommandLine.ParserState]
public CommandLine.IParserState LastParserState
{
get;
set;
}
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
var help = new CommandLine.Text.HelpText();
help.AddDashesToOption = true;
if (this.LastParserState == null)
{
//--help オプションで表示される時?
help.AddPreOptionsLine("使用できるオプション...
}
else if (this.LastParserState.Errors != null &&
this.LastParserState.Errors.Count > 0)
{
//エラーがあった時
//エラーメッセージを取得する。インデントは2と...
string errMsg = help.RenderParsingErrorsText(...
help.AddPreOptionsLine(errMsg);
}
else
{
//不明なオプションが指定されている時?
help.AddPreOptionsLine("理解できないオプショ...
help.AddPreOptionsLine("以下に使用できるオプ...
}
//オプションの説明を追加
help.AddOptions(this);
//オプションの説明の後に改行を入れる
help.AddPostOptionsLine("");
return help;
}
}
}}
上記のコードで、必須オプションの欠落とフォーマットのエラ...
#pre{{
-s option violates format.
-o/--output required option is missing.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
さらに説明を補足します。上記の例では、エラーの原因が「thi...
「this.LastParserState.Errors」はParsingErrorオブジェクト...
また、ParsingErrorオブジェクトのBadOptionプロパティによっ...
これらを駆使してエラーメッセージを自分で作成することがで...
**自動でメッセージを作成する最も簡単な方法 [#j05d9e29]
HelpText.AutoBuildとHelpText.DefaultParsingErrorsHandler...
#code(vbnet){{
'解析に失敗した時に表示するメッセージを返すメソッド
<CommandLine.HelpOption> _
Public Function GetUsage() As String
'メッセージを自動的に作成する
Return CommandLine.Text.HelpText.AutoBuild(Me, _
Sub(current) CommandLine.Text.HelpText.DefaultPar...
Me, current))
End Function
}}
#code(csharp){{
//解析に失敗した時に表示するメッセージを返すメソッド
[CommandLine.HelpOption]
public string GetUsage()
{
//メッセージを自動的に作成する
return CommandLine.Text.HelpText.AutoBuild(this, curr...
CommandLine.Text.HelpText.DefaultParsingErrorsHan...
}
}}
このようにした時に表示されるメッセージは、例えば次によう...
#pre{{
TestApplication 1.0.0.0
Copyright c 2013 DOBON!
ERROR(S):
-s option violates format.
-o/--output required option is missing.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
この中で、「TestApplication」というのはアプリケーションの...
#column(補足){{
このようなアプリケーションのタイトルとバージョンの説明はH...
}}
さらに、「AssemblyInfo.cs」(VB.NETでは「AssemblyInfo.vb...
例えばAssemblyInfo.csに次のような記述を追加したとします。
#code(vbnet){{
<Assembly: CommandLine.AssemblyLicense( _
"このアプリケーションは、MITライセンスで公開します。"...
"The MIT License (MIT) <http://opensource.org/license...
<Assembly: CommandLine.AssemblyUsage( _
"使用法: TestApp -o ファイル [-v] [-s サイズ]", _
" TestApp --output=ファイル")>
}}
#code(csharp){{
[assembly: CommandLine.AssemblyLicense(
"このアプリケーションは、MITライセンスで公開します。",
"The MIT License (MIT) <http://opensource.org/license...
[assembly: CommandLine.AssemblyUsage(
"使用法: TestApp -o ファイル [-v] [-s サイズ]",
" TestApp --output=ファイル")]
}}
するとエラーメッセージは、次のように変わります。
#pre{{
TestApplication 1.0.0.0
Copyright c 2013 DOBON!
ERROR(S):
-s option violates format.
-o/--output required option is missing.
このアプリケーションは、MITライセンスで公開します。
The MIT License (MIT) <http://opensource.org/licenses/mit...
使用法: TestApp -o ファイル [-v] [-s サイズ]
TestApp --output=ファイル
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
**エラーメッセージを日本語にする [#n1c08a14]
RenderParsingErrorsTextやAutoBuild(DefaultParsingErrorsH...
まず以下のようなBaseSentenceBuilderの派生クラス「Japanese...
#code(vbnet){{
Public Class JapaneseSentenceBuilder
Inherits CommandLine.Text.BaseSentenceBuilder
Public Overrides ReadOnly Property AndWord() As String
Get
Return "且つ"
End Get
End Property
Public Overrides ReadOnly Property ErrorsHeadingText(...
Get
Return "エラー:"
End Get
End Property
Public Overrides ReadOnly Property OptionWord() As St...
Get
Return "オプション"
End Get
End Property
Public Overrides ReadOnly Property RequiredOptionMiss...
Get
Return "必須のオプションが指定されていません"
End Get
End Property
Public Overrides ReadOnly Property ViolatesFormatText...
Get
Return "書式が正しくありません"
End Get
End Property
Public Overrides ReadOnly Property ViolatesMutualExcl...
Get
Return "一緒に使用できないオプションが使われ...
End Get
End Property
End Class
}}
#code(csharp){{
public class JapaneseSentenceBuilder : CommandLine.Text.B...
{
public override string AndWord
{
get { return "且つ"; }
}
public override string ErrorsHeadingText
{
get { return "エラー:"; }
}
public override string OptionWord
{
get { return "オプション"; }
}
public override string RequiredOptionMissingText
{
get { return "必須のオプションが指定されていませ...
}
public override string ViolatesFormatText
{
get { return "書式が正しくありません"; }
}
public override string ViolatesMutualExclusivenessText
{
get { return "一緒に使用できないオプションが使わ...
}
}
}}
このクラスを使えば、RenderParsingErrorsTextやDefaultParsi...
それでもあえてAutoBuildを使う場合は、例えば以下のような方...
#code(vbnet){{
<CommandLine.HelpOption> _
Public Function GetUsage() As String
'エラーメッセージのないメッセージを作成
Dim help = CommandLine.Text.HelpText.AutoBuild(Me)
'日本語のエラーメッセージを作成
Dim jhelp = New CommandLine.Text.HelpText(New Japanes...
CommandLine.Text.HelpText.DefaultParsingErrorsHandler...
'日本語のエラーメッセージを追加
help.AddPreOptionsLine(jhelp)
Return help
End Function
}}
#code(csharp){{
[CommandLine.HelpOption]
public string GetUsage()
{
//エラーメッセージのないメッセージを作成
var help = CommandLine.Text.HelpText.AutoBuild(this);
//日本語のエラーメッセージを作成
var jhelp = new CommandLine.Text.HelpText(new Japanes...
CommandLine.Text.HelpText.DefaultParsingErrorsHandler...
//日本語のエラーメッセージを追加
help.AddPreOptionsLine(jhelp);
return help;
}
}}
すると、エラーメッセージは以下のようになります。
#pre{{
TestApplication 1.0.0.0
Copyright c 2013
このアプリケーションは、MITライセンスで公開します。
The MIT License (MIT) <http://opensource.org/licenses/mit...
使用法: TestApp -o ファイル [-v] [-s サイズ]
TestApp --output=ファイル
エラー:
-s オプション 書式が正しくありません.
-o/--output 必須のオプションが指定されていません.
-o ファイル, --output=ファイル Required. 出力先のフ...
-v ファイルを上書き保存する
-s サイズ 出力するファイルのサイズ
--help Display this help screen.
}}
エラーメッセージが表示される位置が変わりましたが、エラー...
**メッセージをコンソール以外に表示する [#u623bf1d]
前に触れましたが、ParserクラスのHelpWriterプロパティによ...
Parser.DefaultのHelpWriterはConsole.Errorなので、標準エラ...
コンソールアプリケーションであれば標準エラー出力ストリー...
以下にその例を示します。
#code(vbnet){{
Module Module1
'エントリポイント
Sub Main(args As String())
'Optionsクラスのインスタンスを作成
Dim opts = New Options()
'メッセージを書き込むStringWriterを作成
Dim sw = New System.IO.StringWriter()
'Parserを作成して、HelpWriterをStringWriterに変更
Dim p = New CommandLine.Parser(Sub(w) w.HelpWrite...
'コマンドライン引数を解析する
Dim isSuccess As Boolean = p.ParseArguments(args,...
'メッセージを取得する
sw.Close()
Dim helpMsg As String = sw.ToString()
'メッセージがある時は、表示する
If Not String.IsNullOrEmpty(helpMsg) Then
Console.WriteLine(helpMsg)
End If
Console.ReadLine()
End Sub
End Module
}}
#code(csharp){{
//エントリポイント
static void Main(string[] args)
{
//Optionsクラスのインスタンスを作成
var opts = new Options();
//メッセージを書き込むStringWriterを作成
var sw = new System.IO.StringWriter();
//Parserを作成して、HelpWriterをStringWriterに変更
var p = new CommandLine.Parser(with => with.HelpWrite...
//コマンドライン引数を解析する
bool isSuccess = p.ParseArguments(args, opts);
//メッセージを取得する
sw.Close();
string helpMsg = sw.ToString();
//メッセージがある時は、表示する
if (!string.IsNullOrEmpty(helpMsg))
{
Console.WriteLine(helpMsg);
}
Console.ReadLine();
}
}}
**最後に [#m74d80ce]
Command Line Parser Libraryについて長々と説明してきました...
//これより下は編集しないでください
#pageinfo(,2013-04-22 (月) 01:36:11,DOBON!,2013-04-22 (月...
ページ名:
▲
▼
[
トップ
] [
新規
|
子ページ作成
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
]