diff --git a/commands/host/_lib/upsun-disk-helper.sh b/commands/host/_lib/upsun-disk-helper.sh index d388f4a..5fdf0b7 100644 --- a/commands/host/_lib/upsun-disk-helper.sh +++ b/commands/host/_lib/upsun-disk-helper.sh @@ -1,5 +1,26 @@ #ddev-generated #annertech-ddev + +# GNU numfmt is not on macOS. Print an IEC size (1024) with two decimals. +format_iec() { + local value="$1" + local from_unit="${2:-1}" + python3 - "$value" "$from_unit" << 'PY' +import sys +n = int(sys.argv[1]) * int(sys.argv[2]) +units = ["", "K", "M", "G", "T", "P"] +i = 0 +v = float(n) +while abs(v) >= 1024 and i < len(units) - 1: + v /= 1024.0 + i += 1 +if i == 0: + print(str(int(v))) +else: + print(f"{v:.2f}{units[i]}") +PY +} + upsun_disk_helper() { local project_id="$1" local project_name="$2" @@ -24,11 +45,11 @@ upsun_disk_helper() { echo "" echo "Total assigned (app+mysqldb+solrsearch):" - numfmt --to iec --format "%3.2f" "$total_assigned" + format_iec "$total_assigned" echo "" echo "Total storage available in project:" - numfmt --from-unit=1048576 --to iec --format="%3.2f" "$total_available" + format_iec "$total_available" 1048576 echo_yellow "" echo_yellow "WARNING: command uses hardcoded values for service totals. Verify numbers with table above!" diff --git a/tests/upsun-disk-darwin.test.sh b/tests/upsun-disk-darwin.test.sh new file mode 100644 index 0000000..86b9939 --- /dev/null +++ b/tests/upsun-disk-darwin.test.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +root=$(cd "$(dirname "$0")/.." && pwd) +helper="$root/commands/host/_lib/upsun-disk-helper.sh" + +set +e +numfmt --to iec --format "%3.2f" 1048576 >/tmp/numfmt.out 2>/tmp/numfmt.err +red=$? +set -e +if [ "$red" -eq 0 ]; then + echo "numfmt unexpectedly succeeded" >&2 + exit 1 +fi +grep -q "command not found" /tmp/numfmt.err + +funcs=$(awk ' + /^format_iec\(\) \{/ {p=1} + p {print} + /^}$/ && p {exit} +' "$helper") +eval "$funcs" +one=$(format_iec 1048576) +five=$(format_iec 5 1048576) +small=$(format_iec 1536) +[ "$one" = "1.00M" ] +[ "$five" = "5.00M" ] +[ "$small" = "1.50K" ] +if grep -Eq '^[^#]*numfmt ' "$helper"; then + echo "helper still calls numfmt" >&2 + exit 1 +fi +echo "upsun disk darwin ok (numfmt exit $red, 1MiB $one, 5 units $five)"