Skip to content

Instantly share code, notes, and snippets.

@mbenford
Created July 15, 2019 17:51
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 mbenford/eff155219ea46042408315d2ccdf5736 to your computer and use it in GitHub Desktop.
Save mbenford/eff155219ea46042408315d2ccdf5736 to your computer and use it in GitHub Desktop.
Git custom command that moves all commits between @{u} and HEAD into a new branch and deletes them from the current branch
#!/bin/bash
# Moves all commits between @{u} and HEAD into a new branch
# and deletes them from the current branch.
#
# Copyright (c) 2019 Michael Benford <michael@michaelbenford.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
set -e
error() {
echo "error: $1" 1>&2
exit 1
}
new_branch=$1
# check if a branch name is provided
if [ -z "$new_branch" ]; then
error "missing branch name"
fi
# check if the provided branch already exists
if git rev-parse --verify --quiet $new_branch &>/dev/null; then
error "a branch named '$new_branch' already exists"
fi
# check if the HEAD is detached
if ! git symbolic-ref HEAD &>/dev/null; then
error "HEAD is detached"
fi
# check if there is any unstaged changes
if ! git diff-index HEAD &>/dev/null; then
error "unstaged local changes"
fi
# check if there is an upstream available
if ! git rev-parse @{u} &>/dev/null; then
error "no upstream configured for the current branch"
fi
current_branch=$(git symbolic-ref --short HEAD)
commits=$(git rev-list --count @{u}..HEAD)
git branch $new_branch >/dev/null
git reset --hard @{u} >/dev/null
echo "$commits commits cut from $current_branch"
git checkout $new_branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment