Skip to content

Instantly share code, notes, and snippets.

@reececomo
Created November 11, 2024 09:01
Show Gist options
  • Select an option

  • Save reececomo/909478c61237fee10790f78282c874f0 to your computer and use it in GitHub Desktop.

Select an option

Save reececomo/909478c61237fee10790f78282c874f0 to your computer and use it in GitHub Desktop.
zsh command to replace a file with the one from the default branch (or some other branch)
pluck() {
INFO="Description: Replace a single file's contents with the value from remote branch"
local filename branch matches file_choice
filename=$1
pluckbranch=${2:-origin/$(git symbolic-ref refs/remotes/origin/HEAD | sed 's|^refs/remotes/origin/||' 2> /dev/null)}
currentbranch=$(git branch --show-current 2> /dev/null)
# Define color codes
RED='\033[31m'
YELLOW='\033[33m'
GREEN='\033[32m'
RESET='\033[0m'
if [[ -z $filename ]]; then
echo -e "${RED}give a filename or search pattern\n${RESET}${INFO}\nUsage: pluck [filename] [branch?=$pluckbranch]${RESET}"
return 1
fi
# Search for exact match first
exact_matches=($(git ls-tree -r --name-only $currentbranch | grep -x "$filename"))
matches=($(git ls-tree -r --name-only $currentbranch | grep -i "$filename"))
if [[ ${#exact_matches[@]} -eq 0 ]]; then
if [[ ${#matches[@]} -eq 0 ]]; then
echo -e "${RED}No files containing '$filename' found in $currentbranch.${RESET}"
return 1
fi
fi
if [[ ${#exact_matches[@]} -eq 1 ]]; then
file_choice=${exact_matches[1]}
elif [[ ${#matches[@]} -eq 1 ]]; then
echo -e "${GREEN}Found: \"${matches}\". Confirm pluck? (hit return to continue)${RESET}"
read -r response
if [[ -z $response || $response =~ ^[Yy](es)?$ ]]; then
file_choice=${matches[1]}
else
echo "${RED}aborted${RESET}"
return 1
fi
else
echo -e "\n${YELLOW}Multiple matching files found. Which one would you like to pluck?\n${RESET}"
select file_choice in "${matches[@]}"; do
[[ -n $file_choice ]] && break
done
fi
if [[ -n $file_choice ]]; then
echo -e "Plucking \"$file_choice\" from $pluckbranch..."
git show "$pluckbranch:$file_choice" > "$file_choice" && echo -e "${GREEN}$file_choice plucked from $pluckbranch\n${RESET}"
else
echo -e "${RED}No file selected.${RESET}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment