Skip to content

Instantly share code, notes, and snippets.

@rondy
Created March 30, 2012 22:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondy/2256526 to your computer and use it in GitHub Desktop.
Save rondy/2256526 to your computer and use it in GitHub Desktop.
Prompt branch name to deploy on Capistrano (OOP way)
namespace :deploy do
task :set_branch do
set :branch, prompt_branch_name
end
before "deploy:update" , "deploy:set_branch"
end
def prompt_branch_name
BranchedDeploy.new.prompt
end
class BranchedDeploy
def prompt
begin
branch = ask
end while invalid_branch? branch
branch
end
private
# => * Type branch name to deploy: (master, feature_1) |master|
def ask
Capistrano::CLI.ui.ask(" * Type branch name to deploy (#{git_branch.all.join(', ')}):") { |q| q.default = git_branch.current }
end
def invalid_branch?(branch)
!git_branch.exists? branch
end
def git_branch
@git_branch ||= GitBranch.new
end
end
class GitBranch
def current
branches.detect { |branch| branch.start_with? "*" }[2..-1]
end
def all
branches.collect(&removing_asterisk_from_current_branch)
end
def exists?(branch)
branches.include? branch
end
private
# => ["* master", "feature_1"]
def branches
@branches ||= `git branch`.split("\n").map(&:strip)
end
def removing_asterisk_from_current_branch
lambda { |branch| branch.gsub(/^\* /,"") }
end
end
@elpic
Copy link

elpic commented Oct 4, 2012

Thank you

@ruudk
Copy link

ruudk commented Jun 19, 2013

Thanks!

Works great but for some reason it keeps looping with the same question. If I remove the while invalid_branch? branch part it works fine (but without the check). Any idea?

@ruudk
Copy link

ruudk commented Jun 20, 2013

Found the problem with the loop.

def exists?(branch)
    # change    branches.include? branch    to :
    all.include? branch
end

@phstc
Copy link

phstc commented Jun 25, 2014

A simpler approach:

def branch_name(default_branch)
  branch = ENV.fetch('BRANCH', default_branch)

  if branch == '.'
    # current branch
    `git rev-parse --abbrev-ref HEAD`.chomp
  else
    branch
  end
end

set :branch, branch_name('master')

Usage:

BRANCH=. cap [staging] deploy
# => deploy current branch

BRANCH=master cap [staging] deploy
# => deploy master branch

cap [staging] deploy
# => deploy default branch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment