Skip to content

Instantly share code, notes, and snippets.

@subfuzion
Last active July 16, 2021 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subfuzion/4b24415fcd7d1250d8ea3eaa0aea35a0 to your computer and use it in GitHub Desktop.
Save subfuzion/4b24415fcd7d1250d8ea3eaa0aea35a0 to your computer and use it in GitHub Desktop.
#!/bin/sh
strip_trailing_slashes() {
printf "$1" | sed 's/[/]*$//'
}
# If empty arg, return .
# If nothing but slashes, return /
# If no slashes after stripping all trailing slashes, return .
# Otherwise, return everything up until last path component
dirname() {
if [ -z "$1" ]; then printf '.'; return; fi
if ! $(printf "$1" | grep -q '[^/]'); then printf '/'; return; fi
local s="$(strip_trailing_slashes $1)"
if ! $(printf "$s" | grep -q '/'); then printf '.'; fi
printf "$(strip_trailing_slashes $(printf $s | sed 's/[^/]*$//'))"
}
dirname "$@"
#!/bin/sh
# fail and pass counters
FC=0
PC=0
# params: expected, actual, error_message
fail() {
FC=$(expr $FC + 1)
printf " [FAIL] expected: \'$1\', actual: \'$2\'"
if ! [ -z "$3" ]; then printf " ($3)"; fi
printf "\n"
}
# params expect, actual, error_message
assert() {
if ! [ "x$1" = "x$2" ]; then fail "$1" "$2" "$3"; return 1; fi
PC=$(expr $PC + 1)
}
# params expected, actual, error_message
assert_fail() {
if [ "x$1" = "x$2" ]; then fail "$1" "$2" "$3"; return 1; fi
PC=$(expr $PC + 1)
}
# https://stackoverflow.com/a/36692524/758334
oneliner() {
printf "$1" | sed -n -e '1p' | sed -e 's#//*#/#g' -e 's#\(.\)/$#\1#' -e 's#^[^/]*$#.#' -e 's#\(.\)/[^/]*$#\1#'
}
# test input, expect
T() {
printf "=> test: input \'$1\', expect: \'$2\'\n"
assert "$2" "$(dirname.sh $1)"
# test against `dirname` for compatibility
assert "$(dirname $1)" "$(dirname.sh $1)" "dirname compatibility"
# test against oneliner
assert "$2" "$(oneliner $1)" "oneliner compatibility"
}
for t in '""' '.' '.foo' './foo' 'foo' 'foo/' 'foo///' '..' '..foo' '..foo//' '../'
do
T "$t" '.'
done
for t in '/' '//' '///'
do
T "$t" '/'
done
for t in 'a/b/c' 'a/b/c/' 'a/b/c///'
do
T "$t" 'a/b'
done
for t in '/a/b/c' '/a/b/c/' '/a/b/c///'
do
T "$t" '/a/b'
done
for t in '//a/b/c' '//a/b/c//'
do
T "$t" '//a/b'
done
printf "==========================================\n"
if [ "$FC" -gt 0 ]; then
printf "FAIL ($FC tests failed, $PC tests passed)\n"
printf "==========================================\n"
exit 1
else
printf "SUCCESS: ($PC tests passed)\n"
printf "==========================================\n"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment