summaryrefslogtreecommitdiff
path: root/lib/rubygems/user_interaction.rb
blob: ffccb6031410bbe685c9e9c48419bb64ed8e158d (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
103
104
105
106
107
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
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
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

module Gem

  ####################################################################
  # Module that defines the default UserInteraction.  Any class
  # including this module will have access to the +ui+ method that
  # returns the default UI.
  module DefaultUserInteraction

    # Return the default UI.
    def ui
      DefaultUserInteraction.ui
    end

    # Set the default UI.  If the default UI is never explicity set, a
    # simple console based UserInteraction will be used automatically.
    def ui=(new_ui)
      DefaultUserInteraction.ui = new_ui
    end

    def use_ui(new_ui, &block)
      DefaultUserInteraction.use_ui(new_ui, &block)
    end

    # The default UI is a class variable of the singleton class for
    # this module.

    @ui = nil

    class << self
      def ui
        @ui ||= Gem::ConsoleUI.new
      end
      def ui=(new_ui)
        @ui = new_ui
      end
      def use_ui(new_ui)
        old_ui = @ui
        @ui = new_ui
        yield
      ensure
        @ui = old_ui
      end
    end
  end

  ####################################################################
  # Make the default UI accessable without the "ui." prefix.  Classes
  # including this module may use the interaction methods on the
  # default UI directly.  Classes may also reference the +ui+ and
  # <tt>ui=</tt> methods.
  #
  # Example:
  #
  #   class X
  #     include Gem::UserInteraction
  #
  #     def get_answer
  #       n = ask("What is the meaning of life?")
  #     end
  #   end
  module UserInteraction
    include DefaultUserInteraction
    [
      :choose_from_list, :ask, :ask_yes_no, :say, :alert, :alert_warning,
      :alert_error, :terminate_interaction
    ].each do |methname|
      class_eval %{
        def #{methname}(*args)
          ui.#{methname}(*args)
        end
      }
    end
  end

  ####################################################################
  # StreamUI implements a simple stream based user interface.
  class StreamUI

    attr_reader :ins, :outs, :errs

    def initialize(in_stream, out_stream, err_stream=STDERR)
      @ins = in_stream
      @outs = out_stream
      @errs = err_stream
    end
    
    # Choose from a list of options.  +question+ is a prompt displayed
    # above the list.  +list+ is a list of option strings.  Returns
    # the pair [option_name, option_index].
    def choose_from_list(question, list)
      @outs.puts question
      list.each_with_index do |item, index|
        @outs.puts " #{index+1}. #{item}"
      end
      @outs.print "> "
      @outs.flush

      result = @ins.gets

      return nil, nil unless result

      result = result.strip.to_i - 1
      return list[result], result
    end

    # Ask a question.  Returns a true for yes, false for no.  If not
    # connected to a tty, raises an exception if default is nil,
    # otherwise returns default.
    def ask_yes_no(question, default=nil)
      if not @ins.tty? then
        if default.nil? then
          raise(
              Gem::OperationNotSupportedError,
              "Not connected to a tty and no default specified")
        else
          return default
        end
      end
      qstr = case default
      when nil
        'yn'
      when true
        'Yn'
      else
        'yN'
      end
      result = nil
      while result.nil?
        result = ask("#{question} [#{qstr}]")
        result = case result
        when /^[Yy].*/
          true
        when /^[Nn].*/
          false
        when /^$/
          default
        else
          nil
        end
      end
      return result
    end
    
    # Ask a question.  Returns an answer if connected to a tty, nil
    # otherwise.
    def ask(question)
      return nil if not @ins.tty?
      @outs.print(question + "  ")
      @outs.flush
      result = @ins.gets
      result.chomp! if result
      result
    end
    
    # Display a statement.
    def say(statement="")
      @outs.puts statement
    end
    
    # Display an informational alert.
    def alert(statement, question=nil)
      @outs.puts "INFO:  #{statement}"
      return ask(question) if question 
    end
    
    # Display a warning in a location expected to get error messages.
    def alert_warning(statement, question=nil)
      @errs.puts "WARNING:  #{statement}"
      ask(question) if question 
    end
    
    # Display an error message in a location expected to get error
    # messages.
    def alert_error(statement, question=nil)
      @errs.puts "ERROR:  #{statement}"
      ask(question) if question
    end

    # Terminate the appliation normally, running any exit handlers
    # that might have been defined.
    def terminate_interaction(status = 0)
      raise Gem::SystemExitException, status
    end

    # Return a progress reporter object
    def progress_reporter(*args)
      case Gem.configuration.verbose
      when nil, false
        SilentProgressReporter.new(@outs, *args)
      when true
        SimpleProgressReporter.new(@outs, *args)
      else
        VerboseProgressReporter.new(@outs, *args)
      end
    end

    class SilentProgressReporter
      attr_reader :count

      def initialize(out_stream, size, initial_message, terminal_message = nil)
      end

      def updated(message)
      end

      def done
      end
    end

    class SimpleProgressReporter
      include DefaultUserInteraction

      attr_reader :count

      def initialize(out_stream, size, initial_message,
                     terminal_message = "complete")
        @out = out_stream
        @total = size
        @count = 0
        @terminal_message = terminal_message

        @out.puts initial_message
      end

      def updated(message)
        @count += 1
        @out.print "."
        @out.flush
      end

      def done
        @out.puts "\n#{@terminal_message}"
      end
    end

    class VerboseProgressReporter
      include DefaultUserInteraction

      attr_reader :count

      def initialize(out_stream, size, initial_message,
                     terminal_message = 'complete')
        @out = out_stream
        @total = size
        @count = 0
        @terminal_message = terminal_message

        @out.puts initial_message
      end

      def updated(message)
        @count += 1
        @out.puts "#{@count}/#{@total}: #{message}"
      end

      def done
        @out.puts @terminal_message
      end
    end
  end

  ####################################################################
  # Subclass of StreamUI that instantiates the user interaction using
  # standard in, out and error.
  class ConsoleUI < StreamUI
    def initialize
      super(STDIN, STDOUT, STDERR)
    end
  end

  ####################################################################
  # SilentUI is a UI choice that is absolutely silent.
  class SilentUI
    def method_missing(sym, *args, &block)
      self
    end
  end
end