view site_scons/site_tools/copyrecurse/copytree.py @ 17:15107282d9eb

Redefined SYSCONFDIR installation path variable so that it appends APPNAME. * Although this deviates from GNU standards this relatively minor change makes it easier to write paths that are portable to Windows.
author M. George Hansen <technopolitica@gmail.com>
date Thu, 09 Jun 2011 21:40:51 -1000
parents 4706e0194af3
children
line wrap: on
line source

import os.path
import shutil
import fnmatch

def copytree(src, dest, include_pattern='*', exclude_pattern='.*',
             symlinks=False):
    """My own copyTree which does not fail if the directory exists.
    
    Recursively copy a directory tree using copy2().

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.
    
    Behavior is meant to be identical to GNU 'cp -R'.
    """
    def copyItems(src, dest, include_pattern='*', exclude_pattern='.*',
                  symlinks=False):
        """Function that does all the work.
        
        It is necessary to handle the two 'cp' cases:
        - destination does exist
        - destination does not exist
        
        See 'cp -R' documentation for more details
        """
        for item in os.listdir(src):
            if not fnmatch.fnmatch(item, include_pattern) or \
               fnmatch.fnmatch(item, exclude_pattern):
                # Thow out anything that isn't matched by our include filter
                # or that is matched by our exclude filter.
                continue
            srcPath = os.path.join(src, item)
            if os.path.isdir(srcPath):
                srcBasename = os.path.basename(srcPath)
                destDirPath = os.path.join(dest, srcBasename)
                if not os.path.exists(destDirPath):
                    os.makedirs(destDirPath)
                copyItems(srcPath, destDirPath, include_pattern,
                          exclude_pattern)
            elif os.path.islink(item) and symlinks:
                linkto = os.readlink(item)
                os.symlink(linkto, dest)
            else:
                shutil.copy2(srcPath, dest)

    # case 'cp -R src/ dest/' where dest/ already exists
    if os.path.exists(dest):
        destPath = os.path.join(dest, os.path.basename(src))
        if not os.path.exists(destPath):
            os.makedirs(destPath)
    # case 'cp -R src/ dest/' where dest/ does not exist
    else:
        os.makedirs(dest)
        destPath = dest
    # actually copy the files
    copyItems(src, destPath, include_pattern, exclude_pattern)