caploy 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,19 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ .idea/
19
+ .rbenv*
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'http://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in caploy.gemspec
4
+ gemspec
data/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # What?
2
+
3
+ * capistrano deployment task for my projects
4
+
5
+ # Why?
6
+
7
+ * dry
8
+
9
+ # Todo
10
+
11
+ * implement onrollback
12
+ * gem 'cap-recipes'
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
data/caploy.gemspec ADDED
@@ -0,0 +1,29 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/caploy/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Michael Schiller"]
6
+ gem.email = ["michael.schiller@gmx.de"]
7
+ gem.description = %q{capistrano deployment task for my projects}
8
+ gem.summary = %q{capistrano deployment task for my projects}
9
+ gem.homepage = "https://github.com/mschiller/caploy"
10
+
11
+ gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
12
+ gem.files = `git ls-files`.split("\n")
13
+ gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
14
+ gem.name = "caploy"
15
+ gem.require_paths = ["lib"]
16
+
17
+ gem.add_dependency('gemcutter')
18
+
19
+ gem.add_dependency('capistrano', '>= 2.12.0')
20
+ gem.add_dependency('capistrano-ext', '>= 1.2.1')
21
+ gem.add_dependency('capistrano_colors', '>= 0.5.5')
22
+ gem.add_dependency('capistrano-unicorn', '>= 0.1.6')
23
+ gem.add_dependency('capistrano-file_db', '>= 0.1.0')
24
+ gem.add_dependency('capistrano-uptodate', '>= 0.0.2')
25
+ gem.add_dependency('rvm-capistrano', '>= 1.2.2')
26
+ gem.add_dependency('erubis')
27
+
28
+ gem.version = Caploy::VERSION
29
+ end
@@ -0,0 +1,4 @@
1
+ Capistrano::Configuration.instance.load do
2
+ require './config/boot'
3
+ require 'airbrake/capistrano'
4
+ end
@@ -0,0 +1,26 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ load 'deploy/assets' unless ENV['NOASSETS'] # http://guides.rubyonrails.org/asset_pipeline.html#in-production
4
+
5
+ set :assets_dir, 'system' unless exists?(:assets_dir)
6
+ set :local_assets_dir, 'public' unless exists?(:local_assets_dir)
7
+
8
+ namespace :assets do
9
+ namespace :local do
10
+ desc 'Synchronize your local assets using remote assets'
11
+ task :sync do
12
+ if Util.prompt "Are you sure you want to erase your local assets with server assets"
13
+ servers = find_servers :roles => :app
14
+ [assets_dir].flatten.each do |dir|
15
+ system("rsync -a --del --progress --rsh='ssh -p #{fetch(:ssh_port, 22)}' #{user}@#{servers.first}:#{shared_path}/#{dir}/ #{local_assets_dir}")
16
+ end
17
+ end
18
+ end
19
+ end
20
+
21
+ desc 'Synchronize your local assets using remote assets'
22
+ task :pull do
23
+ assets.local.sync
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,23 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ # defaults
4
+ #_cset :bundle_gemfile, "Gemfile"
5
+ #_cset :bundle_dir, File.join(fetch(:shared_path), 'bundle')
6
+ #_cset :bundle_roles, #{role_default} # e.g. [:app, :batch]
7
+ #_cset :bundle_cmd, "/home/deploy/.rbenv/shims/bundle"
8
+ _cset :bundle_without, [:development, :test, :deploy]
9
+ # http://shapeshed.com/journal/using-rbenv-to-manage-rubies/
10
+ # you can also apply a clever technique to allow you switch versions of ruby by pushing a new .rbenv-version file with capistrano. From version 1.1rc bundler allows you to specify a shebang for binstubs. To use this add the following to your capistrano recipe.
11
+ _cset :bundle_flags, "--deployment --quiet --binstubs --shebang ruby-local-exec"
12
+ _cset :rake, 'bundle exec rake'
13
+
14
+ require 'bundler/capistrano'
15
+
16
+ namespace :bundler do
17
+ task :install_gem do
18
+ run "cd #{release_path} && gem install bundler --no-ri --no-rdoc"
19
+ end
20
+ end
21
+
22
+ #before "bundle:install", "bundler:install_gem"
23
+ end
@@ -0,0 +1,58 @@
1
+ Capistrano::Configuration.instance.load do |instance|
2
+
3
+ require File.expand_path("#{File.dirname(__FILE__)}/../../util")
4
+ require File.expand_path("#{File.dirname(__FILE__)}/../../mysql")
5
+
6
+ instance.set :local_rails_env, ENV['RAILS_ENV'] || 'development' unless exists?(:local_rails_env)
7
+ instance.set :db_local_clean, false unless exists?(:db_local_clean)
8
+
9
+ namespace :db do
10
+ namespace :remote do
11
+ desc 'Synchronize the local database to the remote database'
12
+ task :sync, :roles => :db do
13
+ if if Util.prompt 'Are you sure you want to REPLACE THE REMOTE DATABASE with local database'
14
+ Database.local_to_remote(instance)
15
+ end
16
+ end
17
+ end
18
+
19
+ namespace :local do
20
+ desc 'Synchronize your local database using remote database data'
21
+ task :sync, :roles => :db do
22
+ puts "Local database: #{Database::Local.new(instance).database}"
23
+ if rails_env == 'production'
24
+ puts 'Never sync remote production database!'
25
+ else
26
+ if Util.prompt 'Are you sure you want to erase your local database with server database'
27
+ Database.remote_to_local(instance)
28
+ end
29
+ end
30
+ end
31
+ end
32
+
33
+ desc 'Synchronize your local database using remote database data'
34
+ task :pull do
35
+ db.local.sync
36
+ end
37
+
38
+ desc 'Synchronize the local database to the remote database'
39
+ task :push do
40
+ db.remote.sync
41
+ end
42
+ end
43
+ end
44
+
45
+ namespace :deploy do
46
+ after 'deploy:make_symlinks', 'deploy:dynamic_migrations' if fetch(:dynamic_migration, false)
47
+
48
+ task :dynamic_migrations do
49
+ from = source.next_revision(current_revision)
50
+ if capture("cd #{latest_release} && #{source.local.log(from)} db/migrate | wc -l").to_i > 0
51
+ run "cd #{current_release} && RAILS_ENV=#{rails_env} bundle exec rake db:migrate"
52
+ logger.info "New migrations added - running migrations."
53
+ else
54
+ logger.info "Skipping migrations - there are not any new."
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,90 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ require File.expand_path("#{File.dirname(__FILE__)}/../../util")
4
+
5
+ set :keep_releases, 10
6
+ set :use_sudo, false
7
+
8
+ set :protocol, :both
9
+
10
+ set :scm, :git
11
+ set :git_enable_submodules, false
12
+
13
+ # set deployment strategy
14
+ set :deploy_via, :remote_cache
15
+ set :copy_exclude, %w(.git .svn .DS_Store test doc .gitkeep)
16
+ #_cset :repository_cache, "cached-copy" # defaults to :shared_path + 'cached-copy/'
17
+
18
+ # :forward_agent allows us to avoid using and distributing a deploy key.
19
+ # On problems run 'ssh-add' locally
20
+ # In your /etc/ssh/ssh_config or ~/.ssh/config you need to have ForwardAgent enabled for this to work.
21
+ set :ssh_options, {:port => fetch(:ssh_port, 22), :forward_agent => true, :paranoid => true}
22
+
23
+ default_run_options[:pty] = true
24
+
25
+ # if you want to remove the dump file after loading
26
+ set :db_local_clean, true
27
+
28
+ task :test_and_prepare_cap_env do
29
+ abort "You must set :user before using defaults" unless fetch(:user, nil)
30
+ abort "You must set :repository before using defaults" unless fetch(:repository, nil)
31
+ abort "You must set :branch before using defaults" unless fetch(:branch, nil)
32
+ abort "You must set :deploy_to before using defaults" unless fetch(:deploy_to, nil)
33
+
34
+ set :uptodate_branch, fetch(:branch)
35
+ set :uptodate_scm, :git
36
+ #:uptodate_scm_bynary ('git') - path to SCM binary
37
+ #:uptodate_remote_repository ('origin') - remote repository
38
+ #:uptodate_time (60) - time in seconds for checking remote repository
39
+ #:uptodate_behaviour - (:confirm)
40
+ # :confirm - show outdated message and ask to confirm the further execution
41
+ # :abort - show outdated message and abort further execution
42
+ require 'capistrano/uptodate'
43
+
44
+ require 'capistrano_colors'
45
+ capistrano_color_matchers = [
46
+ {:match => /command finished/, :color => :hide, :prio => 10},
47
+ {:match => /executing command/, :color => :blue, :prio => 10, :attribute => :underscore},
48
+ {:match => /^transaction: commit$/, :color => :magenta, :prio => 10, :attribute => :blink},
49
+ {:match => /git/, :color => :white, :prio => 20, :attribute => :reverse},
50
+ ]
51
+ colorize(capistrano_color_matchers)
52
+
53
+ #Dynamically skip Capistrano hooks example
54
+ # before 'deploy:update_code', 'db:dump' unless fetch(:skip_dump, false)
55
+ # $ cap staging deploy -S skip_dump=true
56
+ end
57
+
58
+ before 'deploy', 'test_and_prepare_cap_env'
59
+ before 'deploy:migrations', 'test_and_prepare_cap_env'
60
+ after 'deploy:update', 'deploy:cleanup'
61
+
62
+ desc "Show currently deployed revision on server."
63
+ task :revisions, :roles => :app do
64
+ current, previous, latest = current_revision[0, 7], previous_revision[0, 7], real_revision[0, 7]
65
+ puts "\n" << "-"*63
66
+ puts "===== Master Revision: \033[1;33m#{latest}\033[0m\n\n"
67
+ puts "===== [ \033[1;36m#{application.capitalize} - #{stage.to_s.capitalize}\033[0m ]"
68
+ puts "=== Deployed Revision: \033[1;32m#{current}\033[0m"
69
+ puts "=== Previous Revision: \033[1;32m#{previous}\033[0m\n\n"
70
+
71
+ # If deployed and master are the same, show the difference between the last 2 deployments.
72
+ base_label, new_label, base_rev, new_rev = latest != current ? \
73
+ ["deployed", "master", current, latest] : \
74
+ ["previous", "deployed", previous, current]
75
+
76
+ # Show difference between master and deployed revisions.
77
+ if (diff = `git log #{base_rev}..#{new_rev} --oneline`) != ""
78
+ # Colorize refs
79
+ diff.gsub!(/^([a-f0-9]+) /, "\033[1;32m\\1\033[0m - ")
80
+ diff = " " << diff.gsub("\n", "\n ") << "\n"
81
+ # Indent commit messages nicely, max 80 chars per line, line has to end with space.
82
+ diff = diff.split("\n").map { |l| l.scan(/.{1,120}/).join("\n"<<" "*14).gsub(/([^ ]*)\n {14}/m, "\n"<<" "*14<<"\\1") }.join("\n")
83
+ puts "=== Difference between #{base_label} revision and #{new_label} revision:\n\n"
84
+ puts diff
85
+ end
86
+ end
87
+
88
+ after "deploy", "revisions"
89
+ after "deploy:migrations", "revisions"
90
+ end
@@ -0,0 +1,38 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :info do
4
+ desc <<-DESC
5
+ Tail all or a single remote file
6
+
7
+ The logfile can be specified with a LOGFILE-environment variable.
8
+ It defaults to RAILS_ENV.log
9
+ DESC
10
+ task :tail, :roles => :app do
11
+ ENV["LOGFILE"] ||= "#{rails_env}.log"
12
+ begin
13
+ stream "tail -f #{shared_path}/log/#{ENV["LOGFILE"]}"
14
+ rescue Interrupt
15
+ puts "\n--interrupted by user--"
16
+ puts ""
17
+ end
18
+ end
19
+
20
+ desc "Display the currently deployed Application, Revision and Release"
21
+ task :version, :roles => :app, :except => { :no_release => true } do
22
+ rev = current_revision
23
+ rel = current_release.split('/').pop
24
+
25
+ puts ""
26
+ puts " AppName: #{fetch(:application)}"
27
+ puts " Version: #{rev}"
28
+ puts " Release: #{rel}"
29
+ puts ""
30
+ end
31
+
32
+ desc "Display the uname"
33
+ task :uname do
34
+ run "uname -a"
35
+ end
36
+ end
37
+
38
+ end
@@ -0,0 +1,12 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ desc "tail production log files"
4
+ task :tail_logs, :roles => :app do
5
+ run "tail -f #{shared_path}/log/*.log" do |channel, stream, data|
6
+ trap("INT") { puts 'Interupted'; exit 0; }
7
+ puts # for an extra line break before the host name
8
+ puts "#{channel[:host]}: #{data}"
9
+ break if stream == :err
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,108 @@
1
+ require "ms_deploy/render"
2
+
3
+ Capistrano::Configuration.instance.load do
4
+
5
+ namespace :nginx do
6
+ desc <<-DESC
7
+ Starts the nginx web-server.
8
+ DESC
9
+ task :start do
10
+ #run "sudo god start nginx"
11
+ run "sudo /etc/init.d/nginx start"
12
+ end
13
+
14
+ desc <<-DESC
15
+ #Stops the nginx web-server.
16
+ DESC
17
+ task :stop do
18
+ #run "sudo god stop nginx"
19
+ run "sudo /etc/init.d/nginx stop"
20
+ end
21
+
22
+ desc <<-DESC
23
+ Restarts the nginx web-server.
24
+ DESC
25
+ task :restart do
26
+ #run "sudo god restart nginx"
27
+ run "sudo /etc/init.d/nginx restart"
28
+ end
29
+
30
+ task :setup, :roles => :web do
31
+ protocol = fetch(:protocol, nil).to_s
32
+ template_path = File.expand_path('../../templates/nginx/vhost.erb', __FILE__)
33
+ vars = {
34
+ 'application' => application,
35
+ 'project_root' => deploy_to + '/current',
36
+ 'domain' => vhost_domain, 'stage' => stage,
37
+ 'auth_basic_title' => fetch(:auth_basic_title, nil),
38
+ 'auth_basic_password_file' => fetch(:auth_basic_password_file, nil),
39
+ 'protocol' => 'http',
40
+ 'nginx_cert_dir' => fetch(:nginx_cert_dir, '/etc/nginx/cert'),
41
+ 'with_upstream_server' => true,
42
+ 'with_file_expire_max' => fetch(:with_file_expire_max, true),
43
+ 'optional_http_content' => fetch(:optional_nginx_server_http_content, ''),
44
+ 'optional_https_content' => fetch(:optional_nginx_server_https_content, ''),
45
+ 'optional_nginx_http_content' => fetch(:optional_nginx_http_content, ''),
46
+ 'optional_nginx_https_content' => fetch(:optional_nginx_https_content, ''),
47
+ 'cert_type' => fetch(:cert_type, 'pem'),
48
+ 'key_type' => fetch(:cert_type, 'key'),
49
+ 'serve_static_files' => fetch(:serve_static_files, true),
50
+ }
51
+
52
+ sites_path = fetch(:nginx_sites_enabled_path, "/etc/nginx/sites-enabled")
53
+
54
+ if protocol.nil? or protocol == 'http' or protocol == 'both'
55
+ config_path = "#{shared_path}/config/#{application}_vhost.conf"
56
+
57
+ put(render_erb_template(template_path, vars), config_path)
58
+
59
+ with_user(fetch(:setup_user, user)) do
60
+ try_sudo "rm -f #{sites_path}/#{application}_#{stage}.conf"
61
+ try_sudo "ln -s #{config_path} #{sites_path}/#{application}_#{stage}.conf"
62
+ end
63
+ end
64
+ if protocol == 'https' or protocol == 'both'
65
+ vars.merge!({'protocol' => 'https'})
66
+
67
+ config_path = "#{shared_path}/config/#{application}_ssl_vhost.conf"
68
+
69
+ put(render_erb_template(template_path, vars), config_path)
70
+
71
+ with_user(fetch(:setup_user, user)) do
72
+ try_sudo "rm -f #{sites_path}/#{application}_#{stage}_ssl.conf"
73
+ try_sudo "ln -s #{config_path} #{sites_path}/#{application}_#{stage}_ssl.conf"
74
+ end
75
+ end
76
+ end
77
+
78
+ task :uninstall do
79
+ protocol = fetch(:protocol, nil)
80
+ sites_path = fetch(:nginx_sites_enabled_path, "/etc/nginx/sites-enabled")
81
+
82
+ with_user(fetch(:setup_user, user)) do
83
+ if protocol.blank? or protocol == 'http' or protocol == 'both'
84
+ try_sudo "rm -f #{sites_path}/#{application}_#{stage}.conf"
85
+ elsif protocol == 'https' or protocol == 'both'
86
+ try_sudo "rm -f #{sites_path}/#{application}_#{stage}_ssl.conf"
87
+ end
88
+ end
89
+ end
90
+ end
91
+
92
+ after :"deploy:setup", :"nginx:setup";
93
+
94
+ def with_user(new_user, &block)
95
+ old_user = user
96
+ set :user, new_user
97
+ close_sessions
98
+ yield
99
+ set :user, old_user
100
+ close_sessions
101
+ end
102
+
103
+ def close_sessions
104
+ sessions.values.each { |session| session.close }
105
+ sessions.clear
106
+ end
107
+
108
+ end
@@ -0,0 +1,11 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :deploy do
4
+ desc "build missing paperclip styles"
5
+ task :build_missing_paperclip_styles, :roles => :app do
6
+ run "cd #{release_path}; RAILS_ENV=#{rails_env} bundle exec rake paperclip:refresh:missing_styles"
7
+ end
8
+ end
9
+
10
+ #after("deploy:update_code", "deploy:build_missing_paperclip_styles")
11
+ end
@@ -0,0 +1,32 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :passenger do
4
+ desc "Restart Application"
5
+ task :restart do
6
+ run "touch #{current_path}/tmp/restart.txt"
7
+ end
8
+ end
9
+
10
+ namespace :deploy do
11
+ #desc "Archive images from public tree"
12
+ #task :archive_images do
13
+ # run "tar -c public/system > images.tar"
14
+ #end
15
+ #
16
+ #desc "Install images into deployed public tree"
17
+ #task :install_images do
18
+ # # scp images to server
19
+ # # untar images into public/
20
+ #end
21
+
22
+ task :restart do
23
+ passenger.restart
24
+ end
25
+
26
+ task :start do
27
+ end
28
+
29
+ task :stop do
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,25 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ _cset :puma_binary, "bundle exec puma"
4
+ _cset :pumactl_binary, "bundle exec pumactl"
5
+ _cset :puma_state, "tmp/puma_state"
6
+ _cset :puma_tcp_port, 9292
7
+ _cset :puma_control_tcp_port, puma_tcp_port.to_i + 1
8
+ _cset :puma_thread_pool, '0:16'
9
+
10
+ namespace :deploy do
11
+ task :start, :roles => :app, :except => { :no_release => true } do
12
+ set :puma_socket, fetch(:puma_socket, "unix:///tmp/sockets/#{application}_#{rails_env}.sock")
13
+
14
+ tcp = puma_tcp_port.nil? ? '' : "-b tcp://127.0.0.1:#{puma_tcp_port}"
15
+ run "cd #{current_path} && RAILS_ENV=#{rails_env} #{puma_binary} -t #{puma_thread_pool} -S #{puma_state} --control tcp://127.0.0.1:#{puma_control_tcp_port} -b #{puma_socket} #{tcp}" # --control-token xxx
16
+ end
17
+ task :stop, :roles => :app, :except => { :no_release => true } do
18
+ run "cd #{current_path} && RAILS_ENV=#{rails_env} #{pumactl_binary} -S #{puma_state} stop"
19
+ end
20
+ task :restart, :roles => :app, :except => { :no_release => true } do
21
+ run "cd #{current_path} && RAILS_ENV=#{rails_env} #{pumactl_binary} -S #{puma_state} restart"
22
+ end
23
+ end
24
+
25
+ end
@@ -0,0 +1,7 @@
1
+ Capistrano::Configuration.instance.load do
2
+ abort "You must set :user before using defaults" unless fetch(:user)
3
+
4
+ set :default_environment, {
5
+ 'PATH' => "/home/#{fetch(:user)}/.rbenv/shims:/home/#{fetch(:user)}/.rbenv/bin:$PATH"
6
+ }
7
+ end
@@ -0,0 +1,41 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :redis do
4
+
5
+ desc "Install redis"
6
+ task :install do
7
+ ["#{sudo} rm -r /tmp/redis",
8
+ "#{sudo} rm /usr/local/bin/redis-*",
9
+ "git clone git://github.com/antirez/redis.git /tmp/redis",
10
+ "cd /tmp/redis && git pull",
11
+ "cd /tmp/redis && git checkout v2.0.4-stable",
12
+ "cd /tmp/redis && make clean",
13
+ "cd /tmp/redis && make",
14
+ "cd /tmp/redis && #{sudo} make install",
15
+ "#{sudo} cp /tmp/redis/redis.conf /etc/",
16
+ "#{sudo} sed -i 's/daemonize no/daemonize yes/' /etc/redis.conf",
17
+ "#{sudo} sed -i 's/# bind 127.0.0.1/bind 127.0.0.1/' /etc/redis.conf"
18
+ ].each {|cmd| run cmd}
19
+ end
20
+
21
+ desc "Start the Redis server"
22
+ task :start do
23
+ run "redis-server /etc/redis.conf"
24
+ end
25
+
26
+ desc "Stop the Redis server"
27
+ task :stop do
28
+ run 'echo "SHUTDOWN" | nc localhost 6379'
29
+ #sudo 'kill `cat /var/run/redis.pid`'
30
+ end
31
+
32
+ desc "Restart the Redis server"
33
+ task :restart do
34
+ redis.stop
35
+ sleep(1)
36
+ redis.start
37
+ end
38
+
39
+ end
40
+
41
+ end
@@ -0,0 +1,8 @@
1
+ Capistrano::Configuration.instance.load do
2
+ abort "You must set :ruby_version before using defaults" unless fetch(:ruby_version)
3
+
4
+ #$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
5
+ require "rvm/capistrano"
6
+ set :rvm_ruby_string, fetch(:ruby_version)
7
+ set :rvm_type, :user
8
+ end
@@ -0,0 +1,9 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :deploy do
4
+ task :seed, :roles => :app do
5
+ run "cd #{current_path} && RAILS_ENV=#{rails_env} bundle exec rake db:seed"
6
+ end
7
+ end
8
+
9
+ end
@@ -0,0 +1,75 @@
1
+ Capistrano::Configuration.instance.load do
2
+
3
+ namespace :deploy do
4
+ namespace :prepare do
5
+ task :create_config_files, :roles => :app do
6
+ run "mkdir -p #{shared_path}/config/"
7
+ config_file_to_setup.each do |config_file|
8
+ put(File.read(config_file_path(config_file)), "#{shared_path}/config/#{config_file}", :via => :scp)
9
+ end
10
+ end
11
+
12
+ desc "Set up shared directory structure"
13
+ task :create_shared_folders, :roles => :app do
14
+ directories_to_create.each { |directory| run "mkdir -p #{directory}" }
15
+ end
16
+
17
+ task :set_permissions, :roles => :app do
18
+ try_sudo "chown -R #{user}:#{fetch(:group, user)} #{deploy_to}" if fetch(:use_sudo, false)
19
+ end
20
+
21
+ task :database, :roles => :db do
22
+ _cset :db_admin_user, 'root'
23
+ _cset :db_admin_password, Capistrano::CLI.password_prompt("Type your mysql password for user '#{db_admin_user}' (not set if empty): ")
24
+ _cset :db_name, application.gsub(/\W+/, '')[0..5] + '_' + rails_env.to_s
25
+ _cset :db_user_name, application
26
+ _cset :db_user_password, ''
27
+
28
+ unless db_admin_password.to_s.empty?
29
+ unless database_exits?
30
+ create_database
31
+ end
32
+ setup_database_permissions
33
+ end
34
+ end
35
+ end
36
+ end
37
+
38
+ before 'deploy:setup', 'deploy:prepare:database';
39
+ before :'deploy:setup', :'deploy:prepare:create_config_files';
40
+ before :'deploy:setup', :'deploy:prepare:create_shared_folders';
41
+ after 'deploy:setup', 'deploy:prepare:set_permissions';
42
+
43
+ end
44
+
45
+ def config_file_path(config_file_name)
46
+ config_file = "#{rails_root}/config/#{config_file_name}"
47
+ raise "No config file '#{config_file}'" unless File.exists? config_file
48
+ config_file
49
+ end
50
+
51
+ def database_exits?
52
+ exists = false
53
+
54
+ run "mysql --user=#{db_admin_user} --password=#{db_admin_password} --execute=\"show databases;\"" do |channel, stream, data|
55
+ exists = exists || data.include?(db_name)
56
+ end
57
+
58
+ exists
59
+ end
60
+
61
+ def create_database
62
+ create_sql = <<-SQL
63
+ CREATE DATABASE #{db_name};
64
+ SQL
65
+
66
+ run "mysql --user=#{db_admin_user} --password=#{db_admin_password} --execute=\"#{create_sql}\""
67
+ end
68
+
69
+ def setup_database_permissions
70
+ grant_sql = <<-SQL
71
+ GRANT ALL PRIVILEGES ON #{db_name}.* TO #{db_user_name}@localhost IDENTIFIED BY '#{db_user_password}';
72
+ SQL
73
+
74
+ run "mysql --user=#{db_admin_user} --password=#{db_admin_password} --execute=\"#{grant_sql}\""
75
+ end