Skip to content

Commit

Permalink
Fix character classes for BusyBox tr to avoid using sed
Browse files Browse the repository at this point in the history
  • Loading branch information
sschmid committed Oct 28, 2024
1 parent 45c1f20 commit 0e35d77
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/pw
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
Expand Down
16 changes: 16 additions & 0 deletions test/pw.bats
Original file line number Diff line number Diff line change
Expand Up @@ -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"
# }

0 comments on commit 0e35d77

Please sign in to comment.