zsh-goto/goto.plugin.zsh

126 lines
2.4 KiB
Bash

#!/usr/bin/zsh
#
# goto.zsh, a tool for bookmarking directories
function _awk {
if command -v gawk &>/dev/null; then
gawk "${@}"
elif command -v awk &>/dev/null; then
awk "${@}"
else
echo "Unable to find an awk!" >&2; return 1
fi
}
function _sed {
# MacOS support - prefer GNU sed eg. from Homebrew to 'sed'
if command -v gsed &>/dev/null; then
gsed "$@"
elif command -v sed &>/dev/null; then
sed "$@"
else
echo "Unable to find a sed!" >&2; return 1
fi
}
function _goto_file {
echo "${GOTO_FILE:-${HOME}/.labels.tsv}"
}
####################################################################################################
function goto {
: "${1:=--help}"
case "$1" in
-h|--help|help)
cat <<EOF
Usage:
$ goto [label]
Change directory to a labeled location.
See label for label control operations
EOF
;;
*)
cd "$(label get "$1")"
;;
esac
}
function _goto {
for label in $(label ls)
do
compadd "$@" "${label}"
done
}
compdef _goto goto
####################################################################################################
function label {
: "${1:=--help}"
case "$1" in
-h|--help|help)
cat <<EOF
Usage:
$ label [add | get | rm | ls]
Set, list or manipulate configured labeles.
Note: the words 'help' and 'ls' among others are reserved, and cannot be labeled.
EOF
;;
add)
label rm "$2"
_sed -i '' -e '$a\' `_goto_file` # Fix potentially missing last newline
printf '%s %s\n' "${1}" $(echo "$2" | _sed "s^${HOME}^~^g") >> `_goto_file`
;;
get)
realpath "$(_awk "/^$2\s/ {print \$2;exit}" `_goto_file` | _sed "s|^~|$HOME|")"
;;
rm)
_sed -i "^$2^d" `_goto_file`
;;
ls)
_awk '{print $1;}' `_goto_file`
;;
*)
echo "Unknown command: $@" >&2
return 1
;;
esac
}
_label() {
local line state
_arguments -C \
"1: :->cmds" \
"*::arg:->args"
case "$state" in
cmds)
_values "label command" \
"add[Create or overwrite a label.]" \
"ls[List existing labels.]" \
"get[Fetch the location of a label.]" \
"rm[Delete a label.]"
;;
args)
case "$line[1]" in
rm|get)
_labels
;;
esac
;;
esac
}
compdef _label label