square/rangeclient

View on GitHub
bin/er

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby

require 'rangeclient'

require 'optparse'

options = {
  :timeout => 60,
}
optparse = OptionParser.new do |opts|
  opts.on('-e', '--expand', 'Print one element per line') do |arg|
    options[:expand] = arg
  end
  opts.on('-c', '--count', 'Print the count of range elements, not the range itself') do |arg|
    options[:count] = arg
  end
  opts.on('-s', '--sort', 'Sort expanded output') do |arg|
    options[:sorted] = arg
  end
  opts.on('-v', '--vip range:80', 'Which host or host:port to query') do |arg|
    host, port = arg.split(':', 2)
    options[:host] = host
    options[:port] = port unless port.nil?
  end
  opts.on('-p', '--port 80', 'Port to use when connecting') do |arg|
    options[:port] = arg
  end
  opts.on('--[no-]ssl', 'Enable SSL') do |ssl|
    options[:ssl] = ssl
  end
  opts.on('--ca-file FILE', 'PEM-formatted CA certificates to validate against when SSL is enabled') do |cafile|
    options[:ca_file] = cafile
  end
  opts.on('-t', '--timeout TIMEOUT', "Wait this long for a response") do |arg|
    options[:timeout] = arg.to_i
  end
  opts.on_tail('-h', '--help', "This help message") do
    puts opts
    exit
  end
end
optparse.parse!

range = Range::Client.new(options)

in_range = ARGV.join ','

if in_range.empty?
  puts optparse
  STDERR.puts "[ERROR] No range specified"
  exit 1
end

if in_range  == '-'
  in_range = STDIN.readlines.map { |l| l.chomp }.join ','
end

nodes = range.expand(in_range)

if not range.rangeexception.nil?
  STDERR.puts "[WARNING] " + range.rangeexception
end

if options[:count]
  # if counting, return count
  puts nodes.size
elsif not nodes.size.zero?
  # if we got a result, display it accordingly
  if options[:expand]
    nodes.sort! if options[:sorted]
    nodes.each do |node|
      puts node
    end
  else
    puts range.compress(nodes)
  end
else
  STDERR.puts "[WARNING] No nodes returned"
  exit 1
end