BadScript 2
Loading...
Searching...
No Matches
Parser.cs
Go to the documentation of this file.
1// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
2
3using System;
4using System.Collections.Generic;
5using System.IO;
6using System.Linq;
7
10
11using CSharpx;
12
14
15namespace CommandLine
16{
20 public class Parser : IDisposable
21 {
22 private static readonly Lazy<Parser> DefaultParser =
23 new Lazy<Parser>(() => new Parser(new ParserSettings { HelpWriter = Console.Error }));
24
25 private bool disposed;
26
30 public Parser()
31 {
32 Settings = new ParserSettings { Consumed = true };
33 }
34
43 public Parser(Action<ParserSettings> configuration)
44 {
45 if (configuration == null)
46 {
47 throw new ArgumentNullException("configuration");
48 }
49
51 configuration(Settings);
52 Settings.Consumed = true;
53 }
54
55 public Parser(Func<ParserSettings> factory)
56 {
57 if (factory == null)
58 {
59 throw new ArgumentNullException(nameof(factory));
60 }
61
62 Settings = factory();
63 Settings.Consumed = true;
64 }
65
66 internal Parser(ParserSettings settings)
67 {
68 Settings = settings;
69 Settings.Consumed = true;
70 }
71
75 public static Parser Default => DefaultParser.Value;
76
80 public ParserSettings Settings { get; }
81
82#region IDisposable Members
83
87 public void Dispose()
88 {
89 Dispose(true);
90
91 GC.SuppressFinalize(this);
92 }
93
94#endregion
95
100 {
101 Dispose(false);
102 }
103
120 public ParserResult<T> ParseArguments<T>(IEnumerable<string> args)
121 {
122 if (args == null)
123 {
124 throw new ArgumentNullException("args");
125 }
126
127 Maybe<Func<T>> factory = typeof(T).IsMutable()
128 ? Maybe.Just<Func<T>>(Activator.CreateInstance<T>)
129 : Maybe.Nothing<Func<T>>();
130
131 return MakeParserResult(InstanceBuilder.Build(factory,
132 (arguments, optionSpecs) =>
133 Tokenize(arguments, optionSpecs, Settings),
134 args,
142 ),
144 );
145 }
146
164 public ParserResult<T> ParseArguments<T>(Func<T> factory, IEnumerable<string> args)
165 {
166 if (factory == null)
167 {
168 throw new ArgumentNullException("factory");
169 }
170
171 if (!typeof(T).IsMutable())
172 {
173 throw new ArgumentException("factory");
174 }
175
176 if (args == null)
177 {
178 throw new ArgumentNullException("args");
179 }
180
181 return MakeParserResult(InstanceBuilder.Build(Maybe.Just(factory),
182 (arguments, optionSpecs) =>
183 Tokenize(arguments, optionSpecs, Settings),
184 args,
192 ),
194 );
195 }
196
216 public ParserResult<object> ParseArguments(IEnumerable<string> args, params Type[] types)
217 {
218 if (args == null)
219 {
220 throw new ArgumentNullException("args");
221 }
222
223 if (types == null)
224 {
225 throw new ArgumentNullException("types");
226 }
227
228 if (types.Length == 0)
229 {
230 throw new ArgumentOutOfRangeException("types");
231 }
232
233 return MakeParserResult(InstanceChooser.Choose((arguments, optionSpecs) =>
234 Tokenize(arguments, optionSpecs, Settings),
235 types,
236 args,
244 ),
246 );
247 }
248
249 private static Result<IEnumerable<Token>, Error> Tokenize(IEnumerable<string> arguments,
250 IEnumerable<OptionSpecification> optionSpecs,
251 ParserSettings settings)
252 {
253 return settings.GetoptMode
255 settings.IgnoreUnknownArguments,
256 settings.EnableDashDash,
257 settings.PosixlyCorrect
258 )(arguments, optionSpecs)
260 settings.IgnoreUnknownArguments,
261 settings.EnableDashDash
262 )(arguments, optionSpecs);
263 }
264
266 {
267 return DisplayHelp(parserResult,
268 settings.HelpWriter,
269 settings.MaximumDisplayWidth
270 );
271 }
272
273 private static ParserResult<T> DisplayHelp<T>(ParserResult<T> parserResult,
274 TextWriter helpWriter,
275 int maxDisplayWidth)
276 {
277 parserResult.WithNotParsed(errors =>
278 Maybe.Merge(errors.ToMaybe(), helpWriter.ToMaybe())
279 .Do((_, writer) =>
280 writer.Write(HelpText.AutoBuild(parserResult, maxDisplayWidth))
281 )
282 );
283
284 return parserResult;
285 }
286
287 private static IEnumerable<ErrorType> HandleUnknownArguments(bool ignoreUnknownArguments)
288 {
289 return ignoreUnknownArguments
290 ? Enumerable.Empty<ErrorType>()
291 .Concat(ErrorType.UnknownOptionError)
292 : Enumerable.Empty<ErrorType>();
293 }
294
295 private void Dispose(bool disposing)
296 {
297 if (disposed)
298 {
299 return;
300 }
301
302 if (disposing)
303 {
304 if (Settings != null)
305 {
307 }
308
309 disposed = true;
310 }
311 }
312 }
313}
The Maybe type models an optional value. A value of type Maybe a either contains a value of type a (r...
Definition Maybe.cs:33
static Func< IEnumerable< string >, IEnumerable< OptionSpecification >, Result< IEnumerable< Token >, Error > > ConfigureTokenizer(StringComparer nameComparer, bool ignoreUnknownArguments, bool enableDashDash, bool posixlyCorrect)
static ParserResult< object > Choose(Func< IEnumerable< string >, IEnumerable< OptionSpecification >, Result< IEnumerable< Token >, Error > > tokenizer, IEnumerable< Type > types, IEnumerable< string > arguments, StringComparer nameComparer, bool ignoreValueCase, CultureInfo parsingCulture, bool autoHelp, bool autoVersion, IEnumerable< ErrorType > nonFatalErrors)
static Func< IEnumerable< string >, IEnumerable< OptionSpecification >, Result< IEnumerable< Token >, Error > > ConfigureTokenizer(StringComparer nameComparer, bool ignoreUnknownArguments, bool enableDashDash)
Definition Tokenizer.cs:166
Base type of all errors.
Definition Error.cs:110
Provides methods to parse command line arguments.
Definition Parser.cs:21
static ParserResult< T > MakeParserResult< T >(ParserResult< T > parserResult, ParserSettings settings)
Definition Parser.cs:265
void Dispose()
Frees resources owned by the instance.
Definition Parser.cs:87
static readonly Lazy< Parser > DefaultParser
Definition Parser.cs:22
void Dispose(bool disposing)
Definition Parser.cs:295
Parser(ParserSettings settings)
Definition Parser.cs:66
Parser(Action< ParserSettings > configuration)
Initializes a new instance of the Parser class, configurable with ParserSettings using a delegate.
Definition Parser.cs:43
~Parser()
Finalizes an instance of the CommandLine.Parser class.
Definition Parser.cs:99
ParserResult< T > ParseArguments< T >(IEnumerable< string > args)
Parses a string array of command line arguments constructing values in an instance of type T ....
Definition Parser.cs:120
ParserSettings Settings
Gets the instance that implements CommandLine.ParserSettings in use.
Definition Parser.cs:80
static ParserResult< T > DisplayHelp< T >(ParserResult< T > parserResult, TextWriter helpWriter, int maxDisplayWidth)
Definition Parser.cs:273
Parser()
Initializes a new instance of the CommandLine.Parser class.
Definition Parser.cs:30
ParserResult< object > ParseArguments(IEnumerable< string > args, params Type[] types)
Parses a string array of command line arguments for verb commands scenario, constructing the proper i...
Definition Parser.cs:216
static Result< IEnumerable< Token >, Error > Tokenize(IEnumerable< string > arguments, IEnumerable< OptionSpecification > optionSpecs, ParserSettings settings)
Definition Parser.cs:249
static Parser Default
Gets the singleton instance created with basic defaults.
Definition Parser.cs:75
Parser(Func< ParserSettings > factory)
Definition Parser.cs:55
static IEnumerable< ErrorType > HandleUnknownArguments(bool ignoreUnknownArguments)
Definition Parser.cs:287
Models a parser result. When inherited by CommandLine.Parsed<T>, it contains an instance of type T w...
Provides settings for CommandLine.Parser. Once consumed cannot be reused.
bool PosixlyCorrect
Whether getopt-like processing should follow the POSIX rules (the equivalent of using the "+" prefix ...
int MaximumDisplayWidth
Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
bool EnableDashDash
Gets or sets a value indicating whether enable double dash '–' syntax, that forces parsing of all sub...
bool AllowMultiInstance
Gets or sets a value indicating whether options are allowed to be specified multiple times....
bool CaseInsensitiveEnumValues
Gets or sets a value indicating whether perform case sensitive comparisons of values....
bool AutoHelp
Gets or sets a value indicating whether implicit option or verb 'help' should be supported.
void Dispose()
Frees resources owned by the instance.
bool IgnoreUnknownArguments
Gets or sets a value indicating whether the parser shall move on to the next argument and ignore the ...
CultureInfo ParsingCulture
Gets or sets the culture used when parsing arguments to typed properties.
TextWriter HelpWriter
Gets or sets the System.IO.TextWriter used for help method output. Setting this property to null,...
bool AutoVersion
Gets or sets a value indicating whether implicit option or verb 'version' should be supported.
Represents the result of a computation.
ErrorType
Discriminator enumeration of CommandLine.Error derivates.
Definition Error.cs:13