Skip to content

Instantly share code, notes, and snippets.

@camiloaa
Last active May 5, 2024 17:33
Show Gist options
  • Save camiloaa/fe072d569a8f71ab344e668dce9abfbe to your computer and use it in GitHub Desktop.
Save camiloaa/fe072d569a8f71ab344e668dce9abfbe to your computer and use it in GitHub Desktop.
Create a copy of an existing file with full history in just two commits
#!/bin/sh
# Create a copy of an existing file with full history in just two commits
# All other scripts I found used at least three commits, often four
if [ ! $# -eq 2 ]; then
echo "Usage: git split <orig> <copy>"
echo ""
echo "Copy file <orig> to <copy> keeping both versions with full history"
exit 1
fi
BASE_COMMIT=`git rev-parse --short HEAD`
BASE_BRANCH=`git rev-parse --abbrev-ref HEAD`
# Create the new file
git mv $1 $2
git commit -m "Create $2"
SPLIT_COMMIT=`git rev-parse --short HEAD`
echo "Created $2 in $SPLIT_COMMIT"
# Return to the original commit
git reset --hard $BASE_COMMIT
# Force a merge commit
git merge --no-ff $SPLIT_COMMIT -m "Duplicate $1 to $2"
# Restore the original file
echo "Duplicate $1 to $2"
git checkout $BASE_COMMIT -- $1
git add $1
git commit --amend --reuse-message=HEAD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment