#
# $Id: path.py,v 1.5 2001/11/25 14:13:39 doughellmann Exp $
#
# Copyright 2001 Doug Hellmann.
#
#
#                         All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Doug
# Hellmann not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

"""Provide a common set of path management functions.

Many of the os.path functions are fronted by functions here to allow
for tracing and consistent use of those functions.

"""

__rcs_info__ = {
    #
    #  Creation Information
    #
    'module_name'  : '$RCSfile: path.py,v $',
    'rcs_id'       : '$Id: path.py,v 1.5 2001/11/25 14:13:39 doughellmann Exp $',
    'creator'      : 'Doug Hellmann <DougHellmann@bigfoot.com>',
    'project'      : 'UNSPECIFIED',
    'created'      : 'Sat, 03-Feb-2001 12:49:56 EST',

    #
    #  Current Information
    #
    'author'       : '$Author: doughellmann $',
    'version'      : '$Revision: 1.5 $',
    'date'         : '$Date: 2001/11/25 14:13:39 $',
}
try:
    __version__ = __rcs_info__['version'].split(' ')[1]
except:
    __version__ = '0.0'

#
# Import system modules
#
import string
import os
import sys
import glob

#
# Import Local modules
#
from happydoclib.StreamFlushTest import StreamFlushTest

#
# Module
#


def rmkdir(path):
    "Create a directory and all of its children."
    if not path:
        return
    parts = os.path.split(path)
    if len(parts) > 1:
        parent, child = parts
        if not (os.path.isdir(parent) or os.path.islink(parent)):
            rmkdir(parent)
    if not (os.path.isdir(path) or os.path.islink(path)):
        os.mkdir(path)
    return


def applyPrefixToPath(path, prefix):
    "Add the prefix value to every part of a given path."
    parts = string.split( path, os.sep )
    #print 'PARTS:', parts
    prefix_len = len(prefix)
    real_parts = []
    for p in parts:
        if not p:
            pass
        elif p not in ( '.', '..' ) and (p[:prefix_len] != prefix):
            #print 'modifying "%s"' % p
            p = '%s%s' % (prefix, p)
        real_parts.append(p)

    #print 'REAL PARTS:', real_parts
    name = apply(os.path.join, real_parts)
    if path and path[0] == os.sep:
        name = os.sep + name
    return name

def removePrefix(path, prefix):
    "Remove prefix from the beginning of path, if present."
    one_up = os.path.dirname(path)
    common_prefix = commonPrefix(one_up, prefix)
    #print 'PATH: removePrefix( %s, %s )' % (path, prefix)
    #print 'PATH:     common_prefix', common_prefix
    if common_prefix == prefix:
        path = path[len(common_prefix):]
    while path and (path[0] == os.sep):
        path = path[1:]
    #print 'PATH:     result', path
    return path

def commonPrefix(path1, path2):
    """Find parts of path1 and path2 at the beginning of each which are the same.

    Arguments

      path1 -- A filesystem path.

      path2 -- A filesystem path.

    Returns a string containing the full path which occurs at the
    beginning of both path1 and path2.

    This function differs from os.path.commonprefix in that a part of
    the path is considered the same only if the *full* directory or
    subdirectory name matches.
    """
    #print 'commonPrefix(%s, %s)' % (path1, path2)
    if not path1 or not path2:
        return ''
    path1_parts = string.split(path1, os.sep)
    path2_parts = string.split(path2, os.sep)
    common = []
    for p1, p2 in map(None, path1_parts, path2_parts):
        if p1 == p2:
            common.append(p1)
        else:
            break
    common = string.join(common, os.sep)
    if path1 and path1[0] == '/' and common and common[0] != '/':
        common = '/' + common
    #print '->"%s"' % common
    return common

def joinWithCommonMiddle(path1prefix, path1, path2):
    """Join path1 and path2.

    Arguments

      path1prefix -- Beginning of path1 which should be ignored for
                     comparisons between path1 and path2.

      path1 -- First path to join.

      path2 -- Second path to join, may have part of path1 after
               path1prefix.

    This function is a bit weird.  The result of::

      joinWithCommonMiddle('/root/one', '/root/one/two', 'two/three/filename.txt')

    is::

      /root/one/two/three/filename.txt
    
    """
    #
    # Find the part of path1 which is *not* part of path1prefix
    #
    #print 'joinWithCommonMiddle(%s, %s, %s)' % (path1prefix, path1, path2)
    common_prefix = commonPrefix(path1prefix, path1)
    #print '  common prefix:', common_prefix
    real_base = removePrefix(path1, common_prefix)
    #print '  real base:', real_base
    #
    # Remove the prefix common to the docset_real_base and
    # file_name.
    #
    common_prefix = commonPrefix(real_base, path2)
    #print '  common prefix with real base and path2:', common_prefix
    path2 = removePrefix(path2, common_prefix)
    #print '  fixed path2:', path2
            
    name = join( path1, path2 )
    #print '->"%s"' % name
    return name
    

def computeRelativeHTMLLink(fromName, toName, baseDirectory):
    """Compute the relative link between fromName and toName.

    Parameters

      'fromName' -- Named output node from which to compute the link.

      'toName' -- Named output node to which link should point.

      'baseDirectory' -- Name of the base directory in which both
      fromName and toName will reside.
      
    Both fromName and toName are strings refering to URL targets.
    This method computes the relative positions of the two nodes
    and returns a string which, if used as the HREF in a link in
    fromName will point directly to toName.
    """
    dbg=0
    if dbg: print '\nPATH: FROM: ', fromName
    if dbg: print 'PATH: TO  : ', toName
    if dbg: print 'PATH: BASE: ', baseDirectory

    #
    # Normalize directory names
    #
    fromName = os.path.normpath(fromName)
    toName = os.path.normpath(toName)
    if dbg: print 'PATH: FROM NORMALIZED : ', fromName
    if dbg: print 'PATH: TO NORMALIZED   : ', toName
    
    #
    # Remove the base directory prefix from both
    #
    fromName = removePrefix(fromName, baseDirectory)
    toName = removePrefix(toName, baseDirectory)
    if dbg: print 'PATH: FROM - PREFIX : ', fromName
    if dbg: print 'PATH: TO   - PREFIX : ', toName
    
    if fromName == toName:
        if dbg: print '\tPATH: same name'
        relative_link = os.path.basename(toName)
    else:
        common_prefix = commonPrefix(os.path.dirname(fromName), os.path.dirname(toName))
        from_name_no_prefix = fromName[len(common_prefix):]
        while from_name_no_prefix and (from_name_no_prefix[0] == os.sep):
            from_name_no_prefix = from_name_no_prefix[1:]
            if dbg: print '\tPATH: from, no prefix:', from_name_no_prefix
            if dbg and from_name_no_prefix == 'z.html':
                raise 'debug'
        subdir_path = os.path.dirname(from_name_no_prefix)
        parts = string.split(subdir_path, os.sep)
        if dbg: print '\tPATH: parts:', parts
        if parts and parts[0]:
            levels = len(string.split(subdir_path, os.sep))
        else:
            levels = 0
        up_levels = (os.pardir + os.sep) * levels
        to_name_no_prefix = toName[len(common_prefix):]
        if to_name_no_prefix and (to_name_no_prefix[0] == os.sep):
            to_name_no_prefix = to_name_no_prefix[1:]
        relative_link = "%s%s" % (up_levels, to_name_no_prefix)
    if dbg: print 'PATH: LINK: ', relative_link, '\n'
    return relative_link


def findFilesInDir(directoryName, filenamePattern='*'):
    """Find all files in the directory which match the glob pattern.

    Parameters

      directoryName -- String containing the name of a directory on
      the file system.

      filenamePattern -- String containing a regular expression to be
      used by the glob module for matching when looking for files in
      'directoryName'.

    """
    search_pat = os.path.join( directoryName, filenamePattern )
    found = glob.glob( search_pat )
    return found
    

def removeRelativePrefix(filename):
    """Remove './', '../', etc. from the front of filename.

    Returns a new string, unless no changes are made.
    """
    if filename and filename[0] in '.':
        while filename and (filename[0] in './'):
            filename = filename[1:]
    return filename


##
## os.path functions
##
def join( *args ):
    "os.path.join"
    return apply(os.path.join, args)

def cwd():
    "os.getcwd"
    return os.getcwd()

def normpath( p ):
    "os.path.normpath"
    return os.path.normpath(p)

def isdir( f ):
    "os.path.isdir"
    return os.path.isdir(f)

def exists( f ):
    "os.path.exists"
    return os.path.exists(f)

def basename( f ):
    "os.path.basename"
    return os.path.basename(f)

def dirname( f ):
    "os.path.dirname"
    return os.path.dirname(f)

def splitext( f ):
    "os.path.splitext"
    return os.path.splitext(f)

def split( f ):
    "os.path.split"
    return os.path.split(f)


class PathTest(StreamFlushTest):

    def testApplyPrefixToPath(self):
        expected = '/BLAH_tmp/BLAH_foo'
        actual = applyPrefixToPath('/tmp/foo', 'BLAH_')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testApplyPrefixToPathEmpty(self):
        expected = ''
        actual = applyPrefixToPath('', 'BLAH_')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testApplyPrefixToPathRelative(self):
        expected = '../BLAH_tmp/BLAH_foo'
        actual = applyPrefixToPath('../tmp/foo', 'BLAH_')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testRemovePrefix(self):
        expected = 'foo'
        actual = removePrefix('/tmp/foo', '/tmp')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testRemovePrefixNotThere(self):
        expected = 'tmp/foo'
        actual = removePrefix('/tmp/foo', '/blah')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testRemovePrefixEmptyPath(self):
        expected = ''
        actual = removePrefix('', '/blah')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testRemovePrefixEmptyPrefix(self):
        expected = 'tmp/foo'
        actual = removePrefix('/tmp/foo', '')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testCommonPrefix(self):
        expected = '/tmp'
        actual = commonPrefix('/tmp/foo', '/tmp/blah')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testCommonPrefixNone(self):
        expected = ''
        actual = commonPrefix('/var/tmp/foo', '/tmp/blah')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testCommonPrefixEmptyPaths(self):
        expected = ''
        actual = commonPrefix('', '/tmp/blah')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        expected = ''
        actual = commonPrefix('/var/tmp/foo', '')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
        
    def testJoinWithCommonMiddle(self):
        expected = '/root/one/two/three/filename.txt'
        actual = joinWithCommonMiddle('/root/one', '/root/one/two', 'two/three/filename.txt')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testJoinWithCommonMiddleNotCommon(self):
        expected = '/root/one/four/two/three/filename.txt'
        actual = joinWithCommonMiddle('/root/one/five', '/root/one/four', 'two/three/filename.txt')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testJoinWithCommonMiddleEmptyPrefix(self):
        expected = '/root/one/four/two/three/filename.txt'
        actual = joinWithCommonMiddle('', '/root/one/four', 'two/three/filename.txt')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
    
    def testJoinWithCommonMiddleEmptyPath1(self):
        expected = 'two/three/filename.txt'
        actual = joinWithCommonMiddle('/root/one/five', '', 'two/three/filename.txt')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
        
        
    def testJoinWithCommonMiddleEmptyPath2(self):
        expected = '/root/one/two/'
        actual = joinWithCommonMiddle('/root/one', '/root/one/two', '')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testComputeRelativeHTMLLink(self):
        expected = 'my.gif'
        actual = computeRelativeHTMLLink('index.html', 'my.gif', '/tmp/base/dir')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testComputeRelativeHTMLLinkUpOneDirectory(self):
        expected = '../my.gif'
        actual = computeRelativeHTMLLink('index.html', '../my.gif', '/tmp/base/dir')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
        

    def testComputeRelativeHTMLLinkInParentDirectory(self):
        expected = '../my.gif'
        actual = computeRelativeHTMLLink('/tmp/base/dir/index.html',
                                         '/tmp/base/my.gif',
                                         '/tmp/base')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testRemoveRelativePrefixCurrentDir(self):
        expected = 'foo'
        actual = removeRelativePrefix('./foo')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return

    def testRemoveRelativePrefixParentDir(self):
        expected = 'foo'
        actual = removeRelativePrefix('../foo')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
        
    def testJoin(self):
        expected = os.path.join('tmp', 'foo')
        actual = join('tmp', 'foo')
        assert actual == expected, \
               'Path modification failed.\n\tExpected "%s",\n\tgot      "%s"' \
               % (expected, actual)
        return
               
