Last active
October 24, 2024 19:12
-
-
Save havenwood/a07e51966eb65d85251ff067f0c44bd5 to your computer and use it in GitHub Desktop.
A `which` command for Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'fileutils' | |
module FileUtils | |
# Returns the full path to an executable command if it exists in the PATH. | |
# | |
# FileUtils.which('ruby') # => "/usr/bin/ruby" | |
# FileUtils.which('matz') # => nil | |
# | |
# Keyword arguments: | |
# | |
# - <tt>env: 'PATH'</tt> - the PATH environment variable. | |
# - <tt>separator: File::PATH_SEPARATOR</tt> - the PATH separator. | |
# | |
def which(command, env: 'PATH', separator: File::PATH_SEPARATOR) | |
ENV.fetch(env) { break }.split(separator).each do |dir| | |
next unless Dir.exist?(dir) | |
path = File.join(dir, command) | |
next unless File.file?(path) && File.executable?(path) | |
return path | |
end | |
nil | |
end | |
module_function :which | |
end | |
path = FileUtils.which(ARGV.unshift) | |
abort unless path | |
puts path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment