recipes/__init__.py
author David Douard <david.douard@logilab.fr>
Tue, 13 Jan 2015 14:19:00 +0100
changeset 1783 e3aad84adf03
parent 1781 37db6358b486
permissions -rw-r--r--
[pkg] prepare 4.0.0

#
from os import listdir
from os.path import join, dirname, isfile

def create_recipes(cnx, recipes_directory, update=False):
    """Create Recipe entities from python files found in
    `recipes_directory` (or the parent directory if it's a file).

    For each python file, add a Recipe which name is the python
    filename (without its .py extension) and with the file's content
    as Recipe.script value.

    If `update` is True, existing Recipe are updated (matches
    Recipe.name)
    """
    recipes = []
    if isfile(recipes_directory):
        recipes_directory = dirname(recipes_directory)
    for recipe in listdir(recipes_directory):
        if recipe.endswith('.py') and not recipe.startswith('_'):
            try:
                rname = recipe[:-3].decode('utf-8')
                script = open(join(recipes_directory, recipe)).read().decode('utf-8')
                rset = cnx.execute('Recipe R WHERE R name %(name)s',
                                   {'name': rname})
                if rset and update:
                    r = rset.one()
                    r.cw_set(script=script)
                else:
                    r = cnx.create_entity('Recipe',
                                          name=rname,
                                          script=script)
                recipes.append(r)
            except Exception as exc:
                print "ERROR:", exc
                cnx.warning('Failed to create Recipe %s (%s)'%(rname, exc))
    return recipes