class Bundler::Runtime

def clean(dry_run = false)

def clean(dry_run = false)
  gem_bins             = Dir["#{Gem.dir}/bin/*"]
  git_dirs             = Dir["#{Gem.dir}/bundler/gems/*"]
  git_cache_dirs       = Dir["#{Gem.dir}/cache/bundler/git/*"]
  gem_dirs             = Dir["#{Gem.dir}/gems/*"]
  gem_files            = Dir["#{Gem.dir}/cache/*.gem"]
  gemspec_files        = Dir["#{Gem.dir}/specifications/*.gemspec"]
  spec_gem_paths       = []
  # need to keep git sources around
  spec_git_paths       = @definition.sources.select {|s| s.is_a?(Bundler::Source::Git) }.map {|s| s.path.to_s }
  spec_git_cache_dirs  = []
  spec_gem_executables = []
  spec_cache_paths     = []
  spec_gemspec_paths   = []
  specs.each do |spec|
    spec_gem_paths << spec.full_gem_path
    # need to check here in case gems are nested like for the rails git repo
    md = %r{(.+bundler/gems/.+-[a-f0-9]{7,12})}.match(spec.full_gem_path)
    spec_git_paths << md[1] if md
    spec_gem_executables << spec.executables.collect do |executable|
      e = "#{Bundler.rubygems.gem_bindir}/#{executable}"
      [e, "#{e}.bat"]
    end
    spec_cache_paths << spec.cache_file
    spec_gemspec_paths << spec.spec_file
    spec_git_cache_dirs << spec.source.cache_path.to_s if spec.source.is_a?(Bundler::Source::Git)
  end
  spec_gem_paths.uniq!
  spec_gem_executables.flatten!
  stale_gem_bins       = gem_bins - spec_gem_executables
  stale_git_dirs       = git_dirs - spec_git_paths
  stale_git_cache_dirs = git_cache_dirs - spec_git_cache_dirs
  stale_gem_dirs       = gem_dirs - spec_gem_paths
  stale_gem_files      = gem_files - spec_cache_paths
  stale_gemspec_files  = gemspec_files - spec_gemspec_paths
  output = stale_gem_dirs.collect do |gem_dir|
    full_name = Pathname.new(gem_dir).basename.to_s
    parts   = full_name.split('-')
    name    = parts[0..-2].join('-')
    version = parts.last
    output  = "#{name} (#{version})"
    if dry_run
      Bundler.ui.info "Would have removed #{output}"
    else
      Bundler.ui.info "Removing #{output}"
      FileUtils.rm_rf(gem_dir)
    end
    output
  end + stale_git_dirs.collect do |gem_dir|
    full_name = Pathname.new(gem_dir).basename.to_s
    parts    = full_name.split('-')
    name     = parts[0..-2].join('-')
    revision = parts[-1]
    output   = "#{name} (#{revision})"
    if dry_run
      Bundler.ui.info "Would have removed #{output}"
    else
      Bundler.ui.info "Removing #{output}"
      FileUtils.rm_rf(gem_dir)
    end
    output
  end
  unless dry_run
    stale_gem_bins.each { |bin| FileUtils.rm(bin) if File.exist?(bin) }
    stale_gem_files.each { |file| FileUtils.rm(file) if File.exist?(file) }
    stale_gemspec_files.each { |file| FileUtils.rm(file) if File.exist?(file) }
    stale_git_cache_dirs.each { |dir| FileUtils.rm_rf(dir) if File.exist?(dir) }
  end
  output
end