Skip to content

Instantly share code, notes, and snippets.

@singajeet
Created March 16, 2018 18:00
Show Gist options
  • Save singajeet/330953133fb227369c874507e8bdc430 to your computer and use it in GitHub Desktop.
Save singajeet/330953133fb227369c874507e8bdc430 to your computer and use it in GitHub Desktop.
Script to navigate on command prompt using key-folder mapping
#! env zsh
#############################################
# nav.sh -> Helps navigating projects through
# shortcuts
# Author: Ajeet Singh
#############################################
MAP_FILE=~/.nav.map
function _nav_options(){
local -a index_map
while IFS=$ read line; do
f_line=${line//=/:/}
index_map+=$f_line
done < $MAP_FILE
_describe -t index_map 'nav command' index_map
}
function nav_add(){
check=${+_path_map[$1]}
if [ $check -eq 1 ];
then
echo "Key '$1' already exists! Choose some other key"
else
_path_map[$1]=`pwd`
echo "$1=`pwd`" >> $MAP_FILE
echo "New mapping saved: [$1=`pwd`]"
fi
}
function nav_remove(){
check=${+_path_map[$1]}
if [ $check -eq 1 ];
then
unset _path_map
_exp=/^$1=/d
sed -i $_exp $MAP_FILE
nav_prep_map
echo "Key '$1' has been removed!"
else
echo "Key '$1' do not exists!"
fi
}
function nav_prep_map(){
typeset -gA _path_map
while IFS=$':=' read key value;
do
_path_map[$key]=$value
done < $MAP_FILE
}
function nav_usage(){
echo ""
echo "nav [id] [options]"
echo "\t-h => display this usage"
echo "\t<id> => unique id for a path"
echo "\t-l => list id-to-path mappings"
echo "\t-a=[id] => create a new map entry"
echo "\t\t having [id] as key and 'pwd' as value"
echo "\t-r=[id] => removes an entry from map"
echo ""
}
function nav_list_map(){
echo ""
echo "ID-to-Path mappings:"
echo "--------------------"
echo ""
for key in "${(@k)_path_map}";
do
echo "$key=$_path_map[$key]"
done
echo ""
}
function nav(){
nav_prep_map
if [ "$1" != "" ];
then
if [ "$1" = "-h" ];
then
nav_usage
elif [ "$1" = "-l" ];
then
nav_list_map
elif [[ $1 =~ -a= ]]; #check if passed arg is similar to '-a=[id]'
then
local arg
local _new_id
arg=$1
_new_id=${arg[(ws:=:)2]}
nav_add $_new_id
if [ $? -eq 0 ];
then
echo "Completed!"
else
echo "Error: while saving id=$_new_id"
fi
elif [[ $1 =~ -r= ]]; #check if opt is '-r=[id]'
then
local arg
local _id
arg=$1
_id=${arg[(ws:=:)2]}
nav_remove $_id
else
check=${+_path_map[$1]} #check cmd exists in map or not
if [ $check -eq 1 ];
then
cd $_path_map[$1]
else
echo ""
echo "Invalid id or parameter passed!"
echo "Use -l to see all mappings"
echo "Use -h for more info"
echo ""
nav_usage
fi
fi
else
echo ""
echo "No option or id passed as argument!"
echo "Use -h for more info"
echo ""
nav_usage
fi
}
compdef _nav_options nav
nav_prep_map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment