Automatic pull, merge and push for git feature branches

We use this script to automatically merge all features into staging and re-merge those features with deploy-ed code. It will stop when there is a merge conflict -> resolve and start it again.

Automatic –>
often -> smaller conflicts.
no thinking/typing -> less mistakes/headaches.

Usage
e.g. store it in scripts folder or turn it into a rake task

scripts/push_and_merge_all
scripts/push_and_merge_all stage # to also deploy everything to staging

Code

#!/usr/bin/env ruby
require 'rubygems'
require 'rake'

sh "git status | grep 'nothing to commit' && echo 'you are clean''" # ensure we are not dirty
current_branch = `git branch | grep '*'`.split.last
sh "git fetch origin" # get up-to-date info about what needs pulling

def merge(branch, options)
  sh "git checkout #{branch}"
  push_and_pull
  options[:with].each do |merged_branch|
    sh "git checkout #{merged_branch}"
    push_and_pull
    sh "git checkout #{branch} && git merge #{merged_branch}"
  end
  push_and_pull
end

def push_and_pull
  status= `git status 2> /dev/null`
  remote_pattern = /# Your branch is (.*?) /
  diverge_pattern = /# Your branch and (.*) have diverged/
  if status =~ remote_pattern
    if $1 == 'ahead'
      sh "git push"
    else
      sh "git pull"
    end
  elsif status =~ diverge_pattern
    sh "git pull && git push"
  end
end

to_stage = ['master', 'feature_a', 'feature_b']
to_stage.each{|branch| merge(branch, :with => ['deploy']) }
merge('staging', :with => to_stage)

sh "cap deploy" if ARGV[0] == 'stage'
sh "git checkout #{current_branch}"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s