#!/usr/bin/env ruby

# Facets Rakefile

require 'autorake'

#
# Generate facet/ redirection files
#
# Build facet redirect directory. This generates
# a file for every lib core/ and more/ entry.
#

LIBDIR = 'lib'
REDIR  = 'facet'
SRCDIR = 'facets'

desc "Create redirection facet/ lib"
task :redirect do
  count = 0
  dest = File.join( LIBDIR, REDIR )
  FileUtils.rm_r(dest) if File.directory?(dest)
  Dir.chdir( LIBDIR ) do
    ['core','more'].each{ |d|
      from = File.join( SRCDIR, d )
      files = Dir.glob( File.join( from, '**/*.rb' ) )
      files.each { |e|
        re = Regexp.new( Regexp.escape( from + '/' ) )
        link = e.sub( re, 'facet/')
        FileUtils.mkdir_p( File.dirname( link ) )
        File.open( link, "w+" ) { |w| w << "require '#{e}'" }
        count += 1
      }
    }
  end
  puts "Created #{count} redirection files in #{REDIR}/ folder."
end


#
# Generate API documentation
#
# Rdoc w/ subtasks 'all', 'more' or 'core',
# where teh deafult it 'all'.
#

#desc "rdoc all libs"
#task :rdocs => [:rdoc_core, :rdoc_more] do 
#end

#desc "rdoc for core lib"
#task :rdocs_core do
#  project.rdoc(YAML.load(<<-END))
#    title: Facets/CORE
#    include:
#      - 'lib/facets/core/**/*'
#      - '[A-Z]*'
#    output: doc/rdoc/core
#  END
#end

#desc "rdocs for more lib"
#task :rdocs_more do
#  project.rdoc(YAML.load(<<-END))
#    title: Facets/MORE
#    include:
#      - 'lib/facets/more/**/*'
#      - '[A-Z]*'
#    output: doc/rdoc/more
#  END
#end


#
# List core methods
#
# Output a list of all methods.
#

MTHPATH = "lib/facets/core"

desc "Output core method list"
task :list do
  index_methods
  puts method_list_outline
end

private

# Read in the facets directory and sort-out per class

METHODS = {}

def index_methods
  Dir.chdir(MTHPATH) do
    dg = Dir.glob('*/**/*.rb')
    dg.each { |f|
      klass, *meth= f.split('/')
      METHODS[ klass ] ||= []
      METHODS[ klass ] << "#{meth.join('/').chomp('.rb')}"
    }
    METHODS.keys.each { |k| METHODS[k].sort! }
  end
end

def method_list_outline
  s = ''
  METHODS.keys.sort.each { |k|
  ms = METHODS[k].collect{|m| m.gsub(%r{^self\/},'::')}.sort
    s << "#{k}:\n"
    ms.each { |m| s << "  #{m}\n" }
  }
  s
end

desc "Build fiery facets"
task :fiery => ['lib/fieryfacets.rb'] do
  puts "Fiery Facets Complete!"
end

file 'lib/fieryfacets.rb' do
  core = Dir.glob('lib/facets/core/**/*')
  core.reject!{ |f| ! File.file?(f) }

  str = ''
  core.each do |f|
    str << File.read(f)
    str << "\n\n"
  end

  str.gsub!(/^\s*[#].*?$/,'')
  str.gsub!(/^=begin.*?=end/m, '')
  str.gsub!(/^\s*require.*?$/, '')
  str.gsub!(/^\s*\n/,'')

  File.open('lib/fieryfacets.rb','w') do |f|
    f << str
  end
end

desc "list files that lack tests"
task :notest do
  stubs  = `grep -lr "#\s*stub" lib/facets/*`
  stubs = stubs.split("\n")
  tested = `grep -Lr "=begin test" lib/facets/*`
  tested = tested.split("\n")
  tested -= stubs
  puts tested.join("\n")
end

