]> git.corax.cc Git - toolbox/commitdiff
include/opt: Use column command to align help text
authorMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 11:48:17 +0000 (20:48 +0900)
committerMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 11:48:17 +0000 (20:48 +0900)
When printing the help text, the opt module aligns columns manually
by tracking the longest option name and inserting the required amount
of spaces into the output. This is needlessly complicated considering
there are simpler ways to align output.

This commit modifies the opt module to use the column command to
align the table of options in the help text.

include/opt.sh

index 7e3875b2dea0ee94fa680056839ee56a587011ba..6d4035b51d0c28b21462737d7d3db8c00d358c64 100644 (file)
@@ -34,7 +34,6 @@ __init() {
        declare -Axg __opt_action
        declare -Axg __opt_map
        declare -xgi __opt_num=0
-       declare -xgi __opt_longest=0
 
        opt_add_arg "h" "help" "" 0 \
                    "Print this text" \
@@ -62,7 +61,6 @@ opt_add_arg() {
        local regex="$6"
        local action="$7"
 
-       local optlen
        local num_flags
        local bflags
        local i
@@ -91,8 +89,6 @@ opt_add_arg() {
                esac
        done
 
-       optlen="${#long}"
-
        __opt_short["$long"]="$short"
        __opt_long["$short"]="$long"
        __opt_flags["$long"]="$bflags"
@@ -103,10 +99,6 @@ opt_add_arg() {
        __opt_map["-$short"]="$long"
        __opt_map["--$long"]="$long"
 
-       if (( __opt_longest < optlen )); then
-               __opt_longest="$optlen"
-       fi
-
        ((__opt_num++))
 
        return 0
@@ -129,17 +121,13 @@ opt_print_help() {
        for short in $(array_sort "${__opt_short[@]}"); do
                local long
                local desc
-               local optlen
-               local padding
 
                long="${__opt_long[$short]}"
                desc="${__opt_desc[$long]}"
-               optlen="${#long}"
-               padding=$((__opt_longest - optlen))
 
-               printf " -%s  --%s %*s %s\n" \
-                      "$short" "$long" "$padding" "" "$desc"
-       done
+               printf "\t-%s\t--%s\t%s\n" \
+                      "$short" "$long" "$desc"
+       done | column -s $'\t' -t
 
        return 2
 }