#
# Find up a file in a directory hierarchy.
#
# @param $1 File to find
#
# @return Path to the nearest file location.
#
# @see http://unix.stackexchange.com/questions/6463/find-searching-in-parent-directories-instead-of-subdirectories
#
find_up() {
DIR=$(pwd)
while [[ "$DIR" != "" && ! -e "$DIR/$1" ]]; do
DIR=${DIR%/*}
done
[ ! -z "$DIR" ] && echo "$DIR/$1"
}
# Keep track of last swapped php version
LAST_PHP_VERSION="off"
# Set these to 1 to print messages when swapping php versions
SWAP_PHP_VERBOSE=0
SWAP_PHP_DEBUG=0
#
# Swaps php versions using phpbrew
#
# If there's a ".php-version" file in the current dir or in any of its parents, this function will
# swap the current php version to the one specified in the file. If there are multiple
# ".php-version" files among the directory hierarchy, the nearest file is used.
#
# @see https://github.com/phpbrew/phpbrew
#
# @param $1 Current working dir
#
swap_php_version() {
[ $SWAP_PHP_DEBUG -eq 1 ] && echo "Running swap_php_version()..."
FILE=$(find_up .php-version)
[ $SWAP_PHP_DEBUG -eq 1 ] && echo "FILE=$FILE"
if [ ! -z "$FILE" ]; then
VERSION=$(<$FILE)
if [ "$VERSION" != "$LAST_PHP_VERSION" ]; then
phpbrew use $VERSION
LAST_PHP_VERSION=$VERSION
[ $SWAP_PHP_VERBOSE -eq 1 ] && echo "PHP version swapped to $VERSION"
fi
elif [ "$LAST_PHP_VERSION" != "off" ]; then
phpbrew off > /dev/null
LAST_PHP_VERSION="off"
[ $SWAP_PHP_VERBOSE -eq 1 ] && echo "PHP version swapped to system default"
fi
}
# Keep track of last dir
LAST_PHP_DIR=""
swap_php_version_when_cd() {
[ $SWAP_PHP_DEBUG -eq 1 ] && echo "Running swap_php_version_when_cd()..."
CURRENT_DIR=$(pwd)
if [ "$LAST_PHP_DIR" != "$CURRENT_DIR" ]; then
LAST_PHP_DIR=$CURRENT_DIR
swap_php_version $@
fi
}
PROMPT_COMMAND="swap_php_version_when_cd"