Created
March 30, 2012 22:32
-
-
Save rondy/2256526 to your computer and use it in GitHub Desktop.
Prompt branch name to deploy on Capistrano (OOP way)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Found the problem with the loop.