Class: CmdParser

Inherits:
Object
  • Object
show all
Defined in:
lib/commons.rb

Constant Summary collapse

@@data =
{}
@@bindings =
{}

Class Method Summary collapse

Class Method Details

.assertObject



237
238
239
240
241
242
243
# File 'lib/commons.rb', line 237

def self.assert
    error_message = yield
    if error_message
        puts error_message
        exit
    end
end

.assert_not_set(forbidden_key, actual_param, forbidden_param, message = "incompatible commands") ⇒ Object



245
246
247
248
249
250
# File 'lib/commons.rb', line 245

def self.assert_not_set(forbidden_key, actual_param, forbidden_param, message="incompatible commands")
    if CmdParser.opt(forbidden_key) != nil
        puts "Do not use #{forbidden_param} with #{actual_param} (#{message}). Aborting."
        exit
    end
end

.autoset_flag(short, long, description, flag, incompatibles = []) ⇒ Object



215
216
217
218
219
220
221
222
223
224
# File 'lib/commons.rb', line 215

def self.autoset_flag(short, long, description, flag, incompatibles=[])
    @@bindings[flag] = short
    @@opts.on(short, long, description) do
        incompatibles.each do |incompatible|
            CmdParser.assert_not_set incompatible, short, @@bindings[incompatible]
        end
        
        CmdParser.set flag, true
    end
end

.autoset_param(short, long, description, flag, incompatibles = []) ⇒ Object



226
227
228
229
230
231
232
233
234
235
# File 'lib/commons.rb', line 226

def self.autoset_param(short, long, description, flag, incompatibles=[])
    @@bindings[flag] = short
    @@opts.on(short, long, description) do |v|
        incompatibles.each do |incompatible|
            CmdParser.assert_not_set incompatible, short, @@bindings[incompatible]
        end
        
        CmdParser.set flag, v
    end
end

.opt(key) ⇒ Object



179
180
181
# File 'lib/commons.rb', line 179

def self.opt(key)
    return @@data[key]
end

.set(key, value) ⇒ Object



183
184
185
# File 'lib/commons.rb', line 183

def self.set(key, value)
    @@data[key] = value
end

.setup(cmd, *args) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/commons.rb', line 187

def self.setup(cmd, *args)
    parser = OptionParser.new do |opts|
        opts.banner = "Usage: #{cmd} [options] #{args.join " "}"
        
        @@opts = opts
        yield opts
        @@opts = nil
        
        opts.on("-v", "--verbose", "Writes a lot of information") do
            CmdParser.set :verbose, true
        end
        
        opts.on("-h", "--help", "Prints this help") do
            puts opts
            exit
        end
    end
    
    parser.parse! ARGV
    
    arguments = {}
    for i in 0...args.size
        arguments[args[i]] = ARGV[i]
    end
    
    return arguments
end