zsh-goto/goto.plugin.zsh

127 lines
2.4 KiB
Bash
Raw Normal View History

#!/usr/bin/zsh
#
# goto.zsh, a tool for bookmarking directories
2016-09-30 17:19:41 +00:00
2017-04-18 00:29:17 +00:00
function _awk {
2022-08-11 05:32:51 +00:00
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
}
2018-01-16 20:33:54 +00:00
function _goto_file {
echo "${GOTO_FILE:-${HOME}/.labels.tsv}"
2022-08-11 05:32:51 +00:00
}
2016-09-30 17:19:41 +00:00
2022-08-11 05:32:51 +00:00
####################################################################################################
2016-09-30 17:19:41 +00:00
function goto {
2022-08-11 05:32:51 +00:00
: "${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
}
2018-03-04 03:19:27 +00:00
function _goto {
2022-08-11 05:32:51 +00:00
for label in $(label ls)
2018-03-04 03:19:27 +00:00
do
2022-08-11 05:32:51 +00:00
compadd "$@" "${label}"
2018-03-04 03:19:27 +00:00
done
2022-08-11 05:32:51 +00:00
}
2018-03-04 03:19:27 +00:00
compdef _goto goto
2022-08-11 05:32:51 +00:00
####################################################################################################
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