Module: Hammer::Shell
- Included in:
- Hammer
- Defined in:
- lib/hammer/shell.rb
Overview
ANSI color/output helpers. Mixed into command instances; also callable directly as ‘Hammer::Shell.say(…)`.
Class Method Summary collapse
- .ask(prompt, default: nil) ⇒ Object
- .color!(value) ⇒ Object
- .color? ⇒ Boolean
-
.error(text) ⇒ Object
Raise a controlled Hammer::Error.
- .paint(text, color = nil, bold: false) ⇒ Object
-
.print_error(text) ⇒ Object
Print a red [error] line to stderr (does not exit).
- .say(text = '', color = nil, bold: false) ⇒ Object
-
.sh(cmd) ⇒ Object
Run a shell command.
- .yes?(prompt) ⇒ Boolean
Class Method Details
.ask(prompt, default: nil) ⇒ Object
47 48 49 50 51 52 53 54 |
# File 'lib/hammer/shell.rb', line 47 def ask(prompt, default: nil) suffix = default ? " [#{default}]" : '' print paint("#{prompt}#{suffix}: ", :cyan) line = $stdin.gets return default if line.nil? line = line.chomp line.empty? ? default : line end |
.color!(value) ⇒ Object
18 19 20 |
# File 'lib/hammer/shell.rb', line 18 def color!(value) @color = value end |
.color? ⇒ Boolean
13 14 15 16 |
# File 'lib/hammer/shell.rb', line 13 def color? return @color if defined?(@color) @color = $stdout.tty? && ENV['NO_COLOR'].nil? end |
.error(text) ⇒ Object
Raise a controlled Hammer::Error. If unhandled, the dispatcher prints the message in red and exits 1 - no backtrace, no help spam.
error 'config file missing' unless File.exist?(path)
37 38 39 |
# File 'lib/hammer/shell.rb', line 37 def error(text) raise Hammer::Error, text end |
.paint(text, color = nil, bold: false) ⇒ Object
22 23 24 25 26 27 |
# File 'lib/hammer/shell.rb', line 22 def paint(text, color = nil, bold: false) return text.to_s unless color? && (color || bold) code = COLORS[color] || 0 prefix = bold ? "\e[1;#{code}m" : "\e[#{code}m" "#{prefix}#{text}\e[0m" end |
.print_error(text) ⇒ Object
Print a red [error] line to stderr (does not exit). Used internally by the dispatcher to render Hammer::Error messages.
43 44 45 |
# File 'lib/hammer/shell.rb', line 43 def print_error(text) warn paint("[error] #{text}", :red, bold: true) end |
.say(text = '', color = nil, bold: false) ⇒ Object
29 30 31 |
# File 'lib/hammer/shell.rb', line 29 def say(text = '', color = nil, bold: false) puts paint(text, color, bold: bold) end |
.sh(cmd) ⇒ Object
Run a shell command. Echoes the command in gray, raises Hammer::Error on non-zero exit. Returns true on success.
64 65 66 67 68 |
# File 'lib/hammer/shell.rb', line 64 def sh(cmd) say "$ #{cmd}", :gray error "command failed: #{cmd}" unless system(cmd) true end |
.yes?(prompt) ⇒ Boolean
56 57 58 59 60 |
# File 'lib/hammer/shell.rb', line 56 def yes?(prompt) answer = ask("#{prompt} (y/N)") return false if answer.nil? answer.to_s.strip.downcase.start_with?('y') end |