module Rmate

Constants

DATE
VERSION
VERSION_STRING

Public Instance Methods

connect_and_handle_cmds(host, port, unixsocketpath, cmds) click to toggle source
# File lib/rmate.rb, line 160
def connect_and_handle_cmds(host, port, unixsocketpath, cmds)
  socket = nil
  unixsocketpath = File.expand_path(unixsocketpath) unless unixsocketpath.nil?
  if unixsocketpath.nil? || !File.exist?(unixsocketpath)
    $stderr.puts "Using TCP socket to connect: ‘#{host}:#{port}’" if $settings.verbose
    begin
      socket = TCPSocket.new(host, port)
    rescue Exception => e
      abort "Error connecting to ‘#{host}:#{port}’: #{e.message}"
    end
  else
    $stderr.puts "Using UNIX socket to connect: ‘#{unixsocketpath}’" if $settings.verbose
    socket = UNIXSocket.new(unixsocketpath)
  end
  server_info = socket.readline.chomp
  $stderr.puts "Connect: ‘#{server_info}’" if $settings.verbose

  cmds.each { |cmd| cmd.send(socket) }

  socket.puts "."
  handle_cmd(socket) while !socket.eof?
  socket.close
  $stderr.puts "Done" if $settings.verbose
end
handle_close(socket, variables, data) click to toggle source
# File lib/rmate.rb, line 134
def handle_close(socket, variables, data)
  path = variables["token"]
  $stderr.puts "Closed #{path}" if $settings.verbose
end
handle_cmd(socket) click to toggle source
# File lib/rmate.rb, line 139
def handle_cmd(socket)
  cmd = socket.readline.chomp

  variables = {}
  data = ""

  while line = socket.readline.chomp
    break if line.empty?
    name, value     = line.split(': ', 2)
    variables[name] = value
    data << socket.read(value.to_i) if name == "data"
  end
  variables.delete("data")

  case cmd
  when "save"   then handle_save(socket, variables, data)
  when "close"  then handle_close(socket, variables, data)
  else          abort "Received unknown command “#{cmd}”, exiting."
  end
end
handle_save(socket, variables, data) click to toggle source
# File lib/rmate.rb, line 115
def handle_save(socket, variables, data)
  path = variables["token"]
  if File.writable?(path) || !File.exist?(path)
    $stderr.puts "Saving #{path}" if $settings.verbose
    begin
      backup_path = "#{path}~"
      backup_path = "#{backup_path}~" while File.exist? backup_path
      FileUtils.cp(path, backup_path, :preserve => true) if File.exist?(path)
      open(path, 'wb') { |file| file << data }
      File.unlink(backup_path) if File.exist? backup_path
    rescue
      # TODO We probably want some way to notify the server app that the save failed
      $stderr.puts "Save failed! #{$!}" if $settings.verbose
    end
  else
    $stderr.puts "Skipping save, file not writable." if $settings.verbose
  end
end