Class: Freyia::Shell::Basic

Inherits:
Object
  • Object
show all
Defined in:
lib/freyia/shell/basic.rb

Direct Known Subclasses

Color

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base:) ⇒ Basic

Initialize base, mute and padding to nil.



15
16
17
18
19
20
# File 'lib/freyia/shell/basic.rb', line 15

def initialize(base:)
  @base = base
  @mute = false
  @padding = 0
  @always_force = false
end

Instance Attribute Details

#baseObject

Returns the value of attribute base.



10
11
12
# File 'lib/freyia/shell/basic.rb', line 10

def base
  @base
end

#paddingObject

Returns the value of attribute padding.



11
12
13
# File 'lib/freyia/shell/basic.rb', line 11

def padding
  @padding
end

Instance Method Details

#ask(statement, *args) ⇒ Object

Asks something to the user and receives a response.

If a default value is specified it will be presented to the user and allows them to select that value with an empty response. This option is ignored when limited answers are supplied.

If asked to limit the correct responses, you can pass in an array of acceptable answers. If one of those is not supplied, they will be shown a message stating that one of those answers must be given and re-asked the question.

If asking for sensitive information, the :echo option can be set to false to mask user input from $stdin.

If the required input is a path, then set the path option to true. This will enable tab completion for file paths relative to the current working directory on systems that support Readline.

Example

ask "What is your name?"

ask "What is the planet furthest from the sun?", default: "Neptune"

ask "What is your favorite Neopolitan flavor?",
    limited_to: ["strawberry", "chocolate", "vanilla"]

ask "What is your password?", echo: false

ask "Where should the file be saved?", path: true


83
84
85
86
87
88
89
90
91
92
# File 'lib/freyia/shell/basic.rb', line 83

def ask(statement, *args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  color = args.first

  if options[:limited_to]
    ask_filtered(statement, color, options)
  else
    ask_simply(statement, color, options)
  end
end

#error(statement) ⇒ Object

Called if something goes wrong during the execution. This is used by Freyia internally and should not be used inside your scripts. If something went wrong, you can always raise an exception. If you raise a Freyia::Error, it will be rescued and wrapped in the method below.



256
257
258
# File 'lib/freyia/shell/basic.rb', line 256

def error(statement)
  stderr.puts statement
end

#file_collision(destination) ⇒ Object

Deals with file collision and returns true if the file should be overwritten and false otherwise. If a block is given, it uses the block response as the content for the diff.

Parameters

destination<String>

the destination file to solve conflicts

block<Proc>

an optional block that returns the value to be used in diff and merge



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
# File 'lib/freyia/shell/basic.rb', line 211

def file_collision(destination) # rubocop:todo Metrics
  return true if @always_force

  options = block_given? ? "[Ynaqdhm]" : "[Ynaqh]"

  loop do # rubocop:todo Metrics/BlockLength
    answer = ask(
      %[Overwrite #{destination}? (enter "h" for help) #{options}],
      add_to_history: false
    )

    case answer
    when nil
      say ""
      return true
    when is?(:yes), is?(:force), ""
      return true
    when is?(:no), is?(:skip)
      return false
    when is?(:always)
      return @always_force = true
    when is?(:quit)
      say "Aborting..."
      raise SystemExit
    when is?(:diff)
      show_diff(destination, yield) if block_given?
      say "Retrying..."
    when is?(:merge)
      if block_given? && !merge_tool.empty?
        merge(destination, yield)
        return nil
      end

      say "Please specify merge tool to `FREYIA_MERGE` env."
    else
      say file_collision_help(block_given?)
    end
  end
end

#indent(count = 1) ⇒ Object

Sets the output padding while executing a block and resets it.



45
46
47
48
49
50
# File 'lib/freyia/shell/basic.rb', line 45

def indent(count = 1)
  orig_padding = padding
  self.padding = padding + count
  yield
  self.padding = orig_padding
end

#muteObject

Mute everything that’s inside given block



24
25
26
27
28
29
# File 'lib/freyia/shell/basic.rb', line 24

def mute
  @mute = true
  yield
ensure
  @mute = false
end

#mute?Boolean

Check if base is muted

Returns:

  • (Boolean)


33
34
35
# File 'lib/freyia/shell/basic.rb', line 33

def mute?
  @mute
end

#no?(statement, color = nil) ⇒ Boolean

Asks the user a question and returns true if the user replies “n” or “no”.

Returns:

  • (Boolean)


160
161
162
# File 'lib/freyia/shell/basic.rb', line 160

def no?(statement, color = nil)
  !!(ask(statement, color, add_to_history: false) =~ is?(:no))
end

Prints values in columns

Parameters

Array[String, String, …]



169
170
171
172
# File 'lib/freyia/shell/basic.rb', line 169

def print_in_columns(array)
  printer = ColumnPrinter.new(stdout)
  printer.print(array)
end

Prints a table.

Parameters

Array[Array[String, String, …]]

Options

indent<Integer>

Indent the first column by indent value.

colwidth<Integer>

Force the first column to colwidth spaces wide.

borders<Boolean>

Adds ascii borders.



184
185
186
187
# File 'lib/freyia/shell/basic.rb', line 184

def print_table(array, options = {})
  printer = TablePrinter.new(stdout, options)
  printer.print(array)
end

Prints a long string, word-wrapping the text to the current width of the terminal display. Ideal for printing heredocs.

Parameters

String

Options

indent<Integer>

Indent each line of the printed paragraph by indent value.



198
199
200
201
# File 'lib/freyia/shell/basic.rb', line 198

def print_wrapped(message, options = {})
  printer = WrappedPrinter.new(stdout, options)
  printer.print(message)
end

#say(message = "", color = nil, force_new_line = (message.to_s !~ %r{( |\t)\Z})) ⇒ Object

Say (print) something to the user. If the sentence ends with a whitespace or tab character, a new line is not appended (print + flush). Otherwise are passed straight to puts (behavior got from Highline).

Example

say("I know you knew that.")


101
102
103
104
105
106
107
108
109
# File 'lib/freyia/shell/basic.rb', line 101

def say(message = "", color = nil, force_new_line = (message.to_s !~ %r{( |\t)\Z}))
  return if quiet?

  buffer = prepare_message(message, *color)
  buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")

  stdout.print(buffer)
  stdout.flush
end

#say_error(message = "", color = nil, force_new_line = (message.to_s !~ %r{( |\t)\Z})) ⇒ Object

Say (print) an error to the user. If the sentence ends with a whitespace or tab character, a new line is not appended (print + flush). Otherwise are passed straight to puts (behavior got from Highline).

Example

say_error("error: something went wrong")


118
119
120
121
122
123
124
125
126
# File 'lib/freyia/shell/basic.rb', line 118

def say_error(message = "", color = nil, force_new_line = (message.to_s !~ %r{( |\t)\Z}))
  return if quiet?

  buffer = prepare_message(message, *color)
  buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")

  stderr.print(buffer)
  stderr.flush
end

#say_status(status, message, log_status = true) ⇒ Object

Say a status with the given color and appends the message. Since this method is used frequently by automations, it allows nil or false to be given in log_status, avoiding the message from being shown. If a Symbol is given in log_status, it’s used as the color.



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/freyia/shell/basic.rb', line 133

def say_status(status, message, log_status = true) # rubocop:disable Style/OptionalBooleanParameter
  return if quiet? || log_status == false

  spaces = "  " * (padding + 1)
  status = status.to_s.rjust(12)
  margin = (" " * status.length) + spaces

  color  = log_status.is_a?(Symbol) ? log_status : :green
  status = set_color status, color, true if color

  message = message.to_s.chomp.gsub(%r{(?<!\A)^}, margin)
  buffer = "#{status}#{spaces}#{message}\n"

  stdout.print(buffer)
  stdout.flush
end

#set_color(string) ⇒ Object

Apply color to the given string with optional bold. Disabled in the Freyia::Shell::Basic class.



263
264
265
# File 'lib/freyia/shell/basic.rb', line 263

def set_color(string, *) #:nodoc:
  string
end

#yes?(statement, color = nil) ⇒ Boolean

Asks the user a question and returns true if the user replies “y” or “yes”.

Returns:

  • (Boolean)


153
154
155
# File 'lib/freyia/shell/basic.rb', line 153

def yes?(statement, color = nil)
  !!(ask(statement, color, add_to_history: false) =~ is?(:yes))
end