Allow explicit target directory argument to rbenv-version-file

Can be used for `.ruby-version` file lookup in the ancestry of a
specific directory. In this mode of operation, global version files
aren't taken into consideration, and the command fails unless a local
version file was found.
This commit is contained in:
Mislav Marohnić 2015-12-23 15:19:54 +01:00
parent 90373d78b9
commit ca25259900
2 changed files with 35 additions and 14 deletions

View file

@ -1,35 +1,45 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Usage: rbenv version-file [<dir>]
# Summary: Detect the file that sets the current rbenv version # Summary: Detect the file that sets the current rbenv version
set -e set -e
[ -n "$RBENV_DEBUG" ] && set -x [ -n "$RBENV_DEBUG" ] && set -x
target_dir="$1"
find_local_version_file() { find_local_version_file() {
local root="$1" local root="$1"
while true; do while ! [[ "$root" =~ ^//[^/]*$ ]]; do
[[ "$root" =~ ^//[^/]*$ ]] && break
if [ -e "${root}/.ruby-version" ]; then if [ -e "${root}/.ruby-version" ]; then
echo "${root}/.ruby-version" echo "${root}/.ruby-version"
exit return 0
elif [ -e "${root}/.rbenv-version" ]; then elif [ -e "${root}/.rbenv-version" ]; then
echo "${root}/.rbenv-version" echo "${root}/.rbenv-version"
exit return 0
fi fi
[ -n "$root" ] || break [ -n "$root" ] || break
root="${root%/*}" root="${root%/*}"
done done
return 1
} }
find_local_version_file "$RBENV_DIR" find_global_version_file() {
[ "$RBENV_DIR" = "$PWD" ] || find_local_version_file "$PWD" local global_version_file="${RBENV_ROOT}/version"
global_version_file="${RBENV_ROOT}/version" if [ -e "$global_version_file" ]; then
if [ -e "$global_version_file" ]; then
echo "$global_version_file" echo "$global_version_file"
elif [ -e "${RBENV_ROOT}/global" ]; then elif [ -e "${RBENV_ROOT}/global" ]; then
echo "${RBENV_ROOT}/global" echo "${RBENV_ROOT}/global"
elif [ -e "${RBENV_ROOT}/default" ]; then elif [ -e "${RBENV_ROOT}/default" ]; then
echo "${RBENV_ROOT}/default" echo "${RBENV_ROOT}/default"
else else
echo "$global_version_file" echo "$global_version_file"
fi
}
if [ -n "$target_dir" ]; then
find_local_version_file "$target_dir"
else
find_local_version_file "$RBENV_DIR" || {
[ "$RBENV_DIR" != "$PWD" ] && find_local_version_file "$PWD"
} || find_global_version_file
fi fi

View file

@ -97,3 +97,14 @@ create_file() {
RBENV_DIR="${RBENV_TEST_DIR}/widget/blank" run rbenv-version-file RBENV_DIR="${RBENV_TEST_DIR}/widget/blank" run rbenv-version-file
assert_success "${RBENV_TEST_DIR}/project/.ruby-version" assert_success "${RBENV_TEST_DIR}/project/.ruby-version"
} }
@test "finds version file in target directory" {
create_file "project/.ruby-version"
run rbenv-version-file "${PWD}/project"
assert_success "${RBENV_TEST_DIR}/project/.ruby-version"
}
@test "fails when no version file in target directory" {
run rbenv-version-file "$PWD"
assert_failure ""
}