seancojr
11/24/2008 - 5:57 PM

caprc.rb

# DESCRIPTION: Cap task to setup the current (initialized) git directory as a remote repository.
#
# INSTALL: Copy to home directory as ~/.caprc
# RUN: cap git:setup scm=t
#
# AUTHOR: Geoffrey Grosenbach http://peepcode.com
#
# Assumes ability to run commands as sudo and the presence of a "git" user and group on remote server. 
#   The Capistrano :user is used only to connect and setup directories.

if ENV['scm']
  role :scm,                 "git.example.com"
  set  :user,                "deploy"
  set  :scm_hostname,        "git.example.com"
  set  :remote_git_repo_dir, "/git"
end

namespace :git do

  desc "Setup remote Git repo from the current directory"
  task :setup, :roles => :scm do
    repo            = File.basename(FileUtils.pwd)
    remote_repo_dir = "#{remote_git_repo_dir}/#{repo}.git"
    unless Capistrano::CLI.ui.agree("Are you sure you want to setup '#{repo}'? (yes/no): ")
      puts "Git setup aborted."
      exit
    end

    unless File.exists?(".git")
      puts "!!! You must first initialize the current directory with Git. !!!"
      exit
    end

    sudo [
      "mkdir -p #{remote_repo_dir}",
      "cd #{remote_repo_dir}",
      "git --bare init",
      "chown -R git:git #{remote_repo_dir}"
    ].join(" && ")

    system "git remote add origin git@#{scm_hostname}:#{remote_repo_dir}"
    system "git push origin master"
    # Configure new remote repo as the origin
    system %(echo "[branch \\"master\\"]\n\tremote = origin\n\tmerge = refs/heads/master" >> .git/config)
  end

end