Module: CliHelper

Defined in:
lib/cli_helper.rb

Overview

module Slop

Constant Summary collapse

DEFAULTS =
{
  version:        '0.0.1',# the version of this program
  arguments:      [],     # whats left after options and parameters are extracted
  verbose:        false,
  debug:          false,
  help:           false,
  support_config_files: false,
  disable_help:   false,
  disable_debug:  false,
  disable_verbose: false,
  disable_version: false,
  suppress_errors: false,
  user_name:      Nenv.user || Nenv.user_name || Nenv.logname || 'The Unknown Programmer',
  home_path:      Pathname.new(Nenv.home),
  cli:            'a place holder for the Slop object',
  errors:         [],
  warnings:       []
}

Instance Method Summary collapse

Instance Method Details

#abort_if_errorsObject

Display global warnings and errors arrays and exit if necessary



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/cli_helper.rb', line 273

def abort_if_errors
  unless configatron.warnings.empty?
    STDERR.puts
    STDERR.puts "The following warnings were generated:"
    STDERR.puts
    configatron.warnings.each do |w|
      STDERR.puts "\tWarning: #{w}"
    end
    STDERR.print "\nAbort program? (y/N) "
    answer = (STDIN.gets).chomp.strip.downcase
    configatron.errors << "Aborted by user" if answer.size>0 && 'y' == answer[0]
    configatron.warnings = []
  end
  unless configatron.errors.empty?
    STDERR.puts
    STDERR.puts "Correct the following errors and try again:"
    STDERR.puts
    configatron.errors.each do |e|
      STDERR.puts "\t#{e}"
    end
    STDERR.puts
    exit(-1)
  end
end

#cli_helper(my_banner = '') {|param| ... } ⇒ Object

Invoke Slop with common CLI parameters and custom parameters provided via a block. Create ‘?’ for all boolean parameters that have a ‘–name’ flag form. Returns a Slop::Options object

Yields:

  • (param)


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/cli_helper.rb', line 108

def cli_helper(my_banner='')
  param = Slop::Options.new

  if my_banner.empty?
    param.banner = "Usage: #{my_name} [options] ..."
  else
    param.banner = my_banner
    param.separator "\nUsage: #{my_name} [options] ..."
  end

  param.separator "\nWhere:"

  if  configatron.disable_help      &&
      configatron.disable_verbose   &&
      configatron.disable_debug     &&
      configatron.disable_version
    # NOOP
  else
    param.separator "\n  Common Options Are:"
  end

  unless configatron.disable_help
    param.bool '-h', '--help',    'show this message'
  end

  unless configatron.disable_verbose
    param.bool '-v', '--verbose', 'enable verbose mode'
  end

  unless configatron.disable_debug
    param.bool '-d', '--debug',   'enable debug mode'
  end

  unless configatron.disable_version
    param.on '--version', "print the version: #{configatron.version}" do
      puts configatron.version
      exit
    end
  end

  param.separator "\n  Program Options Are:"

  yield(param) if block_given?

  if configatron.support_config_files
    param.paths '--config',    'read config file(s) [*.rb, *.yml, *.ini]'
  end

  parser = Slop::Parser.new(param, suppress_errors: configatron.suppress_errors)
  configatron.cli = parser.parse(ARGV)

  # TODO: DRY this conditional block
  if configatron.support_config_files

    configatron.cli[:config].each do |cf|
      unless cf.exist? || cf.directory?
        error "Config file is missing: #{cf}"
      else
        file_type = case cf.extname.downcase
          when '.rb'
            :ruby
          when '.yml', '.yaml'
            :yaml
          when '.ini', '.txt'
            :ini
          when '.erb'
            extname = cf.basename.to_s.downcase.gsub('.erb','').split('.').last
            if %w[ yml yaml].include? extname
              :yaml
            elsif %w[ ini txt ].include? extname
              :ini
            elsif 'rb' == extname
              raise 'MakesNoSenseToMe: *.rb.erb is not supported'
            else
              :unknown
            end
        else
          :unknown
        end

        case file_type
          when :ruby
            load cf
          when :yaml
            configatron.configure_from_hash(
              config_file_hash = configatron.configure_from_hash(
                cli_helper_process_yaml(
                  cli_helper_process_erb(cf.read)
                )
              )
            )
          when :ini
            configatron.configure_from_hash(
              configatron.configure_from_hash(
                cli_helper_process_ini( cf # FIXME: fork parseconfig
                  # cli_helper_process_erb(cf.read)
                )
              )
            )
          else
            error "Do not know how to parse this file: #{cf}"
        end # case type_type
      end # unless cf.exist? || cf.directory?
    end # configatron.cli.config.each do |cf|
  end # if configatron.support_config_files

  configatron.configure_from_hash(configatron.cli.to_hash)
  configatron.arguments = configatron.cli.arguments

  bools = param.options.select do |o|
    o.is_a? Slop::BoolOption
  end.select{|o| o.flags.select{|f|f.start_with?('--')}}.
      map{|o| o.flags.last.gsub('--','')} # SMELL: depends on convention

  bools.each do |m|
    s = m.to_sym
    define_method(m+'?') do
      configatron[s]
    end unless self.respond_to?(m+'?')
    define_method((m+'!').to_sym) do
      configatron[s] = true
    end unless self.respond_to?(m+'!')
  end


  if self.respond_to?(:help?) && help?
    show_usage
    exit
  end

  return param
end

#cli_helper_process_erb(file_contents) ⇒ Object



88
89
90
91
# File 'lib/cli_helper.rb', line 88

def cli_helper_process_erb(file_contents)
  erb_contents = ERB.new(file_contents).result
  return erb_contents
end

#cli_helper_process_ini(file_path, file_contents = '') ⇒ Object



98
99
100
101
102
# File 'lib/cli_helper.rb', line 98

def cli_helper_process_ini(file_path, file_contents='')
  # FIXME: mod the parseconfig gem to use a parse method on strings
  an_ini_object = ParseConfig.new(file_path)
  return an_ini_object.params
end

#cli_helper_process_yaml(file_contents = '') ⇒ Object



93
94
95
96
# File 'lib/cli_helper.rb', line 93

def cli_helper_process_yaml(file_contents='')
  a_hash = YAML.load file_contents
  return a_hash
end

#error(a_string) ⇒ Object

Adds a string to the global $errors array



299
300
301
# File 'lib/cli_helper.rb', line 299

def error(a_string)
  configatron.errors << a_string
end

#get_pathnames_from(an_array, extnames = ['.json', '.txt', '.docx']) ⇒ Object

Returns an array of valid files of one type



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/cli_helper.rb', line 255

def get_pathnames_from(an_array, extnames=['.json', '.txt', '.docx'])
  an_array = [an_array] unless an_array.is_a? Array
  extnames = [extnames] unless extnames.is_a? Array
  extnames = extnames.map{|e| e.downcase}
  file_array = []
  an_array.each do |a|
    pfn = Pathname.new(a)
    if pfn.directory?
      file_array << get_pathnames_from(pfn.children, extnames)
    else
      file_array << pfn if pfn.exist? && extnames.include?(pfn.extname.downcase)
    end
  end
  return file_array.flatten
end

#meObject

Return full pathname of program



74
75
76
# File 'lib/cli_helper.rb', line 74

def me
  configatron.me
end

#my_nameObject

Returns the basename of the program as a string



79
80
81
# File 'lib/cli_helper.rb', line 79

def my_name
  configatron.my_name
end

#show_usageObject

Prints to STDOUT the usage/help string



249
250
251
# File 'lib/cli_helper.rb', line 249

def show_usage
  puts usage()
end

#usageObject

Returns the usage/help information as a string



242
243
244
245
246
# File 'lib/cli_helper.rb', line 242

def usage
  a_string = configatron.cli.to_s + "\n"
  a_string += HELP + "\n" if defined?(HELP)
  return a_string
end

#versionObject

Returns the version of the program as a string



84
85
86
# File 'lib/cli_helper.rb', line 84

def version
  configatron.version
end

#warning(a_string) ⇒ Object

Adds a string to the global $warnings array



304
305
306
# File 'lib/cli_helper.rb', line 304

def warning(a_string)
  configatron.warnings << a_string
end