Skip to content

Instantly share code, notes, and snippets.

@digitalmoksha
Created August 29, 2016 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalmoksha/03e6526d4309a16b2c092c944c3eba8c to your computer and use it in GitHub Desktop.
Save digitalmoksha/03e6526d4309a16b2c092c944c3eba8c to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Merge multiple git repositories into a new one.
# Users `git filter-branch` to rewrite paths, so that `git log` works seamlessly
# Built from the script at http://dominik.honnef.co/posts/2016/04/merging-git-repositories/
#------------------------------------------------------------------------------
new_repo = '/tmp/new_repo'
base = 'git@github.com:customer'
dest_branch = 'master'
projects = [
{repo: 'project_one', new_directory: 'one', branch: 'stable'},
{repo: 'project_two', new_directory: 'two', branch: 'stable'}
]
`mkdir -p "#{new_repo}"`
Dir.chdir(new_repo) do
puts "--> creating new repository at #{new_repo} and switching to branch '#{dest_branch}'"
`git init`
`git commit --allow-empty -m "Initial commit"`
if dest_branch != 'master'
`git checkout -b #{dest_branch}`
end
projects.each do |prj|
puts "\n--> Fetching '#{base}/#{prj[:repo]}' into '#{prj[:new_directory]}'"
`git remote add "#{prj[:new_directory]}" "#{base}/#{prj[:repo]}"`
system("git fetch '#{prj[:new_directory]}'")
puts "\n--> Rewriting history to reference '#{prj[:new_directory]}'"
system("git filter-branch -f --index-filter \
'git ls-files -s | sed \"s%\\\t\\\"*%&'\"#{prj[:new_directory]}\"'/%\" | \
GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info && \
mv \"$GIT_INDEX_FILE.new\" \"$GIT_INDEX_FILE\"' \"#{prj[:new_directory]}/#{prj[:branch]}\"")
system("git merge -m 'Merge #{prj[:repo]}' '#{prj[:new_directory]}/#{prj[:branch]}'")
`git remote rm "#{prj[:new_directory]}"`
puts "\n--> Merged branch '#{prj[:branch]}' into destination branch '#{dest_branch}'"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment