# -*- ruby -*-

Gem.refresh

require 'autotest/restart'
require 'autotest/isolate'

Autotest.add_hook :run_command do |_, cmd|
  cmd.sub! ' -e ', ' -we '
end

Autotest.add_hook :initialize do |at|
  at.testlib = ''

  at.failed_results_re = /^\s+\d+\) (?:Failure|Error):\n(.*?):/
  at.completed_re = /\d+ tests, \d+ assertions, \d+ failures, \d+ errors/

  at.add_exception %r%/\.git/%
  at.add_exception %r%\.rbc$%
  at.add_exception %r%test/rubygems/rubygems%

  at.find_directories.clear
  at.find_directories.push 'lib', 'test'

  at.add_mapping %r%^lib/rubygems.rb$% do |_, m|
    "test/rubygems/test_gem.rb"
  end

  at.add_mapping %r%^lib/rubygems/(.*).rb$% do |_, m|
    "test/rubygems/test_gem_#{m[1].gsub '/', '_'}.rb"
  end

  args = ARGV.reject { |a| a =~ /^-/ }
  at.find_directories = args unless args.empty?

  def at.handle_results results
    results = results.gsub(/\e\[\d+m/, '') # strip ascii color
    failed = results.scan(self.failed_results_re).map { |m, k|
      /(?<k>\w+)#(?<m>\w+)/ =~ m
      [m, k]
    }

    completed = results[self.completed_re]

    if completed then
      completed = completed.scan(/(\d+) (\w+)/).map { |v, k| [k, v.to_i] }

      self.latest_results = Hash[*completed.flatten]
      self.files_to_test  = consolidate_failures failed

      color = failed.empty? ? :green : :red
      hook color unless $TESTING
    else
      self.latest_results = nil
    end

    self.tainted = true unless self.files_to_test.empty?
  end

  def at.path_to_classname s
    sep = File::SEPARATOR

    f = s.sub(/^test#{sep}rubygems#{sep}/, '').sub(/\.rb$/, '').split sep

    f = f.map { |path| path.split(/_|(\d+)/).map { |seg| seg.capitalize }.join }

    f.join('::').
      gsub('Rdoc', 'RDoc').
      gsub('GemDependencyApi', 'GemDependencyAPI')
  end
end
