Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active August 11, 2020 07:15
Show Gist options
  • Save mholtzhausen/aa15d6e54205a702b4a9550926c626ab to your computer and use it in GitHub Desktop.
Save mholtzhausen/aa15d6e54205a702b4a9550926c626ab to your computer and use it in GitHub Desktop.
A script to make a function <name> that will autocomplete when finding a /<script> folder upstream
# ...
source ~/scriptfinder ss scripts
#! /bin/bash
FNAME=${1-cmd}
FOLDER=${2-scripts}
FCNAME="_${FNAME}_completion_scriptFinder"
if [[ $_ = $0 ]] ; then echo -e "For this script to work you have to source it eg. \n\t source $_ $@"; exit; fi
findfolder(){
local wd=$(realpath "${1-./}")
local path="${2-scripts}"
while [ "$wd" != "/" ] ; do
sf="$wd/$path"
if [ -d "$sf" ]; then
echo $sf
break;
fi
wd=`dirname "$wd"`
done
}
FDEF=$(cat <<EOF
function ${FCNAME}
{
local len=\$(("\${#COMP_WORDS[@]}"));
if [[ \$len -gt 2 ]]; then return; fi;
owd=\`pwd\`;
sf=\$(findfolder \$(pwd) "$FOLDER");
if [ "\$sf" ]; then
cd \$sf;
COMPREPLY=(\$(compgen -f "\${COMP_WORDS[1]}"));
cd \$owd;
fi;
}
EOF
)
eval $FDEF
FDEF=$(cat <<EOF
function ${FNAME} {
local sfolder=\$(findfolder \$(pwd) "$FOLDER");
local command="\$sfolder/\$@";
echo "Running Script: \$command";
\$command;
}
EOF
)
eval $FDEF
if [[ $# -lt 2 ]]; then
cat <<EOF
This script will create a bash function that will autocomplete to files in
the nearest specified folder to make it easy to execute commands that affect
downstream folders
eg. in folder '/src/project1' you have a folder '/scripts'
every time you want to execute a script from that folder, you have to find
the relative path.
if you find yourself in 'src/project1/data/migrations/2020' and you wish to execute
some script from the scripts folder, it would be
'../../../scripts/somescript'
instead you can run this utility:
'source ./scriptFinder runscript scripts/'
this will create a 'runscript' funtion that when <tab><tab>'ed will list the functions
in the nearest upstream 'scripts/' folder.
if you find yourself in 'src/project1/data/migrations/2020' and you wish to execute
some script from the scripts folder, it would be
- 'runscript <tab><tab>'
- select the script
- execute
SYNTAX: source ./scriptFinder <commandName> <autocompleteFolder>
EOF
else
echo "Created function '$FNAME'"
echo " - Bash Autocomplete will list the scripts in the nearest '$FOLDER' location"
echo " - The function will execute the function found in that location"
export -f $FCNAME
export -f $FNAME
complete -F $FCNAME $FNAME
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment