Skip to content

Commit

Permalink
[fs/mode2octal] New AWK script to convert mode strings to octal
Browse files Browse the repository at this point in the history
  • Loading branch information
sideeffect42 committed Sep 19, 2024
1 parent 3ffe12c commit 48d2b8c
Show file tree
Hide file tree
Showing 5 changed files with 4,246 additions and 1 deletion.
12 changes: 12 additions & 0 deletions lib/fs/mode2octal.awk
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
k = 0
m = substr($0, 1, 10)
for (i = 8; i >= 0; --i) {
c = substr(m, 10-i, 1)
k += ((c~/[rwxst]/)*2^i)
if ((i % 3) == 0) {
k += (tolower(c)~/[st]/)*2^(9+i/3)
}
}
printf("%04o" ORS, k)
}
78 changes: 78 additions & 0 deletions spec/fs/mode2octal.spec
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
Describe 'fs/mode2octal'
EnableSandbox

SetupCommandFromFile mode2octal lib/fs/mode2octal.awk

modes_txt=${SHELLSPEC_SPECFILE%/*}/modes.txt

make_random_subset() {
rand_modes_txt="${SHELLSPEC_WORKDIR:?}/rand_modes.txt"
pick_random_lines 10% "${modes_txt}" >"${rand_modes_txt}"
}
BeforeAll 'make_random_subset'

It "converts plain mode strings to the correct octal values"

test_func() {
@awk -F'\t' '{ print $2 }' <"${rand_modes_txt}" \
| mode2octal
}

When call test_func

check_output() {
exec 7<"${rand_modes_txt}"

while read -r _oct_is
do
read -r _oct_should _string <&7

test "${_oct_is}" = "${_oct_should}" || {
printf 'mode string %s was converted to %s (but expected %s)\n' \
"${_string}" "${_oct_is}" "${_oct_should}"
}
done <<EOF
$1
EOF

exec 7>&-
}

The status should be success
The result of function check_output should equal ''
The stderr should equal ''
End


It "converts ls(1) long output to the correct octal values"

test_func() {
@awk -F'\t' '{ printf "%s 1 nobody nogroup 0 Jan 1 1970 %s"ORS, $2, $1 }' <"${rand_modes_txt}" \
| mode2octal
}

When call test_func

check_output() {
exec 7<"${rand_modes_txt}"

while read -r _oct_is
do
read -r _oct_should _string <&7

test "${_oct_is}" = "${_oct_should}" || {
printf 'mode string %s was converted to %s (but expected %s)\n' \
"${_string}" "${_oct_is}" "${_oct_should}"
}
done <<EOF
$1
EOF

exec 7>&-
}

The status should be success
The result of function check_output should equal ''
The stderr should equal ''
End
End
Loading

0 comments on commit 48d2b8c

Please sign in to comment.