"""FTP Filename globbing utility."""

import ftputil
import fnmatch
import re

__all__ = ["ftpglob"]

def ftpglob(connection,pathname):
    """Return a list of paths matching a pathname pattern.

    The pattern may contain simple shell-style wildcards a la fnmatch.

    """
    if not has_magic(pathname):
        if connection.path.exists(pathname):
            return [pathname]
        else:
            return []
    dirname, basename = connection.path.split(pathname)
    if not dirname:
        return ftpglob1(connection, connection.curdir, basename)
    elif has_magic(dirname):
        list = ftpglob(connection,dirname)
    else:
        list = [dirname]
    if not has_magic(basename):
        result = []
        for dirname in list:
            if basename or connection.path.isdir(dirname):
                name = connection.path.join(dirname, basename)
                if connection.path.exists(name):
                    result.append(name)
    else:
        result = []
        for dirname in list:
            sublist = ftpglob1(connection, dirname, basename)
            for name in sublist:
                result.append(connection.path.join(dirname, name))
    return result

def ftpglob1(connection, dirname, pattern):
    if not dirname: dirname = connection.curdir
    try:
        names = connection.listdir(dirname)
    except ftputil.FTPError:
        return []
    if pattern[0]!='.':
        names=filter(lambda x: x[0]!='.',names)
    return fnmatch.filter(names,pattern)

magic_check = re.compile('[*?[]')

def has_magic(s):
    return magic_check.search(s) is not None

