require 'webrick' require 'fileutils' if ARGV.length != 0 root = ARGV.first.gsub('\\', '/') else root = '.' end BACKUP_DIR = 'bak' BACKUP_VERSIONS = 3 module WEBrick module HTTPServlet class FileHandler alias do_PUT do_GET end class DefaultFileHandler def do_PUT(req, res) file = "#{@config[:DocumentRoot]}#{req.path}" res.body = '' unless Dir.exists? BACKUP_DIR Dir.mkdir BACKUP_DIR end FileUtils.cp(file, get_backup_filename("#{BACKUP_DIR}/#{File.basename(file, '.html')}")) File.open(file, "w+") {|f| f.puts(req.body)} end def do_OPTIONS(req, res) res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT,PUT,DAV,dav" res['x-api-access-type'] = 'file' res['dav'] = 'tw5/put' end def get_backup_filename(basename) (1..BACKUP_VERSIONS) .map {|i| p = "#{basename}.#{i}.html" d = File.exists?(p) ? File.mtime(p) : Time.at(0) {"date" => d, "path" => p, "index" => i}} .sort_by {|f| [f['date'], f['index']]}[0]['path'] end end end end server = WEBrick::HTTPServer.new({:Port => 8000, :DocumentRoot => root, :BindAddress => "127.0.0.1"}) trap "INT" do puts "Shutting down..." server.shutdown end server.start