1. David Chambers
  2. Mango

Source

Mango / utils.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import htmlentitydefs
import os
import re

from mango.exceptions import EmptySettingError
from mango.settings import *

def absolutize(path):
    """
    Returns the absolute path of `path`. If `path` is not (already) an absolute
    path, it is assumed to be relative to the project directory.
    
    >>> absolutize('mango/examples') == absolutize('mango/../mango/examples/')
    True
    """
    path = path.rstrip(u'/')
    if os.path.isabs(path):
        return path
    fragments = []
    head, tail = os.path.split(path)
    while tail:
        fragments.insert(0, tail)
        head, tail = os.path.split(head)
    return os.path.abspath(os.path.join(PROJECT_PATH, *fragments))

def posts_directory():
    """ Creates "posts" directory if it does not already exist. """
    try:
        os.makedirs(DOCUMENTS_PATH)
    except OSError:
        if not os.path.exists(DOCUMENTS_PATH):
            raise OSError('Unable to create %s. Check permissions.' % DOCUMENTS_PATH)

def primary_author_email():
    """
    Returns the primary author's e-mail address as specified in Mango's
    settings file.
    
    >>> primary_author_email()
    u'... <...@...>'
    """
    if not PRIMARY_AUTHOR_EMAIL:
        raise EmptySettingError('PRIMARY_AUTHOR_EMAIL setting is empty',
                'Add PRIMARY_AUTHOR_EMAIL to `mango/settings/custom.py`.')

    name = PRIMARY_AUTHOR_NAME
    email = PRIMARY_AUTHOR_EMAIL
    if name and email:
        email = '%s <%s>' % (name, email)
    return email

# taken from http://effbot.org/zone/re-sub.htm#unescape-html (thanks, Fredrik!)
def unescape(text):
    """
    Removes HTML or XML character references and entities from a text string.
    
    >>> unescape('E = mc&#178;')
    u'E = mc\\xb2'
    >>> unescape('Jack &amp; Jill')
    u'Jack & Jill'
    """
    def fixup(m):
        text = m.group(0)
        if text[:2] == '&#':
            # character reference
            try:
                if text[:3] == '&#x':
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass # leave as is
        return text
    return re.sub('&#?\w+;', fixup, text)