1require 'rubygems/command'
2
3class Gem::Commands::WhichCommand < Gem::Command
4  def initialize
5    super 'which', 'Find the location of a library file you can require',
6          :search_gems_first => false, :show_all => false
7
8    add_option '-a', '--[no-]all', 'show all matching files' do |show_all, options|
9      options[:show_all] = show_all
10    end
11
12    add_option '-g', '--[no-]gems-first',
13               'search gems before non-gems' do |gems_first, options|
14      options[:search_gems_first] = gems_first
15    end
16  end
17
18  def arguments # :nodoc:
19    "FILE          name of file to find"
20  end
21
22  def defaults_str # :nodoc:
23    "--no-gems-first --no-all"
24  end
25
26  def execute
27    found = false
28
29    options[:args].each do |arg|
30      arg = arg.sub(/#{Regexp.union(*Gem.suffixes)}$/, '')
31      dirs = $LOAD_PATH
32
33      spec = Gem::Specification.find_by_path arg
34
35      if spec then
36        if options[:search_gems_first] then
37          dirs = gem_paths(spec) + $LOAD_PATH
38        else
39          dirs = $LOAD_PATH + gem_paths(spec)
40        end
41      end
42
43      # TODO: this is totally redundant and stupid
44      paths = find_paths arg, dirs
45
46      if paths.empty? then
47        alert_error "Can't find ruby library file or shared library #{arg}"
48      else
49        say paths
50        found = true
51      end
52    end
53
54    terminate_interaction 1 unless found
55  end
56
57  def find_paths(package_name, dirs)
58    result = []
59
60    dirs.each do |dir|
61      Gem.suffixes.each do |ext|
62        full_path = File.join dir, "#{package_name}#{ext}"
63        if File.exist? full_path and not File.directory? full_path then
64          result << full_path
65          return result unless options[:show_all]
66        end
67      end
68    end
69
70    result
71  end
72
73  def gem_paths(spec)
74    spec.require_paths.collect { |d| File.join spec.full_gem_path, d }
75  end
76
77  def usage # :nodoc:
78    "#{program_name} FILE [FILE ...]"
79  end
80
81end
82
83