Merge contents.

    It does a simply merge of all files defined under 'static' key.

    If you have JS or CSS file with embeded django tags like {% url ... %} or
    {% static ... %} you should declare them under 'template' key. This
    function will render them and append to the merged output.

    To use the render option you have to define both 'config' and 'path' on
    merger dictionary.

def merge(obj):
    """
    Merge contents.

    It does a simply merge of all files defined under 'static' key.

    If you have JS or CSS file with embeded django tags like {% url ... %} or
    {% static ... %} you should declare them under 'template' key. This
    function will render them and append to the merged output.

    To use the render option you have to define both 'config' and 'path' on
    merger dictionary.
    """

    merge = ''

    for f in obj.get('static', []):
        print 'Merging: {}'. format(f)
        merge += _read(f)

    def doless(f):
        print 'Compiling LESS: {}'.format(f)
        ret, tmp = commands.getstatusoutput('lesscpy '+f)
        if ret == 0:
            return tmp
        else:
            print 'LESS to CSS failed for: {} (Do you have lesscpy installed?)'.format(f)
        return ''

    if merger.get('config'): #only imports django if we have a config file defined
        import re

        for p in merger['path']: sys.path.append(p)
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", merger['config'])

        try:
            from django.template.loader import get_template_from_string
            from django.template.base import Context
            from django.utils.encoding import smart_str
            from django.conf import settings
        except:
            print 'Do you really have django well installed?'
            sys.exit(1)

        for f in obj.get('template', []):
            print 'Merging django template: {}'. format(f)
            t = _read(f)

            if settings.FORCE_SCRIPT_NAME:
                t = re.sub(r'\{%\s+url\b', settings.FORCE_SCRIPT_NAME+'{% url ', t)

            tmp = smart_str(get_template_from_string(t).render(Context({})))

            if f.endswith('.less'):
                pass
                #TODO compilar tmp para css

            merge += tmp

    for f in obj.get('less', []):
        merge += doless(f)

    return merge