git checkout --orphan NEWBRANCH <commitid>
git commit -a
git checkout --orphan <new_branch> [<start_point>]
Create a new orphan branch, named <new_branch>
, started from
<start_point>
and switch to it. The first commit made on this new
branch will have no parents and it will be the root of a new
history totally disconnected from all the other branches and
commits.
The index and the working tree are adjusted as if you had
previously run "git checkout <start_point>
". This allows you to
start a new history that records a set of paths similar to
<start_point>
by easily running "git commit -a
" to make the root
commit.
EDIT
The following script will do the job in a single shot (note that in order to eliminate possible causes for failure, it will need to clean the working tree from untracked files, but it will ask for permission of doing so):
copy_as_root_commit
#!/bin/sh
myname="$(basename "$0")"
if [ $# -ne 2 ]
then
echo 1>&2 "Usage: $myname <commitid> <new_branch>"
exit 1
fi
commitid=$(git rev-parse "$1")
new_branch="$2"
set -e
untracked_stuff="$(git clean -dxf -n)"
if [ "$untracked_stuff" ]
then
echo "$myname needs to clean the working tree before proceeding:"
printf "%s\n" "$untracked_stuff"
while read -p "Remove above files? (y/n) " answer
do
case "$answer" in
[yY]) break ;;
[nN]) exit 1 ;;
esac
done
fi
git clean -dxf \
&& git checkout --orphan "$new_branch" "$commitid" \
&& git commit -m "Initial commit (a copy of $commitid)" \
&& echo "Successfully created new root branch '$new_branch'" \
|| echo "Failed to create new root branch '$new_branch'"
Usage:
copy_as_root_commit <commitid> <new_branch>
Examples:
copy_as_root_commit master~4 NEW_ROOT
copy_as_root_commit ce04aa6 NEWBRANCH