shinypress / shinypress /

from itertools import izip as zip
import re

def matches(mime, exp):
    Check if the given MIME type mime matches the MIME type expression exp.

    If the two MIME types are exactly equal, this will return True:
    >>> mime_matches('text/plain', 'text/plain')

    This also supports wildcard matches, but not across multiple components
    >>> mime_matches('text/plain', 'text/*')
    >>> mime_matches('text/plain/quack', 'text/*')

    It also works fine with prefixes and suffixes on the wildcard:
    >>> mime_matches('text/x-tex', 'text/x*ex')
    >>> mime_matches('text/x-tex', 'text/a*b')
    # TODO: read the MIME type spec (is it a RFC?), to find out if this is sane.
    if mime == exp:
        return True

    all_matched = True

    mime_components = mime.split('/')
    exp_components = exp.split('/')

    if len(mime_components) != len(exp_components):
        return False

    for left, right in zip(mime_components, exp_components):
        regex = '.*'.join(re.escape(x) for x in right.split('*'))
        if not re.match(regex, left):
            all_matched = False

    return all_matched

def any_matches(mime, exps):
    return any(
        matches(mime, exp)
        for exp in exps

def get_preferred(mime, preferred):
    Find the first mime type expression in preferred which matches the given
    mime type. If no mime type matches, return None.

    >>> get_preferred_mime_type('text/plain', ['text/plain', 'text/*'])
    >>> get_preferred_mime_type('text/plain', ['text/*', 'text/plain'])
    >>> get_preferred_mime_type('image/jpeg', ['text/plain', 'image/*', '*/*'])
    >>> get_preferred_mime_type('image/jpeg', ['*/*', 'image/jpeg', 'image/*'])
    >>> get_preferred_mime_type('image/jpeg', ['image/png', 'text/*'])
    for target in preferred:
        if matches(mime, target):
            return target