#!/usr/bin/env ruby require 'erb' fail_gently = ARGV.include?("--fail-gently") if ARGV.include?("-i") puts "*******************************************************" puts system("du -sh ~/dumps") puts puts "*******************************************************" exit end ### require "yaml" config_path = 'config/database.yml' begin # go to project root current = Dir.pwd until (File.exists? config_path) Dir.chdir '..' if current == Dir.pwd if fail_gently puts "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" puts "* *" puts "* *" puts "* Script is not called from inside a Rails project, *" puts "* *" puts "* THE DATABASE WILL NOT BE DUMPED. *" puts "* *" puts "* *" puts "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" sleep 5 exit else raise "Call me from inside a Rails project." end end current = Dir.pwd end config = YAML::load(ERB.new(File.read(config_path)).result) environment = ARGV.reject{ |arg| arg[0].chr == '-' }.first || 'production' config = config[environment] or raise "No #{environment} database found.\nUsage: dumple ENVIRONMENT" dump_dir = "#{ENV['HOME']}/dumps" unless File.directory?(dump_dir) Dir.mkdir(dump_dir) system("chmod 700 #{dump_dir}") end if ARGV.find{ |arg| arg == '--for_download'} dump_path = "#{dump_dir}/dump_for_download.dump" else dump_path = "#{dump_dir}/#{config['database']}_#{Time.now.strftime("%Y%m%d_%H%M%S")}.dump" end puts "> Dumping database for \"#{environment}\" environment ..." host = config['host'] case config['adapter'] when /mysql/ command = "mysqldump -u\"#{config['username']}\" -p\"#{config['password']}\" #{config['database']} -r #{dump_path}" if port = config['port'] command << " -h#{host || '127.0.0.1'} -P#{port}" else command << " -h#{host || 'localhost'}" end system(command) when /postgres/ command = "PGPASSWORD=\"#{config['password']}\" pg_dump -U\"#{config['username']}\" #{config['database']} -Fc -f #{dump_path}" if host command << " -h#{host}" end if port = config['port'] command << " -p #{port}" end system(command) else raise "Adapter \"#{config['adapter']} is not supported" end system "chmod 600 #{dump_path}" dump_size_kb = (File.size(dump_path) / 1024).round puts "> Dumped to #{dump_path} (#{dump_size_kb} KB)" rescue Exception => e $stderr.puts e.message exit 1 end