#!/usr/bin/env python
# Copyright (c) 2002 Nathan Sharfi
# Copyright terms are included in a file called 'license.txt'.

"""I  contain utilities for accessing files on the OS' hard disk."""

import os, re

class InvalidDirectoryError(IOError):
    def __init__(self, directory):
        self.directory = directory
    def __str__(self):
        return "Invalid Directory: %s" % (self.directory)

class InvalidDirectoryWarning(UserWarning):
    def __init__(self, directory):
        self.directory = directory
    def __str__(self):
        return "Invalid Directory: %s" % (self.directory)

def swapExtension(filename, ext):
    if ext[0] != '.':
        ext = '.' + ext
    return os.path.splitext(filename)[0] + ext

def extensionMatch(filename, ext):
    "I return True if filename has ext as its extension."
    return os.path.splitext(filename)[1] == ext

# -----------------------------------------------------------------------------
def filterDirectory(pred, directory):
    """I return a list of filenames in directory where pred(filename) is true.
    pred."""
    if not os.path.isdir(directory):
        raise InvalidDirectoryError(directory)
    
    l = map(os.path.normcase, os.listdir(directory))
    l = [ os.path.join(directory, f) for f in l if pred(f) ]
    return l

def filterMove(pred, src, dest):
    """Move all files from src to dest if pred(filename) is true."""
    # test stuff.
    if not os.path.isdir(src):
        raise InvalidDirectoryError(src)
    if not os.path.isdir(dest):
        warn('%s does not exist, creating...' % (dest),
             InvalidDirectoryWarning(dest))
        os.path.mkdir(dest)
    
    
    files = filterDirectory(pred, src)
    for f in files:
        os.renames(f, os.path.join(dest, f))

if __name__ == '__main__':
    print 'try the unit test!'
    
