Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/local/bin/bash
#nl2spc() {
# sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'
#}
#set -x
fn-args() {
local argline=$(type $1 | grep declare | grep -v "declare desc" | head -1)
echo -e "${argline// /"\n"}" | awk -F= '/=/{print "<"$1">"}' | tr "\n" " "
}
fn-desc() {
eval "$(type $1 | grep desc | head -1)"; echo $desc
}
fn-info() {
declare fn="$1" showsource="$2"
echo "$fn $(fn-args $fn)"
echo " $(fn-desc $fn)"
echo
if [[ "$showsource" ]]; then
type $fn | tail -n +2
echo
fi
}
declare -A CMDS
cmd-list() {
declare desc="Lists available commands"
declare ns="$1"
cmd-list-keys "$ns" | sed "s/$ns://"
}
cmd-list-keys() {
declare ns="$1"
for k in "${!CMDS[@]}"; do
echo "$k"
done | grep "^$ns:" | sort
}
cmd-list-ns() {
for k in "${!CMDS[@]}"; do
echo "$k"
done | grep -v : | sort
}
cmd-export() {
declare desc="Exports a function as a command"
declare fn="$1" as="${2:-$1}"
local ns=""
for n in $(cmd-list-ns); do
echo "$fn" | grep "^$n-" &> /dev/null && ns="$n"
done
CMDS["$ns:${as/$ns-/}"]="$fn"
}
cmd-export-ns() {
declare ns="$1" desc="$2"
eval "$1() {
declare desc=\"$desc\"
cmd-ns $1 \$@;
}"
cmd-export "$1"
CMDS["$1"]="$1"
}
cmd-ns() {
local ns="$1"; shift
local cmd="$1"; shift || true
if cmd-list "$ns" | grep ^$cmd\$ &> /dev/null; then
${CMDS["$ns:$cmd"]} $@
else
if [[ "$cmd" ]]; then
echo "No such command: $cmd"
elif [[ "$ns" ]]; then
echo "$(fn-desc "$ns")"
fi
echo
echo "Available commands:"
for cmd in $(cmd-list "$ns"); do
printf " %-18s %s\n" "$cmd" "$(fn-desc "${CMDS["$ns:$cmd"]}")"
done
echo
exit 2
fi
}
cmd-help() {
declare desc="Shows help information for a command"
declare args="$@"
if [[ "$args" ]]; then
for cmd; do true; done # last arg
local ns="${args/%$cmd/}"; ns="${ns/% /}"; ns="${ns/ /-}"
local fn="${CMDS["$ns:$cmd"]}"
fn-info "$fn" 1
else
echo
for cmd in $(cmd-list); do
cmd-help "$cmd"
done
fi
}
cmd-export cmd-help help
cmd-export-ns sys "Internal system commands"
sys-shell() {
declare desc="Enters interactive shell"
PS1="prog # " bash --init-file prog
}
cmd-export sys-shell
sys-run() {
declare desc="Run arbitrary function directly"
declare fn="$1" args="$2"
$fn $args
}
cmd-export sys-run
hello() {
declare desc="Displays a friendly hello"
declare firstname="$1" lastname="$2"
echo "Hello, $firstname $lastname."
}
cmd-export hello
cmd-export-ns foobar "Foobar commands"
foobar-action() {
echo "Foobar"
}
cmd-export foobar-action
foobar-action2() {
echo "Foobar2"
}
cmd-export foobar-action2
cmd-export-ns foobar-ns "sub namespace"
foobar-ns-f1() {
echo "f1"
}
cmd-export foobar-ns-f1
[[ "$0" == "$BASH_SOURCE" ]] && cmd-ns "" $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment