Skip to content

Instantly share code, notes, and snippets.

@Sanix-Darker
Last active May 29, 2022 01:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Sanix-Darker/e571c1fdc2d0a5ecdb9959fecaa3416a to your computer and use it in GitHub Desktop.
Save Sanix-Darker/e571c1fdc2d0a5ecdb9959fecaa3416a to your computer and use it in GitHub Desktop.
[SHELL] git finder
#!/bin/bash
# by d4rk3r
# A smart way to search for a code
# inside your git history whatever the branch you're
# -- Setup :
# -- After getting the bash script
# chmod +x /path/to/gf.sh
# -- to add the execute right to the script
# -- You can add it to your .bashrc env
# gf s 'pattern' -- to search for some code
# -- then after copy the line of the commit,
# gf o commit_id:file_name:line....
# -- gf will switch to that commit and open the line where the code is,
# -- after quitting, gf will restore your repo to the precedent branch where you were working
_git_search(){
# a smart git command to get commit, file and line where
# the string is available
git rev-list --all | (
while read revision; do
git grep -n -F ${1} $revision
done
) > ${HOME}/.gf-out
}
_search(){
echo "[-] Searching for '${1}' in this repo..."
sleep 2
# We less in the list of results
_git_search "${1}"
less ${HOME}/.gf-out
}
_open_code(){
# getting your current branch
branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
# A smart split from the incomming $1 parameter
arr=($(echo "$1" | tr ':' '\n'))
commit=${arr[0]}
file=${arr[1]}
line=${arr[2]}
# some verbose
echo "[-] Moving on commit : $commit"
sleep 1
echo "[-] Moving on file : $file"
sleep 1
echo "[-] Moving on line : $line"
sleep 1
# A checkout on the commit then a less on the line of the file
git checkout "$commit"
less +"$line" "$file"
sleep 2
echo "\n[-] Rolling back to your precedent branch..."
# comming back to reality
git checkout "$branch"
}
_help_commands(){
echo "[-] gf help center:"
echo "[-] gf s 'search-kwy-word'"
echo "[-] gf o 'commit_id:file_name:line'"
}
main(){
echo "[-] gf started..."
if [ "$1" == "search" ] || [ "$1" == "s" ]; then
_search $2
elif [ "$1" == "open" ] || [ "$1" == "o" ]; then
_open_code $2
else
echo "[x] Error: Bad parameter provided..."
_help_commands
fi
}
main $1 $2
@Sanix-Darker
Copy link
Author

Sanix-Darker commented Jan 12, 2022

Search for a "code" inside a git project history whatever the branch and the time.

# s or search
gf s 'function name or any word you have in mind'

# To open the file at that line : 
# o or open
gf o 'commit_id:file_name:line'

@evandrix
Copy link

evandrix commented Jan 12, 2022

@evandrix
Copy link

@Sanix-Darker
Copy link
Author

Sanix-Darker commented Jan 12, 2022

Thanks @evandrix !
Updated !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment