Last active
June 3, 2025 15:17
-
-
Save kristopolous/13f375f8a0fe4674adfac03ed48f1b5c to your computer and use it in GitHub Desktop.
This allows you to do git cp sha1:path destination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# To use do something like add this to your .gitconfig | |
# [alias] | |
# cp = "!$HOME/.local/bin/git-cp.sh" | |
# | |
# Then you can do things like | |
# $ git cp sha1:/path/to/old/file /tmp | |
set -e | |
usage() { | |
echo "Usage: git-cp.sh <sha1>:/path/to/file [destination]" | |
echo "" | |
echo "Copy a file from a specific commit to your current working directory" | |
echo "or to a specified destination." | |
echo "" | |
echo "Arguments:" | |
echo " <sha1>:/path/to/file Source file reference (commit SHA1 and file path)" | |
echo " [destination] Optional destination (file or directory)" | |
exit 1 | |
} | |
# Check if at least one argument is provided | |
if [ $# -lt 1 ]; then | |
usage | |
fi | |
# Parse the source argument | |
source="$1" | |
# Check if the source follows the expected pattern | |
if [[ ! "$source" =~ ^([a-f0-9]+):(.*) ]]; then | |
echo "Error: Invalid source format. Expected <sha1>:/path/to/file" | |
usage | |
fi | |
# Extract the commit SHA1 and file path | |
commit="${BASH_REMATCH[1]}" | |
source_path="${BASH_REMATCH[2]}" | |
# Validate that the commit exists | |
if ! git rev-parse --verify "$commit^{commit}" >/dev/null 2>&1; then | |
echo "Error: Commit '$commit' not found" | |
exit 1 | |
fi | |
# Determine the destination | |
if [ $# -ge 2 ]; then | |
destination="$2" | |
else | |
# If no destination is provided, use the basename of the source | |
destination=$(basename "$source_path") | |
fi | |
# Check if destination is a directory | |
if [ -d "$destination" ]; then | |
# If destination is a directory, append the basename of the source | |
destination="${destination%/}/$(basename "$source_path")" | |
fi | |
# Extract the file from the specified commit | |
git show "$commit:$source_path" > "$destination" | |
echo "File copied successfully" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment