Exemple #1
0
def generate_feed(req):
    prefix = lib.absolute_prefix()
    news = _enum_news()
    feed = ""
    lastmodified = ""
    for id in news:
        filename = lib.valid_dir(djoin(dirname(__file__), basename(id)))
        filename = filename + ".md" if exists(filename +
                                              ".md") else filename + ".news"
        if id == news[0]: lastmodified = lib.get_time_for_file(filename, True)
        content, headline, author = parse_news(id)
        content = sub('style=".*?"', "", escape(content))
        uri = djoin(lib.get_config("CanonicalName"), prefix, "News",
                    "?id=" + id)
        feed += lib.get_template("feedentry") % {
            "uri": uri,
            "title": headline,
            "mtime": lib.get_time_for_file(filename, True),
            "content": content,
            "author": author
        }
    req.content_type = "application/atom+xml; charset=UTF-8"
    return lib.get_template("feed") % {
        "uri":
        djoin(lib.get_config("CanonicalName"), prefix),
        "self":
        djoin(lib.get_config("CanonicalName"), prefix, "News", "?feed=true"),
        "mtime":
        lastmodified,
        "content":
        feed
    }
Exemple #2
0
def execute(argv, argv0, engine):
    import lib, inflection, re
    os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings")
    from aioweb import settings

    sys.path.append(os.getcwd())
    if len(argv) < 2:
        usage(argv0)

    controller_name = inflection.camelize(argv[0]) + "Controller"
    controller_file_name = inflection.underscore(argv[0]) + ".py"
    method_name = inflection.underscore(argv[1])

    controllers_dir = lib.dirs(settings, format=["tests_controllers"])
    dest_file = os.path.join(controllers_dir, controller_file_name)

    os.makedirs(os.path.dirname(dest_file), exist_ok=True)
    template = lib.get_template("tests/controller_method.py", settings)

    if not os.path.exists(dest_file):
        print("Sorry but {} does not exist!".format(dest_file))
        return

    print("adding 'test_{}' to {}".format(method_name, dest_file))

    with open(template, "r") as f:
        method_code = f.read().replace("METHOD", method_name).replace(
            "CLASS", controller_name).replace("CONTROLLER_NAME",
                                              controller_file_name[:-3])

    lib.insert_in_python(dest_file, ["class test_{}".format(controller_name)],
                         method_code.split("\n"),
                         in_end=True,
                         ignore_pass=True)
Exemple #3
0
def parse_news(id, req=None):
    if not type(id) is str: return

    newstpl = lib.get_template("news")
    filename = lib.valid_dir(djoin(dirname(__file__), basename(id)))
    if exists(filename + ".news"):
        filename += ".news"
        mode = "plain"
    elif exists(filename + ".md"):
        filename += ".md"
        mode = "markdown"
    else:
        raise Exception()

    time = lib.get_time_for_file(filename)
    with open(filename) as newsfile:
        author = lib.escape(newsfile.readline().replace("\n", ""))
        headline = lib.escape(newsfile.readline().replace("\n", ""))
        newscontent = lib.escape("\n".join(newsfile.readlines()))

    if mode is "markdown":
        newscontent = markdown(newscontent)

    return (newstpl % {
        "headline": headline,
        "author": author,
        "date": time,
        "id": id,
        "content": newscontent,
        "uri": lib.ljoin("News", "?id=" + id)
    }, headline, author)
Exemple #4
0
def execute(argv, argv0, engine):
    if not argv:
        usage(argv0)

    import lib
    os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings")
    from aioweb import settings

    table, model_name, model_class = lib.names(argv[0],
                                               ["table", "model", "class"])
    dest_path = os.path.join(lib.dirs(settings, format=["tests"]),
                             "models/" + model_name + ".py")

    os.makedirs(os.path.dirname(dest_path), exist_ok=True)
    if os.path.exists(dest_path):
        if lib.ask("{} already exists!\nDo You wanna rewrite it?".format(
                dest_path)) == 'n':
            return

    template = lib.get_template("tests/model.py", settings)
    with open(template, "r") as f:
        print("generating " + dest_path)
        content = f.read().replace("MODEL", model_name).replace(
            "CLASS", model_class).replace("TABLE", table)
        with open(dest_path, "w") as df:
            df.write(content)
Exemple #5
0
def execute(argv, argv0, engine):
    import lib, inflection
    os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings")
    from aioweb import settings

    sys.path.append(os.getcwd())
    if len(argv) < 2:
        usage(argv0)
    controller_name = inflection.camelize(argv[0]) + "Controller"
    controller_file_name = inflection.underscore(argv[0]) + ".py"
    methods = argv[1:]
    dest_file = os.path.join(lib.dirs(settings, format=["controllers"]), controller_file_name)
    os.makedirs(os.path.dirname(dest_file), exist_ok=True)
    template = lib.get_template("controllers/simple_controller.py", settings)

    if os.path.exists(dest_file):
        if lib.ask("{} already exists!\nDo you wanna replace it?".format(dest_file)) == 'n':
            print("Controller generation was aborted!")
            return

    print("creating {}".format(dest_file))

    with open(template, "r") as f:
        controller_code = f.read().replace("CLASS", controller_name)
        with open(dest_file, "w") as df:
            df.write(controller_code)

    for method in methods:
        engine["commands"]["generate"]["controller_method"]([argv[0], method], argv0, engine)
    engine["commands"]["generate"]["test"]["controller"](argv, argv0, engine)
Exemple #6
0
def generate_entries (req=None,current=None):
	if req: return

	entry_tpl = lib.get_template ("menu")
	retval = ""
	for entry in lib.get_config ("Entries","Static"):
		if "src" in entry: uri = lib.ljoin ("Static","?page="+entry["uri"])
		else:              uri = entry["uri"] if entry["uri_is_relative"] is False else lib.ljoin (entry["uri"])
		retval += entry_tpl % {"icon": entry["icon"], "name": entry["name"], "path": uri, "cls": "em" if current == entry["uri"] else ""}
	return retval
Exemple #7
0
def generate_entries(req=None, current=None):
    if req: return

    entry_tpl = lib.get_template("menu")
    retval = ""
    for entry in lib.get_config("Entries", "Static"):
        if "src" in entry: uri = lib.ljoin("Static", "?page=" + entry["uri"])
        else:
            uri = entry[
                "uri"] if entry["uri_is_relative"] is False else lib.ljoin(
                    entry["uri"])
        retval += entry_tpl % {
            "icon": entry["icon"],
            "name": entry["name"],
            "path": uri,
            "cls": "em" if current == entry["uri"] else ""
        }
    return retval
Exemple #8
0
def execute(argv, argv0, engine):
    import lib, inflection
    os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings")
    from aioweb import settings

    if len(argv) == 0:
        usage(argv0)
    module_full_path = argv
    chase = engine["commands"]
    for i, m in enumerate(module_full_path):
        rc = chase.get(m)
        if not rc:
            chase = None
            break
        elif type(rc) == str:
            module_full_path[i] = rc
            chase = chase.get(rc)
        else:
            chase = rc
    dest_file = os.path.join("wyrm", "modules", *module_full_path) + ".py"

    if type(chase) == dict:
        print("CONFLICT: " + '"' + ' '.join(module_full_path) +
              '" is a module collection!')
        sys.exit(1)

    elif os.path.exists(dest_file):
        rc = lib.ask(dest_file +
                     " already exists!\nDo You wanna rewrite it???")
        if rc == 'n': sys.exit(0)

    elif callable(chase):
        rc = lib.ask("This module already exists! Do You wanna replace it?")
        if rc == 'n': sys.exit(0)

    print("generating " + '"' + ' '.join(module_full_path) + '"')
    os.makedirs(os.path.dirname(dest_file), exist_ok=True)

    template = lib.get_template("wyrm/module.py", settings)
    with open(template, "r") as f:
        module_code = f.read().replace("MODULE_FULL_NAME",
                                       ' '.join(module_full_path))
        with open(dest_file, "w") as df:
            df.write(module_code)
Exemple #9
0
def index (req,page=None):
	entries = lib.get_config ("Entries","Static")
	pagemeta = None
	for entry in entries:
		if entry["uri"] == page and "src" in entry:
			pagemeta = entry
			break
	else:
		req.headers_out["location"] = lib.get_config ("SitePrefix").encode()
		req.status = apache.HTTP_MOVED_TEMPORARILY
		return

	with open ( lib.valid_dir (djoin (dirname(__file__),pagemeta["src"])) ) as pagefile:
		text = lib.escape ("\n".join (pagefile.readlines()))
	if ".md" in pagemeta["src"]:
		text = markdown (text)
	text = lib.get_template ("static") % {"content": text}

	return lib.respond (req, text, pagemeta["title"],pagemeta["caption"],pagemeta["description"],module_info(active=page))
Exemple #10
0
def index(req, page=None):
    entries = lib.get_config("Entries", "Static")
    pagemeta = None
    for entry in entries:
        if entry["uri"] == page and "src" in entry:
            pagemeta = entry
            break
    else:
        req.headers_out["location"] = lib.get_config("SitePrefix").encode()
        req.status = apache.HTTP_MOVED_TEMPORARILY
        return

    with open(lib.valid_dir(djoin(dirname(__file__),
                                  pagemeta["src"]))) as pagefile:
        text = lib.escape("\n".join(pagefile.readlines()))
    if ".md" in pagemeta["src"]:
        text = markdown(text)
    text = lib.get_template("static") % {"content": text}

    return lib.respond(req, text, pagemeta["title"], pagemeta["caption"],
                       pagemeta["description"], module_info(active=page))
Exemple #11
0
def generate_page(page, news_amount_factor, show_nav=True):
    if not type(page) is int: return

    news_per_page = int(
        lib.get_config("NewsPerPage") * float(news_amount_factor))

    news = _enum_news()
    pages = int(ceil(len(news) / float(news_per_page)))

    content = "".join([
        parse_news(id)[0]
        for id in news[page * news_per_page:page * news_per_page +
                       news_per_page]
    ])

    page_str = ""
    if show_nav:
        for i in range(pages):
            page_str += '<a class="link %(cls)s" href="?page=%(i)i">%(i)i</a> | ' % {
                "i": i,
                "cls": "em" if i == page else ""
            }

        if page > 0:
            page_str = '<a class="link" href="?page=0"><img width="16" height="16" class="inline" src="/static/first.png" alt="goto first page"/>Newest</a> | <a rel="prev" class="link" href="?page=%(i)i"><img width="16" height="16" class="inline" src="/static/prev.png" alt="goto newer page"/>Newer</a> | ' % {
                "i": page - 1
            } + page_str
        if page < (pages - 1):
            page_str += '<a rel="next" class="link" href="?page=%(i)i">Older<img class="inline" width="16" height="16" src="/static/next.png" alt="goto older page"/></a> | <a class="link" href="?page=%(l)i">Oldest<img class="inline" width="16" height="16" src="/static/last.png" alt="goto last page"/></a>' % {
                "i": page + 1,
                "l": pages - 1
            }

    return lib.get_template("news_pages") % {
        "pages": page_str,
        "content": content
    }
Exemple #12
0
def execute(argv, argv0, engine):
    if not argv:
        usage(argv0)

    import lib
    os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings")
    from aioweb import settings

    additional_fields = lib.get_fields_from_argv(argv[1:], usage, argv0)
    if not additional_fields: additional_fields = [("string", "somefield")]

    table, model_name, model_class = lib.names(argv[0],
                                               ["table", "model", "class"])
    factories_dir = lib.dirs(settings, format=["factories"])

    os.makedirs(factories_dir, exist_ok=True)
    dest_path = os.path.join(factories_dir, '{}_factory.py'.format(table))

    if os.path.exists(dest_path):
        if lib.ask(dest_path + " exists\nDo You wanna rewrite it?") == 'n':
            print("factory generation cancelled")
            return

    template = lib.get_template("tests/factory.py", settings)
    with open(template, "r") as f:
        print("generating " + dest_path)
        content = f.read().replace("MODEL", model_name).replace(
            "CLASS", model_class).replace("TABLE", table)
        with open(dest_path, "w") as df:
            df.write(content)
        lib.insert_in_python(
            dest_path, ["import"],
            ['from app.models.{} import {}'.format(model_name, model_class)])
        lib.insert_in_python(
            dest_path, ["return"],
            map(lambda prm: '    "{}": None, '.format(prm[1]),
                additional_fields))
Exemple #13
0
def execute(argv, argv0, engine):
    import lib

    if len(argv) == 0 or len(argv) > 2 or argv[0] in [
            '-h', '--help'
    ] or argv[-1] in ['-h', '--help']:
        usage(argv0)
        sys.exit(1)
    name = argv[0]
    dirname = argv[-1]
    appdir = dirname
    if len(argv) >= 2:
        appdir = os.path.join(dirname, name)

    gen_path = lib.get_template("new")
    if not gen_path:
        print("ERROR: can't locate generator templates!")
        sys.exit(1)

    if os.path.exists(appdir):
        print("cleaning {}".format(os.path.abspath(appdir)))
        if os.listdir(appdir):
            rc = lib.ask(
                "{} is not empty.\nDo you wanna empty this folder?".format(
                    os.path.abspath(appdir)))
            if rc != 'y':
                print("Generation was aborted.")
                sys.exit(1)

        for entry in os.listdir(appdir):
            path = os.path.join(appdir, entry)
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.unlink(path)
        print("coping files...")
        for entry in os.listdir(gen_path):
            src = os.path.join(gen_path, entry)
            dest = os.path.join(appdir, entry)
            if os.path.isdir(src):
                shutil.copytree(src, dest)
            else:
                shutil.copy2(src, dest)
    else:
        if appdir != dirname:
            os.makedirs(dirname, exist_ok=True)
        print("coping files...")
        shutil.copytree(gen_path, appdir)

    os.makedirs(os.path.join(appdir, "wyrm/generators"), exist_ok=True)
    os.makedirs(os.path.join(appdir, "wyrm/modules"), exist_ok=True)

    if appdir != dirname:
        print("patching setup.py")
        print(lib.get_template("setup.py"))
        shutil.copy2(lib.get_template("setup.cfg"),
                     os.path.join(dirname, "setup.cfg"))
        shutil.copy2(lib.get_template("setup.py"),
                     os.path.join(dirname, "setup.py"))
        with open(os.path.join(dirname, "setup.py"), "r") as f:
            setup_py = f.read().replace("APP_NAME", name)
        with open(os.path.join(dirname, "setup.py"), "w") as f:
            f.write(setup_py)