Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active January 24, 2017 20:14
Show Gist options
  • Save nilium/494391e56a0a8a4df066fef44e51d5b4 to your computer and use it in GitHub Desktop.
Save nilium/494391e56a0a8a4df066fef44e51d5b4 to your computer and use it in GitHub Desktop.
Vendor cd functions for why did I do this
# To be sourced in either zsh or bash
# cdv works better if you use zsh and cd is synonymous with pushd
# vendor_subpath looks for any vendor directory in the current directory and in any directory above it. If found, it
# will search that directory first for an exact match and then the shortest inexact match for the path given (arg 1).
#
# E.g., vendor_subpath foo/bar will search first for an exact vendor/foo/bar directory. If none is found, it will then
# try to find vendor/*foo/bar* and pick the shortest.
vendor_subpath () {
(
setvendor=0
popvendor 2>/dev/null
if [[ "$1" == "-" || "$1" == "" ]]
then
echo "$PWD"
exit 0
elif [[ "$1" == vendor ]]
then
setvendor=1
fi
while [[ ! -d vendor && "$PWD" != / ]]
do
cd ..
done
if [[ -d vendor && setvendor == 1 ]]
then
echo "$PWD/vendor"
exit 0
elif [[ ! -d vendor ]]
then
echo "vendor_subpath: no vendor dir found" 1>&2
exit 1
fi
if [[ -d "vendor/$1" ]]
then
echo "$PWD/vendor/$1"
exit 0
fi
if [[ "$nowild" == 1 ]]
then
exit 1
fi
p="$(find vendor -ipath "*${1}*" | sort | head -n 1)"
if [[ "$p" != "" && -d "$p" ]]
then
echo "$PWD/$p"
exit 0
fi
exit 1
)
}
# popv will change the current directory to the directory containing the vendor directory if currently in a vendor
# directory. This is only useful if you don't use popd instead or want very specifically to return to that directory and
# not a prior, different directory.
popv () {
if [[ "$PWD" == *"/vendor/"* ]]
then
pushd "${PWD%/vendor/*}"
else
echo 'popv: not in vendor directory' 1>&2
return 1
fi
}
# pushv pushes a found vendor directory onto the stack.
pushv () {
local cdv__path="$(vendor_subpath "$1")"
if [[ $? && -d "$cdv__path" ]]
then
pushd "$cdv__path"
else
echo "cdv: $1 not found" 1>&2
return 1
fi
}
# cdv changes directory to a found vendor directory.
cdv () {
local cdv__path="$(vendor_subpath "$1")"
if [[ $? && -d "$cdv__path" ]]
then
cd "$cdv__path"
else
echo "cdv: $1 not found" 1>&2
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment