#!/usr/bin/env python
#
# $Id: hdpath.py,v 1.5 2001/03/18 18:31:21 doughellmann Exp $
#
# Time-stamp: <01/03/18 13:24:19 dhellmann>
#
# 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: hdpath.py,v $',
    'rcs_id'       : '$Id: hdpath.py,v 1.5 2001/03/18 18:31:21 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/03/18 18:31:21 $',
}

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

#
# Import Local modules
#


#
# 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 )
    real_parts = []
    for p in parts:
        if p in ( '.', '..' ):
            real_parts.append(p)
        else:
            real_parts.append( '%s%s' % (prefix, p) )
    name = apply(os.path.join, real_parts)
    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)
    if common_prefix == prefix:
        path = path[len(common_prefix):]
    while path and (path[0] == os.sep):
        path = path[1:]
    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 '\nFROM: ', fromName
    #if dbg: print 'TO  : ', toName
    #if dbg: print 'BASE: ', baseDirectory

    #
    # Normalize directory names
    #
    fromName = os.path.normpath(fromName)
    toName = os.path.normpath(toName)
    #if dbg: print 'FROM NORMALIZED : ', fromName
    #if dbg: print 'TO NORMALIZED   : ', toName
    
    #
    # Remove the base directory prefix from both
    #
    fromName = removePrefix(fromName, baseDirectory)
    toName = removePrefix(toName, baseDirectory)
    #if dbg: print 'FROM - PREFIX : ', fromName
    #if dbg: print 'TO   - PREFIX : ', toName
    
    if fromName == toName:
        #if dbg: print '\tsame 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 '\tfrom, 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 '\tparts:', 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 '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.
    """
    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)
