-
-
Notifications
You must be signed in to change notification settings - Fork 190
/
chruby.sh
106 lines (88 loc) · 2.35 KB
/
chruby.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
CHRUBY_VERSION="0.3.9"
RUBIES=()
for dir in "$PREFIX/opt/rubies" "$HOME/.rubies"; do
[[ -d "$dir" && -n "$(ls -A "$dir")" ]] && RUBIES+=("$dir"/*)
done
unset dir
function chruby_reset()
{
[[ -z "$RUBY_ROOT" ]] && return
PATH=":$PATH:"; PATH="${PATH//:$RUBY_ROOT\/bin:/:}"
[[ -n "$GEM_ROOT" ]] && PATH="${PATH//:$GEM_ROOT\/bin:/:}"
if (( $UID != 0 )); then
[[ -n "$GEM_HOME" ]] && PATH="${PATH//:$GEM_HOME\/bin:/:}"
GEM_PATH=":$GEM_PATH:"
[[ -n "$GEM_HOME" ]] && GEM_PATH="${GEM_PATH//:$GEM_HOME:/:}"
[[ -n "$GEM_ROOT" ]] && GEM_PATH="${GEM_PATH//:$GEM_ROOT:/:}"
GEM_PATH="${GEM_PATH#:}"; GEM_PATH="${GEM_PATH%:}"
unset GEM_HOME
[[ -z "$GEM_PATH" ]] && unset GEM_PATH
fi
PATH="${PATH#:}"; PATH="${PATH%:}"
unset RUBY_ROOT RUBY_ENGINE RUBY_VERSION RUBYOPT GEM_ROOT
hash -r
}
function chruby_use()
{
if [[ ! -x "$1/bin/ruby" ]]; then
echo "chruby: $1/bin/ruby not executable" >&2
return 1
fi
[[ -n "$RUBY_ROOT" ]] && chruby_reset
export RUBY_ROOT="$1"
export RUBYOPT="$2"
export PATH="$RUBY_ROOT/bin:$PATH"
typeset unset RUBYGEMS_GEMDEPS
eval "$("$RUBY_ROOT/bin/ruby" - <<EOF
puts "export RUBY_ENGINE=#{defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'};"
puts "export RUBY_VERSION=#{RUBY_VERSION};"
puts "export RUBY_PATCHLEVEL=#{RUBY_PATCHLEVEL};"
begin; require 'rubygems'; puts "export GEM_ROOT=#{Gem.default_dir.inspect};"; rescue LoadError; end
EOF
)"
export PATH="${GEM_ROOT:+$GEM_ROOT/bin:}$PATH"
if (( $UID != 0 )); then
export GEM_HOME="$HOME/.gem/$RUBY_ENGINE/$RUBY_VERSION"
export GEM_PATH="$GEM_HOME${GEM_ROOT:+:$GEM_ROOT}${GEM_PATH:+:$GEM_PATH}"
export PATH="$GEM_HOME/bin:$PATH"
fi
hash -r
}
function chruby()
{
case "$1" in
-h|--help)
echo "usage: chruby [RUBY|VERSION|system] [RUBYOPT...]"
;;
-V|--version)
echo "chruby: $CHRUBY_VERSION"
;;
"")
local dir star
for dir in "${RUBIES[@]}"; do
dir="${dir%%/}"
if [[ "$dir" == "$RUBY_ROOT" ]]; then star="*"
else star=" "
fi
echo " $star ${dir##*/}"
done
;;
system) chruby_reset ;;
*)
local dir match
for dir in "${RUBIES[@]}"; do
dir="${dir%%/}"
case "${dir##*/}" in
"$1") match="$dir" && break ;;
*"$1"*) match="$dir" ;;
esac
done
if [[ -z "$match" ]]; then
echo "chruby: unknown Ruby: $1" >&2
return 1
fi
shift
chruby_use "$match" "$*"
;;
esac
}