summaryrefslogtreecommitdiff
path: root/tool/lib/find_executable.rb
blob: 89c6fb8f3b7aa1c25e7f38f808b5d8ae66274aa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# frozen_string_literal: true
require "rbconfig"

module EnvUtil
  def find_executable(cmd, *args)
    exts = RbConfig::CONFIG["EXECUTABLE_EXTS"].split | [RbConfig::CONFIG["EXEEXT"]]
    ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
      next if path.empty?
      path = File.join(path, cmd)
      exts.each do |ext|
        cmdline = [path + ext, *args]
        begin
          return cmdline if yield(IO.popen(cmdline, "r", err: [:child, :out], &:read))
        rescue
          next
        end
      end
    end
    nil
  end
  module_function :find_executable
end