Skip to content

Instantly share code, notes, and snippets.

@neocsr
Forked from myronmarston/heroku.rake
Created October 2, 2012 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neocsr/3816260 to your computer and use it in GitHub Desktop.
Save neocsr/3816260 to your computer and use it in GitHub Desktop.
Rake task to download a sql dump from a heroku app
namespace :heroku do
def app_name
@app_name ||= Heroku::Command::BaseWithApp.new([]).app
end
def latest_bundle(timeout = 30)
puts "Attempting to get latest bundle..."
get_bundle = lambda do
bundles = Heroku::Command.run('bundles', {})
bundles.sort { |b1, b2| b1[:created_at] <=> b2[:created_at] }
bundles.last
end
bundle = nil
require 'timeout'
Timeout.timeout(timeout) do
while bundle.nil? || bundle[:state] == 'capturing' do
sleep 0.5
bundle = get_bundle.call
end
end
puts "Latest bundle capture has completed"
bundle
end
def invoke(task)
Rake::Task["heroku:#{task}"].invoke
end
task :heroku_setup do
require 'heroku'
require 'heroku/command'
end
task :unpack_tar_setup do
require 'zlib'
require 'archive/tar/minitar'
end
task :destroy_all_bundles => :heroku_setup do |t|
Heroku::Command.run('bundles', {}).try(:each) do |bundle|
Heroku::Command.run('bundles:destroy', [bundle[:name]])
end
end
task :capture_new_bundle => :heroku_setup do |t|
begin
Heroku::Command.run('bundles:capture', [])
rescue SystemExit
puts "Apparently only one bundle is allowed. Deleting all bundles so we can try again..."
invoke('destroy_all_bundles')
Heroku::Command.run('bundles:capture', [])
end
end
task :download_newest_bundle => :heroku_setup do |t|
bundle = latest_bundle
puts "Downloading latest bundle..."
Heroku::Command.run('bundles:download', [bundle[:name]])
end
task :unpack_sqldump, :tar_file, :extract_to, :needs => :unpack_tar_setup do |t, args|
tgz = Zlib::GzipReader.new(File.open(args.tar_file, 'rb'))
Archive::Tar::Minitar::Input.open(tgz) do |inp|
inp.each do |entry|
if entry.full_name =~ /pgdump\.sql/
inp.extract_entry(args.extract_to, entry)
ENV['SQL_DUMP_FILE'] = File.join(args.extract_to, entry.full_name) # so other rake tasks can use it...
puts "sql dump file written to: #{ENV['SQL_DUMP_FILE']}"
end
end
end
end
task :download_sql_dump => :environment do |t|
invoke('capture_new_bundle')
invoke('download_newest_bundle')
tar_file = File.join(Rails.root, "#{app_name}.tar.gz")
extract_to = File.join(Rails.root, "tmp", "bundles")
Rake::Task["heroku:unpack_sqldump"].invoke(tar_file, extract_to)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment