module RHC::Helpers

Constants

DEFAULT_DELAY_THROTTLE
INDENT
MAX_RETRIES

Public Instance Methods

color(s, color) click to toggle source
# File lib/rhc/helpers.rb, line 161
def color(s, color)
  $terminal.color(s, color)
end
config() click to toggle source
# File lib/rhc/helpers.rb, line 93
def config
  raise "Operations requiring configuration must define a config accessor"
end
date(s) click to toggle source
# File lib/rhc/helpers.rb, line 49
def date(s)
  now = Time.now
  d = datetime_rfc3339(s)
  if now.year == d.year
    return d.strftime('%l:%M %p').strip if now.yday == d.yday
  end
  d.strftime('%b %d %l:%M %p')
rescue ArgumentError
  "Unknown date"
end
datetime_rfc3339(s) click to toggle source
# File lib/rhc/helpers.rb, line 60
def datetime_rfc3339(s)
  DateTime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
  # Replace with d = DateTime.rfc3339(s)
end
debug(msg) click to toggle source

Output helpers

# File lib/rhc/helpers.rb, line 111
def debug(msg)
  $stderr.puts "DEBUG: #{msg}" if debug?
end
decode_json(s) click to toggle source
# File lib/rhc/helpers.rb, line 45
def decode_json(s)
  RHC::Vendor::OkJson.decode(s)
end
deprecated(msg,short = false) click to toggle source
# File lib/rhc/helpers.rb, line 123
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 may be removed in future releases."

  msg << info unless short
  if RHC::Helpers.disable_deprecated?
    raise DeprecatedError.new(msg % ['an error','a warning',0])
  else
    warn "Warning: #{msg}\n" % ['a warning','an error',1]
  end
end
deprecated_command(correct,short = false) click to toggle source
# File lib/rhc/helpers.rb, line 115
def deprecated_command(correct,short = false)
  deprecated("This command is deprecated. Please use '#{correct}' instead.",short)
end
deprecated_option(deprecated,new) click to toggle source
# File lib/rhc/helpers.rb, line 119
def deprecated_option(deprecated,new)
  deprecated("The option '#{deprecated}' is deprecated. Please use '#{new}' instead")
end
disable_deprecated?() click to toggle source
# File lib/rhc/helpers.rb, line 33
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
error(msg, *args) click to toggle source
# File lib/rhc/helpers.rb, line 157
def error(msg, *args)
  say color(msg, :red), *args
end
get(uri, opts=nil, *args) click to toggle source
# File lib/rhc/helpers.rb, line 73
def get(uri, opts=nil, *args)
  opts = {'User-Agent' => user_agent}.merge(opts || {})
  RestClient.get(uri, opts, *args)
end
header(s,opts = {}) { || ... } click to toggle source
# File lib/rhc/helpers.rb, line 223
def header(s,opts = {})
  @indent ||= 0
  indent s
  indent "="*s.length
  if block_given?
    @indent += 1
    yield
    @indent -= 1
  end
end
host_exists?(host) click to toggle source

Check if host exists

# File lib/rhc/helpers.rb, line 342
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
hosts_file_contains?(host) click to toggle source
# File lib/rhc/helpers.rb, line 350
def hosts_file_contains?(host)
  # :nocov:
  resolver = Resolv::Hosts.new
  begin
    resolver.getaddress host
  rescue Resolv::ResolvError
  end
  # :nocov:
end
indent(str) click to toggle source
# File lib/rhc/helpers.rb, line 235
def indent(str)
  @indent ||= 0
  say "%s%s" % [" " * @indent * INDENT,str]
end
info(msg, *args) click to toggle source
# File lib/rhc/helpers.rb, line 149
def info(msg, *args)
  say color(msg, :cyan), *args
end
jruby?() click to toggle source

Platform helpers

# File lib/rhc/helpers.rb, line 324
def jruby? ; RUBY_PLATFORM =~ %rjava/ end
mac?() click to toggle source
# File lib/rhc/helpers.rb, line 327
def mac? ; RbConfig::CONFIG['host_os'] =~ %r^darwin/ end
openshift_rest_node() click to toggle source
# File lib/rhc/helpers.rb, line 103
def openshift_rest_node
  "#{openshift_url}/broker/rest/api"
end
openshift_server() click to toggle source
# File lib/rhc/helpers.rb, line 97
def openshift_server
  config.get_value('libra_server')
end
openshift_url() click to toggle source
# File lib/rhc/helpers.rb, line 100
def openshift_url
  "https://#{openshift_server}"
end
paragraph(&block) click to toggle source

paragraph

highline helper which creates a section with margins of 1, 1

# File lib/rhc/helpers.rb, line 306
def paragraph(&block)
  section(:top => 1, :bottom => 1, &block)
end
pluralize(count, s) click to toggle source
# File lib/rhc/helpers.rb, line 165
def pluralize(count, s)
  count == 1 ? "#{count} #{s}" : "#{count} #{s}s"
end
results() { || ... } click to toggle source

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 316
def results(&block)
  paragraph do
    say "RESULT:"
    yield
  end
end
say(msg, *args) click to toggle source
# File lib/rhc/helpers.rb, line 136
def say(msg, *args)
  if Hash[*args][:stderr]
    $stderr.puts msg
  else
    super(msg)
  end
  msg
end
section(params={}, &block) click to toggle source
# File lib/rhc/helpers.rb, line 269
def section(params={}, &block)
  top = params[:top]
  top = 0 if top.nil?
  bottom = params[:bottom]
  bottom = 0 if bottom.nil?

  # add more newlines if top is greater than the last section's bottom margin
  top_margin = @@section_bottom_last

  # negitive previous bottoms indicate that an untracked newline was
  # printed and so we do our best to negate it since we can't remove it
  if top_margin < 0
    top += top_margin
    top_margin = 0
  end

  until top_margin >= top
    say "\n"
    top_margin += 1
  end

  block.call

  bottom_margin = 0
  until bottom_margin >= bottom
    say "\n"
    bottom_margin += 1
  end

  @@section_bottom_last = bottom
end
ssh_key_display_format() click to toggle source

common SSH key display format in ERB

# File lib/rhc/helpers.rb, line 330
    def ssh_key_display_format
      ERB.new "       Name: <%= key.name %>
       Type: <%= key.type %>
Fingerprint: <%= key.fingerprint %>

"
    end
success(msg, *args) click to toggle source
# File lib/rhc/helpers.rb, line 145
def success(msg, *args)
  say color(msg, :green), *args
end
table(items, opts={}, &block) click to toggle source

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 171
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, s.length].max if s.respond_to?(:length)
    end
  end
  align = opts[:align] || []
  join = opts[:join] || ' '
  if opts[:header]
    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).strip
  end
end
table_heading(value) click to toggle source

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 196
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",
    :uuid           => "UUID",
    :current_scale  => "Current",
    :scales_from    => "Minimum",
    :scales_to      => "Maximum",
    :url            => "URL",
    :ssh            => "SSH",
    :gear_profile   => "Gear Size"
  })

  headings[value]
end
unix?() click to toggle source
# File lib/rhc/helpers.rb, line 326
def unix? ; !jruby? && !windows? end
user_agent() click to toggle source

Web related requests

# File lib/rhc/helpers.rb, line 69
def user_agent
  "rhc/#{RHC::VERSION::STRING} (ruby #{RUBY_VERSION}; #{RUBY_PLATFORM})#{" (API #{RHC::Rest::API_VERSION})" rescue ''}"
end
warn(msg, *args) click to toggle source
# File lib/rhc/helpers.rb, line 153
def warn(msg, *args)
  say color(msg, :yellow), *args
end
windows?() click to toggle source
# File lib/rhc/helpers.rb, line 325
def windows? ; RUBY_PLATFORM =~ %rwin(32|dows|ce)|djgpp|(ms|cyg|bcc)win|mingw32/ end