# gem install observr
# observr test/.observr

def sh(cmd)
  pid = spawn(cmd)
  Process.wait(pid)
end

def clear
  puts "\e[H\e[2J"
end

def run_tests(test = nil)
  clear
  test = @last_test if @last_test && test.nil?
  if (ft = focused_tests).any?
    puts "Running focused test(s)..."
    test = ft.join(' ')
  end
  if test && File.exist?(test)
    @last_test = test
    cmd = "ruby #{test}"
    puts cmd
    sh cmd
    puts
    cmd = "make && bin/natalie #{test}"
    puts cmd
    sh cmd
  else
    run_suite
  end
end

def run_suite
  clear
  sh "make test"
end

def focused_tests
  Dir['test/**/*_test.rb'].to_a.select { |f| File.read(f).match(/fit ['"]/) }
end

watch('^test/.*_test\.rb') { |m| run_tests(m.to_s) }
watch('^spec/.*_spec\.rb') { |m| run_tests(m.to_s) }
watch('^src/(.*)\.c'     ) { |m| run_tests }
watch('^src/(.*)\.rb'    ) { |m| run_tests }
watch('^lib/(.*)\.rb'    ) { |m| run_tests }

Signal.trap('QUIT') { run_suite } # Ctrl-\
