Platform independent detection method 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 does not work on systems without unix or without which command (although I'm not sure what it is).

I need a git detection method that satisfies these conditions:

  • works on cross platform platform even on Windows
  • doesn't display anything in $ stdout or $ stderr
  • small amount of code

Update: The solution is to avoid using which in general and redirect the 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 error, saving us the transition to $?.success? which is necessary when using feedback signals.

+6
git windows ruby shell detect
source share
4 answers

There is no such thing as /dev/null Windows.

One approach that we take in different projects is to define NULL based on RbConfig::CONFIG['host_os']

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

Then use this to redirect STDOUT and STDERR to it.

In this regard, I made a trivial link to my blog

But, if you just want to check the presence of git, and not the location, you do not need to do what with a simple system call and checking the result of $? will be sufficient.

Hope this helps

+4
source share

It is a solution that avoids crawling to detect executable files, and can also reliably determine where the executable is located. This is an alternative to which .

 def which cmd exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = "#{path}/#{cmd}#{ext}" return exe if File.executable? exe } end return nil end 

Using:

 # Mac OS X where 'ruby' #=> /opt/local/Cellar/ruby-enterprise-edition/2010.02/bin/ruby # Windows where 'ruby' #=> C:\Program Files\Ruby192\bin/ruby.exe 
+1
source share

Perhaps running on JRuby and using JGit can be a truly platform-independent option.

0
source share

I think you will need to do this:

  • Verify that the machine is windows and unix based
  • If using Unix, use which
  • If Windows, is there an equivalent of "which" in windows?
0
source share

All Articles