Class: QB::Options

Inherits:
Object
  • Object
show all
Includes:
SemanticLogger::Loggable
Defined in:
lib/qb/options.rb,
lib/qb/options/option.rb

Defined Under Namespace

Classes: Option

Constant Summary collapse

QB_DEFAULTS =

Default initial values for #qb.

Returns:

  • (Hash)
{
  'hosts' => ['localhost'].freeze,
  'facts' => true,
  'print' => [].freeze,
  'verbose' => false,
  'run' => true,
  'ask' => false,
}.freeze
SPACER =

Appended on the end of an opts.on call to create a newline after the option (making the help output a bit easier to read)

You might think the empty string would be reasonable, but OptionParser blows up if you do that.

Returns:

  • (String)
' '

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(role, argv) ⇒ Options

Returns a new instance of Options.

Parameters:

  • role (Role)

    the role to parse the args for.



327
328
329
330
331
332
333
# File 'lib/qb/options.rb', line 327

def initialize role, argv
  @role = role
  @argv = argv
  @qb = QB_DEFAULTS.dup
  
  parse!
end

Instance Attribute Details

#ansibleObject (readonly)

Returns the value of attribute ansible.



53
54
55
# File 'lib/qb/options.rb', line 53

def ansible
  @ansible
end

#qbObject (readonly)

Returns the value of attribute qb.



63
64
65
# File 'lib/qb/options.rb', line 63

def qb
  @qb
end

#role_optionsObject (readonly)

Returns the value of attribute role_options.



58
59
60
# File 'lib/qb/options.rb', line 58

def role_options
  @role_options
end

Class Method Details

.add(opts, options, role, include_path = []) ⇒ Object

add the options from a role to the OptionParser



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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/qb/options.rb', line 126

def self.add opts, options, role, include_path = []
  QB.debug "adding options", "role" => role
  
  role.option_metas.each do |option_meta|
    if option_meta.key? 'include'
      include_role opts, options, option_meta, include_path
      
    else
      # create an option
      option = Option.new role, option_meta, include_path
      
      on_args = []
      
      if option.meta['type'] == 'boolean'
        # don't use short names when included (for now)
        if include_path.empty? && option.meta['short']
          on_args << "-#{ option.meta['short'] }"
        end
        
        on_args << "--[no-]#{ option.cli_name }"
        
      else
        ruby_type = case option.meta['type']
        when nil
          raise QB::Role::MetadataError.squished <<-END
            must provide type in QB metadata for option
            #{ option.meta_name }
          END
          
        when 'string', 'str'
          String
          
        when 'array', 'list'
          Array
          
        when 'integer', 'int'
          Integer
          
        when 'version'
          QB::Package::Version
          
        when 'hash', 'dict'
          Class.new.tap { |klass|
            opts.accept(klass) { |value|
              value.split(',').map { |pair_str|
                split = pair_str.split ':'
                if split.length > 2
                  raise ArgumentError.dedented <<-END
                    
                    Can only have a single ':' in `hash` options.
                    
                    Found #{ pair_str.inspect }
                    
                    In #{ value.inspect }
                    
                  END
                end
                [split[0], split[1]]
              }.to_h
            }
          }
          
        when 'path'
          String
          # Class.new.tap { |klass|
          #   opts.accept(klass) { |value|
          #     
          #   }
          # }
        
        when 'glob'
          Class.new.tap { |klass|
            opts.accept(klass) { |glob|
              if glob.start_with? '//'
                glob = NRSER.git_root(Dir.getwd).
                  join(glob[2..-1]).
                  to_s
              end
              
              Dir[glob]
            }
          }
          
        when Hash
          if option.meta['type'].key? 'one_of'
            Class.new.tap { |klass|
              opts.accept(klass) { |value|
                if option.meta['type']['one_of'].include? value
                  value
                else
                  raise QB::Role::MetadataError,
                    "option '#{ option.cli_name }' must be one of: #{ option.meta['type']['one_of'].join(', ') }"
                end
              }
            }
          else
            raise QB::Role::MetadataError,
              "bad type for option #{ option.meta_name }: #{ option.meta['type'].inspect }"
          end
        else
          raise QB::Role::MetadataError,
            "bad type for option #{ option.meta_name }: #{ option.meta['type'].inspect }"
        end
        
        # don't use short names when included (for now)
        if include_path.empty? && option.meta['short']
          on_args << "-#{ option.meta['short'] } #{ option.meta_name.upcase }"
        end
        
        if option.meta['accept_false']
          on_args << "--[no-]#{ option.cli_name }=#{ option.meta_name.upcase }"
        else
          on_args << "--#{ option.cli_name }=#{ option.meta_name.upcase }"
        end
          
        
        on_args << ruby_type
      end
      
      on_args << option.description
      
      if option.required?
        on_args << "REQUIRED."
      end
      
      if role.defaults.key? option.var_name
        if option.meta['type'] == 'boolean'
          on_args << if role.defaults[option.var_name]
            "DEFAULT: --#{ option.cli_name }"
          else
            "DEFAULT: --no-#{ option.cli_name }"
          end
        elsif !role.defaults[option.var_name].nil?
          on_args << "DEFAULT: #{ role.defaults[option.var_name] }"
        end
      end
      
      if option.has_examples?
        on_args << 'examples:'
        
        option.examples.each_with_index {|example, index|
          lines = example.lines.to_a
          
          # was this debuggin? had to be...
          # pp lines
          
          on_args << ((index + 1).to_s + '.').ljust(4) + lines.first.chomp
          
          lines[1..-1].each {|line|
            on_args << (" ".ljust(4) + line.chomp)
          }
        }
      end
      
      on_args << SPACER
      
      QB.debug "adding option", option: option, on_args: on_args
      
      opts.on(*on_args) do |value|
        QB.debug  "setting option",
                  option: option,
                  value: value
        
        option.value = value
      end
      
      options[option.cli_name] = option
    end
  end # each var
end

.cli_ize_name(option_name) ⇒ String

turn a name into a "command line" version by replacing underscores with dashes.

Examples:

QB::Options.cli_ize_name "my_var" # => "my-var"

Parameters:

  • option_name (String)

    the input option name.

Returns:

  • (String)

    the CLI-ized name.



80
81
82
# File 'lib/qb/options.rb', line 80

def self.cli_ize_name option_name
  option_name.gsub '_', '-'
end

.include_role(opts, options, include_meta, include_path) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/qb/options.rb', line 100

def self.include_role opts, options, include_meta, include_path
  role_name = include_meta['include']
  role = QB::Role.require role_name
  new_include_path = if include_meta.key? 'as'
    case include_meta['as']
    when nil, false
      # include it in with the parent role's options
      include_path
    when String
      include_path + [include_meta['as']]
    else
      raise QB::Role::MetadataError.new,
        "bad 'as' value: #{ include_meta.inspect }"
    end
  else
    include_path + [role.namespaceless]
  end
  
  QB.debug "including #{ role.name } as #{ new_include_path.join('-') }"
  
  opts.separator "Options for included #{ role.name } role:"
  
  add opts, options, role, new_include_path
end

.parse!(role, argv) ⇒ Array<Hash<String, Option|Object>>

destructively removes options from @argv and populates ansible, role, and qb option hashes.

Parameters:

  • role (QB::Role)

    the role to parse the options for.

  • args (Array<String>)

    CLI args -- ARGV with the role arg shifted off.

Returns:

  • (Array<Hash<String, Option|Object>>)

    a two-element array:

    1. the options for the role, hash of Option#cli_name to Option instances.

    2. the general qb options, hash of String key to option values.

Raises:

  • if bad options are found.



316
317
318
319
# File 'lib/qb/options.rb', line 316

def self.parse! role, argv
  options = self.new role, argv
  [options.role_options, options.qb]
end

.var_ize_name(option_name) ⇒ String

turn a name into a "ruby / ansible variable" version by replacing dashes with underscores.

Examples:

QB::Options.cli_ize_name "my-var" # => "my_var"

Parameters:

  • option_name (String)

    the input option name.

Returns:

  • (String)

    the ruby / ansible var-ized name.



96
97
98
# File 'lib/qb/options.rb', line 96

def self.var_ize_name option_name
  option_name.gsub '-', '_'
end

Instance Method Details

#ask?return_type

TODO:

Document ask? method.

Returns @todo Document return value.

Parameters:

  • arg_name (type)

    @todo Add name param description.

Returns:

  • (return_type)

    @todo Document return value.



345
346
347
# File 'lib/qb/options.rb', line 345

def ask?
  @qb['ask']
end