3

Initialize rbenv and run ruby script from shell script

I want svnserve to run pre-commit hook, written on ruby. As the svnserve is run as root user, it knows nothing about user rbenv installation.

I set a soft link /usr/bin/ruby -> /home/admin/.rbenv/shims/ruby . As result, when i try

#!/usr/bin/ruby
puts "Pre-commit hook!"

It shows error:

Transmitting file data .svn: Commit failed (details follow):
svn: Commit blocked by pre-commit hook (exit code 255) with no output.

When i run manually on Server:

admin $ sudo ./pre-commit
/usr/bin/ruby: line 4: exec: rbenv: not found

So, i suppose, that rbenv initialization is needed, but how?

sadfuzzy
  • 442
  • 5
  • 20

2 Answers2

7

In hooks path:

pre-commit:

#!/bin/bash
export HOME=/home/user
if [ -d $HOME/.rbenv ]; then
  export PATH="$HOME/.rbenv/shims:$PATH"
  eval "$(rbenv init -)"
fi
$0.rb $*

pre-commit.rb:

#!/usr/bin/env ruby
ARGV.each_with_index { |arg, index| puts "Index #{index}: Argument #{arg}" }
Brian Morearty
  • 2,794
  • 30
  • 35
sadfuzzy
  • 442
  • 5
  • 20
  • 1
    Current versions of rbenv use `$HOME/.rbenv/shims` instead of `$HOME/.rbenv/bin`. Otherwise sadfuzzy's script is still good. – seren Jan 19 '17 at 06:34
2

you should initialize rbenv before using it.

/path/to/user/home/.rbenv/bin/rbenv init

then set ruby version globally:

rbenv global DESIRED-RUBY-VERSION

or localy:

rbenv local DESIRED-RUBY-VERSION

or per shell:

rbenv shell DESIRED-RUBY-VERSION

though not sure shell setting will work without a tty.

so you could create a shell script, pre-commit.sh and register it as a svn hook.

inside it initialize rbenv and call your pre-commit.rb file

  • 1
    Well, i know :) but how it can be done in one script (it is called by subversion)? – sadfuzzy Nov 20 '12 at 14:16
  • 2
    i guess your hook should be a shell script that firstly initialize `rbenv` then call a ruby script? –  Nov 20 '12 at 14:28
  • You are completely right! I want to initialize and run ruby code from the script. – sadfuzzy Nov 20 '12 at 14:31
  • +1 for this. I had a similar issue and ended up by creating 2 scripts - `hook.sh` that initializes `rbenv` and call my second script - `hook.rb` – James Evans Nov 20 '12 at 14:44
  • How should i pass params into ruby script from pre-commit hookm which will initialize rbenv? – sadfuzzy Nov 21 '12 at 08:48
  • 1
    @sadfuzzy, how does your params looks? you could pass them as arguments - `pre-commit.rb "arg1" "arg2" "etc"` and read them by `$*` in your ruby script. please note quotes around args, they are used to handle the case when your args contains spaces –  Nov 21 '12 at 09:37
  • Thanks! I've found this yet. Here is the solution: pre-commit: `#!/bin/bash export HOME=/home/user if [ -d $HOME/.rbenv ]; then export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" fi $0.rb $*` pre-commit.rb: `#!/usr/bin/env ruby ARGV.each_with_index { |arg, index| puts "Index #{index}: Argument #{arg}" } ` – sadfuzzy Nov 21 '12 at 10:03