From 0e35d77b9cb1376c8310923db69dc2bc7fbe0715 Mon Sep 17 00:00:00 2001 From: Simon Schmid Date: Mon, 28 Oct 2024 21:49:56 +0100 Subject: [PATCH] Fix character classes for BusyBox tr to avoid using sed --- src/pw | 8 ++++++-- test/pw.bats | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/pw b/src/pw index 28c607d..11c944f 100755 --- a/src/pw +++ b/src/pw @@ -187,9 +187,13 @@ pw::output() { pw::gen() { local -i length=${1:-${PW_GEN_LENGTH}} local password="" class="${2:-"${PW_GEN_CLASS}"}" + + # Fix character classes for BusyBox tr + [[ "${class}" == "[:graph:]" ]] && class="[:alnum:][:punct:]" + [[ "${class}" == "[:print:]" ]] && class="[:alnum:][:punct:][:space:]" + while (( "${#password}" != length )); do - # alpine tr does not support [:graph:], use sed instead - password+=$(dd if=/dev/urandom bs=$(( length / 64 + 1 )) count=1 2>/dev/null | LC_CTYPE=C LC_ALL=C tr -d '\0[:space:]' | LC_CTYPE=C LC_ALL=C sed "s/[^${class}]//g" | head -c $(( length - ${#password} ))) + password+=$(dd if=/dev/urandom bs=$(( length / 64 + 1 )) count=1 2>/dev/null | LC_CTYPE=C LC_ALL=C tr -dc "${class}" | head -c $(( length - ${#password} ))) done pw::output "${password}" } diff --git a/test/pw.bats b/test/pw.bats index 9b0e0cd..70b33a3 100644 --- a/test/pw.bats +++ b/test/pw.bats @@ -78,3 +78,19 @@ assert_pw_home() { assert_success assert_output "22222222" } + +# @test "BusyBox: replaces [:graph:] with [:alnum:][:punct:]" { +# export PW_GEN_LENGTH=64 +# export PW_GEN_CLASS="[:graph:]" +# run pw -p gen +# assert_success +# assert_output "check manually" +# } + +# @test "alpine: replaces [:print:] with [:alnum:][:punct:][:space:]" { +# export PW_GEN_LENGTH=64 +# export PW_GEN_CLASS="[:print:]" +# run pw -p gen +# assert_success +# assert_output "check manually" +# }