croupier 0.0.1 → 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/MIT-LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 Juanjo Bazán
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # Croupier
2
+
3
+ Croupier generates random samples of numbers with specific probability distributions.
4
+
5
+ ## Install
6
+
7
+ You need to have Ruby and Rubygems installed in your system. Then install croupier with:
8
+
9
+ $ gem install croupier
10
+
11
+ ## Getting Started
12
+
13
+ Once you have croupier installed in your machine, you can run the gem using the `croupier` executable:
14
+
15
+ $ croupier
16
+
17
+ The common case for invoking Cruopier is:
18
+
19
+ $ croupier <distribution> <sample_size> [<options>]
20
+
21
+ where:
22
+
23
+ * <distribution> is the name of the desired distribution of the random sample.
24
+ * <sample_size> is an integer representing the size of the desired sample.
25
+ * <options> are any extra parameters needed by the actual distribution. (If not options are provided croupier will use the default parameters for the distribution being called).
26
+
27
+ ### Examples
28
+
29
+ $ croupier uniform 500 # => 500 numbers with uniform distribution in [0,1] (default interval)
30
+ $ croupier uniform 125 -min 7 -max 15 # => 125 numbers with uniform distribution in [7,15]
31
+ $ croupier exponential 1000 -lambda 1.3 # => 1000 numbers following an exponential distribution with rate 1.3
32
+
33
+ ### Available distributions and options
34
+
35
+ To get a list of all the available distributions use the ```--help``` (or ```-h```) option with croupier:
36
+
37
+ $ croupier --help
38
+
39
+ To get a list of all the available options for a given distribution use ```--help``` (or ```-h```) option with any available distribution:
40
+
41
+ $ croupier exponential --help # => will list all the options for the exponential distribution
42
+
43
+ ## Using Croupier from a ruby application
44
+
45
+ If you want to generate random numbers from your ruby code you can use the Distribution class that you need.
46
+ All the available distributions are located in the ```Croupier::Distributions``` module and are represented by a class inheriting from the ```Croupier::Distribution``` class.
47
+ First of all require the croupier library:
48
+
49
+ require 'croupier'
50
+
51
+ And then use the the distribution you want to generate the sample. You can get just one number (using ```.generate_single_number```) or an array of any given size (using ```.generate_numbers(N)```)
52
+
53
+ dist = ::Croupier::Distributions::Exponential.new(:lambda => 1.7)
54
+ dist.generate_numbers(100) #=> returns an array of 100 random numbers following an exponential with rate 1.7
55
+ dist.generate_single_number #=> returns one random number following an exponential with rate 1.7
56
+
57
+ ## License
58
+
59
+ Croupier is released under the MIT license.
60
+
61
+ ## Credits
62
+
63
+ Developed by Juanjo Bazán [`@xuanxu`](http://twitter.com/xuanxu) & Sergio Arbeo [`@serabe`](http://twitter.com/serabe)
data/RUNNING_TESTS.md ADDED
@@ -0,0 +1,33 @@
1
+ ## Running tests
2
+
3
+ The tests suite of the gem is located in the /test folder, and it's divided in two sets that run separately:
4
+
5
+ * Ruby Tests
6
+ * R tests
7
+
8
+ ### Ruby Tests
9
+
10
+ The ruby set of tests are meant to test the general behaviour of the library.
11
+ You can run these tests using the default Rake task:
12
+
13
+ $ rake
14
+
15
+ ### R tests
16
+
17
+ There's a group of tests validating the probability distribution of several samples of numbers generated with Croupier.
18
+ These tests are statistical tests included in R scripts.
19
+ To run them you need to have R installed in your system. You can get the R software from ```http://www.r-project.org/```
20
+ The testsuite uses the 'testthat' package. You can install it from the R console with the folowing command:
21
+
22
+ install.packages("testthat", repos = "http://cran.r-project.org/", type="source")
23
+
24
+ Once you have R and all the dependencies installed in your system, you can run the test/testsuite.R file:
25
+
26
+ Using Rscript:
27
+
28
+ $ Rscript testsuite.R
29
+
30
+ or from the R console:
31
+
32
+ source('testsuite.R')
33
+
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require 'rake/testtask'
2
+
3
+ Rake::TestTask.new do |t|
4
+ t.libs << "test"
5
+ t.test_files = FileList['test/**/test*.rb']
6
+ t.verbose = true
7
+ end
8
+ task :default => :test
9
+
data/bin/croupier ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ #--
4
+ # Copyright (c) 2012 Juanjo Bazan
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to
8
+ # deal in the Software without restriction, including without limitation the
9
+ # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10
+ # sell copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22
+ # IN THE SOFTWARE.
23
+ #++
24
+
25
+ require 'croupier'
26
+ Croupier.application.run
data/lib/croupier.rb CHANGED
@@ -1,3 +1,64 @@
1
+ require 'croupier/cli/trollop'
2
+ require 'croupier/exceptions'
3
+ require 'croupier/distribution'
4
+ Dir[File.join(File.dirname(__FILE__), "./croupier/distributions/*.rb")].each {|f| require f}
5
+ require 'croupier/cli/application'
6
+ #####################################################################
7
+ # Croupier module.
8
+ # Used as a namespace containing all the Croupier code.
9
+ # The module defines a Croupier::CLI::Application and interacts with the user output console.
10
+ #
1
11
  module Croupier
12
+ STDERR = $stderr
13
+ STDOUT = $stdout
2
14
 
15
+ # Croupier module singleton methods.
16
+ #
17
+ class << self
18
+ # Current Croupier Application
19
+ def application
20
+ @application ||= ::Croupier::CLI::Application.new
21
+ end
22
+
23
+ # Set the current Croupier application object.
24
+ def application=(app)
25
+ @application = app
26
+ end
27
+
28
+ # Stops the execution of the Croupier application.
29
+ def stop(msg = "Error: Croupier finished.")
30
+ self.error_message msg
31
+ exit(false)
32
+ end
33
+
34
+ # Writes message to the standard output
35
+ def message(msg)
36
+ STDOUT.puts msg
37
+ STDOUT.flush
38
+ end
39
+
40
+ # Writes message to the error output
41
+ def error_message(msg)
42
+ STDERR.puts msg
43
+ STDERR.flush
44
+ end
45
+
46
+ # Writes to the standard output
47
+ def write(str)
48
+ STDOUT.write str
49
+ STDOUT.flush
50
+ end
51
+
52
+ # Clear current console line
53
+ def clear_line!
54
+ self.write "\r"
55
+ end
56
+
57
+ # Trap SIGINT signal
58
+ def trap_interrupt
59
+ trap('INT') do
60
+ Croupier.stop("\nCroupier Exiting... Interrupt signal received.")
61
+ end
62
+ end
63
+ end
3
64
  end
@@ -0,0 +1,80 @@
1
+ module Croupier
2
+ module CLI
3
+ #####################################################################
4
+ # Croupier main command line interface application object.
5
+ #
6
+ # When invoking +croupier+ from the command line,
7
+ # a Croupier::CLI::Application object is created and run.
8
+ #
9
+ class Application
10
+ attr_accessor :distribution_list, :distributions_options
11
+
12
+ # Initialize a Croupier::CLI::Application object.
13
+ # It Checks and loads the available distributions.
14
+ def initialize
15
+ @distribution_list, @distributions_options = {}, {}
16
+ ::Croupier::Distributions.constants.each{|distrib|
17
+ d = ::Croupier::Distributions.const_get(distrib)
18
+ if d.is_a?(Class) && d.superclass == Croupier::Distribution
19
+ @distribution_list[d.cli_name] = d
20
+ @distributions_options[d.cli_name] = d.cli_options
21
+ end
22
+ }
23
+ end
24
+
25
+ # Run the Croupier application. The run method performs the following steps:
26
+ #
27
+ # * Parses the application options.
28
+ # * Identifies the probability distribution, sample size and options to use.
29
+ # * Asks the actual distribution to generate the numbers, and outputs them.
30
+ def run
31
+ Croupier.trap_interrupt
32
+ distribution, sample_size, params = parse_distribution_options
33
+ distribution.new(params).generate_numbers(sample_size).each{|n| Croupier.message n}
34
+ end
35
+
36
+ private
37
+
38
+ def parse_distribution_options
39
+ #Trollop needs this vars locally
40
+ available_distribution_list = @distribution_list.keys
41
+ available_distributions_options = @distributions_options
42
+
43
+ opts = Trollop::options do
44
+ banner <<-EOS
45
+ Croupier will generate random numbers with the specified distribution.
46
+
47
+ Currently you can use this distributions:
48
+ [#{available_distribution_list.join(', ')}]
49
+
50
+ Usage:
51
+ croupier <distribution> <n> [options]
52
+ where <n> is the quantity of numbers Croupier will generate.
53
+
54
+ Get options list for any distribution with: croupier <distrib> --help
55
+
56
+ EOS
57
+ stop_on available_distribution_list
58
+ end
59
+
60
+ dist = ARGV.shift # get the distribution name
61
+ dist_opts = case
62
+ when available_distribution_list.include?(dist)
63
+ Trollop::options do
64
+ banner (available_distributions_options[dist][:banner] || "Options (#{dist}):")
65
+ available_distributions_options[dist][:options].each{|ooo|
66
+ opt ooo[0], ooo[1], ooo[2]
67
+ }
68
+ end
69
+ else
70
+ Trollop::die "unknown distribution #{dist.inspect}"
71
+ end
72
+
73
+ sample_size = ARGV.shift.to_i # get the sample size
74
+ Trollop::die "Sample size must be a positive integer" if sample_size.nil? || sample_size < 1
75
+
76
+ return [@distribution_list[dist], sample_size, dist_opts]
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,791 @@
1
+ ## lib/trollop.rb -- trollop command-line processing library
2
+ ## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net)
3
+ ## Copyright:: Copyright 2007 William Morgan
4
+ ## License:: the same terms as ruby itself
5
+
6
+ require 'date'
7
+
8
+ module Trollop
9
+
10
+ VERSION = "1.16.2"
11
+
12
+ ## Thrown by Parser in the event of a commandline error. Not needed if
13
+ ## you're using the Trollop::options entry.
14
+ class CommandlineError < StandardError; end
15
+
16
+ ## Thrown by Parser if the user passes in '-h' or '--help'. Handled
17
+ ## automatically by Trollop#options.
18
+ class HelpNeeded < StandardError; end
19
+
20
+ ## Thrown by Parser if the user passes in '-h' or '--version'. Handled
21
+ ## automatically by Trollop#options.
22
+ class VersionNeeded < StandardError; end
23
+
24
+ ## Regex for floating point numbers
25
+ FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/
26
+
27
+ ## Regex for parameters
28
+ PARAM_RE = /^-(-|\.$|[^\d\.])/
29
+
30
+ ## The commandline parser. In typical usage, the methods in this class
31
+ ## will be handled internally by Trollop::options. In this case, only the
32
+ ## #opt, #banner and #version, #depends, and #conflicts methods will
33
+ ## typically be called.
34
+ ##
35
+ ## If you want to instantiate this class yourself (for more complicated
36
+ ## argument-parsing logic), call #parse to actually produce the output hash,
37
+ ## and consider calling it from within
38
+ ## Trollop::with_standard_exception_handling.
39
+ class Parser
40
+
41
+ ## The set of values that indicate a flag option when passed as the
42
+ ## +:type+ parameter of #opt.
43
+ FLAG_TYPES = [:flag, :bool, :boolean]
44
+
45
+ ## The set of values that indicate a single-parameter (normal) option when
46
+ ## passed as the +:type+ parameter of #opt.
47
+ ##
48
+ ## A value of +io+ corresponds to a readable IO resource, including
49
+ ## a filename, URI, or the strings 'stdin' or '-'.
50
+ SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date]
51
+
52
+ ## The set of values that indicate a multiple-parameter option (i.e., that
53
+ ## takes multiple space-separated values on the commandline) when passed as
54
+ ## the +:type+ parameter of #opt.
55
+ MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
56
+
57
+ ## The complete set of legal values for the +:type+ parameter of #opt.
58
+ TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
59
+
60
+ INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc:
61
+
62
+ ## The values from the commandline that were not interpreted by #parse.
63
+ attr_reader :leftovers
64
+
65
+ ## The complete configuration hashes for each option. (Mainly useful
66
+ ## for testing.)
67
+ attr_reader :specs
68
+
69
+ ## Initializes the parser, and instance-evaluates any block given.
70
+ def initialize *a, &b
71
+ @version = nil
72
+ @leftovers = []
73
+ @specs = {}
74
+ @long = {}
75
+ @short = {}
76
+ @order = []
77
+ @constraints = []
78
+ @stop_words = []
79
+ @stop_on_unknown = false
80
+
81
+ #instance_eval(&b) if b # can't take arguments
82
+ cloaker(&b).bind(self).call(*a) if b
83
+ end
84
+
85
+ ## Define an option. +name+ is the option name, a unique identifier
86
+ ## for the option that you will use internally, which should be a
87
+ ## symbol or a string. +desc+ is a string description which will be
88
+ ## displayed in help messages.
89
+ ##
90
+ ## Takes the following optional arguments:
91
+ ##
92
+ ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
93
+ ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
94
+ ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
95
+ ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
96
+ ## [+:required+] If set to +true+, the argument must be provided on the commandline.
97
+ ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
98
+ ##
99
+ ## Note that there are two types of argument multiplicity: an argument
100
+ ## can take multiple values, e.g. "--arg 1 2 3". An argument can also
101
+ ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
102
+ ##
103
+ ## Arguments that take multiple values should have a +:type+ parameter
104
+ ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
105
+ ## value of an array of the correct type (e.g. [String]). The
106
+ ## value of this argument will be an array of the parameters on the
107
+ ## commandline.
108
+ ##
109
+ ## Arguments that can occur multiple times should be marked with
110
+ ## +:multi+ => +true+. The value of this argument will also be an array.
111
+ ## In contrast with regular non-multi options, if not specified on
112
+ ## the commandline, the default value will be [], not nil.
113
+ ##
114
+ ## These two attributes can be combined (e.g. +:type+ => +:strings+,
115
+ ## +:multi+ => +true+), in which case the value of the argument will be
116
+ ## an array of arrays.
117
+ ##
118
+ ## There's one ambiguous case to be aware of: when +:multi+: is true and a
119
+ ## +:default+ is set to an array (of something), it's ambiguous whether this
120
+ ## is a multi-value argument as well as a multi-occurrence argument.
121
+ ## In thise case, Trollop assumes that it's not a multi-value argument.
122
+ ## If you want a multi-value, multi-occurrence argument with a default
123
+ ## value, you must specify +:type+ as well.
124
+
125
+ def opt name, desc="", opts={}
126
+ raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
127
+
128
+ ## fill in :type
129
+ opts[:type] = # normalize
130
+ case opts[:type]
131
+ when :boolean, :bool; :flag
132
+ when :integer; :int
133
+ when :integers; :ints
134
+ when :double; :float
135
+ when :doubles; :floats
136
+ when Class
137
+ case opts[:type].name
138
+ when 'TrueClass', 'FalseClass'; :flag
139
+ when 'String'; :string
140
+ when 'Integer'; :int
141
+ when 'Float'; :float
142
+ when 'IO'; :io
143
+ when 'Date'; :date
144
+ else
145
+ raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
146
+ end
147
+ when nil; nil
148
+ else
149
+ raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
150
+ opts[:type]
151
+ end
152
+
153
+ ## for options with :multi => true, an array default doesn't imply
154
+ ## a multi-valued argument. for that you have to specify a :type
155
+ ## as well. (this is how we disambiguate an ambiguous situation;
156
+ ## see the docs for Parser#opt for details.)
157
+ disambiguated_default =
158
+ if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
159
+ opts[:default].first
160
+ else
161
+ opts[:default]
162
+ end
163
+
164
+ type_from_default =
165
+ case disambiguated_default
166
+ when Integer; :int
167
+ when Numeric; :float
168
+ when TrueClass, FalseClass; :flag
169
+ when String; :string
170
+ when IO; :io
171
+ when Date; :date
172
+ when Array
173
+ if opts[:default].empty?
174
+ raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
175
+ end
176
+ case opts[:default][0] # the first element determines the types
177
+ when Integer; :ints
178
+ when Numeric; :floats
179
+ when String; :strings
180
+ when IO; :ios
181
+ when Date; :dates
182
+ else
183
+ raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
184
+ end
185
+ when nil; nil
186
+ else
187
+ raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
188
+ end
189
+
190
+ raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default
191
+
192
+ opts[:type] = opts[:type] || type_from_default || :flag
193
+
194
+ ## fill in :long
195
+ opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
196
+ opts[:long] =
197
+ case opts[:long]
198
+ when /^--([^-].*)$/
199
+ $1
200
+ when /^[^-]/
201
+ opts[:long]
202
+ else
203
+ raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
204
+ end
205
+ raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
206
+
207
+ ## fill in :short
208
+ opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
209
+ opts[:short] = case opts[:short]
210
+ when /^-(.)$/; $1
211
+ when nil, :none, /^.$/; opts[:short]
212
+ else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
213
+ end
214
+
215
+ if opts[:short]
216
+ raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
217
+ raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
218
+ end
219
+
220
+ ## fill in :default for flags
221
+ opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
222
+
223
+ ## autobox :default for :multi (multi-occurrence) arguments
224
+ opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
225
+
226
+ ## fill in :multi
227
+ opts[:multi] ||= false
228
+
229
+ opts[:desc] ||= desc
230
+ @long[opts[:long]] = name
231
+ @short[opts[:short]] = name if opts[:short] && opts[:short] != :none
232
+ @specs[name] = opts
233
+ @order << [:opt, name]
234
+ end
235
+
236
+ ## Sets the version string. If set, the user can request the version
237
+ ## on the commandline. Should probably be of the form "<program name>
238
+ ## <version number>".
239
+ def version s=nil; @version = s if s; @version end
240
+
241
+ ## Adds text to the help display. Can be interspersed with calls to
242
+ ## #opt to build a multi-section help page.
243
+ def banner s; @order << [:text, s] end
244
+ alias :text :banner
245
+
246
+ ## Marks two (or more!) options as requiring each other. Only handles
247
+ ## undirected (i.e., mutual) dependencies. Directed dependencies are
248
+ ## better modeled with Trollop::die.
249
+ def depends *syms
250
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
251
+ @constraints << [:depends, syms]
252
+ end
253
+
254
+ ## Marks two (or more!) options as conflicting.
255
+ def conflicts *syms
256
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
257
+ @constraints << [:conflicts, syms]
258
+ end
259
+
260
+ ## Defines a set of words which cause parsing to terminate when
261
+ ## encountered, such that any options to the left of the word are
262
+ ## parsed as usual, and options to the right of the word are left
263
+ ## intact.
264
+ ##
265
+ ## A typical use case would be for subcommand support, where these
266
+ ## would be set to the list of subcommands. A subsequent Trollop
267
+ ## invocation would then be used to parse subcommand options, after
268
+ ## shifting the subcommand off of ARGV.
269
+ def stop_on *words
270
+ @stop_words = [*words].flatten
271
+ end
272
+
273
+ ## Similar to #stop_on, but stops on any unknown word when encountered
274
+ ## (unless it is a parameter for an argument). This is useful for
275
+ ## cases where you don't know the set of subcommands ahead of time,
276
+ ## i.e., without first parsing the global options.
277
+ def stop_on_unknown
278
+ @stop_on_unknown = true
279
+ end
280
+
281
+ ## Parses the commandline. Typically called by Trollop::options,
282
+ ## but you can call it directly if you need more control.
283
+ ##
284
+ ## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
285
+ def parse cmdline=ARGV
286
+ vals = {}
287
+ required = {}
288
+
289
+ opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
290
+ opt :help, "Show this message" unless @specs[:help] || @long["help"]
291
+
292
+ @specs.each do |sym, opts|
293
+ required[sym] = true if opts[:required]
294
+ vals[sym] = opts[:default]
295
+ vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
296
+ end
297
+
298
+ resolve_default_short_options!
299
+ rewrite_long_true_flags!
300
+
301
+ ## resolve symbols
302
+ given_args = {}
303
+ @leftovers = each_arg cmdline do |arg, params|
304
+ sym = case arg
305
+ when /^-([^-])$/
306
+ @short[$1]
307
+ when /^--([^-]\S*)$/
308
+ @long[$1]
309
+ else
310
+ raise CommandlineError, "invalid argument syntax: '#{arg}'"
311
+ end
312
+ raise CommandlineError, "unknown argument '#{arg}'" unless sym
313
+
314
+ if given_args.include?(sym) && !@specs[sym][:multi]
315
+ raise CommandlineError, "option '#{arg}' specified multiple times"
316
+ end
317
+
318
+ given_args[sym] ||= {}
319
+
320
+ given_args[sym][:arg] = arg
321
+ given_args[sym][:params] ||= []
322
+
323
+ # The block returns the number of parameters taken.
324
+ num_params_taken = 0
325
+
326
+ unless params.nil?
327
+ if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
328
+ given_args[sym][:params] << params[0, 1] # take the first parameter
329
+ num_params_taken = 1
330
+ elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
331
+ given_args[sym][:params] << params # take all the parameters
332
+ num_params_taken = params.size
333
+ end
334
+ end
335
+
336
+ num_params_taken
337
+ end
338
+
339
+ ## check for version and help args
340
+ raise VersionNeeded if given_args.include? :version
341
+ raise HelpNeeded if given_args.include? :help
342
+
343
+ ## check constraint satisfaction
344
+ @constraints.each do |type, syms|
345
+ constraint_sym = syms.find { |sym| given_args[sym] }
346
+ next unless constraint_sym
347
+
348
+ case type
349
+ when :depends
350
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
351
+ when :conflicts
352
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
353
+ end
354
+ end
355
+
356
+ required.each do |sym, val|
357
+ raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
358
+ end
359
+
360
+ ## parse parameters
361
+ given_args.each do |sym, given_data|
362
+ arg = given_data[:arg]
363
+ params = given_data[:params]
364
+
365
+ opts = @specs[sym]
366
+ raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
367
+
368
+ vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
369
+
370
+ case opts[:type]
371
+ when :flag
372
+ vals[sym] = !opts[:default]
373
+ when :int, :ints
374
+ vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
375
+ when :float, :floats
376
+ vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
377
+ when :string, :strings
378
+ vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
379
+ when :io, :ios
380
+ vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
381
+ when :date, :dates
382
+ vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
383
+ end
384
+
385
+ if SINGLE_ARG_TYPES.include?(opts[:type])
386
+ unless opts[:multi] # single parameter
387
+ vals[sym] = vals[sym][0][0]
388
+ else # multiple options, each with a single parameter
389
+ vals[sym] = vals[sym].map { |p| p[0] }
390
+ end
391
+ elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
392
+ vals[sym] = vals[sym][0] # single option, with multiple parameters
393
+ end
394
+ # else: multiple options, with multiple parameters
395
+ end
396
+
397
+ ## modify input in place with only those
398
+ ## arguments we didn't process
399
+ cmdline.clear
400
+ @leftovers.each { |l| cmdline << l }
401
+
402
+ ## allow openstruct-style accessors
403
+ class << vals
404
+ def method_missing(m, *args)
405
+ self[m] || self[m.to_s]
406
+ end
407
+ end
408
+ vals
409
+ end
410
+
411
+ def parse_date_parameter param, arg #:nodoc:
412
+ begin
413
+ begin
414
+ time = Chronic.parse(param)
415
+ rescue NameError
416
+ # chronic is not available
417
+ end
418
+ time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
419
+ rescue ArgumentError
420
+ raise CommandlineError, "option '#{arg}' needs a date"
421
+ end
422
+ end
423
+
424
+ ## Print the help message to +stream+.
425
+ def educate stream=$stdout
426
+ width # just calculate it now; otherwise we have to be careful not to
427
+ # call this unless the cursor's at the beginning of a line.
428
+
429
+ left = {}
430
+ @specs.each do |name, spec|
431
+ left[name] = "--#{spec[:long]}" +
432
+ (spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
433
+ case spec[:type]
434
+ when :flag; ""
435
+ when :int; " <i>"
436
+ when :ints; " <i+>"
437
+ when :string; " <s>"
438
+ when :strings; " <s+>"
439
+ when :float; " <f>"
440
+ when :floats; " <f+>"
441
+ when :io; " <filename/uri>"
442
+ when :ios; " <filename/uri+>"
443
+ when :date; " <date>"
444
+ when :dates; " <date+>"
445
+ end
446
+ end
447
+
448
+ leftcol_width = left.values.map { |s| s.length }.max || 0
449
+ rightcol_start = leftcol_width + 6 # spaces
450
+
451
+ unless @order.size > 0 && @order.first.first == :text
452
+ stream.puts "#@version\n" if @version
453
+ stream.puts "Options:"
454
+ end
455
+
456
+ @order.each do |what, opt|
457
+ if what == :text
458
+ stream.puts wrap(opt)
459
+ next
460
+ end
461
+
462
+ spec = @specs[opt]
463
+ stream.printf " %#{leftcol_width}s: ", left[opt]
464
+ desc = spec[:desc] + begin
465
+ default_s = case spec[:default]
466
+ when $stdout; "<stdout>"
467
+ when $stdin; "<stdin>"
468
+ when $stderr; "<stderr>"
469
+ when Array
470
+ spec[:default].join(", ")
471
+ else
472
+ spec[:default].to_s
473
+ end
474
+
475
+ if spec[:default]
476
+ if spec[:desc] =~ /\.$/
477
+ " (Default: #{default_s})"
478
+ else
479
+ " (default: #{default_s})"
480
+ end
481
+ else
482
+ ""
483
+ end
484
+ end
485
+ stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
486
+ end
487
+ end
488
+
489
+ def width #:nodoc:
490
+ @width ||= if $stdout.tty?
491
+ begin
492
+ require 'curses'
493
+ Curses::init_screen
494
+ x = Curses::cols
495
+ Curses::close_screen
496
+ x
497
+ rescue Exception
498
+ 80
499
+ end
500
+ else
501
+ 80
502
+ end
503
+ end
504
+
505
+ def wrap str, opts={} # :nodoc:
506
+ if str == ""
507
+ [""]
508
+ else
509
+ str.split("\n").map { |s| wrap_line s, opts }.flatten
510
+ end
511
+ end
512
+
513
+ ## The per-parser version of Trollop::die (see that for documentation).
514
+ def die arg, msg
515
+ if msg
516
+ $stderr.puts "Error: argument --#{@specs[arg][:long]} #{msg}."
517
+ else
518
+ $stderr.puts "Error: #{arg}."
519
+ end
520
+ $stderr.puts "Try --help for help."
521
+ exit(-1)
522
+ end
523
+
524
+ private
525
+
526
+ ## yield successive arg, parameter pairs
527
+ def each_arg args
528
+ remains = []
529
+ i = 0
530
+
531
+ until i >= args.length
532
+ if @stop_words.member? args[i]
533
+ remains += args[i .. -1]
534
+ return remains
535
+ end
536
+ case args[i]
537
+ when /^--$/ # arg terminator
538
+ remains += args[(i + 1) .. -1]
539
+ return remains
540
+ when /^--(\S+?)=(.*)$/ # long argument with equals
541
+ yield "--#{$1}", [$2]
542
+ i += 1
543
+ when /^--(\S+)$/ # long argument
544
+ params = collect_argument_parameters(args, i + 1)
545
+ unless params.empty?
546
+ num_params_taken = yield args[i], params
547
+ unless num_params_taken
548
+ if @stop_on_unknown
549
+ remains += args[i + 1 .. -1]
550
+ return remains
551
+ else
552
+ remains += params
553
+ end
554
+ end
555
+ i += 1 + num_params_taken
556
+ else # long argument no parameter
557
+ yield args[i], nil
558
+ i += 1
559
+ end
560
+ when /^-(\S+)$/ # one or more short arguments
561
+ shortargs = $1.split(//)
562
+ shortargs.each_with_index do |a, j|
563
+ if j == (shortargs.length - 1)
564
+ params = collect_argument_parameters(args, i + 1)
565
+ unless params.empty?
566
+ num_params_taken = yield "-#{a}", params
567
+ unless num_params_taken
568
+ if @stop_on_unknown
569
+ remains += args[i + 1 .. -1]
570
+ return remains
571
+ else
572
+ remains += params
573
+ end
574
+ end
575
+ i += 1 + num_params_taken
576
+ else # argument no parameter
577
+ yield "-#{a}", nil
578
+ i += 1
579
+ end
580
+ else
581
+ yield "-#{a}", nil
582
+ end
583
+ end
584
+ else
585
+ if @stop_on_unknown
586
+ remains += args[i .. -1]
587
+ return remains
588
+ else
589
+ remains << args[i]
590
+ i += 1
591
+ end
592
+ end
593
+ end
594
+
595
+ remains
596
+ end
597
+
598
+ def parse_integer_parameter param, arg
599
+ raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^\d+$/
600
+ param.to_i
601
+ end
602
+
603
+ def parse_float_parameter param, arg
604
+ raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
605
+ param.to_f
606
+ end
607
+
608
+ def parse_io_parameter param, arg
609
+ case param
610
+ when /^(stdin|-)$/i; $stdin
611
+ else
612
+ require 'open-uri'
613
+ begin
614
+ open param
615
+ rescue SystemCallError => e
616
+ raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
617
+ end
618
+ end
619
+ end
620
+
621
+ def collect_argument_parameters args, start_at
622
+ params = []
623
+ pos = start_at
624
+ while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
625
+ params << args[pos]
626
+ pos += 1
627
+ end
628
+ params
629
+ end
630
+
631
+ def rewrite_long_true_flags!
632
+ @specs.each do |name, spec|
633
+ negative = "no-" + spec[:long]
634
+ spec[:long] = negative if spec[:type] == :flag && spec[:default] == true
635
+ @long[negative] = name
636
+ end
637
+ end
638
+
639
+ def resolve_default_short_options!
640
+ @order.each do |type, name|
641
+ next unless type == :opt
642
+ opts = @specs[name]
643
+ next if opts[:short]
644
+
645
+ c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
646
+ if c # found a character to use
647
+ opts[:short] = c
648
+ @short[c] = name
649
+ end
650
+ end
651
+ end
652
+
653
+ def wrap_line str, opts={}
654
+ prefix = opts[:prefix] || 0
655
+ width = opts[:width] || (self.width - 1)
656
+ start = 0
657
+ ret = []
658
+ until start > str.length
659
+ nextt =
660
+ if start + width >= str.length
661
+ str.length
662
+ else
663
+ x = str.rindex(/\s/, start + width)
664
+ x = str.index(/\s/, start) if x && x < start
665
+ x || str.length
666
+ end
667
+ ret << (ret.empty? ? "" : " " * prefix) + str[start ... nextt]
668
+ start = nextt + 1
669
+ end
670
+ ret
671
+ end
672
+
673
+ ## instance_eval but with ability to handle block arguments
674
+ ## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html
675
+ def cloaker &b
676
+ (class << self; self; end).class_eval do
677
+ define_method :cloaker_, &b
678
+ meth = instance_method :cloaker_
679
+ remove_method :cloaker_
680
+ meth
681
+ end
682
+ end
683
+ end
684
+
685
+ ## The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
686
+ ## passes the block to it, then parses +args+ with it, handling any errors or
687
+ ## requests for help or version information appropriately (and then exiting).
688
+ ## Modifies +args+ in place. Returns a hash of option values.
689
+ ##
690
+ ## The block passed in should contain zero or more calls to +opt+
691
+ ## (Parser#opt), zero or more calls to +text+ (Parser#text), and
692
+ ## probably a call to +version+ (Parser#version).
693
+ ##
694
+ ## The returned block contains a value for every option specified with
695
+ ## +opt+. The value will be the value given on the commandline, or the
696
+ ## default value if the option was not specified on the commandline. For
697
+ ## every option specified on the commandline, a key "<option
698
+ ## name>_given" will also be set in the hash.
699
+ ##
700
+ ## Example:
701
+ ##
702
+ ## require 'trollop'
703
+ ## opts = Trollop::options do
704
+ ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
705
+ ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
706
+ ## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
707
+ ## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
708
+ ## end
709
+ ##
710
+ ## ## if called with no arguments
711
+ ## p opts # => { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
712
+ ##
713
+ ## ## if called with --monkey
714
+ ## p opts # => {:monkey_given=>true, :monkey=>true, :goat=>true, :num_limbs=>4, :help=>false, :num_thumbs=>nil}
715
+ ##
716
+ ## See more examples at http://trollop.rubyforge.org.
717
+ def options args=ARGV, *a, &b
718
+ @last_parser = Parser.new(*a, &b)
719
+ with_standard_exception_handling(@last_parser) { @last_parser.parse args }
720
+ end
721
+
722
+ ## If Trollop::options doesn't do quite what you want, you can create a Parser
723
+ ## object and call Parser#parse on it. That method will throw CommandlineError,
724
+ ## HelpNeeded and VersionNeeded exceptions when necessary; if you want to
725
+ ## have these handled for you in the standard manner (e.g. show the help
726
+ ## and then exit upon an HelpNeeded exception), call your code from within
727
+ ## a block passed to this method.
728
+ ##
729
+ ## Note that this method will call System#exit after handling an exception!
730
+ ##
731
+ ## Usage example:
732
+ ##
733
+ ## require 'trollop'
734
+ ## p = Trollop::Parser.new do
735
+ ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
736
+ ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
737
+ ## end
738
+ ##
739
+ ## opts = Trollop::with_standard_exception_handling p do
740
+ ## o = p.parse ARGV
741
+ ## raise Trollop::HelpNeeded if ARGV.empty? # show help screen
742
+ ## o
743
+ ## end
744
+ ##
745
+ ## Requires passing in the parser object.
746
+
747
+ def with_standard_exception_handling parser
748
+ begin
749
+ yield
750
+ rescue CommandlineError => e
751
+ $stderr.puts "Error: #{e.message}."
752
+ $stderr.puts "Try --help for help."
753
+ exit(-1)
754
+ rescue HelpNeeded
755
+ parser.educate
756
+ exit
757
+ rescue VersionNeeded
758
+ puts parser.version
759
+ exit
760
+ end
761
+ end
762
+
763
+ ## Informs the user that their usage of 'arg' was wrong, as detailed by
764
+ ## 'msg', and dies. Example:
765
+ ##
766
+ ## options do
767
+ ## opt :volume, :default => 0.0
768
+ ## end
769
+ ##
770
+ ## die :volume, "too loud" if opts[:volume] > 10.0
771
+ ## die :volume, "too soft" if opts[:volume] < 0.1
772
+ ##
773
+ ## In the one-argument case, simply print that message, a notice
774
+ ## about -h, and die. Example:
775
+ ##
776
+ ## options do
777
+ ## opt :whatever # ...
778
+ ## end
779
+ ##
780
+ ## Trollop::die "need at least one filename" if ARGV.empty?
781
+ def die arg, msg=nil
782
+ if @last_parser
783
+ @last_parser.die arg, msg
784
+ else
785
+ raise ArgumentError, "Trollop::die can only be called after Trollop::options"
786
+ end
787
+ end
788
+
789
+ module_function :options, :die, :with_standard_exception_handling
790
+
791
+ end # module