# File lib/rhc/helpers.rb, line 175 def certificate_file(file) file && OpenSSL::X509::Certificate.new(IO.read(File.expand_path(file))) rescue => e debug e raise OptionParser::InvalidOption.new(nil, "The certificate '#{file}' cannot be loaded: #{e.message} (#{e.class})") end
# File lib/rhc/helpers.rb, line 158 def client_from_options(opts) RHC::Rest::Client.new({ :url => openshift_rest_endpoint.to_s, :debug => options.debug, :timeout => options.timeout, }.merge!(ssl_options).merge!(opts)) end
# File lib/rhc/helpers.rb, line 278 def color(s, color) $terminal.color(s, color) end
# File lib/rhc/helpers.rb, line 256 def confirm_action(question) return if options.confirm return if !options.noprompt && paragraph{ agree("#{question} (yes|no): ") } raise RHC::ConfirmationError end
# File lib/rhc/helpers.rb, line 48 def date(s) now = Date.today d = datetime_rfc3339(s).to_time if now.year == d.year return d.strftime('%l:%M %p').strip if now.yday == d.yday d.strftime('%b %d %l:%M %p') else d.strftime('%b %d, %Y %l:%M %p') end rescue ArgumentError "Unknown date" end
# File lib/rhc/helpers.rb, line 84 def datetime_rfc3339(s) DateTime.strptime(s, '%Y-%m-%dT%H:%M:%S%z') # Replace with d = DateTime.rfc3339(s) end
Output helpers
# File lib/rhc/helpers.rb, line 186 def debug(msg) $stderr.puts "DEBUG: #{msg}" if debug? end
# File lib/rhc/helpers.rb, line 192 def debug? false end
# File lib/rhc/helpers.rb, line 189 def debug_error(e) debug "#{e.message} (#{e.class})\n #{e.backtrace.join("\n ")}" end
# File lib/rhc/helpers.rb, line 44 def decode_json(s) RHC::Vendor::OkJson.decode(s) end
# File lib/rhc/helpers.rb, line 204 def deprecated(msg,short = false) HighLine::use_color = false if windows? # handle deprecated commands that does not start through highline info = " For porting and testing purposes you may switch this %s to %s by setting the DISABLE_DEPRECATED environment variable to %d. It is not recommended to do so in a production environment as this option will be removed in a future release." msg << info unless short raise DeprecatedError.new(msg % ['an error','a warning',0]) if disable_deprecated? warn "Warning: #{msg}\n" % ['a warning','an error',1] end
# File lib/rhc/helpers.rb, line 196 def deprecated_command(correct,short = false) deprecated("This command is deprecated. Please use '#{correct}' instead.",short) end
# File lib/rhc/helpers.rb, line 200 def deprecated_option(deprecated,new) deprecated("The option '#{deprecated}' is deprecated. Please use '#{new}' instead") end
# File lib/rhc/helpers.rb, line 32 def disable_deprecated? # 1) default for now is false # 2) when releasing a 1.0 beta flip this to true # 3) all deprecated aliases should be removed right before 1.0 disable = false env_disable = ENV['DISABLE_DEPRECATED'] disable = true if env_disable == '1' disable end
# File lib/rhc/helpers.rb, line 61 def distance_of_time_in_words(from_time, to_time = 0) from_time = from_time.to_time if from_time.respond_to?(:to_time) to_time = to_time.to_time if to_time.respond_to?(:to_time) distance_in_minutes = (((to_time - from_time).abs)/60).round distance_in_seconds = ((to_time - from_time).abs).round case distance_in_minutes when 0..1 return distance_in_minutes == 0 ? "less than 1 minute" : "#{distance_in_minutes} minute" when 2..44 then "#{distance_in_minutes} minutes" when 45..89 then "about 1 hour" when 90..1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours" when 1440..2519 then "about 1 day" when 2520..43199 then "#{(distance_in_minutes.to_f / 1440.0).round} days" when 43200..86399 then "about 1 month" else "about #{(distance_in_minutes.to_f / 43200.0).round} months" end end
# File lib/rhc/helpers.rb, line 274 def error(msg, *args) say color(msg, :red), *args end
def tee(&block)
original = [$stdout, $stderr] $stdout, $stderr = (tees = original.map{ |io| StringTee.new(io) }) yield
ensure
$stdout, $stderr = original tees.each(&:close_write).map(&:string)
end
# File lib/rhc/helpers.rb, line 372 def header(str,opts = {}, &block) str = underline(str) str = str.map{ |s| color(s, opts[:color]) } if opts[:color] say str if block_given? indent &block end end
Check if host exists
# File lib/rhc/helpers.rb, line 476 def host_exists?(host) # :nocov: # Patch for BZ840938 to support Ruby 1.8 on machines without /etc/resolv.conf dns = Resolv::DNS.new((Resolv::DNS::Config.default_config_hash || {})) dns.getresources(host, Resolv::DNS::Resource::IN::A).any? # :nocov: end
# File lib/rhc/helpers.rb, line 484 def hosts_file_contains?(host) with_tolerant_encoding do begin resolver = Resolv::Hosts.new resolver.getaddress host rescue => e debug "Error while resolving with Resolv::Hosts: #{e.message}(#{e.class})\n #{e.backtrace.join("\n ")}" end end end
# File lib/rhc/helpers.rb, line 386 def indent(&block) @@indent += 1 begin yield ensure @@indent -= 1 end end
# File lib/rhc/helpers.rb, line 266 def info(msg, *args) say color(msg, :cyan), *args end
Platform helpers
# File lib/rhc/helpers.rb, line 463 def jruby? ; RUBY_PLATFORM =~ %rjava/ end
# File lib/rhc/helpers.rb, line 466 def mac? ; RbConfig::CONFIG['host_os'] =~ %r^darwin/ end
# File lib/rhc/helpers.rb, line 139 def openshift_online_server? openshift_server =~ %ropenshift.redhat.com$/ end
# File lib/rhc/helpers.rb, line 152 def openshift_rest_endpoint uri = to_uri((options.server rescue nil) || ENV['LIBRA_SERVER'] || "openshift.redhat.com") uri.path = '/broker/rest/api' if uri.path.blank? || uri.path == '/' uri end
# File lib/rhc/helpers.rb, line 136 def openshift_server to_host((options.server rescue nil) || ENV['LIBRA_SERVER'] || "openshift.redhat.com") end
# File lib/rhc/helpers.rb, line 142 def openshift_url "https://#{openshift_server}" end
paragraph
highline helper which creates a section with margins of 1, 1
# File lib/rhc/helpers.rb, line 445 def paragraph(&block) section(:top => 1, :bottom => 1, &block) end
# File lib/rhc/helpers.rb, line 282 def pluralize(count, s) count == 1 ? "#{count} #{s}" : "#{count} #{s}s" end
results
highline helper which creates a paragraph with a header to distinguish the final results of a command from other output
# File lib/rhc/helpers.rb, line 455 def results(&block) section(:top => 1, :bottom => 0) do say "RESULT:" yield end end
Run a command and export its output to the user. Output is not capturable on all platforms.
# File lib/rhc/helpers.rb, line 516 def run_with_tee(cmd) status, stdout, stderr = nil if windows? #:nocov: TODO: Test block system(cmd) status = $?.exitstatus #:nocov: else stdout, stderr = [$stdout, $stderr].map{ |t| StringTee.new(t) } status = Open4.spawn(cmd, 'stdout' => stdout, 'stderr' => stderr, 'quiet' => true) stdout, stderr = [stdout, stderr].map(&:string) end [status, stdout, stderr] end
# File lib/rhc/helpers.rb, line 217 def say(msg, *args) output = if Hash[*args][:stderr] $stderr else separate_blocks $terminal.instance_variable_get(:@output) end Array(msg).each do |statement| statement = statement.to_str next unless statement.present? template = ERB.new(statement, nil, "%") statement = template.result(binding) statement = $terminal.wrap(statement) unless $terminal.instance_variable_get(:@wrap_at).nil? statement = $terminal.send(:page_print, statement) unless $terminal.instance_variable_get(:@page_at).nil? output.print(' ' * @@indent * INDENT) unless @@last_line_open @@last_line_open = if statement[-1, 1] == " " or statement[-1, 1] == "\t" output.print(statement) output.flush else output.puts(statement) end end msg end
# File lib/rhc/helpers.rb, line 424 def section(params={}, &block) top = params[:top] || 0 bottom = params[:bottom] || 0 # the first section cannot take a newline top = 0 unless @@margin @@margin = [top, @@margin || 0].max value = block.call say "\n" if @@last_line_open @@margin = [bottom, @@margin].max value end
# File lib/rhc/helpers.rb, line 166 def ssl_options { :ssl_version => options.ssl_version, :client_cert => certificate_file(options.ssl_client_cert), :ca_file => options.ssl_ca_file && File.expand_path(options.ssl_ca_file), :verify_mode => options.insecure ? OpenSSL::SSL::VERIFY_NONE : nil, }.delete_if{ |k,v| v.nil? } end
# File lib/rhc/helpers.rb, line 262 def success(msg, *args) say color(msg, :green), *args end
# File lib/rhc/helpers.rb, line 468 def system_path(path) return path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File.const_defined?('ALT_SEPARATOR') and File::ALT_SEPARATOR.present? path end
given an array of arrays "items", construct an array of strings that can be used to print in tabular form.
# File lib/rhc/helpers.rb, line 288 def table(items, opts={}, &block) items = items.map &block if block_given? widths = [] items.each do |item| item.each_with_index do |s, i| item[i] = s.to_s widths[i] = [widths[i] || 0, item[i].length].max end end align = opts[:align] || [] join = opts[:join] || ' ' if opts[:header] opts[:header].each_with_index do |s, i| widths[i] = [widths[i] || 0, s.length].max end sep = opts[:separator] || "=" ary = Array.new(opts[:header].length) items.unshift ary.each_with_index {|obj, idx| ary[idx] = sep.to_s * (widths[idx] || 1)} items.unshift(opts[:header]) end items.map do |item| item.each_with_index.map{ |s,i| s.send((align[i] == :right ? :rjust : :ljust), widths[i], ' ') }.join(join).rstrip end end
This will format table headings for a consistent look and feel
If a heading isn't explicitly defined, it will attempt to look up the parts If those aren't found, it will capitalize the string
# File lib/rhc/helpers.rb, line 316 def table_heading(value) # Set the default proc to look up undefined values headings = Hash.new do |hash,key| items = key.to_s.split('_') # Look up each piece individually hash[key] = items.length > 1 ? # Recusively look up the heading for the parts items.map{|x| headings[x.to_sym]}.join(' ') : # Capitalize if this part isn't defined items.first.capitalize end # Predefined headings (or parts of headings) headings.merge!({ :creation_time => "Created", :expires_in_seconds => "Expires In", :uuid => "UUID", :current_scale => "Current", :scales_from => "Minimum", :scales_to => "Maximum", :gear_sizes => "Allowed Gear Sizes", :consumed_gears => "Gears Used", :max_gears => "Gears Allowed", :gear_info => "Gears", :plan_id => "Plan", :url => "URL", :ssh_string => "SSH", :connection_info => "Connection URL", :gear_profile => "Gear Size", :visible_to_ssh? => 'Available', }) headings[value] end
# File lib/rhc/helpers.rb, line 146 def to_host(s) s =~ %r(^http(?:s)?://) ? URI(s).host : s end
# File lib/rhc/helpers.rb, line 149 def to_uri(s) URI(s =~ %r(^http(?:s)?://) ? s : "https://#{s}") end
# File lib/rhc/helpers.rb, line 381 def underline(s) [s, "-"*s.length] end
# File lib/rhc/helpers.rb, line 465 def unix? ; !jruby? && !windows? end
Web related requests
# File lib/rhc/helpers.rb, line 93 def user_agent "rhc/#{RHC::VERSION::STRING} (ruby #{RUBY_VERSION}; #{RUBY_PLATFORM})#{" (API #{RHC::Rest::API_VERSION})" rescue ''}" end
# File lib/rhc/helpers.rb, line 270 def warn(msg, *args) say color(msg, :yellow), *args end
# File lib/rhc/helpers.rb, line 464 def windows? ; RUBY_PLATFORM =~ %rwin(32|dows|ce)|djgpp|(ms|cyg|bcc)win|mingw32/ end
# File lib/rhc/helpers.rb, line 495 def with_tolerant_encoding(&block) # :nocov: if RUBY_VERSION.to_f >= 1.9 orig_default_internal = Encoding.default_internal Encoding.default_internal = 'ISO-8859-1' else orig_default_kcode = $KCODE $KCODE = 'N' end yield ensure if RUBY_VERSION.to_f >= 1.9 Encoding.default_internal = orig_default_internal else $KCODE = orig_default_kcode end # :nocov: end