template-bash-command/cmd

353 lines
8.5 KiB
Plaintext
Raw Normal View History

2021-08-15 15:56:56 -05:00
#!/bin/bash
2021-08-06 12:48:11 -05:00
# shellcheck disable=SC2016
set -e
2021-08-15 15:56:56 -05:00
# export PATH="/bin:/usr/bin:/usr/local/bin" # safer, if you can
2021-08-06 12:48:11 -05:00
(( BASH_VERSINFO[0] < 4 )) && echo "Bash 4+ required." && exit 1
: "${PAGER:=more}"
: "${EDITOR:=vi}"
: "${HELP_BROWSER:=}"
: "${EXE:="${0##*/}"}"
: "${XDG_CONFIG_HOME:="$HOME/.config"}"
2021-08-06 12:48:11 -05:00
declare -A HELP
declare -A CONFIG
2021-08-06 12:48:11 -05:00
HELP[main]='
2021-08-10 17:47:07 -05:00
# Bash Template Command
*This `README.md` is autogenerated.*
This is a GitHub template repo that will be copied instead of forked to
create a new Bash command with a command something like this:
```
gh repo create rwxrob/mycmd -p rwxrob/template-bash-command
```
This `cmd` inside can then be renamed and finished.
2021-08-10 17:47:07 -05:00
Obviously, not all of this is needed for many Bash scripts, but anything
with more than two subcommands will benefit from the builtin tab
completion, embedded Markdown help documentation support, and included
functions (`usage`, `_filter`, `_buffer`, `_have`, etc.)
## Naming Conventions
* Name repos containing single bash commands with `cmd-`
* Name template repos beginning with `template-`
* Start command functions with `command_` to be completed
* Start command functions with `command__` to not be completed
## Dependencies
Required:
* Bash 4+
Optional:
* `pandoc` - for rich help docs
* `jq` - for `json` and anything that uses it
2021-08-10 17:47:07 -05:00
## Justification
Bash is the dominate shell scripting language and the official default
Linux interactive shell, which reduces cognitive overhead; every command
line *is* a line of code that could be put into script as is. Bash
scripts are at the core of cloud, containers, and Kubernetes. Bash 4+
with its associative array support, powerful regular expressions, and
multiple ways of feeding data to loops easily covers the needs
previously requiring Python and Perl scripts. Bash scripts are also much
more powerful, safer, flexible, and performant than POSIX shell or Zsh.
2021-08-10 13:18:33 -05:00
2021-08-10 18:37:51 -05:00
## Guidelines
2021-08-06 12:48:11 -05:00
2021-08-10 18:37:51 -05:00
* Write GitHub Flavored Markdown only
* Use present tense ("outputs" over "will output")
* Prefer term "output" and "display" over ~~print~~
2021-08-10 18:37:51 -05:00
* Follow the [naming conventions](#naming-conventions)
2021-08-15 15:56:56 -05:00
* Use the official bash path: `#!/bin/bash`
* Use of `#!/usr/bin/bash` is outdated
2021-08-10 17:47:07 -05:00
* Using `#!/usr/bin/env bash` introduces unnecessary risk
2021-08-10 18:37:51 -05:00
* Explicitly export `PATH` in script when possible
2021-08-10 17:47:07 -05:00
* Always check script with [`shellcheck`] before releasing
* Always use `bc` for *any* floating point math
[`shellcheck`]: <https://www.shellcheck.net>
## Legal
Copyright 2021 Rob Muhlestein <rob@rwx.gg>
Released under Apache-2.0 License
Please mention <https://rwxrob.tv>'
2021-08-10 17:47:07 -05:00
HELP[foo]='Foos things.'
2021-08-06 12:48:11 -05:00
command_foo() {
2021-08-06 12:48:11 -05:00
_filter "$@" && return $?
echo "would foo: $*"
}
HELP[bar]='
```
'"$EXE"' bar
```
Bar the things.'
2021-08-06 12:48:11 -05:00
command_bar() {
2021-08-09 18:01:36 -05:00
_buffer "$@" && return $?
2021-08-06 12:48:11 -05:00
echo "would bar: $*"
}
HELP[json]='
## Convert to JSON String
```
'"$EXE"' json STRING
'"$EXE"' json <<< STRING
'"$EXE"' json < FILE
'"$EXE"' json < <(COMMAND)
```
Converts input into JSON string using `jq` (if found) containing only
escaped (`\\n`) line returns.'
command_json() { _jsonstr "$@"; }
command__hidden() {
2021-08-06 12:48:11 -05:00
_filter "$@" && return $?
echo "would run _hidden: $*"
}
# ------------------ builtin commands and functions ------------------
2021-08-10 18:02:36 -05:00
# (https://github.com/rwxrob/template-bash-command)
HELP[usage]='Displays a summary of usage.'
2021-08-06 12:48:11 -05:00
command_usage() {
2021-08-06 12:48:11 -05:00
local -a cmds
for c in "${COMMANDS[@]}"; do
[[ ${c:0:1} =~ _ ]] && continue
2021-08-18 19:54:40 -05:00
cmds+=("$c")
2021-08-06 12:48:11 -05:00
done
2021-08-18 19:54:40 -05:00
local IFS='|'
printf "usage: %s (%s)\n" "$EXE" "${cmds[*]}"
2021-08-06 12:48:11 -05:00
}
HELP[help]='
2021-08-10 17:47:07 -05:00
```
'"$EXE"' help [COMMAND]
2021-08-10 17:47:07 -05:00
```
Displays specific help information. If no argument is passed displays
general help information (main). Otherwise, the documentation for the
specific argument keyword is displayed, which usually corresponds to
a COMMAND name (but not necessarily). All documentation is written in
2021-08-10 17:47:07 -05:00
GitHub Flavored Markdown and will displayed as a web page if `pandoc`
and `$HELP_BROWSER` are detected, otherwise, just the Markdown is sent
to `$PAGER` (default: more).
2021-08-10 13:18:33 -05:00
2021-08-10 17:47:07 -05:00
Also see `readme` and `usage` commands.
'
2021-08-06 12:48:11 -05:00
command_help() {
2021-08-18 19:54:40 -05:00
local name="${1:-main}" title body
2021-08-10 20:59:02 -05:00
title=$(_help_title "$name") || true
2021-08-10 13:18:33 -05:00
if [[ -z "$title" ]]; then
body="${HELP[$name]}"
2021-08-10 13:18:33 -05:00
title="$EXE $name"
[[ $name = main ]] && title="$EXE"
else
body="${HELP[$name]}"
2021-08-10 13:18:33 -05:00
body=${body#*$title}
fi
2021-08-06 12:48:11 -05:00
local file="/tmp/help-$EXE-$name.html"
if _have pandoc ; then
if _have "$HELP_BROWSER" && [[ -t 1 ]] ;then
pandoc -f gfm -s --metadata title="$title" \
2021-08-10 13:18:33 -05:00
-o "$file" <<< "$body"
2021-08-06 12:48:11 -05:00
[[ -z "$2" ]] && cd /tmp && exec "$HELP_BROWSER" "$file"
return 0
fi
pandoc -f gfm -s --metadata title="$title" \
2021-08-10 13:18:33 -05:00
-t plain <<< "$body" | "$PAGER"
2021-08-06 12:48:11 -05:00
return 0
fi
2021-08-10 13:18:33 -05:00
echo -e "$title\n\n$body" | "$PAGER"
2021-08-06 12:48:11 -05:00
}
HELP[readme]='
## Generate `README.md` File
2021-08-10 17:47:07 -05:00
```
'"$EXE"' readme > README.md
2021-08-10 17:47:07 -05:00
```
The `readme` command will output the embedded help documentation in raw
GitHub Flavored Markdown suitable for use as a `README.md` file on
GitHub or similar hosting service.'
2021-08-10 17:47:07 -05:00
command_readme() {
_trim "${HELP[main]}"
echo
2021-08-10 17:47:07 -05:00
while IFS= read -r name; do
[[ $name = main ]] && continue
body=$(_trim "${HELP[$name]}")
[[ $body =~ ^\# ]] || body="## The \`$name\` Command"$'\n\n'$body
printf "%s\n\n" "$body"
done < <(printf "%s\n" "${!HELP[@]}" | LC_COLLATE=C sort)
echo -e "----\n\n*Autogenerated $(date)*\n"
2021-08-10 17:47:07 -05:00
}
HELP[config]='
```
'"$EXE"' config
'"$EXE"' config KEY
'"$EXE"' config KEY VALUE
```
The `config` command is for reading, writing, and displaying standard
open desktop configurations properties.
### Arguments
With no arguments outputs all the currently cached configuration
settings.
With a single KEY argument fetches the value for that key and outputs
it.
With more than one argument the remaining arguments after the KEY will
be combined into the VALUE and written to the `config` file in the
standard configuration home location (Search for `XDG_CONFIG_HOME` for
more information).
### Configuration `config` File Format
The file (which is always named `config` and almost always located at
`~/.config/'"$EXE"'/config`) uses the simplest possible format to
facilitate standard UNIX parsing and filtering with any number of
existing tools (and no `jq` dependency).
* One KEY=VALUE per line
* KEYs may be anything but the equal sign (`=`)
* VALUEs may be anything but line returns must be escaped
Note that this is *not* the same as Java properties and other similar
format. It is designed for ultimate simplicity, efficiency, and
portability.'
command_config() {
case $# in
0) _dump_config ;;
1) printf "${CONFIG[$1]}" ;;
*) _set_config "$@" ;;
esac
}
2021-08-10 13:18:33 -05:00
_help_title() {
_filter "$@" && return $?;
local name="$1"
while IFS= read -r line; do
[[ $line =~ ^[:space]*$ ]] && continue
[[ $line =~ ^#\ (.+) ]] && echo "${BASH_REMATCH[1]}" && return 0
return 1
done <<< "${HELP[$name]}"
}
_set_config() {
local key="$1"; shift; local val="$*"
val="${val//$'\n'/\\n}"
CONFIG["$key"]="$val"
_write_config
}
_read_config() {
local path="$XDG_CONFIG_HOME/$EXE/config"
while IFS= read -r line; do
[[ $line =~ ^([^=]+)=(.+)$ ]] || continue
CONFIG["${BASH_REMATCH[1]}"]="${BASH_REMATCH[2]}"
done < "$path"
}
_write_config() {
local path="$XDG_CONFIG_HOME/$EXE/config"
mkdir -p "${path%/config}"
_dump_config > "$path"
}
_dump_config() {
paste -d=\
<(printf "%s\n" "${!CONFIG[@]}") \
<(printf "%s\n" "${CONFIG[@]}")
2021-08-10 13:18:33 -05:00
}
2021-08-06 12:48:11 -05:00
2021-08-10 17:47:07 -05:00
_trim() {
local it="${1#"${1%%[![:space:]]*}"}"
echo -e "${it%"${it##*[![:space:]]}"}"
}
_jsonstr() {
_buffer "$@" && return $?
jq -MRsc <<< "$1"
}
2021-08-06 12:48:11 -05:00
_have(){ type "$1" &>/dev/null; }
_filter(){
[[ -n "$1" ]] && return 1
while IFS= read -ra args; do
"${FUNCNAME[1]}" "${args[@]}"
done
}
2021-08-09 18:01:36 -05:00
_buffer() {
2021-08-06 12:48:11 -05:00
[[ -n "$1" ]] && return 1
"${FUNCNAME[1]}" "$(</dev/stdin)"
}
# --------------------- completion and delegation --------------------
# (better than . <(foo bloated_completion) in .bashrc)
2021-08-06 12:48:11 -05:00
while IFS= read -r line; do
[[ $line =~ ^declare\ -f\ command_ ]] || continue
COMMANDS+=( "${line##declare -f command_}" )
2021-08-06 12:48:11 -05:00
done < <(declare -F)
2021-08-18 19:54:40 -05:00
mapfile -t COMMANDS < \
<(LC_COLLATE=C sort < <(printf "%s\n" "${COMMANDS[@]}"))
2021-08-06 12:48:11 -05:00
if [[ -n $COMP_LINE ]]; then
line=${COMP_LINE#* }
for c in "${COMMANDS[@]}"; do
[[ ${c:0:${#line}} == "${line,,}" && ${c:0:1} != _ ]] && echo "$c"
done
exit
fi
for c in "${COMMANDS[@]}"; do
if [[ $c == "$EXE" ]]; then
"command_$EXE" "$@"
2021-08-06 12:48:11 -05:00
exit $?
fi
done
_read_config
2021-08-06 12:48:11 -05:00
if [[ -n "$1" ]]; then
declare cmd="$1"; shift
for c in "${COMMANDS[@]}"; do
if [[ $c == "$cmd" ]]; then
"command_$cmd" "$@"
2021-08-06 12:48:11 -05:00
exit $?
fi
done
fi
command_usage "$@"