fluent predicates for filtering

This commit is contained in:
tpoindex 2019-09-11 23:46:47 -06:00 committed by Sławomir Śledź
parent b19ab5180b
commit 44dbdd3fbc
2 changed files with 89 additions and 0 deletions

View file

@ -398,3 +398,40 @@ maybevalue() {
fi
}
# commonly used predicates for filter
# e.g. list 1 a 2 b 3 c | filter lambda x . 'isint $x'
# inverse another test, e.g. "not isint $x"
not() {
local r=$("$@" 2>/dev/null)
$r && ret false || ret true
}
isint() {
[ "$1" -eq "$1" ] 2>/dev/null && ret true || ret false
}
isempty() {
[ -z "$1" ] && ret true || ret false
}
isfile() {
[ -f "$1" ] && ret true || ret false
}
isnonzerofile() {
[ -s "$1" ] && ret true || ret false
}
isreadable() {
[ -r "$1" ] && ret true || ret false
}
iswritable() {
[ -w "$1" ] && ret true || ret false
}
isdir() {
[ -d "$1" ] && ret true || ret false
}

52
test/predicates_test.sh Executable file
View file

@ -0,0 +1,52 @@
#! /bin/bash
testIsint() {
assertEquals 'true' $(isint 1)
assertEquals 'true' $(isint -1)
assertEquals 'false' $(isint a)
assertEquals 'false' $(isint "")
assertEquals '1 2 3 4 5' "$(list 1 a 2 b 3 c 4 d 5 e | filter lambda x . 'isint $x' | unlist )"
assertEquals '1 2' "$(list 1 a 2 b 3 c 4 d 5 e | filter lambda x . '($(isint $x) && [[ $x -le 2 ]] && ret true) || ret false ' | unlist )"
assertEquals 'false' $(not isint 1)
assertEquals 'true' $(not isint a)
}
testIsempty() {
assertEquals 'true' $(isempty "")
assertEquals 'false' $(isempty a)
assertEquals 'true' $(not isempty a)
assertEquals 'false' $(not isempty "")
}
testIsfile() {
f=$(mktemp)
assertEquals 'true' $(isfile $f)
assertEquals 'false' $(isfile $f.xxx)
assertEquals 'false' $(isfile "")
assertEquals 'true' $(not isfile $f.xxx)
assertEquals 'false' $(isnonzerofile $f)
echo hello world >$f
assertEquals 'true' $(isnonzerofile $f)
assertEquals 'true' $(iswritable $f)
chmod 400 $f
assertEquals 'false' $(iswritable $f)
assertEquals 'true' $(isreadable $f)
chmod 200 $f
assertEquals 'false' $(isreadable $f)
chmod 600 $f
rm $f
}
testIsdir() {
assertEquals 'true' $(isdir .)
assertEquals 'false' $(isdir sir_not_appearing_in_this_film)
}
. ./shunit2-init.sh