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"]
  extension_dirs       = Dir["#{Gem.dir}/extensions/*/*/*"] + Dir["#{Gem.dir}/bundler/gems/extensions/*/*/*"]
  spec_gem_paths       = []
  # need to keep git sources around
  spec_git_paths       = @definition.spec_git_paths
  spec_git_cache_dirs  = []
  spec_gem_executables = []
  spec_cache_paths     = []
  spec_gemspec_paths   = []
  spec_extension_paths = []
  Bundler.rubygems.add_default_gems_to(specs).values.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_extension_paths << spec.extension_dir if spec.respond_to?(:extension_dir)
    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 - ["#{Gem.dir}/bundler/gems/extensions"]
  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
  stale_extension_dirs = extension_dirs - spec_extension_paths
  removed_stale_gem_dirs = stale_gem_dirs.collect {|dir| remove_dir(dir, dry_run) }
  removed_stale_git_dirs = stale_git_dirs.collect {|dir| remove_dir(dir, dry_run) }
  output = removed_stale_gem_dirs + removed_stale_git_dirs
  unless dry_run
    stale_files = stale_gem_bins + stale_gem_files + stale_gemspec_files
    stale_files.each do |file|
      SharedHelpers.filesystem_access(File.dirname(file)) do |_p|
        FileUtils.rm(file) if File.exist?(file)
      end
    end
    stale_dirs = stale_git_cache_dirs + stale_extension_dirs
    stale_dirs.each do |stale_dir|
      SharedHelpers.filesystem_access(stale_dir) do |dir|
        FileUtils.rm_rf(dir) if File.exist?(dir)
      end
    end
  end
  output
end