gemwhich   [plain text]


#!/usr/bin/env ruby
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++


require 'rubygems'
require 'optparse'

EXT = %w( .rb .rbw .so .dll )

$search_gems_first = false
$show_all = false

options = OptionParser.new
options.banner = "gemwhich -- Find the location of a library module."
options.separator("")
options.separator("Usage: gemwhich [options] libname...")
options.on('-a', '--all',
  "Show all matching files"
  ) do |value|
    $show_all = true  
end
options.on('-g', '--gems-first',
  "Search GEM libraries before non-GEMs"
  ) do |value|
    $search_gems_first = true  
end
options.on_tail('-v', '--verbose',
  "Enable verbose output"
  ) do |value|
  $verbose = value
end
options.on_tail('-h', '--help',
  "Display this help message"
  ) do |value|
  puts options
  exit
end
ARGV << '-h' if ARGV.empty?

begin
  options.parse!(ARGV)
rescue OptionParser::InvalidOption => ex
  puts "Error: #{ex.message}"
  exit
end

def find_paths(package_name, dirs)
  result = []
  dirs.each do |dir|
    EXT.each do |ext|
      full_path = File.join(dir, "#{package_name}#{ext}")
      if File.exist?(full_path)
	result << full_path
	return result unless $show_all
      end
    end
  end
  result
end

def gem_paths(spec)
  spec.require_paths.collect { |d|
    File.join(spec.full_gem_path,d)
  }
end 

searcher = Gem::GemPathSearcher.new
ARGV.each do |arg|
  dirs = $LOAD_PATH
  spec = searcher.find(arg)
  if spec
    if $search_gems_first
      dirs = gem_paths(spec) + $LOAD_PATH
    else
      dirs = $LOAD_PATH + gem_paths(spec)
    end
    puts "(checking gem #{spec.full_name} for #{arg})" if $verbose
  end
  paths = find_paths(arg, dirs)
  if paths.empty?
    puts "Can't find #{arg}"
  else
    puts paths
  end
end