# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "pathname"

class String
  def path
    Pathname.new(self)
  end
end

class Pathname
  def path
    self
  end

  def to_win_dir
    self.to_s.sub(%r!\A/cygdrive/(\w)!){|a| $1+":" } # /cygdrive/c -> c:
  end

  def check_directory
    if exist?
      raise self.to_s+" is not directory. failed." if !directory?
      return
    end
    mkdir
  end

  def erase_all
    self.each_entry {|file|
      base = file.to_s
      next if base == "." || base == ".."
      f = self+file
      if f.directory?
	f.erase_all
	next
      end
      if f.exist?
	f.unlink
      end
    }
  end

  def remove_directory
    if exist?
      if directory?
	rmtree
	rmdir if directory?
      else
	raise self.to_s+" is not directory. failed."
      end
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  require "qwik/test-module-path"
  $debug = true
end

if defined?($debug) && $debug
  class TC_UtilPath < Test::Unit::TestCase
    def test_path
      # test_string_path
      assert_instance_of(Pathname, "t".path)
      assert_equal("t", "t".path.to_s)

      # test_path_path
      assert_instance_of(Pathname, "t".path.path)

      # test_to_win_dir
      assert_equal("c:/t", "/cygdrive/c/t".path.to_win_dir)

      # test_erase_all
      dir = "./test".path
      dir.check_directory
      file = "./test/t.txt".path
      file.open("wb") {|f| f.print "t" }
      assert_equal(true, file.exist?)
      dir.erase_all
      assert_equal(false, file.exist?)
      assert_equal(true, dir.exist?)
    end

    def test_check_directory
      return if $0 != __FILE__	# just only for unit test.

      dir = "./test".path
      dir.erase_all if dir.exist?
      dir.rmtree if dir.exist?
      dir.rmdir if dir.exist?
      assert_equal(false, dir.exist?)
      dir.check_directory
      assert_equal(true, dir.exist?)
      dir.check_directory # no error
      assert_equal(true, dir.exist?)
      dir.erase_all
      dir.rmdir
      assert_equal(false, dir.exist?)

      file = "./t.txt".path
      file.open("wb") {|f| f.print "t" }
      assert_raise(RuntimeError) {
	file.check_directory
      }
      file.unlink
    end

    def test_check_pathname
      dir = "./test".path
      dir.rmtree if dir.exist?
      dir.rmdir  if dir.exist?
      dir.mkdir
      assert_equal(true, dir.exist?)
      file = dir+"t"
      file.open("wb"){|f|
	f.print "test"
      }
      assert_equal(true, file.exist?)
      dir.rmtree
      assert_equal(false, dir.exist?)

      # test_extname
      assert_equal("", "t".path.extname)
      assert_equal(".txt", "t.txt".path.extname)
      assert_equal(".gz", "t.tar.gz".path.extname)

      # test_chdir     
      pwd = Dir.pwd
      Dir.chdir("/") {
	assert_not_equal(pwd, Dir.pwd)
      }
      assert_equal(pwd, Dir.pwd)
    end
  end
end
