#!/usr/bin/ruby

require 'rdoc/ri/driver'

def load_object file
  open file, 'rb' do |io|
    Marshal.load io.read
  end
end

ARGV.each do |path|
  store = RDoc::RI::Store.new path

  Dir[File.join(path, '**/*.ri')].each do |file|
    case File.basename file
    when /^cdesc-.*\.ri$/
      klass = load_object file

      store.cache[:modules] << klass.full_name

      ancestors = klass.ancestors.compact.map do |ancestor|
        # HACK for classes we don't know about (class X < RuntimeError)
        String === ancestor ? ancestor : ancestor.full_name
      end

      store.cache[:ancestors][klass.full_name] ||= []
      store.cache[:ancestors][klass.full_name].push(*ancestors)

      attributes = klass.attributes.map do |attribute|
        "#{attribute.type} #{attribute.name}"
      end

      unless attributes.empty? then
        store.cache[:attributes][klass.full_name] ||= []
        store.cache[:attributes][klass.full_name].push(*attributes)
      end
    when /^.*-[ic]\.ri$/
      method = load_object file
      klass_name = method.parent_name

      cache = if method.singleton then
                store.cache[:class_methods]
              else
                store.cache[:instance_methods]
              end
      cache[klass_name] ||= []
      cache[klass_name] << method.name
    end
  end

  store.save_cache
end
