Class: Dev::Common
Overview
Class contains several common useful development methods
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.
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
118 119 120 121 122 123 124 125 126 127 |
# File 'lib/firespring_dev_commands/common.rb', line 118 def ask(, default = nil) msg = " #{}" 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
181 182 183 184 185 186 187 |
# File 'lib/firespring_dev_commands/common.rb', line 181 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
110 111 112 113 114 |
# File 'lib/firespring_dev_commands/common.rb', line 110 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
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/firespring_dev_commands/common.rb', line 90 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) "#{} #{} " 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
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/firespring_dev_commands/common.rb', line 43 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
170 171 172 173 174 175 176 177 178 |
# File 'lib/firespring_dev_commands/common.rb', line 170 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
80 81 82 83 84 85 86 |
# File 'lib/firespring_dev_commands/common.rb', line 80 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
141 142 143 144 145 |
# File 'lib/firespring_dev_commands/common.rb', line 141 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
149 150 151 |
# File 'lib/firespring_dev_commands/common.rb', line 149 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]
132 133 134 135 136 |
# File 'lib/firespring_dev_commands/common.rb', line 132 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)
155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/firespring_dev_commands/common.rb', line 155 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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/firespring_dev_commands/common.rb', line 63 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 |