Module: RubyGit::FileHelpers

Defined in:
lib/ruby_git/file_helpers.rb

Overview

A namespace for several file utility methods that I wish were part of FileUtils.

Class Method Summary collapse

Class Method Details

.which(cmd, paths: ENV['PATH'].split(File::PATH_SEPARATOR), exts: (ENV['PATHEXT']&.split(';') || [''])) ⇒ Pathname?

Cross platform way to find an executable file within a list of paths

Works for both Linux/Unix and Windows.

exts is for Windows. Other platforms should accept the default.

Examples:

Searching over the PATH for a command

path = FileUtils.which('git')

Overriding the default PATH

path = FileUtils.which('git', ['/usr/bin', '/usr/local/bin'])

Parameters:

  • cmd (String)

    The basename of the executable file to search for

  • paths (Array<String>) (defaults to: ENV['PATH'].split(File::PATH_SEPARATOR))

    The list of directories to search for basename in

  • exts (Array<String>) (defaults to: (ENV['PATHEXT']&.split(';') || ['']))

    The list of extensions that indicate that a file is executable

Returns:

  • (Pathname, nil)

    The path to the first executable file found on the path or nil an executable file was not found.



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruby_git/file_helpers.rb', line 28

def self.which(
  cmd,
  paths: ENV['PATH'].split(File::PATH_SEPARATOR),
  exts: (ENV['PATHEXT']&.split(';') || [''])
)
  raise 'PATH is not set' unless ENV.keys.include?('PATH')

  paths
    .product(exts)
    .map { |path, ext| Pathname.new(File.join(path, "#{cmd}#{ext}")) }
    .reject { |path| path.directory? || !path.executable? }
    .find { |exe_path| !exe_path.directory? && exe_path.executable? }
end