Module: Which

Defined in:
lib/commands/rubo/utils/which.rb

Overview

gist.github.com/steakknife/88b6c3837a5e90a08296 Copyright © 2014,2016 Barry Allard <[email protected]> License: MIT

inspiration: stackoverflow.com/questions/2889720/one-liner-in-ruby-for-displaying-a-prompt-getting-input-and-assigning-to-a-var

Which Bourne shell?

   require 'which'

   Which 'sh'

Or all zsh(es)

   require 'which'

   WhichAll 'zsh'

Instance Method Summary collapse

Instance Method Details

#executable_file_extensionsObject



45
46
47
# File 'lib/commands/rubo/utils/which.rb', line 45

def executable_file_extensions
  ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
end

#find_executable(path, cmd, &_block) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/commands/rubo/utils/which.rb', line 53

def find_executable(path, cmd, &_block)
  executable_file_extensions.each do |ext|
    if real_executable?(abs_exe = File.expand_path(cmd + ext, path))
      yield(abs_exe)
    end
  end
end

#real_executable?(file) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/commands/rubo/utils/which.rb', line 41

def real_executable?(file)
  File.executable?(file) && !File.directory?(file)
end

#search_pathsObject



49
50
51
# File 'lib/commands/rubo/utils/which.rb', line 49

def search_paths
  ENV['PATH'].split(File::PATH_SEPARATOR)
end

#which(cmd) ⇒ Object

similar to ‘which {cmd}`, except relative paths are always expanded returns: first match absolute path (String) to cmd (no symlinks followed),

or nil if no executable found


24
25
26
27
28
29
# File 'lib/commands/rubo/utils/which.rb', line 24

def which(cmd)
  which0(cmd) do |abs_exe|
    return abs_exe
  end
  nil
end

#which0(cmd, &found_exe) ⇒ Object

internal use only _found_exe is yielded to on all successful match(es),

with path to absolute file (String)


64
65
66
67
68
69
70
71
# File 'lib/commands/rubo/utils/which.rb', line 64

def which0(cmd, &found_exe)
  # call expand_path(f, nil) == expand_path(f) for relative/abs path cmd
  find_executable(nil, cmd, &found_exe) if File.basename(cmd) != cmd

  search_paths.each do |path|
    find_executable(path, cmd, &found_exe)
  end
end

#which_all(cmd) ⇒ Object

similar to ‘which -a {cmd}`, except relative paths are always expanded returns: always an array, or [] if none found



33
34
35
36
37
38
39
# File 'lib/commands/rubo/utils/which.rb', line 33

def which_all(cmd)
  results = []
  which0(cmd) do |abs_exe|
    results << abs_exe
  end
  results
end