Module: ICouchbase::CLI

Defined in:
lib/icouchbase/cli.rb

Class Method Summary collapse

Class Method Details

.startObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/icouchbase/cli.rb', line 25

def start
  # parse ARGV
  options = {
    :hostname => 'localhost',
    :port => 8091,
    :password => nil,
    :bucket => 'default'
  }
  OptionParser.new do |opts|
    opts.banner = "Usage: icouchbase [options]"
    opts.on("-a", "--address ADDRESS", "Address to connect to (default: #{options[:hostname]}:#{options[:port]})") do |v|
      host, port = v.split(':')
      options[:hostname] = host.empty? ? 'localhost' : host
      options[:port] = port.to_i > 0 ? port.to_i : 8091
    end
    opts.on("-p", "--password PASSWORD", "Password to log with (default: none)") do |v|
      options[:password] = v
    end
    opts.on("-b", "--bucket NAME", "Name of the bucket to connect to (default: #{options[:bucket]})") do |v|
      options[:bucket] = v.empty? ? "default" : v
    end
    opts.on_tail("-?", "--help", "Show this message") do
      puts opts
      exit(0)
    end
  end.parse!

  # establish connection
  begin
    print "Connecting to #{options[:bucket]}@#{options[:hostname]}:#{options[:port]} ... "
    STDOUT.flush
    conn = Couchbase.connect(options)
    puts "DONE"
  rescue Couchbase::Error::Base => ex
    "ERROR: #{ex.message}"
    exit(1)
  end

  history = File.join(ENV['HOME'], ".icouchbase_history")
  at_exit do
    begin
      File.open(history, "w+") do |f|
        f.puts(Readline::HISTORY.to_a)
      end
    rescue StandardError
    end
  end
  begin
    File.readlines(history, "r").each do |line|
      line.strip!
      Readline::HISTORY.push(line) unless line.empty?
    end
  rescue StandardError
  end

  # handle user commands
  puts "Welcome to Interactive Couchbase"
  cmd = Handler.new(conn)
  while true
    input = Readline.readline("couchbase> ", false)
    exit(0) if input.nil?
    input.strip!
    next if input.empty?
    # remove sequential duplicates
    if input != Readline::HISTORY.to_a[-1]
      Readline::HISTORY.push(input)
    end
    puts cmd.exec(input.chomp)
  end
end