# $Idaemons: /home/cvs/pkgtools/lib/pkgmisc.rb,v 1.1 2001/10/04 21:57:41 knu Exp $

if RUBY_VERSION < "1.7"
  Dir.instance_eval %{
    alias _chdir chdir

    def chdir(dir)
      if block_given?
	pwd = Dir.pwd

	begin
	  Dir._chdir(dir)
	  yield
	ensure
	  Dir._chdir(pwd)
	end
      else
	Dir._chdir(dir)
      end
    end
  }
end

module Enumerable
  def partition
    a = []
    b = []
    each do |x|
      if yield(x)
	a << x
      else
	b << x
      end
    end

    return a, b
  end
end

class Array
  def qindex(item)
    lower = -1
    upper = size()
    while lower + 1 != upper
      mid = (lower + upper) / 2

      cmp = self[mid] <=> item

      cmp.zero? and return mid

      if cmp < 0
	lower = mid
      else
	upper = mid
      end
    end

    nil
  end

  alias qinclude? qindex
end

require "shellwords"
include Shellwords

def shelljoin(*args)
  args.collect { |arg|
    if /[*?{}\[\]<>()~&|\\$;\'\`\"\s]/ =~ arg
      '"' + arg.gsub(/([$\\\"\`])/, "\\\\\\1") + '"'
    else
      arg
    end
  }.join(' ')
end
