summaryrefslogtreecommitdiff
path: root/ruwiki/tags/release-0.9.3/lib/ruwiki/utils/command.rb
blob: ba7c0608e5ae32d590e21f929bda70b5eab4ac0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env ruby
#--
# Ruwiki
#   Copyright © 2002 - 2004, Digikata and HaloStatue
#   Alan Chen (alan@digikata.com)
#   Austin Ziegler (ruwiki@halostatue.ca)
#
# Licensed under the same terms as Ruby.
#
# This file may be renamed to change the URI for the wiki.
#
# $Id$
#++

  # Implements the command pattern. Commands are used by the command-line
class Ruwiki::Utils::CommandPattern
  class AbstractCommandError < Exception; end
  class UnknownCommandError < RuntimeError; end
  class CommandAlreadyExists < RuntimeError; end
  class MissingParameterError < ArgumentError
    def initialize(argument)
      @argument = argument
    end

    attr_reader :argument
  end

  class << self
    def add(command)
      command = command.new if command.kind_of?(Class)

      @commands ||= {}
      if @commands.has_key?(command.name)
        raise CommandAlreadyExists
      else
        @commands[command.name] = command
      end

      if command.respond_to?(:altname)
        unless @commands.has_key?(command.altname)
          @commands[command.altname] = command
        end
      end
    end

    def <<(command)
      add(command)
    end

    attr_accessor :default
    def default=(command) #:nodoc:
      if command.kind_of?(Ruwiki::Utils::CommandPattern)
      @default = command
      elsif command.kind_of?(Class)
        @default = command.new
      elsif @commands.has_key?(command)
        @default = @commands[command]
      else
        raise UnknownCommandError
      end
    end

    def command?(command)
      @commands.has_key?(command)
    end

    def command(command)
      if command?(command)
        @commands[command]
      else
        @default
      end
    end

    def [](cmd)
      self.command(cmd)
    end

    def default_ioe(ioe = {})
      ioe[:input]   ||= $stdin
      ioe[:output]  ||= $stdout
      ioe[:error]   ||= $stderr
      ioe
    end
  end

  def [](args, opts = {}, ioe = {})
    call(args, opts, ioe)
  end

  def name
    raise AbstractCommandError
  end

  def call(args, opts = {}, ioe = {})
    raise AbstractCommandError
  end

  def help
    raise AbstractCommandError
  end
end