diff options
| author | EuAndreh <eu@euandre.org> | 2022-08-12 18:50:28 -0300 |
|---|---|---|
| committer | EuAndreh <eu@euandre.org> | 2022-08-12 18:50:28 -0300 |
| commit | a67170c98eca90b34e4069db048dbd157c2d2156 (patch) | |
| tree | 2a6a07c07e0d944db41f2272aecfbf16da06d9f2 /bin/assert-arg | |
| parent | bin/clamp: Replace ad-hoc `assert_arg()` with `assert-arg` (diff) | |
| download | dotfiles-a67170c98eca90b34e4069db048dbd157c2d2156.tar.gz dotfiles-a67170c98eca90b34e4069db048dbd157c2d2156.tar.xz | |
bin/assert-arg: Add helper utility
Diffstat (limited to 'bin/assert-arg')
| -rwxr-xr-x | bin/assert-arg | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/bin/assert-arg b/bin/assert-arg new file mode 100755 index 0000000..d7bc8f4 --- /dev/null +++ b/bin/assert-arg @@ -0,0 +1,78 @@ +#!/bin/sh +set -eu + +usage() { + cat <<-'EOF' + Usage: + assert-arg STRING MESSAGE + assert-arg -h + EOF +} + +help() { + cat <<-'EOF' + + Options: + -h, --help show this message + + STRING the string to check if is empty + MESSAGE the message to print when STRING is empty + + + Examples: + + Assert that $1 contains an argument, named FILENAME: + + $ eval "$(assert-arg "${1:-}" 'FILENAME')" + EOF +} + + +for flag in "$@"; do + case "$flag" in + --) + break + ;; + --help) + usage + help + exit + ;; + *) + ;; + esac +done + +while getopts 'h' flag; do + case "$flag" in + h) + usage + help + exit + ;; + *) + usage >&2 + exit 2 + ;; + esac +done +shift $((OPTIND - 1)) + + +STRING="${1:-}" +MESSAGE="${2:-}" + +if [ -z "$MESSAGE" ]; then + printf 'Missing MESSAGE, an argument to assert-arg.\n\n' >&2 + usage >&2 + exit 2 +fi + + +if [ -z "$STRING" ]; then + printf 'Missing %s.\n\n' "$MESSAGE" >&2 + cat <<-'EOF' + usage >&2 + exit 2 + EOF +fi |
