Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform-independent way of detecting if git is installed

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:

  1. works reliably cross-platform, even on Windows
  2. doesn't output anything to $stdout or $stderr
  3. 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.

like image 409
mislav Avatar asked Jan 04 '11 19:01

mislav


1 Answers

There is not such thing as /dev/null on Windows.

One approach we have been taking in different projects is define NULL based on RbConfig::CONFIG['host_os']

NULL = RbConfig::CONFIG['host_os'] =~ /mingw|mswin/ ? 'NUL' : '/dev/null'

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

like image 194
Luis Lavena Avatar answered Oct 18 '22 06:10

Luis Lavena