=begin
= WebUnit::Utils
  Copyright(C) 2001 yuichi TAKAHASHI
  $Id: utils.rb,v 1.1.1.1 2003/01/21 11:50:40 yuichi Exp $

=end

module WebUnit

  module Utils

=begin
--- Utils#parse_url(url)
      return an Array of protocol, hostname, port, and path.

=end

    def parse_url( url )
      if url =~ %r!^([a-z]+)://([-0-9A-Aa-z_.]+):?([0-9]*)(/.*)?$!
        [ $1, $2, $3 == "" ? 80 : $3.to_i, $4 ? $4 : '' ]
      elsif url =~ %r!^file:(/.*)$!
        [ 'file', nil, nil, $1 ]
      else
        [ nil, nil, nil, url ]
      end
    end

=begin
--- Utils#orthop_url(url)
      return url, is orthopped by Utils#parse_url.

=end

    def orthop_url( url )
      prot, host, port, path = parse_url url
      path.gsub!( %r![^/]*/\.\./!, '/' )
      path.gsub!( %r!/\.*/!, '/' )
      "#{prot}://#{host}:#{port}#{path}"
    end

=begin
--- Utils#complete_url(url,base)
      return url, is completed with ((|base||).
=end

    def complete_url( url, base )
      if base
        prot,host,port,path = parse_url( base )
        prefix = prot + "://" + host + ":" + port.to_s
        case url
        when nil then
          url = base.sub( /\?.*/, '' )
        when %r!^http://! then
          url
        when %r!^/! then
          url = prefix + url
        else
          url = prefix + File::dirname( path ) + "/" + url
        end
        orthop_url( url )
      else
        url
      end
    end

  end

end
