Class: CouchShell::Shell

Inherits:
Object
  • Object
show all
Defined in:
lib/couch-shell/shell.rb

Overview

Starting a shell:

require "couch-shell/shell"

shell = CouchShell::Shell.new(STDIN, STDOUT, STDERR)
# returns at end of STDIN or on a quit command
shell.read_execute_loop

Defined Under Namespace

Classes: FileToUpload, Quit, ShellUserError, UndefinedVariable

Constant Summary collapse

PREDEFINED_VARS =
[
  "uuid", "id", "rev", "idr",
  "content-type", "server"
].freeze
JSON_DOC_START_RX =
/\A[ \t\n\r]*[\(\{]/

Instance Method Summary collapse

Constructor Details

#initialize(stdin, stdout, stderr) ⇒ Shell

Returns a new instance of Shell.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/couch-shell/shell.rb', line 64

def initialize(stdin, stdout, stderr)
  @stdin = stdin
  @stdout = stdout
  @stderr = stderr
  @server_url = nil
  @pathstack = []
  @highline = HighLine.new(@stdin, @stdout)
  @responses = RingBuffer.new(10)
  @eval_context = EvalContext.new(self)
  @viewtext = nil
  @stdout.puts "couch-shell #{VERSION}"
  @username = nil
  @password = nil
end

Instance Method Details

#cd(path, get = false) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/couch-shell/shell.rb', line 102

def cd(path, get = false)
  old_pathstack = @pathstack.dup
  case path
  when nil
    @pathstack = []
  when ".."
    if @pathstack.empty?
      errmsg "Already at server root, can't go up."
    else
      @pathstack.pop
    end
  when %r{\A/\z}
    @pathstack = []
  when %r{\A/}
    @pathstack = []
    cd path[1..-1], false
  when %r{/}
    path.split("/").each { |elem| cd elem, false }
  else
    @pathstack << path
  end
  if get
    if request("GET", nil) != "200"
      @pathstack = old_pathstack
    end
  end
end

#command_cd(argstr) ⇒ Object



489
490
491
# File 'lib/couch-shell/shell.rb', line 489

def command_cd(argstr)
  cd interpolate(argstr), false
end

#command_cg(argstr) ⇒ Object



493
494
495
# File 'lib/couch-shell/shell.rb', line 493

def command_cg(argstr)
  cd interpolate(argstr), true
end

#command_cput(argstr) ⇒ Object



476
477
478
479
# File 'lib/couch-shell/shell.rb', line 476

def command_cput(argstr)
  url = request_command_with_body("PUT", argstr)
  cd url if @responses.current(&:ok?)
end

#command_delete(argstr) ⇒ Object



485
486
487
# File 'lib/couch-shell/shell.rb', line 485

def command_delete(argstr)
  request "DELETE", interpolate(argstr)
end

#command_echo(argstr) ⇒ Object



510
511
512
513
514
# File 'lib/couch-shell/shell.rb', line 510

def command_echo(argstr)
  if argstr
    @stdout.puts interpolate(argstr)
  end
end

#command_editview(argstr) ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
# File 'lib/couch-shell/shell.rb', line 555

def command_editview(argstr)
  if @pathstack.size != 1
    raise ShellUserError, "current directory must be database"
  end
  design_name, view_name = argstr.split(/\s+/, 2)
  if design_name.nil? || view_name.nil?
    raise ShellUserError, "design and view name required"
  end
  request "GET", "_design/#{design_name}", nil, false
  return unless @responses.current(&:ok?)
  design = @responses.current.json
  view = nil
  if design.respond_to?(:views) &&
      design.views.respond_to?(view_name.to_sym)
    view = design.views.__send__(view_name.to_sym)
  end
  mapval = view && view.respond_to?(:map) && view.map
  reduceval = view && view.respond_to?(:reduce) && view.reduce
  t = Tempfile.new(["view", ".js"])
  t.puts("map")
  if mapval
    t.puts mapval
  else
    t.puts "function(doc) {\n  emit(doc._id, doc);\n}"
  end
  if reduceval || view.nil?
    t.puts
    t.puts("reduce")
    if reduceval
      t.puts reduceval
    else
      t.puts "function(keys, values, rereduce) {\n\n}"
    end
  end
  t.close
  continue?(
    "Press ENTER to edit #{view ? 'existing' : 'new'} view, " +
    "CTRL+C to cancel ")
  unless system(editor_bin!, t.path)
    raise ShellUserError, "editing command failed with exit status #{$?.exitstatus}"
  end
  text = t.open.read
  @viewtext = text
  t.close
  mapf = nil
  reducef = nil
  inmap = false
  inreduce = false
  i = 0
  text.each_line { |line|
    i += 1
    case line
    when /^map\s*(.*)$/
      unless $1.empty?
        msg "recover view text with `print viewtext'"
        raise ShellUserError, "invalid map line at line #{i}"
      end
      unless mapf.nil?
        msg "recover view text with `print viewtext'"
        raise ShellUserError, "duplicate map line at line #{i}"
      end
      inreduce = false
      inmap = true
      mapf = ""
    when /^reduce\s*(.*)$/
      unless $1.empty?
        msg "recover view text with `print viewtext'"
        raise ShellUserError, "invalid reduce line at line #{i}"
      end
      unless reducef.nil?
        msg "recover view text with `print viewtext'"
        raise ShellUserError, "duplicate reduce line at line #{i}"
      end
      inmap = false
      inreduce = true
      reducef = ""
    else
      if inmap
        mapf << line
      elsif inreduce
        reducef << line
      elsif line =~ /^\s*$/
        # ignore
      else
        msg "recover view text with `print viewtext'"
        raise ShellUserError, "unexpected content at line #{i}"
      end
    end
  }
  mapf.strip! if mapf
  reducef.strip! if reducef
  mapf = nil if mapf && mapf.empty?
  reducef = nil if reducef && reducef.empty?
  prompt_msg "View parsed, following actions would be taken:"
  if mapf && mapval.nil?
    prompt_msg " Add map function."
  elsif mapf.nil? && mapval
    prompt_msg " Remove map function."
  elsif mapf && mapval && mapf != mapval
    prompt_msg " Update map function."
  end
  if reducef && reduceval.nil?
    prompt_msg " Add reduce function."
  elsif reducef.nil? && reduceval
    prompt_msg " Remove reduce function."
  elsif reducef && reduceval && reducef != reduceval
    prompt_msg " Update reduce function."
  end
  continue? "Press ENTER to submit, CTRL+C to cancel "
  if !design.respond_to?(:views)
    design.set_attr!("views", {})
  end
  if view.nil?
    design.views.set_attr!(view_name, {})
    view = design.views.__send__(view_name.to_sym)
  end
  if mapf.nil?
    view.delete_attr!("map")
  else
    view.set_attr!("map", mapf)
  end
  if reducef.nil?
    view.delete_attr!("reduce")
  else
    view.set_attr!("reduce", reducef)
  end
  request "PUT", "_design/#{design_name}", design.to_s
  unless @responses.current(&:ok?)
    msg "recover view text with `print viewtext'"
  end
ensure
  if t
    t.close
    t.unlink
  end
end

#command_exit(argstr) ⇒ Object

Raises:



497
498
499
# File 'lib/couch-shell/shell.rb', line 497

def command_exit(argstr)
  raise Quit
end

#command_expand(argstr) ⇒ Object



541
542
543
# File 'lib/couch-shell/shell.rb', line 541

def command_expand(argstr)
  @stdout.puts expand(interpolate(argstr))
end

#command_format(argstr) ⇒ Object



524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/couch-shell/shell.rb', line 524

def command_format(argstr)
  unless argstr
    errmsg "expression required"
    return
  end
  val = shell_eval(argstr)
  if val.respond_to?(:couch_shell_format_string)
    @stdout.puts val.couch_shell_format_string
  else
    @stdout.puts val
  end
end

#command_get(argstr) ⇒ Object



468
469
470
# File 'lib/couch-shell/shell.rb', line 468

def command_get(argstr)
  request "GET", interpolate(argstr)
end

#command_member(argstr) ⇒ Object



703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/couch-shell/shell.rb', line 703

def command_member(argstr)
  id, rev = nil, nil
  json = @responses.current(&:json)
  unless json && (id = json.attr_or_nil!("_id")) &&
      (rev = json.attr_or_nil!("_rev")) &&
      (@pathstack.size > 0) &&
      (@pathstack.last == id.to_s)
    raise ShellUserError,
      "`cg' the desired document first, e.g.: `cg /my_db/my_doc_id'"
  end
  # TODO: read json string as attribute name if argstr starts with double
  # quote
  attr_name, new_valstr = argstr.split(/\s+/, 2)
  unless attr_name && new_valstr
    raise ShellUserError,
      "attribute name and new value argument required"
  end
  if new_valstr == "remove"
    json.delete_attr!(attr_name)
  else
    new_val = JsonValue.parse(new_valstr)
    json.set_attr!(attr_name, new_val)
  end
  request "PUT", "?rev=#{rev}", json.to_s
end

#command_post(argstr) ⇒ Object



481
482
483
# File 'lib/couch-shell/shell.rb', line 481

def command_post(argstr)
  request_command_with_body("POST", argstr)
end

#command_print(argstr) ⇒ Object



516
517
518
519
520
521
522
# File 'lib/couch-shell/shell.rb', line 516

def command_print(argstr)
  unless argstr
    errmsg "expression required"
    return
  end
  @stdout.puts shell_eval(argstr)
end

#command_put(argstr) ⇒ Object



472
473
474
# File 'lib/couch-shell/shell.rb', line 472

def command_put(argstr)
  request_command_with_body("PUT", argstr)
end

#command_quit(argstr) ⇒ Object

Raises:



501
502
503
# File 'lib/couch-shell/shell.rb', line 501

def command_quit(argstr)
  raise Quit
end

#command_server(argstr) ⇒ Object



537
538
539
# File 'lib/couch-shell/shell.rb', line 537

def command_server(argstr)
  self.server = argstr
end

#command_sh(argstr) ⇒ Object



545
546
547
548
549
550
551
552
553
# File 'lib/couch-shell/shell.rb', line 545

def command_sh(argstr)
  unless argstr
    errmsg "argument required"
    return
  end
  unless system(argstr)
    errmsg "command exited with status #{$?.exitstatus}"
  end
end

#command_user(argstr) ⇒ Object



729
730
731
732
733
734
735
# File 'lib/couch-shell/shell.rb', line 729

def command_user(argstr)
  prompt_msg("Password:", false)
  @password = @highline.ask(" ") { |q| q.echo = "*" }
  # we save the username only after the password was entered
  # to allow cancellation during password input
  @username = argstr
end

#command_uuids(argstr) ⇒ Object



505
506
507
508
# File 'lib/couch-shell/shell.rb', line 505

def command_uuids(argstr)
  count = argstr ? argstr.to_i : 1
  request "GET", "/_uuids?count=#{count}"
end

#command_view(argstr) ⇒ Object



692
693
694
695
696
697
698
699
700
701
# File 'lib/couch-shell/shell.rb', line 692

def command_view(argstr)
  if @pathstack.size != 1
    raise ShellUserError, "current directory must be database"
  end
  design_name, view_name = argstr.split("/", 2)
  if design_name.nil? || view_name.nil?
    raise ShellUserError, "argument in the form DESIGN/VIEW required"
  end
  request "GET", "_design/#{design_name}/_view/#{view_name}"
end

#continue?(msg) ⇒ Boolean

Returns:

  • (Boolean)


270
271
272
273
274
275
# File 'lib/couch-shell/shell.rb', line 270

def continue?(msg)
  prompt_msg(msg, false)
  unless @stdin.gets.chomp.empty?
    raise ShellUserError, "cancelled"
  end
end

#editor_bin!Object



463
464
465
466
# File 'lib/couch-shell/shell.rb', line 463

def editor_bin!
  ENV["EDITOR"] or
    raise ShellUserError, "EDITOR environment variable not set"
end

#errmsg(str) ⇒ Object



139
140
141
# File 'lib/couch-shell/shell.rb', line 139

def errmsg(str)
  @stderr.puts @highline.color(str, :red)
end

#execute(input) ⇒ Object

When the user enters something, it is passed to this method for execution. You may call if programmatically to simulate user input.

If input is nil, it is interpreted as “end of input”, raising a CouchShell::Shell::Quit exception. This exception is also raised by other commands (e.g. “exit” and “quit”). All other exceptions are caught and displayed on stderr.



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/couch-shell/shell.rb', line 296

def execute(input)
  begin
    execute!(input)
  rescue Quit => e
    raise e
  rescue Interrupt
    @stdout.puts
    errmsg "interrupted"
  rescue UndefinedVariable => e
    errmsg "Variable `" + e.varname + "' is not defined."
  rescue ShellUserError => e
    errmsg e.message
  rescue Exception => e
    errmsg e.message
    errmsg e.backtrace[0..5].join("\n")
  end
end

#execute!(input) ⇒ Object

Basic execute without error handling. Raises various exceptions.



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/couch-shell/shell.rb', line 315

def execute!(input)
  case input
  when nil
    raise Quit
  when ""
    # do nothing
  else
    command, argstr = input.split(/\s+/, 2)
    command_message = :"command_#{command.downcase}"
    if self.respond_to?(command_message)
      send command_message, argstr
    else
      errmsg "unknown command `#{command}'"
    end
  end
end

#expand(url) ⇒ Object



237
238
239
240
# File 'lib/couch-shell/shell.rb', line 237

def expand(url)
  u = @server_url
  "#{u.scheme}://#{u.host}:#{u.port}#{full_path url}"
end

#full_path(path) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/couch-shell/shell.rb', line 242

def full_path(path)
  stack = []
  if path !~ %r{\A/}
    stack = @pathstack.dup
  end
  if @server_url.path && !@server_url.path.empty?
    stack.unshift @server_url.path
  end
  if path && !path.empty? && path != "/"
    stack.push path
  end
  fpath = stack.join("/")
  if fpath !~ %r{\A/}
    "/" + fpath
  else
    fpath
  end
end

#http_client_request(method, absolute_url, body) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/couch-shell/shell.rb', line 215

def http_client_request(method, absolute_url, body)
  file = nil
  headers = {}
  if body.kind_of?(FileToUpload)
    file_to_upload = body
    file = File.open(file_to_upload.filename, "rb")
    #body = [{'Content-Type' => file_to_upload.content_type!,
    #         :content => file}]
    body = {'upload' => file}
  elsif body && body =~ JSON_DOC_START_RX
    headers['Content-Type'] = "application/json"
  end
  hclient = HTTPClient.new
  if @username && @password
    hclient.set_auth lookup_var("server"), @username, @password
  end
  res = hclient.request(method, absolute_url, body, headers)
  Response.new(res)
ensure
  file.close if file
end

#interpolate(str) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/couch-shell/shell.rb', line 342

def interpolate(str)
  return nil if str.nil?
  String.new.force_encoding(str.encoding).tap { |res|
    escape = false
    dollar = false
    expr = nil
    str.each_char { |c|
      if escape
        res << c
        escape = false
        next
      elsif c == '\\'
        escape = true
      elsif c == '$'
        dollar = true
        next
      elsif c == '('
        if dollar
          expr = ""
        else
          res << c
        end
      elsif c == ')'
        if expr
          res << shell_eval(expr).to_s
          expr = nil
        else
          res << c
        end
      elsif dollar
        res << "$"
      elsif expr
        expr << c
      else
        res << c
      end
      dollar = false
    }
  }
end

#lookup_var(var) ⇒ Object



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/couch-shell/shell.rb', line 387

def lookup_var(var)
  case var
  when "uuid"
    command_uuids nil
    if @responses.current(&:ok?)
      json = @responses.current.json
      if json && (uuids = json.couch_shell_ruby_value!["uuids"]) &&
          uuids.kind_of?(Array) && uuids.size > 0
        uuids[0]
      else
        raise ShellUserError,
          "interpolation failed due to unkown json structure"
      end
    else
      raise ShellUserError, "interpolation failed"
    end
  when "id"
    @responses.current { |r| r.attr "id", "_id" } or
      raise ShellUserError, "variable `id' not set"
  when "rev"
    @responses.current { |r| r.attr "rev", "_rev" } or
      raise ShellUserError, "variable `rev' not set"
  when "idr"
    "#{lookup_var 'id'}?rev=#{lookup_var 'rev'}"
  when "content-type"
    @responses.current(&:content_type)
  when "server"
    if @server_url
      u = @server_url
      "#{u.scheme}://#{u.host}:#{u.port}#{u.path}"
    else
      raise ShellUserError, "variable `server' not set"
    end
  when /\Ar(\d)\z/
    i = $1.to_i
    if @responses.readable_index?(i)
      @responses[i]
    else
      raise ShellUserError, "no response index #{i}"
    end
  when /\Aj(\d)\z/
    i = $1.to_i
    if @responses.readable_index?(i)
      if @responses[i].json
        @responses[i].json
      else
        raise ShellUserError, "no json in response #{i}"
      end
    else
      raise ShellUserError, "no response index #{i}"
    end
  when "viewtext"
    @viewtext or
      raise ShellUserError, "viewtext not set"
  else
    raise UndefinedVariable.new(var)
  end
end

#msg(str, newline = true) ⇒ Object



130
131
132
133
134
135
136
137
# File 'lib/couch-shell/shell.rb', line 130

def msg(str, newline = true)
  @stdout.print @highline.color(str, :blue)
  if newline
    @stdout.puts
  else
    @stdout.flush
  end
end

#net_http_request(method, fpath, body) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/couch-shell/shell.rb', line 186

def net_http_request(method, fpath, body)
  res = nil
  Net::HTTP.start(@server_url.host, @server_url.port) do |http|
    req = (case method
           when "GET"
             Net::HTTP::Get
           when "PUT"
             Net::HTTP::Put
           when "POST"
             Net::HTTP::Post
           when "DELETE"
             Net::HTTP::Delete
           else
             raise "unsupported http method: `#{method}'"
           end).new(fpath)
    if @username && @password
      req.basic_auth @username, @password
    end
    if body
      req.body = body
      if req.content_type.nil? && req.body =~ JSON_DOC_START_RX
        req.content_type = "application/json"
      end
    end
    res = Response.new(http.request(req))
  end
  res
end

#normalize_server_url(url) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/couch-shell/shell.rb', line 79

def normalize_server_url(url)
  return nil if url.nil?
  # remove trailing slash
  url = url.sub(%r{/\z}, '')
  # prepend http:// if scheme is omitted
  if url =~ /\A\p{Alpha}(?:\p{Alpha}|\p{Digit}|\+|\-|\.)*:/
    url
  else
    "http://#{url}"
  end
end


144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/couch-shell/shell.rb', line 144

def print_response(res, label = "", show_body = true)
  @stdout.print @highline.color("#{res.code} #{res.message}", :cyan)
  msg " #{label}"
  if show_body
    if res.json
      @stdout.puts res.json.format
    elsif res.body
      @stdout.puts res.body
    end
  elsif res.body
    msg "body has #{res.body.bytesize} bytes"
  end
end

#prompt_msg(msg, newline = true) ⇒ Object



261
262
263
264
265
266
267
268
# File 'lib/couch-shell/shell.rb', line 261

def prompt_msg(msg, newline = true)
  @stdout.print @highline.color(msg, :yellow)
  if newline
    @stdout.puts
  else
    @stdout.flush
  end
end

#readObject



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/couch-shell/shell.rb', line 277

def read
  lead = @pathstack.empty? ? ">>" : @pathstack.join("/") + " >>"
  begin
    @highline.ask(@highline.color(lead, :yellow) + " ") { |q|
      q.readline = true
    }
  rescue NoMethodError
    # this is BAD, but highline 1.6.1 reacts to CTRL+D with a NoMethodError
    return nil
  end
end

#read_execute_loopObject

Start regular shell operation, i.e. reading commands from stdin and executing them. Returns when the user issues a quit command.



334
335
336
337
338
339
340
# File 'lib/couch-shell/shell.rb', line 334

def read_execute_loop
  loop {
    execute(read)
  }
rescue Quit
  msg "bye"
end

#request(method, path, body = nil, show_body = true) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/couch-shell/shell.rb', line 158

def request(method, path, body = nil, show_body = true)
  unless @server_url
    errmsg "Server not set - can't perform request."
    return
  end
  fpath = URI.encode(full_path(path))
  msg "#{method} #{fpath} ", false
  if @server_url.scheme != "http"
    errmsg "Protocol #{@server_url.scheme} not supported, use http."
    return
  end
  # HTTPClient and CouchDB don't work together with simple put/post
  # requests to due some Keep-alive mismatch.
  #
  # Net:HTTP doesn't support file upload streaming.
  if body.kind_of?(FileToUpload) || method == "GET"
    res = http_client_request(method, URI.encode(expand(path)), body)
  else
    res = net_http_request(method, fpath, body)
  end
  @responses << res
  rescode = res.code
  vars = ["r#{@responses.index}"]
  vars << ["j#{@responses.index}"] if res.json
  print_response res, "  vars: #{vars.join(', ')}", show_body
  res.code
end

#request_command_with_body(method, argstr) ⇒ Object



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/couch-shell/shell.rb', line 446

def request_command_with_body(method, argstr)
  if argstr =~ JSON_DOC_START_RX
    url, bodyarg = nil, argstr
  else
    url, bodyarg= argstr.split(/\s+/, 2)
  end
  if bodyarg && bodyarg.start_with?("@")
    filename, content_type = bodyarg[1..-1].split(/\s+/, 2)
    body = FileToUpload.new(filename, content_type)
  else
    body = bodyarg
  end
  real_url = interpolate(url)
  request method, real_url, body
  real_url
end

#server=(url) ⇒ Object



91
92
93
94
95
96
97
98
99
100
# File 'lib/couch-shell/shell.rb', line 91

def server=(url)
  if url
    @server_url = URI.parse(normalize_server_url(url))
    msg "Set server to #{lookup_var 'server'}"
    request("GET", nil)
  else
    @server_url = nil
    msg "Set server to none."
  end
end

#shell_eval(expr) ⇒ Object



383
384
385
# File 'lib/couch-shell/shell.rb', line 383

def shell_eval(expr)
  @eval_context.instance_eval(expr)
end