Commit 16de602b authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Extend functionality of has() with type tests

parent 213fd7f6
Loading
Loading
Loading
Loading
+60 −4
Original line number Diff line number Diff line
@@ -20,10 +20,66 @@ die() {
	exit $CODE
}

has()
{
	type "$1"
} >/dev/null 2>&1

has() {
	# TODO: replace local with let/unlet: https://stackoverflow.com/a/18600920
	local type
	type=`_get_type "$1"` || return 1
	case ${2-} in
		is) _match_type "$type" "$3" ;;
		is-not) ! _match_type "$type" "$3" ;;
		'') true ;;
		*) die "Unknown matching argument: $2" ;;
	esac
} #>/dev/null 2>&1


_get_type() {
	# output one of:
	# - <path>
	# - function
	# - builtin
	# - alias
	# - keyword
	# or return 1
	local type
	case $CURRENT_SHELL in
		bash) type=$(type -t "$1") || return 1
			case $type in
				file) type -p "$1" ;;
				*) echo $type ;;
			esac ;;
		zsh) case `whence -w "$1"` in
				*:\ command|*:\ hashed) whence "$1" ;;
				*:\ function) echo function ;;
				*:\ builtin) echo builtin ;;
				*:\ alias) echo alias ;;
				*:\ reserved) echo keyword ;;
				*) exit 1 ;;
			esac ;;
		sh) type=`type "$1"`
			case $type in
				*\ is\ /*|*\ is\ $1) echo "${type##* is }" ;;
				*function) echo function ;;
				*builtin) echo builtin ;;
				*an\ alias\ *) echo alias ;;
				*keyword) echo keyword ;;
				*) exit 1 ;;
			esac ;;
	esac
}


_match_type() {
	case $2 in
		function|builtin|alias|keyword) [ "$1" = "$2" ]; return ;;
		file) [ -x "$1" ]; return ;;
	esac
	case $CURRENT_SHELL in
		bash|zsh) [[ $1 -ef $2 ]]; return ;;
	esac
	[ `expand "$1"` = `expand "$2"` ]
}


basename_filter()
+53 −0
Original line number Diff line number Diff line
@@ -12,7 +12,60 @@ when has bash
expect no_output
expect [[ $RETVAL -eq 0 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is function
expect no_output
expect [[ $RETVAL -eq 1 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is file
expect no_output
expect [[ $RETVAL -eq 0 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is $BASH
expect no_output
expect [[ $RETVAL -eq 0 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is /bin/ls
expect no_output
expect [[ $RETVAL -eq 1 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is /bin/ls
expect no_output
expect [[ $RETVAL -eq 1 ]]

given  . ~/.shell/lib/shared.sh
when   has bash is-not /bin/ls
expect no_output
expect [[ $RETVAL -eq 0 ]]


given  . ~/.shell/lib/shared.sh
when   has type
expect no_output
expect [[ $RETVAL -eq 0 ]]

given  . ~/.shell/lib/shared.sh
when   has type is builtin
expect no_output
expect [[ $RETVAL -eq 0 ]]

given  . ~/.shell/lib/shared.sh
when   has type is file
expect no_output
expect [[ $RETVAL -eq 1 ]]

given  . ~/.shell/lib/shared.sh
when   has type is function
expect no_output
expect [[ $RETVAL -eq 1 ]]


given  . ~/.shell/lib/shared.sh
given  "foo() { :; }"
when   has foo is function
expect no_output
expect [[ $RETVAL -eq 0 ]]