import posix, string, urlparse

def is_local(url):
    parsedurl=urlparse.urlparse(url)
    if parsedurl[0]!='' and parsedurl[1]!="":
	return 0
    return 1

def construct_path(path, relative):
    if not path:
	return relative
    if path[0]=="/" or not relative:
	return path
    if relative[-1]!="/":
	relative=relative+"/"
    return relative+path

def strip_filename(filepath):
    return string.join(string.split(filepath, "/")[:-1], "/")
def get_filename(filepath):
    return string.split(filepath, "/")[-1]

def add_filename(path, filename):
    if not path:
	return filename
    if path[-1]!="/": path=path+"/"
    return path+filename

def canonical(path):
    new_path=string.split(construct_path(path, posix.getcwd()), "/")
    i=0
    while 1:
	if i>=len(new_path):
	    break
	if new_path[i]=="." or new_path[i]=="":
	    new_path[i:i+1]=[]
	elif new_path[i]=="..":
	    new_path[i-1:i+1]=[]
	    i=i-1
	else:
	    i=i+1
    return "/"+string.join(new_path, "/")

def relative_to(path_source, path_relative):
    path_source=canonical(path_source)
    path_relative=canonical(path_relative)
    source=string.split(path_source, "/")
    relative=string.split(path_relative, "/")
    i=0
    while i<len(relative):
	if len(source)<=i or relative[i]!=source[i]:
	    break
	i=i+1
    return string.join([".."]*(len(relative)-i)+source[i:], "/")
	
