Skip to content

Instantly share code, notes, and snippets.

@dwbutler
Created August 23, 2018 16:27
Show Gist options
  • Save dwbutler/ba10ae8333af4b8f061c635403358b98 to your computer and use it in GitHub Desktop.
Save dwbutler/ba10ae8333af4b8f061c635403358b98 to your computer and use it in GitHub Desktop.
Automatically clean up Heroku slug
CLEANUP_THRESHOLD = 250 * 1_024_000 # 250 megabytes
# See https://robots.thoughtbot.com/how-to-reduce-a-large-heroku-compiled-slug-size
desc "Clean up the Heroku repo to reduce compiled slug size"
task cleanup: :set_app do
force = ENV.fetch('FORCE_CLEANUP', false)
if force || slug_size > CLEANUP_THRESHOLD
puts "Heroku compiled slug size exceeds 250 MB. Cleaning up the Heroku repo."
install_heroku_plugin('heroku-repo')
_execute heroku_command("repo:gc")
_execute heroku_command("repo:purge_cache")
puts "Heroku repo clean up complete. Note that the compiled slug size won't be reduced until the next deploy."
else
puts "Heroku compiled slug size is less than 250 MB. Not cleaning up. Force a cleanup with FORCE_CLEANUP=1"
end
end
task :set_app do
next if defined?(APP)
if ENV['APP']
APP = ENV['APP']
puts "Setting Application to #{APP}"
else
$stderr.puts "Expected environment variable APP to be set"
exit(1)
end
end
def install_heroku_plugin(plugin)
if `heroku plugins | grep #{plugin}`.empty?
puts "Installing Heroku plugin #{plugin}"
_execute "heroku plugins:install #{plugin}"
else
puts "Heroku plugin #{plugin} installed"
end
end
def slug_size
app_info['app']['slug_size']
end
def app_info
@app_info ||= JSON.parse(`#{heroku_command('apps:info --json')}`)
end
def heroku_command(command, opt = { account: ENV['ACCOUNT'] })
command = "heroku #{command} --app #{APP}"
command = "#{command} --account #{opt[:account]}" if opt[:account]
command
end
def _execute(command, exit_on_failure: true)
print "Executing '#{command}'\n"
unless system(command)
puts "Failed to Execute #{command}"
if exit_on_failure
code = $CHILD_STATUS.exitstatus
puts "cowardly exiting with code #{code}"
exit(code)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment