Class: LipsTTYck

Inherits:
Object
  • Object
show all
Defined in:
lib/lipsttyck.rb

Overview

LipsTTYck provides a collection of utilities for formatting shell output. It parses a simple markup syntax for adding color formatting, right-justification of text, headers, and horizontal dividers.

Author:

  • Nick Williams

Version:

  • 0.1.0

Constant Summary collapse

LOG_LEVEL_NEVER =

Logging/Output Levels

0
LOG_LEVEL_FAILURE =
1
LOG_LEVEL_ALWAYS =
2
@@templatePad =

Templates

"\n\n"
@@templatePrefix =
""
@@templatePadding =
" "
@@templateIndentOn =
"#@@templatePrefix#@@templatePadding"
@@templateIndentOff =
""
@@templateH1 =
"#@@templatePrefix@gray(================================================================================)"
@@templateH2 =
"#@@templatePrefix@gray(--------------------------------------------------------------------------------)"
@@templateDiv =
"#@@templateH2"
@@templateBlockquote =
"| "
@@templateEnd =
"#@@templateH2"
@@templateSuccess =

“@green(✓)”, “@green(✔)”︎

"[  @green(OK)  ]"
@@templateFailure =

“@red(✗)”, “@red(✘)”

"[ @red(FAIL) ]"
@@templateSkip =

“@blue(~)”, “@blue(⋯)”

"[ @blue(SKIP) ]"
@@templateColorPrompt =
"@blue"
@@templateColorStdOut =
"@gray"
@@templateColorStdErr =
"@red"

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ LipsTTYck

Initializes a new LipsTTYck instance.

Parameters:

  • config (Hash) (defaults to: {})

    optional configuration settings with which to initialize (overriding any defaults)



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
# File 'lib/lipsttyck.rb', line 43

def initialize(config = {})
  # Config
  @config = {
    "margin" => 80,
    "marginTemplateOverrides" => true,
    "showStdOut" => LOG_LEVEL_NEVER,
    "showStdErr" => LOG_LEVEL_FAILURE
  }

  @config.merge!(config)

  # Flags
  @entryQueued = false

  # Caches
  @cacheLast = ""
  @cacheLine = ""

  # Margin-Sensitive Template Overrides
  if(@config['marginTemplateOverrides'])
    # H1 Override
    @@templateH1 = "#@@templatePrefix@gray("

    @config['margin'].times do
      @@templateH1 += "="
    end

    @@templateH1 += ")"

    # H2 Override
    @@templateH2 = "#@@templatePrefix@gray("

    @config['margin'].times do
      @@templateH2 += "-"
    end

    @@templateH2 += ")"

    # DIV Override
    @@templateDiv = "#@@templateH2"

    # END Override
    @@templateEnd = "#@@templateH2"
  end
end

Instance Method Details

#attempt(label, commands) ⇒ Boolean

Attempts to execute the specified shell command(s), capturing STDIN and STDOUT for optional output to the user.

Parameters:

  • label (String)

    a label to use when prompting for input

  • commands (Array)

    one or more commands to be executed

Returns:

  • (Boolean)

    whetehr or not all commands were executed successfully



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/lipsttyck.rb', line 351

def attempt(label, commands)
  # Setup
  commandOutputLogs = [];
  failed = false

  # Convert single command to an array.
  if !commands.kind_of?(Array)
    commands = [commands]
  end

  # Output label.
  self.out(label, false)

  # Execute each command.
  commands.each do|command|
    # Output progress indicator for current command.
    self.out(".", false, false)

    Open3.popen3(command) do |stdin, stdout, stderr, waitThread|
      commandOutputLogs << {
        :stdout => stdout.eof? ? nil : stdout.read,
        :stderr => stderr.eof? ? nil : stderr.read
      }

      if waitThread.value.to_i > 0
        failed = true
        break
      end
    end
  end

  # Display the result of the attempted commands.
  if failed
    self.out("@FAILURE", true, false, true)
  else
    self.out("@SUCCESS", true, false, true)
  end

  # Output I/O streams according to config.
  if @config['showStdOut'] == LOG_LEVEL_ALWAYS || failed && @config['showStdOut'] == LOG_LEVEL_FAILURE || @config['showStdErr'] == LOG_LEVEL_ALWAYS || failed && @config['showStdErr'] == LOG_LEVEL_FAILURE
    lastIndex = commandOutputLogs.length - 1

    self.out("")

    commandOutputLogs.each_index do |i|
      # STDOUT
      if (@config['showStdOut'] == LOG_LEVEL_ALWAYS) || (failed && @config['showStdOut'] == LOG_LEVEL_FAILURE && i == lastIndex)
        blockquote(commandOutputLogs[i][:stdout], @@templateColorStdOut)
      end

      # STDERR
      if (@config['showStdErr']) == LOG_LEVEL_ALWAYS || (failed && @config['showStdErr'] == LOG_LEVEL_FAILURE && i == lastIndex)
        blockquote(commandOutputLogs[i][:stderr], @@templateColorStdErr)
      end
    end
  end

  return !failed
end

#blockquote(lines, color = "@gray") ⇒ Object

Outputs an indented block of text.

Parameters:

  • lines (String)

    the text to be displayed

  • prefix (String)

    optional string to prepend to each line

  • postfix (String)

    optional string to append to each line

Returns:

  • void



442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/lipsttyck.rb', line 442

def blockquote(lines, color = "@gray")
  if lines
    # Escape special characters.
    lines = self.class.escape(lines)

    lines.each_line do |line|
      self.out("#{color}(| " + line.gsub!(/(\n)$/, "") + ")")
    end

    self.out("")
  end
end

#confirm(label, value = nil, default = true, verbose = false) ⇒ Boolean

Prompts for a boolean response (y/n).

Parameters:

  • label (String)

    the label to be used when prompting

  • value (Boolean) (defaults to: nil)

    the existing value if available

  • default (Boolean) (defaults to: true)

    a default fallback value if the response is blank

  • verbose (Boolean) (defaults to: false)

    whether or not to always prompt, regardless of a passed value

Returns:

  • (Boolean)

    the result of the confirmation prompt



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/lipsttyck.rb', line 301

def confirm(label, value = nil, default = true, verbose = false)
  # Don't continue if verbosity is off and value is already set.
  if !verbose && !self.class.unassigned(value)
    return
  end

  # Default value, falls back to existing value if possible.
  if default.nil? && !self.class.unassigned(value)
    default = value
  end

  # Prompt for input.
  prompt = "#{label}"

  if default
    prompt += " \\\(Y/n\\\): "
  else
    prompt += " \\\(y/N\\\): "
  end

  out("#@@templateColorPrompt(#{prompt})", false)

  response = $stdin.gets.chomp

  # Fall back default value if input is empty.
  if self.class.unassigned(response)
    value = default
  else
    if response.casecmp("y") == 0
      value = true
    elsif response.casecmp("n") == 0
      value = false
    else
      out "Invalid response \"#{response}\""
      value = confirm(label, value, default, verbose)
    end
  end

  return value
end

#in(label, value = nil, default = nil, verbose = false) ⇒ mixed

Prompts for input, first outputting the specified text.

Parameters:

  • label (String)

    the label to be used when prompting

  • value (mixed) (defaults to: nil)

    the existing value if available

  • default (mixed) (defaults to: nil)

    a default fallback value if the response is blank

  • verbose (Boolean) (defaults to: false)

    whether or not to always prompt, regardless of a passed value

Returns:

  • (mixed)

    the result of the prompt



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
286
287
288
289
# File 'lib/lipsttyck.rb', line 259

def in(label, value = nil, default = nil, verbose = false)
  # Don't continue if verbosity is off and value is already set.
  if !verbose && !self.class.unassigned(value)
    return
  end

  # Default value, falls back to existing value if possible.
  if default.nil? && !self.class.unassigned(value)
    default = value
  end

  # Prompt for input.
  prompt = "#{label}"

  if default.nil?
    prompt += ": "
  else
    prompt += " \\\(#{default}\\\): "
  end

  out("#@@templateColorPrompt(#{prompt})", false)

  value = $stdin.gets.chomp

  # Fall back default value if input is empty.
  if self.class.unassigned(value)
    value = default
  end

  return value
end

#out(text, trailingNewline = true, autoIndent = true, rightJustified = false) ⇒ Object

Outputs the specified text, processing any detected markup.

Parameters:

  • text (String)

    the text to be displayed

  • trailingNewline (Boolean) (defaults to: true)

    whether or not to automatically append a trailing newline character

  • autoIndent (Boolean) (defaults to: true)

    whether or not to automatically apply indentation

  • rightJustified (Boolean) (defaults to: false)

    whether or not to right-align the text according to the configured margin width

Returns:

  • void



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
# File 'lib/lipsttyck.rb', line 99

def out(text, trailingNewline = true, autoIndent = true, rightJustified = false)
  formatted = "#{text}"
  unformatted = "#{text}"
  templateIndent = autoIndent ? @@templateIndentOn : @@templateIndentOff
  line = "#@cacheLine"

  # Apply Indentation
  formatted.gsub!(/\n/m, "\n#{templateIndent}")

  # Apply Markup Formatting
  case formatted
    when /@H1(?: (.*))?/im
      formatted = "#@@templateH1\n#{templateIndent}@green(#$1)\n#@@templateH1"

      # Handle Queued Entry
      if @entryQueued
        formatted = "#@@templatePad#{formatted}"
        @entryQueued = false
      end

    when /@H2(?: (.*))?/im
      stripped = $1

      if @cacheLast =~ /^@H[12](.*)/i
        formatted="#{templateIndent}@yellow(#{stripped})\n#@@templateH2"
      else
        formatted="#@@templateH2\n#{templateIndent}@yellow(#{stripped})\n#@@templateH2"
      end

      # Handle Queued Entry
      if @entryQueued
        formatted = "#@@templatePad#{formatted}"
        @entryQueued = false
      end

    when /@DIV(?: (.*))?/im
      if $1
        formatted = "#@@templateDiv\n#$1"
      else
        formatted = "#@@templateDiv"
      end

    when /@BLOCKQUOTE\((.*)(?<!\\)\)/im
      formatted = "#$1".gsub(/\n/m, "\n#@@templateBlockquote")

    when /@SUCCESS(?: (.*))?/im
      formatted = "#@@templateSuccess#@@templatePadding"

    when /@FAILURE(?: (.*))?/im
      formatted = "#@@templateFailure#@@templatePadding"

    when /@SKIP(?: (.*))?/im
      formatted = "#@@templateSkip#@@templatePadding"

    when /@ENTRY(?: (.*))?/im
      @entryQueued = true
      return

    when /@EXIT(?: (.*))?/im
      # Handle Queued Entry
      if @entryQueued
        @entryQueued = false
      else
        # Handle Exit w/ Heading
        if @cacheLast =~ /^@H[12].*/im
          # Handle Double Newline (After Heading)
          if @@templatePad[0,2] == "\n"
            formatted = @@templatePad[2,-1]
          else
            formatted = "#@@templatePad"
          end
        else
          # Handle Exit w/ Text
          if formatted.length > 5
            formatted = "#{templateIndent}" << formatted[6..-1] << "\n#@@templateEnd#@@templatePad"
          else
            formatted = "#@@templateEnd#@@templatePad"
          end
        end

        @entryQueued = false
      end
    else
      formatted = "#{templateIndent}" + formatted.gsub(/\\@/, "@")

      # Handle Queued Entry
      if @entryQueued
        formatted = "#@@templatePad#@@templateDiv\n#{formatted}"
        @entryQueued = false
      end
  end

  stripped = "#{formatted}"

  # Apply Color Formatting
  if formatted.include? "@"
    stripped = formatted.gsub(/(?<!\\)@[A-Za-z0-9\-_]*\((.*?)(?<!\\)\)/, '\1')

    formatted = formatted.gsub(/(?<!\\)@none\((.*?)\)/im, "\033[0m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@black\((.*?)(?<!\\)\)/im, "\033[0;30m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@white\((.*?)(?<!\\)\)/im, "\033[1;37m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@blue\((.*?)(?<!\\)\)/im, "\033[0;34m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@blue_lt\((.*?)(?<!\\)\)/im, "\033[1;34m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@green\((.*?)(?<!\\)\)/im, "\033[0;32m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@green_lt\((.*?)(?<!\\)\)/im, "\033[1;32m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@cyan\((.*?)(?<!\\)\)/im, "\033[0;36m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@cyan_lt\((.*?)(?<!\\)\)/im, "\033[1;36m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@red\((.*?)(?<!\\)\)/im, "\033[0;31m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@red_lt\((.*?)(?<!\\)\)/im, "\033[1;31m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@purple\((.*?)(?<!\\)\)/im, "\033[0;35m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@purple_lt\((.*?)(?<!\\)\)/im, "\033[1;35m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@yellow\((.*?)(?<!\\)\)/im, "\033[0;33m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@yellow_lt\((.*?)(?<!\\)\)/im, "\033[1;33m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@gray\((.*?)(?<!\\)\)/im, "\033[1;30m" << '\1' << "\033[0m")
      .gsub(/(?<!\\)@gray_lt\((.*?)(?<!\\)\)/im, "\033[0;37m" << '\1' << "\033[0m")
  end

  # Strip Escaping Slashes
  escapedPattern = /\\([@\(\)])/im

  stripped.gsub!(escapedPattern, "\\1")
  formatted.gsub!(escapedPattern, "\\1")

  # Apply Right-Justification
  if rightJustified
    paddingSize = (@config['margin'] - line.length) - stripped.length
    padding = "%#{paddingSize}s" % ""

    formatted = "#{padding}#{formatted}"
  end

  # Apply Trailing Newline
  if trailingNewline
    formatted = "#{formatted}\n"
  end

  # Output Formatted String
  print "#{formatted}"

  # Cache Unformatted Version
  @cacheLast = unformatted

  # Cache Current Line
  if !trailingNewline
    @cacheLine = @cacheLine << stripped
  else
    @cacheLine = ""
  end
end

#passthru(commands, colorStdOut = "@gray", colorStdErr = "@red", colorStdIn = "@blue") ⇒ Object

Executes the specified command, passing any output to the respective output streams.

Parameters:

  • commands (Array)

    one or more commands to be executed

Returns:

  • void



419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/lipsttyck.rb', line 419

def passthru(commands, colorStdOut = "@gray", colorStdErr = "@red", colorStdIn = "@blue")
  # Convert single command to an array.
  if !commands.kind_of?(Array)
    commands = [commands]
  end

  commands.each do |command|
    PTY.spawn(command) do |stdout, stdin, pid|
      # self.out("#{colorStdIn}(> " + self.class.escape(command) + ")", true, false)
      stdout.each_line { |line| self.out("#{colorStdOut}(| " + self.class.escape(line.gsub!(/\n/m, "")) + ")") }
    end
  end
end