#!/usr/pkg/bin/ruby40
# -*- ruby -*-

require 'optparse'

testrbargv = []
automatic = false

opts = OptionParser.new("", 24, '  ') { |opts|
  opts.banner = "Usage: specrb [options] [files | -a] [-- untouched arguments]"

  opts.separator ""
  opts.separator "Ruby options:"

  lineno = 1
  opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line|
    eval line, TOPLEVEL_BINDING, "-e", lineno
    lineno += 1
  }

  opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") {
    $DEBUG = true
  }
  opts.on("-w", "--warn", "turn warnings on for your script") {
    $-w = true
  }

  opts.on("-I", "--include PATH",
          "specify $LOAD_PATH (may be used more than once)") { |path|
    $LOAD_PATH.unshift(*path.split(":"))
  }

  opts.on("-r", "--require LIBRARY",
          "require the library, before executing your script") { |library|
    require library
  }

  opts.separator ""
  opts.separator "test/spec options:"

  opts.on("-s", "--specdox", "do AgileDox-like output") {
    testrbargv << "--runner=specdox"
  }
  opts.on("--rdox", "do AgileDox-like output with RDoc formatting") {
    testrbargv << "--runner=rdox"
  }

  opts.on("-a", "--automatic", "gather tests from ./test/, include ./lib/") {
    $LOAD_PATH.unshift "lib"  if File.directory? "lib"
    automatic = true
  }

  opts.separator ""
  opts.separator "test/unit options:"

  opts.on('-n', '--name NAME', String,
          "runs tests matching regexp NAME") { |n|
    testrbargv << "-n" << "/#{n}/"
  }
  
  opts.on('-t', '--testcase TESTCASE', String,
          "runs tests in TestCases matching regexp TESTCASE") { |t|
    testrbargv << "-t" << "/#{t}/"
  }

  opts.separator ""
  opts.separator "Common options:"

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

  opts.on_tail("--version", "Show version") do
    require 'test/spec'
    puts "specrb #{Test::Spec::VERSION}"
    exit
  end

  opts.parse! ARGV
}

files = ARGV

if automatic
  files.concat Dir["test/test_*.rb"]
  files.concat Dir["test/spec_*.rb"]
  files.concat Dir["spec/spec_*.rb"]
end

if files.empty?
  puts opts.banner
  exit 1
end

argv = testrbargv + files 
# Should use -- to separate them *but* there's a bug in
# Test::Unit::AutoRunner#process_args: arguments after -- are ignored.
# (You could also argue that it's a bug in optparse.rb).

require 'test/spec'

Test::Unit.run = false
runner = Test::Unit::AutoRunner.new true
runner.process_args(argv) ||
  abort("internal error calling Test::Unit, please report a bug")
exit runner.run
