Commit 5315a2e6 authored by Matthias Käppler's avatar Matthias Käppler Committed by Michael Kozono

Rewrite Gitlab::Utils.which function

parent a5caf589
......@@ -120,18 +120,14 @@ module Gitlab
Random.rand(Float::MAX.to_i).to_s(36)
end
# See: http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
# Cross-platform way of finding an executable in the $PATH.
# Behaves like `which` on Linux machines: given PATH, try to resolve the given
# executable name to an absolute path, or return nil.
#
# which('ruby') #=> /usr/bin/ruby
def which(cmd, env = ENV)
exts = env['PATHEXT'] ? env['PATHEXT'].split(';') : ['']
env['PATH'].split(File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = File.join(path, "#{cmd}#{ext}")
return exe if File.executable?(exe) && !File.directory?(exe)
end
def which(filename)
ENV['PATH']&.split(File::PATH_SEPARATOR)&.each do |path|
full_path = File.join(path, filename)
return full_path if File.executable?(full_path)
end
nil
......
......@@ -249,10 +249,16 @@ RSpec.describe Gitlab::Utils do
end
describe '.which' do
it 'finds the full path to an executable binary' do
expect(File).to receive(:executable?).with('/bin/sh').and_return(true)
before do
stub_env('PATH', '/sbin:/usr/bin:/home/joe/bin')
end
it 'finds the full path to an executable binary in order of appearance' do
expect(File).to receive(:executable?).with('/sbin/tool').ordered.and_return(false)
expect(File).to receive(:executable?).with('/usr/bin/tool').ordered.and_return(true)
expect(File).not_to receive(:executable?).with('/home/joe/bin/tool')
expect(which('sh', 'PATH' => '/bin')).to eq('/bin/sh')
expect(which('tool')).to eq('/usr/bin/tool')
end
end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment