lib/configliere/commandline.rb in configliere-0.0.2 vs lib/configliere/commandline.rb in configliere-0.0.3

- old
+ new

@@ -5,10 +5,18 @@ # Command line tool to manage param info # module Commandline attr_accessor :rest + # Processing to reconcile all options + # + # Configliere::Commandline's resolve!: + # * processes all commandline params + # * if the --help param was given, prints out a usage statement (using + # any +:description+ set with #define) and then exits + # * lastly, calls the next method in the resolve! chain. + # def resolve! process_argv! dump_help_if_requested begin ; super() ; rescue NoMethodError ; nil ; end end @@ -32,13 +40,14 @@ when arg == '--' self.rest += args break when arg =~ /\A--([\w\-\.]+)(?:=(.*))?\z/ param, val = [$1, $2] - param.gsub!(/\-/, '.') - if val == nil then val = true # --flag option on its own means 'set that option' - elsif val == '' then val = nil end # --flag='' the explicit empty string means nil + param.gsub!(/\-/, '.') # translate --scoped-flag to --scoped.flag + param = param.to_sym unless (param =~ /\./) # symbolize non-scoped keys + if val == nil then val = true # --flag option on its own means 'set that option' + elsif val == '' then val = nil end # --flag='' the explicit empty string means nil self[param] = val else self.rest << arg end end @@ -57,14 +66,17 @@ def normal_params reject{|param, val| param_definitions[param][:internal] } end # die with a warning - def die str + # + # @param str [String] the string to dump out before exiting + # @param exit_code [Integer] UNIX exit code to set, default -1 + def die str, exit_code=-1 puts help warn "\n****\n#{str}\n****" - exit -1 + exit exit_code end # Retrieve the given param, or prompt for it def param_or_ask attr, hint=nil return self[attr] if include?(attr) @@ -78,20 +90,25 @@ # help_str += ["\nCommands", commands.map{|cmd, desc| " %-20s %s"%[cmd.to_s+':', desc]}.join("\n")] if respond_to?(:commands) help_str += [ "\nEnvironment Variables can be used to set:", params_from_environment.map{|param, env| " %-27s %s"%[env.to_s+':', param]}.join("\n"), ] if respond_to?(:params_from_environment) help_str.join("\n") end + def dump_help extra_msg=nil + $stderr.puts help + $stderr.puts "\n\n"+extra_msg unless extra_msg.blank? + end + # Usage line def usage %Q{usage: #{File.basename($0)} [...--param=val...]} end protected # Ouput the help string if requested def dump_help_if_requested return unless self[:help] - $stderr.puts help + dump_help exit end end Param.class_eval do