This is how I detect git in ruby:
`which git 2>/dev/null` and $?.success?
However, this is not cross-platform. It fails on non-unix systems or those without the which command (although I’m not sure what those are).
I need a way to detect git that satisfies these conditions:
- works reliably cross-platform, even on Windows
- doesn’t output anything to $stdout or $stderr
- small amount of code
Update: the solution is to avoid using which altogether and to redirect output to NUL on Windows.
require 'rbconfig'
void = RbConfig::CONFIG['host_os'] =~ /msdos|mswin|djgpp|mingw/ ? 'NUL' : '/dev/null'
system "git --version >>#{void} 2>&1"
The system command returns true on success and false on failure, saving us the trip to $?.success? which is needed when using backticks.
There is not such thing as
/dev/nullon Windows.One approach we have been taking in different projects is define
NULLbased onRbConfig::CONFIG['host_os']Then use that to redirect both STDOUT and STDERR to it.
As for which, I made a trivial reference on my blog
But, if you just want to check git presence and not location, no need to do which, with a simple system call and check of the resulting in
$?will be enough.Hope this helps