#!/bin/bash # NOTE(crutcher): # This is a work in progress. Don't pay too mutch attention to it. It has # the basic functionality that I want, but it has bad naming conventions, # relies too much on sed, and has some issues with how aliases are stored. # Components of a subcommand dispatcher's subcommands: # * function # * aliases # * shorthelp # * usage # * help function cmd_aliases() { local aliases=${1}_aliases; echo ${!aliases}; } function define_aliases() { eval "${1}_aliases='$2'"; for name in $2; do if [ -z "$(alias2cmd $name)" ]; then eval alias2cmd__${name}=$1; else echo Error: alias \"$name\" already maps to \"$(alias2cmd $name)\" exit 1; fi done local primary_alias=$(echo $2 | sed 's/ .*//'); primary_alias_list="$primary_alias_list $primary_alias" } function alias2cmd() { local var=alias2cmd__${1}; echo ${!var}; } function dispatch() { local name=$1; shift; args="$@"; cmd=$(alias2cmd $name); if [ ! -z "$cmd" ]; then $cmd "$@"; else helpCmd; fi } function print_cmd_blurb() { local cmd=$1; local aliases=$(cmd_aliases $cmd); local primary_alias=$(echo $aliases | sed 's/ .*//'); local other_aliases=$(echo $aliases | sed 's/^[^ ]\+ *//'); echo -n $primary_alias if [ ! -z "$other_aliases" ] ; then echo -n ' ('$(echo $other_aliases | sed 's/ \+/, /g')')'; fi local shorthelp=${cmd}_shorthelp; echo ' -' ${!shorthelp} } function print_cmd_usage() { local cmd=$1; local cmd_usage=${cmd}_usage; if [ ! -z "${!cmd_usage}" ] ; then echo 'usage:' ${!cmd_usage} fi } function print_available_cmds() { echo 'Available Commands:'; for name in $primary_alias_list; do echo -n ' '; print_cmd_blurb $(alias2cmd $name); done } define_aliases helpCmd "help" helpCmd_usage="help [COMMAND]" helpCmd_shorthelp="display help" function helpCmd() { local cmd=$(alias2cmd $1); if [ -z "$cmd" ]; then if [ ! -z "$1" ]; then echo Error: Unknown Command \"$1\"; fi HELP_PREAMBLE echo -ne '\nHelp : ' print_available_cmds; elif [ "$cmd" == helpCmd ]; then print_cmd_blurb $cmd; print_cmd_usage $cmd; cat <