Module: Librarian::Posix

Defined in:
lib/librarian/posix.rb

Defined Under Namespace

Classes: CommandFailure

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.which(cmd) ⇒ Object

Cross-platform way of finding an executable in the $PATH.

which('ruby') #=> /usr/bin/ruby

From:

https://github.com/defunkt/hub/commit/353031307e704d860826fc756ff0070be5e1b430#L2R173


16
17
18
19
20
21
22
23
24
25
26
# File 'lib/librarian/posix.rb', line 16

def which(cmd)
  exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(';') : ['']
  ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
    path = File.expand_path(path)
    exts.each do |ext|
      exe = File.join(path, cmd + ext)
      return exe if File.file?(exe) && File.executable?(exe)
    end
  end
  nil
end

.which!(cmd) ⇒ Object



28
29
30
# File 'lib/librarian/posix.rb', line 28

def which!(cmd)
  which(cmd) or raise Error, "cannot find #{cmd}"
end

Instance Method Details

#rescuing(*klasses) ⇒ Object



52
53
54
55
56
57
# File 'lib/librarian/posix.rb', line 52

def rescuing(*klasses)
  begin
    yield
  rescue *klasses
  end
end

#run!(command, options = { }) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/librarian/posix.rb', line 59

def run!(command, options = { })
  out, err = nil, nil
  chdir = options[:chdir].to_s if options[:chdir]
  env = options[:env] || { }
  old_env = Hash[env.keys.map{|k| [k, ENV[k]]}]
  out, err, wait = nil, nil, nil
  begin
    ENV.update env
    Dir.chdir(chdir || Dir.pwd) do
      IO.popen3(*command) do |i, o, e, w|
        rescuing(Errno::EBADF){ i.close } # jruby/1.9 can raise EBADF
        out, err, wait = o.read, e.read, w
      end
    end
  ensure
    ENV.update old_env
  end
  s = wait ? wait.value : $? # wait is 1.9+-only
  s.success? or CommandFailure.raise! command, s, err
  out
end