Skip to content

Instantly share code, notes, and snippets.

@sparr
Created August 8, 2024 12:22
Show Gist options
  • Save sparr/56e74530d8873e814d1362a301675e35 to your computer and use it in GitHub Desktop.
Save sparr/56e74530d8873e814d1362a301675e35 to your computer and use it in GitHub Desktop.
Shell script to copy a file in a git repository while retaining its history
#!/bin/sh
#
# Duplicates a file in git, retaining history for the copy
# This requires four commits that cannot(?) be squased
# Inspired by https://stackoverflow.com/q/3887736
# Deprecated by https://github.com/tj/git-extras/blob/main/bin/git-cp
if [ "$#" -ne 2 ]
then
echo "Usage: $(basename "$0") source destination"
exit 1
fi
MESSAGE="Copy \"$1\" to \"$2\" with history"
# Rename and commit the destination file
git mv "$1" "$2"
git commit -n -m "${MESSAGE} (create new file)"
# Go back, rename and commit a temp copy
REV=$(git rev-parse HEAD)
git reset --hard HEAD^
# TODO(sparr): Handle foo.temp already existing
git mv "$1" "$1.temp"
git commit -n -m "${MESSAGE} (create temp file)"
# Merge the two two commits above, leaving two files
git merge "${REV}"
git commit -a -n -m "${MESSAGE} (merge)"
# Rename the temp file back to the original source file
git mv "$1.temp" "$1"
git commit -n -m "${MESSAGE} (rename temp file)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment