Class: Infopark::UserIO

Inherits:
Object
  • Object
show all
Defined in:
lib/infopark/user_io.rb,
lib/infopark/user_io/version.rb

Overview

TODO

  • beep (a) on #acknowledge, #ask or #confirm (and maybe on #listen, too)

Defined Under Namespace

Modules: Global Classes: Aborted, MissingEnv, Progress

Constant Summary collapse

VERSION =
"0.2.1"

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output_prefix: nil) ⇒ UserIO



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/infopark/user_io.rb', line 49

def initialize(output_prefix: nil)
  case output_prefix
  when String
    @output_prefix = "[#{output_prefix}] "
  when Proc, Method
    @output_prefix_proc = ->() { "[#{output_prefix.call}] " }
  when :timestamp
    @output_prefix_proc = ->() { "[#{Time.now.strftime("%T.%L")}] " }
  end
  @line_pending = {}
end

Class Attribute Details

.globalObject

Returns the value of attribute global.



46
47
48
# File 'lib/infopark/user_io.rb', line 46

def global
  @global
end

Instance Method Details

#<<(msg) ⇒ Object



157
158
159
# File 'lib/infopark/user_io.rb', line 157

def <<(msg)
  tell(msg.chomp, newline: msg.end_with?("\n"))
end

#acknowledge(*text) ⇒ Object



96
97
98
99
100
101
102
# File 'lib/infopark/user_io.rb', line 96

def acknowledge(*text)
  tell("-" * 80)
  tell(*text, color: :cyan, bright: true)
  tell("-" * 80)
  tell("Please press ENTER to continue.")
  read_line
end

#ask(*text, default: nil) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/infopark/user_io.rb', line 104

def ask(*text, default: nil)
  # TODO implementation error if default not boolean or nil
  tell("-" * 80)
  tell(*text, color: :cyan, bright: true)
  tell("-" * 80)
  default_answer = default ? "yes" : "no" unless default.nil?
  tell("(yes/no) #{default_answer && "[#{default_answer}] "}> ", newline: false)
  until %w(yes no).include?(answer = read_line.strip.downcase)
    if answer.empty?
      answer = default_answer
      break
    end
    tell("I couldn't understand “#{answer}”.", newline: false, color: :red, bright: true)
    tell(" > ", newline: false)
  end
  answer == "yes"
end

#background_other_threadsObject



140
141
142
143
144
145
# File 'lib/infopark/user_io.rb', line 140

def background_other_threads
  unless @foreground_thread
    @background_data = []
    @foreground_thread = Thread.current
  end
end

#confirm(*text) ⇒ Object



128
129
130
# File 'lib/infopark/user_io.rb', line 128

def confirm(*text)
  ask(*text) or raise Aborted
end

#edit_file(kind_of_data, filename = nil) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/infopark/user_io.rb', line 165

def edit_file(kind_of_data, filename = nil)
  wait_for_foreground if background?

  editor = ENV['EDITOR'] or raise MissingEnv, "No EDITOR specified."

  filename ||= Tempfile.new("").path
  tell("Start editing #{kind_of_data} using #{editor}…")
  sleep(1.7)
  system(editor, filename)

  File.read(filename)
end

#foregroundObject



147
148
149
150
151
152
153
154
155
# File 'lib/infopark/user_io.rb', line 147

def foreground
  if @foreground_thread
    @background_data.each(&STDOUT.method(:write))
    @foreground_thread = nil
    # take over line_pending from background
    @line_pending[false] = @line_pending[true]
    @line_pending[true] = false
  end
end

#listen(prompt = nil, **options) ⇒ Object



122
123
124
125
126
# File 'lib/infopark/user_io.rb', line 122

def listen(prompt = nil, **options)
  prompt << " " if prompt
  tell("#{prompt}> ", **options, newline: false)
  read_line.strip
end

#new_progress(label) ⇒ Object



132
133
134
# File 'lib/infopark/user_io.rb', line 132

def new_progress(label)
  Progress.new(label, self)
end

#select(description, items, item_describer: :to_s, default: nil) ⇒ Object



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
# File 'lib/infopark/user_io.rb', line 178

def select(description, items, item_describer: :to_s, default: nil)
  return if items.empty?

  describer =
      case item_describer
      when Method, Proc
        item_describer
      else
        ->(item) { item.send(item_describer) }
      end

  choice = nil
  if items.size == 1
    choice = items.first
    tell("Selected #{describer.call(choice)}.", color: :yellow)
    return choice
  end

  items = items.sort_by(&describer)

  tell("-" * 80)
  tell("Please select #{description}:", color: :cyan, bright: true)
  items.each_with_index do |item, i|
    tell("#{i + 1}: #{describer.call(item)}", color: :cyan, bright: true)
  end
  tell("-" * 80)
  default_index = items.index(default)
  default_selection = "[#{default_index + 1}] " if default_index
  until choice
    tell("Your choice #{default_selection}> ", newline: false)
    answer = read_line.strip
    if answer.empty?
      choice = default
    else
      int_answer = answer.to_i
      if int_answer.to_s != answer
        tell("Please enter a valid integer.")
      elsif int_answer < 1 || int_answer > items.size
        tell("Please enter a number from 1 through #{items.size}.")
      else
        choice = items[int_answer - 1]
      end
    end
  end
  choice
end

#start_progress(label) ⇒ Object



136
137
138
# File 'lib/infopark/user_io.rb', line 136

def start_progress(label)
  new_progress(label).tap(&:start)
end

#tell(*texts, newline: true, **line_options) ⇒ Object



61
62
63
64
65
66
# File 'lib/infopark/user_io.rb', line 61

def tell(*texts, newline: true, **line_options)
  lines = texts.flatten.map {|text| text.to_s.split("\n", -1) }.flatten

  lines[0...-1].each {|line| tell_line(line, **line_options) }
  tell_line(lines.last, newline: newline, **line_options)
end

#tell_error(e, **options) ⇒ Object



91
92
93
94
# File 'lib/infopark/user_io.rb', line 91

def tell_error(e, **options)
  tell(e, **options, color: :red, bright: true)
  tell(e.backtrace, **options, color: :red) if Exception === e
end

#tell_pty_stream(stream, **color_options) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/infopark/user_io.rb', line 68

def tell_pty_stream(stream, **color_options)
  color_prefix, color_postfix = compute_color(**color_options)
  write_raw(output_prefix) unless line_pending?
  write_raw(color_prefix)
  nl_pending = false
  uncolored_prefix = "#{color_postfix}#{output_prefix}#{color_prefix}"
  until stream.eof?
    chunk = stream.read_nonblock(100)
    next if chunk.empty?
    write_raw("\n#{uncolored_prefix}") if nl_pending
    chunk.chop! if nl_pending = chunk.end_with?("\n")
    chunk.gsub!(/([\r\n])/, "\\1#{uncolored_prefix}")
    write_raw(chunk)
  end
  write_raw("\n") if nl_pending
  write_raw(color_postfix)
  line_pending!(false)
end

#tty?Boolean



161
162
163
# File 'lib/infopark/user_io.rb', line 161

def tty?
  STDOUT.tty?
end

#warn(*text) ⇒ Object



87
88
89
# File 'lib/infopark/user_io.rb', line 87

def warn(*text)
  tell(*text, color: :yellow, bright: true)
end