Class: Dev::Common
- Defined in:
- lib/firespring_dev_commands/common.rb,
lib/firespring_dev_commands/platform.rb
Overview
Class contains several common useful development methods
Defined Under Namespace
Classes: Platform
Instance Method Summary collapse
-
#ask(message, default = nil) ⇒ Object
Asks for user input using the given message and returns it If a default was specified and the user doesn’t give any input, the default will be returned.
-
#center_pad(string = '', pad: '-', len: 80) ⇒ Object
Center the string and pad on either side with the given padding character.
-
#conditional_colorize(string, colorize:, color:) ⇒ Object
Colorize the string if it has been requested.
-
#confirmation_message(question, default:, colorize:) ⇒ Object
Build a confirmation message, colorizing each individual part appropriately Include the default value in the message if one was specified.
-
#exit_unless_confirmed(message, default: nil, colorize: true) ⇒ Object
Exits unless the user confirms they want to continue If the user answers ‘y’ then the code will continue All other inputs cause the code to exit.
-
#filesize(size) ⇒ Object
Print the given filesize using the most appropriate units.
-
#gather_input(default: nil) ⇒ Object
Receive a string from the user on stdin unless non_interactive is set to true If a default value was specified and no answer was given, return the default.
-
#run_command(command, stdin: $stdin, stdout: $stdout, stderr: $stderr, env: ENV, capture: false) ⇒ Object
Runs a command in a subshell.
-
#running_codebuild? ⇒ Boolean
Checks if CODEBUILD_INITIATOR or INITIATOR env variable are set If they are not set, it assumes it is not running in codebuild and return false Otherwise it returns true.
-
#strip_non_json(str) ⇒ Object
Remove all leading non left-curly-brace characters Remove all trailing non right-curly-brace characters.
-
#tokenize(str) ⇒ Object
This method breaks up a string by spaces, however if it finds quoted strings in it, it attempts to preserve those as a single element e.g.
-
#version_greater_than(required_version, actual_version) ⇒ Object
Takes two versions and attempts to compare them Returns true if the actual_version is greater than the required version (false otherwise).
-
#when_confirmed(message, default: nil, colorize: true) ⇒ Object
Wraps a block of code in a y/n question If the user answers ‘y’ then the block is executed All other inputs cause the block to be skipped.
-
#with_confirmation(message, default = 'y', color_message: true) ⇒ Object
deprecated
Deprecated.
Please use #when_confirmed instead
Instance Method Details
#ask(message, default = nil) ⇒ Object
Asks for user input using the given message and returns it If a default was specified and the user doesn’t give any input, the default will be returned
140 141 142 143 144 145 146 147 148 149 |
# File 'lib/firespring_dev_commands/common.rb', line 140 def ask(, default = nil) msg = " #{message}" msg << " [#{default}]" if default msg << ': ' print msg answer = $stdin.gets.to_s.strip return default if default && answer == '' answer end |
#center_pad(string = '', pad: '-', len: 80) ⇒ Object
Center the string and pad on either side with the given padding character
192 193 194 195 196 197 198 |
# File 'lib/firespring_dev_commands/common.rb', line 192 def center_pad(string = '', pad: '-', len: 80) string = " #{string} " unless string.strip.empty? center_dash = len / 2 string = string.to_s center_str = string.length / 2 string.rjust(center_dash + center_str - 1, pad).ljust(len - 1, pad) end |
#conditional_colorize(string, colorize:, color:) ⇒ Object
Colorize the string if it has been requested
132 133 134 135 136 |
# File 'lib/firespring_dev_commands/common.rb', line 132 def conditional_colorize(string, colorize:, color:) return string.send(color) if colorize string end |
#confirmation_message(question, default:, colorize:) ⇒ Object
Build a confirmation message, colorizing each individual part appropriately Include the default value in the message if one was specified
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/firespring_dev_commands/common.rb', line 112 def (question, default:, colorize:) = conditional_colorize(question, colorize:, color: :light_green) = conditional_colorize('(', colorize:, color: :light_green) << conditional_colorize('y', colorize:, color: :light_yellow) << conditional_colorize('/', colorize:, color: :light_green) << conditional_colorize('n', colorize:, color: :light_yellow) << conditional_colorize(')', colorize:, color: :light_green) unless default.to_s.strip.empty? << ' ' << conditional_colorize('[', colorize:, color: :light_green) << conditional_colorize(default.to_s.strip, colorize:, color: :light_yellow) << conditional_colorize(']', colorize:, color: :light_green) end << conditional_colorize(':', colorize:, color: :light_green) "#{message} #{options} " end |
#exit_unless_confirmed(message, default: nil, colorize: true) ⇒ Object
Exits unless the user confirms they want to continue If the user answers ‘y’ then the code will continue All other inputs cause the code to exit
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/firespring_dev_commands/common.rb', line 65 def exit_unless_confirmed(, default: nil, colorize: true) # If a default is given, it must be y or n raise 'invalid default' if default && !%w(y n).include?(default) # print the colorized message (if requested) with the default (if given) print((, default:, colorize:)) # Default to the default # Read from stdin unless non_interactive is set to true answer = gather_input(default:) return if answer.casecmp('y').zero? puts "\n Cancelled.\n".light_yellow exit 1 end |
#filesize(size) ⇒ Object
Print the given filesize using the most appropriate units
201 202 203 204 205 206 207 208 209 |
# File 'lib/firespring_dev_commands/common.rb', line 201 def filesize(size) return '0.0 B' if size.to_i.zero? units = %w(B KB MB GB TB Pb EB) exp = (Math.log(size) / Math.log(1024)).to_i exp = 6 if exp > 6 format('%.1f %s', size.to_f / (1024**exp), units[exp]) end |
#gather_input(default: nil) ⇒ Object
Receive a string from the user on stdin unless non_interactive is set to true If a default value was specified and no answer was given, return the default
102 103 104 105 106 107 108 |
# File 'lib/firespring_dev_commands/common.rb', line 102 def gather_input(default: nil) answer = $stdin.gets unless ENV['NON_INTERACTIVE'] == 'true' answer = answer.to_s.strip return default if default && answer.empty? answer end |
#run_command(command, stdin: $stdin, stdout: $stdout, stderr: $stderr, env: ENV, capture: false) ⇒ Object
Runs a command in a subshell. By default, the subshell is connected to the stdin/stdout/stderr of the current program By default, the current environment is passed to the subshell You can capture the output of the command by setting capture to true
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 |
# File 'lib/firespring_dev_commands/common.rb', line 10 def run_command(command, stdin: $stdin, stdout: $stdout, stderr: $stderr, env: ENV, capture: false) command = Array(command) output = nil # If capture was specified, write stdout to a pipe so we can return it stdoutread, stdout = ::IO.pipe if capture # Spawn a subprocess to run the command pid = ::Process.spawn(env, *command, in: stdin, out: stdout, err: stderr) # Wait for the subprocess to finish and capture the result _, result = ::Process.wait2(pid) # If capture was specified, close the write pipe, read the output from the read pipe, close the read pipe, and return the output if capture stdout.close output = stdoutread.readlines.join stdoutread.close end # If the exitstatus was non-zero, exit with an error unless result.exitstatus.zero? puts output if capture LOG.error "#{result.exitstatus} exit status while running [ #{command.join(' ')} ]\n".red exit result.exitstatus end output end |
#running_codebuild? ⇒ Boolean
Checks if CODEBUILD_INITIATOR or INITIATOR env variable are set If they are not set, it assumes it is not running in codebuild and return false Otherwise it returns true
163 164 165 166 167 |
# File 'lib/firespring_dev_commands/common.rb', line 163 def running_codebuild? return false if ENV['CODEBUILD_INITIATOR'].to_s.strip.empty? && ENV['INITIATOR'].to_s.strip.empty? true end |
#strip_non_json(str) ⇒ Object
Remove all leading non left-curly-brace characters Remove all trailing non right-curly-brace characters
171 172 173 |
# File 'lib/firespring_dev_commands/common.rb', line 171 def strip_non_json(str) str.sub(/\A[^{]*{/m, '{').sub(/}[^}]*\z/m, '}') end |
#tokenize(str) ⇒ Object
This method breaks up a string by spaces, however if it finds quoted strings in it, it attempts to preserve those as a single element e.g. “foo ‘bin baz’ bar” => [foo, ‘bin baz’, bar]
154 155 156 157 158 |
# File 'lib/firespring_dev_commands/common.rb', line 154 def tokenize(str) str.split(/\s(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/) .reject(&:empty?) .map { |s| s.gsub(/(^ +)|( +$)|(^["']+)|(["']+$)/, '') } end |
#version_greater_than(required_version, actual_version) ⇒ Object
Takes two versions and attempts to compare them Returns true if the actual_version is greater than the required version (false otherwise)
177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'lib/firespring_dev_commands/common.rb', line 177 def version_greater_than(required_version, actual_version) required_version = required_version.to_s.split('.') actual_version = actual_version.to_s.split('.') required_version.each_with_index do |required, index| required = required.to_i actual = actual_version[index].to_i return true if actual > required next if actual == required return false end end |
#when_confirmed(message, default: nil, colorize: true) ⇒ Object
Wraps a block of code in a y/n question If the user answers ‘y’ then the block is executed All other inputs cause the block to be skipped
85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/firespring_dev_commands/common.rb', line 85 def when_confirmed(, default: nil, colorize: true) # If a default is given, it must be y or n raise 'invalid default' if default && !%w(y n).include?(default) # print the colorized message (if requested) with the default (if given) print((, default:, colorize:)) # Default to the default # Read from stdin unless non_interactive is set to true answer = gather_input(default:) # Yield to the block if confirmed yield if answer.casecmp('y').zero? end |
#with_confirmation(message, default = 'y', color_message: true) ⇒ Object
Please use #when_confirmed instead
Wraps a block of code in a y/n question. If the user answers ‘y’ then the block is executed. If the user answers ‘n’ then the block is skipped.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/firespring_dev_commands/common.rb', line 44 def with_confirmation(, default = 'y', color_message: true) = "\n #{message}" << '? '.light_green = .light_green if print print '('.light_green << 'y'.light_yellow << '/'.light_green << 'n'.light_yellow << ') '.light_green answer = default answer = $stdin.gets unless ENV['NON_INTERACTIVE'] == 'true' unless answer.strip.casecmp('y').zero? puts "\n Cancelled.\n".light_yellow exit 1 end puts yield end |