Class: Linecook::CommandSet

Inherits:
Command
  • Object
show all
Defined in:
lib/linecook/command_set.rb

Direct Known Subclasses

Executable

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Command

help, #initialize, signature

Constructor Details

This class inherits a constructor from Linecook::Command

Class Method Details

.command_listObject



37
38
39
40
41
# File 'lib/linecook/command_set.rb', line 37

def command_list
  commands.keys.sort.collect do |name|
    [name, commands[name]]
  end
end

.commandsObject



6
7
8
9
# File 'lib/linecook/command_set.rb', line 6

def commands
  # assume/require word names
  @commands ||= {}
end

.parse(argv = ARGV) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/linecook/command_set.rb', line 11

def parse(argv=ARGV)
  command = super(argv) do |options|
    options.option_break = /\A(?:--\z|[^-])/
    options.preserve_option_break = true
    yield(options) if block_given?
  end

  # The parser is configured to preserve the break, which is desired
  # when it's a command, but you want to get rid of standard breaks.
  if argv[0] == '--'
    argv.shift
  end

  command
end

.run(argv = ARGV, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/linecook/command_set.rb', line 27

def run(argv=ARGV, &block)
  command = parse(argv) do |options|
    if block_given?
      yield([], self, options)
    end
  end
  
  command.call(argv, &block)
end

Instance Method Details

#call(argv = []) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/linecook/command_set.rb', line 44

def call(argv=[])
  if argv.empty?
    raise CommandError, "no command specified"
  end

  command_name  = argv.shift
  command_class = self.class.commands[command_name]

  unless command_class
    raise CommandError, "unknown command: #{command_name.inspect}"
  end

  # Parse options for the command, but yield with the necessary debugging
  # information - note that command_class is always the latest one to be
  # parsed so start with the command name as the callpath.
  command = command_class.parse(argv) do |options|
    if block_given?
      yield([command_name], command_class, options)
    end
  end

  if command.kind_of?(CommandSet)
    # The block causes nested CommandSets to roll back out to the main
    # context with the callpath and latest command_class. Literally it
    # wraps the block defined above.  Non-CommandSet commands will have
    # nil, not a block passed to call - a NOP.
    command.call(argv) do |callpath, cmdclass, options|
      if block_given?
        callpath.unshift(command_name)
        yield(callpath, cmdclass, options)
      end
    end
  else
    process(command, *argv)
  end
end

#process(command, *args) ⇒ Object



81
82
83
# File 'lib/linecook/command_set.rb', line 81

def process(command, *args)
  command.call(args)
end