Class: Clive::Command

Inherits:
Option
  • Object
show all
Includes:
StateActions
Defined in:
lib/clive/command.rb

Overview

A command allows you to separate groups of commands under their own namespace. But it can also take arguments like an Option. Instead of executing the block passed to it executes the block passed to #action.

Examples:


class CLI < Clive

  command :new, arg: '<dir>' do
    # options
    bool :force

    action do |dir|
      # code
    end
  end

end

Direct Known Subclasses

Base

Constant Summary collapse

DEFAULTS =
{
  :group     => nil,
  :head      => false,
  :tail      => false,
  :runner    => Clive::Option::Runner,

  # these two are copied in from Base, so will be merged over
  :formatter => nil,
  :help      => nil,
  :name      => nil
}

Instance Attribute Summary collapse

Attributes inherited from Option

#args, #names

DSL Methods collapse

Instance Method Summary collapse

Methods included from StateActions

#get, #get!, #set, #update

Methods inherited from Option

#<=>, #block?, #inspect, long, #run, short

Constructor Details

#initialize(names = [], description = "", config = {}, &block) ⇒ Command

Returns a new instance of Command.

Parameters:

  • names (Array[Symbol]) (defaults to: [])

    Names that the Command can be ran with.

  • desc (String)

    Description of the Command, this is shown in help and will be wrapped properly.

  • config (Hash) (defaults to: {})

Options Hash (config):

  • :head (Boolean)

    If option should be at top of help list.

  • :tail (Boolean)

    If option should be at bottom of help list.

  • :group (String)

    Name of the group this option belongs to. This is actually set when #group is used.

  • :runner (Runner)

    Class to use for running the block passed to #action. This doesn't have to be Option::Runner, but you probably never need to change this.

  • :formatter (Formatter)

    Help formatter to use for this command, defaults to top-level formatter.

  • :help (Boolean)

    Whether to add a '-h, –help' option to this command which displays help.

  • :args (String)

    Arguments that the option takes. See Argument.

  • :as (Type, Array[Type])

    The class the argument(s) should be cast to. See Type.

  • :match (#match, Array[#match])

    Regular expression that the argument(s) must match.

  • :in (#include?, Array[#include?])

    Collection that argument(s) must be in.

  • :default (Object)

    Default value that is used if argument is not given.


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/clive/command.rb', line 71

def initialize(names=[], description="", config={}, &block)
  @names       = names
  @description = description
  @options     = []
  @_block      = block

  @args = Arguments.create(get_subhash(config, Arguments::Parser::KEYS))
  @config = DEFAULTS.merge(get_subhash(config, DEFAULTS.keys))

  # Create basic header "Usage: filename commandname(s) [options]
  @header = proc { "Usage: #{@config[:name]} #{to_s} [options]" }
  @footer = ""
  @_group = nil

  add_help_option

  current_desc
end

Instance Attribute Details

#optionsArray<Option> (readonly)

Returns List of options created in the Command instance.

Returns:

  • (Array<Option>)

    List of options created in the Command instance


25
26
27
# File 'lib/clive/command.rb', line 25

def options
  @options
end

Instance Method Details

#action(&block) ⇒ Object

The action block is the block which will be executed with any arguments that are found for it. It sets @block so that Option#run does not have to be redefined.

Examples:


command :create, arg: '<name>', 'Creates a new project' do
  bool :bare, "Don't add boilerplate code to created files"

  action do |name|
    if get(:bare)
      # write some empty files
    else
      # create some files with stuff in
    end
  end
end

262
263
264
# File 'lib/clive/command.rb', line 262

def action(&block)
  @block = block
end

#boolean(short = nil, long, description = current_desc, opts = {}, &block) ⇒ Object Also known as: bool

Examples:


bool :auto, 'Auto regenerate on changes'

# Usage
#  --auto      sets :auto to true
#  --no-auto   sets :auto to false

Creates a new Option in the Command which responds to calls with a 'no-' prefix. long must be set.

Parameters:

  • short (Symbol) (defaults to: nil)

    The short name for the option (:a would become -a)

  • long (Symbol)

    The long name for the option (:add would become --add)

  • description (String) (defaults to: current_desc)

    Description of the option

  • opts (Hash) (defaults to: {})

    Options to create the Option with, see Option#initialize


203
204
205
206
207
208
209
210
211
212
213
# File 'lib/clive/command.rb', line 203

def boolean(*args, &block)
  ns, d, o = [], current_desc, {}
  args.each do |i|
    case i
      when ::Symbol then ns << i
      when ::String then d = i
      when ::Hash   then o = i
    end
  end
  @options << Option.new(ns, d, ({:group => @_group, :boolean => true}).merge(o), &block)
end

#config(opts = nil) ⇒ Object

Set configuration values for the command, as if you passed an options hash to #initialize.

Examples:


config arg: '<dir>'

Parameters:

  • See (Hash)

    #initialize


147
148
149
150
151
152
153
# File 'lib/clive/command.rb', line 147

def config(opts=nil)
  if opts
    @config = @config.merge(get_subhash(opts, DEFAULTS.keys))
  else
    @config
  end
end

#desc(arg) ⇒ Object

Short version of #description which can only set.

Examples:


desc 'Displays the current version'
opt(:version) { puts $VERSION }

Parameters:


241
242
243
# File 'lib/clive/command.rb', line 241

def desc(arg)
  @_last_desc = arg
end

#description(arg = nil) ⇒ Object

If an argument is given it will set the description to that, otherwise it will return the description for the command.

Examples:


description 'Displays the current version'
opt(:version) { puts $VERSION }

Parameters:

  • arg (String) (defaults to: nil)

225
226
227
228
229
230
231
# File 'lib/clive/command.rb', line 225

def description(arg=nil)
  if arg
    @_last_desc = arg
  else
    @description
  end
end

#end_groupObject

Sugar for group(nil)


285
286
287
# File 'lib/clive/command.rb', line 285

def end_group
  group nil
end

#find(arg) ⇒ Option? Also known as: []

Finds the option represented by arg, this can either be the long name --opt or the short name -o, if the option can't be found nil is returned.

Examples:


a = Command.new [:command] do
  bool :force
end

a.find('--force')
#=> #<Clive::Option --[no-]force>

Parameters:

Returns:


305
306
307
308
309
310
311
# File 'lib/clive/command.rb', line 305

def find(arg)
  if arg[0..1] == '--'
    find_option(arg[2..-1].gsub('-', '_').to_sym)
  elsif arg[0..0] == '-'
    find_option(arg[1..-1].to_sym)
  end
end

#find_option(arg) ⇒ Option?

Finds the option with the name given by arg, this must be in Symbol form so does not have a dash before it. As with #find if the option does not exist nil will be returned.

Examples:


a = Command.new [:command] do
  bool :force
end

a.find_option(:force)
#=> #<Clive::Option --[no-]force>

Parameters:

  • arg (Symbol)

Returns:


349
350
351
# File 'lib/clive/command.rb', line 349

def find_option(arg)
  @options.find {|opt| opt.names.include?(arg) }
end

Set the footer for #help.

Examples:


footer 'For more help visit http://mysite.com/help'

Parameters:


135
136
137
# File 'lib/clive/command.rb', line 135

def footer(val)
  @footer = val
end

#group(name) ⇒ Object

Set the group name for all options defined after it.

Examples:


group 'Files'
opt :move,   'Moves a file',   args: '<from> <to>'
opt :delete, 'Deletes a file', arg:  '<file>'
opt :create, 'Creates a file', arg:  '<name>'

group 'Network'
opt :upload,   'Uploads everything'
opt :download, 'Downloads everyhting'

Parameters:


280
281
282
# File 'lib/clive/command.rb', line 280

def group(name)
  @_group = name
end

#has?(arg) ⇒ Boolean

Attempts to find the option represented by the string arg, returns true if it exists and false if not.

Examples:


a = Command.new [:command] do
  bool :force
  bool :auto
end

a.has?('--force')    #=> true
a.has?('--auto')     #=> true
a.has?('--no-auto')  #=> false
a.has?('--not-real') #=> false

Parameters:

Returns:

  • (Boolean)

330
331
332
# File 'lib/clive/command.rb', line 330

def has?(arg)
  !!find(arg)
end

#has_option?(arg) ⇒ Boolean

Attempts to find the option with the Symbol name given, returns true if the option exists and false if not.

Parameters:

  • arg (Symbol)

Returns:

  • (Boolean)

357
358
359
# File 'lib/clive/command.rb', line 357

def has_option?(arg)
  !!find_option(arg)
end

#header(val) ⇒ Object

Set the header for #help.

Examples:


header 'Usage: my_app [options] [args]'

Parameters:


125
126
127
# File 'lib/clive/command.rb', line 125

def header(val)
  @header = val
end

#helpString

Returns Help string for this command.

Returns:

  • (String)

    Help string for this command.

See Also:


363
364
365
366
367
368
369
370
371
372
# File 'lib/clive/command.rb', line 363

def help
  f = @config[:formatter]

  f.header   = @header.respond_to?(:call) ? @header.call : @header
  f.footer   = @footer.respond_to?(:call) ? @footer.call : @footer
  f.commands = @commands if @commands
  f.options  = @options

  f.to_s
end

#nameSymbol

Returns Single name to use when referring specifically to this command. Use the first name that was passed in.

Returns:

  • (Symbol)

    Single name to use when referring specifically to this command. Use the first name that was passed in.


92
93
94
# File 'lib/clive/command.rb', line 92

def name
  names.first
end

#option(short = nil, long = nil, description = current_desc, opts = {}, &block) ⇒ Object Also known as: opt

Examples:


opt :type, arg: '<size>', in: %w(small medium large) do
  case size
    when "small"  then set(:size, 1)
    when "medium" then set(:size, 2)
    when "large"  then set(:size, 3)
  end
end

Creates a new Option in the Command. Either short or long must be set.

Parameters:

  • short (Symbol) (defaults to: nil)

    The short name for the option (:a would become -a)

  • long (Symbol) (defaults to: nil)

    The long name for the option (:add would become --add)

  • description (String) (defaults to: current_desc)

    Description of the option

  • opts (Hash) (defaults to: {})

    Options to create the Option with, see Option#initialize


174
175
176
177
178
179
180
181
182
183
184
# File 'lib/clive/command.rb', line 174

def option(*args, &block)
  ns, d, o = [], current_desc, {}
  args.each do |i|
    case i
      when ::Symbol then ns << i
      when ::String then d = i
      when ::Hash   then o = i
    end
  end
  @options << Option.new(ns, d, ({:group => @_group}).merge(o), &block)
end

#run_block(state) ⇒ Hash

Runs the block that was given to #initialize within the context of the command. The state hash is passed (and returned) so that StateActions#set works outside of Option::Runner allowing default values to be set.

Parameters:

  • state (Hash)

    The newly created state for the command.

Returns:

  • (Hash)

    The returned hash is used for the state of the command.


107
108
109
110
111
112
113
114
115
# File 'lib/clive/command.rb', line 107

def run_block(state)
  if @_block
    @state = state
    instance_exec(&@_block)
    @state
  else
    @state = state
  end
end

#to_sString

Returns:


97
98
99
# File 'lib/clive/command.rb', line 97

def to_s
  names.join(',')
end