Skip to content

Instantly share code, notes, and snippets.

@jeroenvisser101
Last active March 4, 2016 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenvisser101/49ff62649fd3a57ffbda to your computer and use it in GitHub Desktop.
Save jeroenvisser101/49ff62649fd3a57ffbda to your computer and use it in GitHub Desktop.
Script that moves a specified number of commits into a branch (when accidentally committed to master)
#!/usr/bin/env ruby
# Get values from
branch_name = ARGV[0]
commit_count = ARGV[1].to_i > 0 ? ARGV[1].to_i : 1
# If no branch is given, or it is a question for help, show usage
if branch_name.nil? or ['-h', '--help'].include? branch_name
puts <<-USAGE
usage: git move-to-branch <branch name> [commits]
branch name The branch name to move the commit(s) to
[commit count] The amount of commits to move to the branch,
defaults to 1.
USAGE
exit
end
# Put working copy changes in temporarly commit (stashing without touching the user's stashes)
`git add -A; git rm $(git ls-files --deleted) 2> /dev/null; OVERCOMMIT_DISABLE=1 git commit -m "--wip--"`
# Add branch to current commit
`git branch #{branch_name}`
# Remove last X commits from current branch
`git reset --hard HEAD~#{commit_count}`
# Checkout previously created branch
`git checkout #{branch_name}`
# Remove the stashed changes (which is the last commit) and restore those files in the working copy
`git reset HEAD~1`
# Let the user know we succeeded
puts "Successfully moved #{commit_count} commits over to branch '#{branch_name}'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment