Module: Rmate

Defined in:
lib/rmate.rb

Defined Under Namespace

Classes: Command, Settings

Constant Summary collapse

DATE =
"2014-02-06"
VERSION =
"1.5.7"
VERSION_STRING =
"rmate version #{Rmate::VERSION} (#{Rmate::DATE})"

Class Method Summary collapse

Class Method Details

.connect_and_handle_cmds(host, port, cmds) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/rmate.rb', line 156

def connect_and_handle_cmds(host, port, cmds)
  socket = TCPSocket.new(host, port)
  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) ⇒ Object



130
131
132
133
# File 'lib/rmate.rb', line 130

def handle_close(socket, variables, data)
  path = variables["token"]
  $stderr.puts "Closed #{path}" if $settings.verbose
end

.handle_cmd(socket) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/rmate.rb', line 135

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) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/rmate.rb', line 111

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