Class: CouchShell::Shell

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

Defined Under Namespace

Classes: BreakReplLoop, FileToUpload, 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.



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/couch-shell/shell.rb', line 55

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
end

Instance Method Details

#cd(path, get = false) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/couch-shell/shell.rb', line 90

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



443
444
445
# File 'lib/couch-shell/shell.rb', line 443

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

#command_cg(argstr) ⇒ Object



447
448
449
# File 'lib/couch-shell/shell.rb', line 447

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

#command_delete(argstr) ⇒ Object



439
440
441
# File 'lib/couch-shell/shell.rb', line 439

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

#command_echo(argstr) ⇒ Object



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

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

#command_editview(argstr) ⇒ Object



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
# File 'lib/couch-shell/shell.rb', line 509

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:



451
452
453
# File 'lib/couch-shell/shell.rb', line 451

def command_exit(argstr)
  raise BreakReplLoop
end

#command_expand(argstr) ⇒ Object



495
496
497
# File 'lib/couch-shell/shell.rb', line 495

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

#command_format(argstr) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/couch-shell/shell.rb', line 478

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



427
428
429
# File 'lib/couch-shell/shell.rb', line 427

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

#command_member(argstr) ⇒ Object



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
# File 'lib/couch-shell/shell.rb', line 657

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



435
436
437
# File 'lib/couch-shell/shell.rb', line 435

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

#command_print(argstr) ⇒ Object



470
471
472
473
474
475
476
# File 'lib/couch-shell/shell.rb', line 470

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

#command_put(argstr) ⇒ Object



431
432
433
# File 'lib/couch-shell/shell.rb', line 431

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

#command_quit(argstr) ⇒ Object

Raises:



455
456
457
# File 'lib/couch-shell/shell.rb', line 455

def command_quit(argstr)
  raise BreakReplLoop
end

#command_server(argstr) ⇒ Object



491
492
493
# File 'lib/couch-shell/shell.rb', line 491

def command_server(argstr)
  self.server = argstr
end

#command_sh(argstr) ⇒ Object



499
500
501
502
503
504
505
506
507
# File 'lib/couch-shell/shell.rb', line 499

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

#command_uuids(argstr) ⇒ Object



459
460
461
462
# File 'lib/couch-shell/shell.rb', line 459

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

#command_view(argstr) ⇒ Object



646
647
648
649
650
651
652
653
654
655
# File 'lib/couch-shell/shell.rb', line 646

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)


250
251
252
253
254
255
# File 'lib/couch-shell/shell.rb', line 250

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

#editor_bin!Object



422
423
424
425
# File 'lib/couch-shell/shell.rb', line 422

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

#errmsg(str) ⇒ Object



127
128
129
# File 'lib/couch-shell/shell.rb', line 127

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

#expand(url) ⇒ Object



217
218
219
220
# File 'lib/couch-shell/shell.rb', line 217

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

#full_path(path) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/couch-shell/shell.rb', line 222

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



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/couch-shell/shell.rb', line 200

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}]
  elsif body && body =~ JSON_DOC_START_RX
    headers['Content-Type'] = "application/json"
  end
  res = HTTPClient.new.request(method, absolute_url, body, headers)
  Response.new(res)
ensure
  file.close if file
end

#interpolate(str) ⇒ Object



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/couch-shell/shell.rb', line 304

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)
          expr = nil
        else
          res << c
        end
      elsif dollar
        res << "$"
      elsif expr
        expr << c
      else
        res << c
      end
      dollar = false
    }
  }
end

#lookup_var(var) ⇒ Object



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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/couch-shell/shell.rb', line 349

def lookup_var(var)
  case var
  when "uuid"
    command_uuids nil
    if @responses.current(&:ok?)
      json = @responses.current.json
      if json && (uuids = json["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



118
119
120
121
122
123
124
125
# File 'lib/couch-shell/shell.rb', line 118

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



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/couch-shell/shell.rb', line 174

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 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



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

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


132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/couch-shell/shell.rb', line 132

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



241
242
243
244
245
246
247
248
# File 'lib/couch-shell/shell.rb', line 241

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

#readObject



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/couch-shell/shell.rb', line 257

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

#repObject



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/couch-shell/shell.rb', line 269

def rep
  input = read
  case input
  when nil
    raise BreakReplLoop
  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

#replObject



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/couch-shell/shell.rb', line 287

def repl
  loop {
    begin
      rep
    rescue Interrupt
      @stdout.puts
      errmsg "interrupted"
    rescue UndefinedVariable => e
      errmsg "Variable `" + e.varname + "' is not defined."
    rescue ShellUserError => e
      errmsg e.message
    end
  }
rescue BreakReplLoop
  msg "bye"
end

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



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/couch-shell/shell.rb', line 146

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



407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/couch-shell/shell.rb', line 407

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
  request method, interpolate(url), body
end

#server=(url) ⇒ Object



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

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



345
346
347
# File 'lib/couch-shell/shell.rb', line 345

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