Пример #1
0
def get_unicode_builder(tmpdir):
    proj = Project.from_path(
        os.path.join(os.path.dirname(__file__), u"ünicöde-project"))
    env = Environment(proj)
    pad = Database(env).new_pad()

    return pad, Builder(pad, str(tmpdir.mkdir("output")))
Пример #2
0
def child_sources_test_project_builder(tmpdir):
    project = Project.from_path(
        os.path.join(os.path.dirname(__file__), "child-sources-test-project"))
    env = Environment(project)
    pad = Database(env).new_pad()

    return Builder(pad, str(tmpdir.mkdir("output")))
Пример #3
0
def theme_project(theme_project_tmpdir, request):
    """Return the theme project created in a temp dir.

    Could be parametrize, if request.param=False themes variables won't be set
    """
    try:
        with_themes_var = request.param
    except AttributeError:
        with_themes_var = True

    # Create the .lektorproject file
    lektorfile_text = textwrap.dedent(
        """
        [project]
        name = Themes Project
        {}
    """.format(
            "themes = blog_theme, project_theme" if with_themes_var else ""
        )
    )

    theme_project_tmpdir.join("themes.lektorproject").write_text(
        lektorfile_text, "utf8", ensure=True
    )
    return Project.from_path(str(theme_project_tmpdir))
Пример #4
0
def scratch_project_with_plugin_no_params(
    scratch_project_data, request, isolated_cli_runner
):
    """Create a scratch project and add a plugin that has the named event listener.

    Return (project, current event, and attached cli_runner).
    """
    base = scratch_project_data

    # Minimum viable setup.py
    current_test_index = (request.param_index,) * 4
    setup_text = textwrap.dedent(
        u"""
        from setuptools import setup

        setup(
            name='lektor-event-test-no-params{}',
            entry_points={{
                'lektor.plugins': [
                    'event-test-no-params{} = lektor_event_test_no_params{}:NoParams{}',
                ]
            }}
        )
    """
    ).format(*current_test_index)
    base.join(
        "packages", "event-test-no-params{}".format(request.param_index), "setup.py"
    ).write_text(setup_text, "utf8", ensure=True)

    # Minimum plugin code
    plugin_text = textwrap.dedent(
        u"""
        from lektor.pluginsystem import Plugin
        import os

        class NoParams{}(Plugin):
            name = 'Event Test'
            description = u'Non-empty string'

            def on_{}(self):
                pass
    """
    ).format(request.param_index, request.param, request.param)
    base.join(
        "packages",
        "event-test-no-params{}".format(request.param_index),
        "lektor_event_test_no_params{}.py".format(request.param_index),
    ).write_text(plugin_text, "utf8", ensure=True)

    # Move into isolated path.
    for entry in os.listdir(str(base)):
        entry_path = os.path.join(str(base), entry)
        if os.path.isdir(entry_path):
            shutil.copytree(entry_path, entry)
        else:
            shutil.copy2(entry_path, entry)

    from lektor.project import Project

    yield (Project.from_path(str(base)), request.param, isolated_cli_runner)
Пример #5
0
def post(ctx, slug=None):
    project = Project.discover()
    env = project.make_env()
    pad = env.new_pad()

    blog = pad.get('/blog')
    latest_post = blog.children.first()
    if latest_post is None:
        next_id = 1
    else:
        next_id = latest_post['id'] + 1

    if slug is None:
        slug = input('Enter slug: ') or '__new_post__'

    new_dirname = os.path.join(
        ROOT_DIR, os.path.dirname(blog.source_filename), slug,
    )
    os.mkdir(new_dirname)

    contents_fn = os.path.join(new_dirname, 'contents.lr')
    with io.open(contents_fn, mode='w', encoding='utf8') as f:
        f.write(blog_post_template.format(
            id=next_id,
            today=datetime.date.today().strftime(r'%Y-%m-%d'),
        ))
Пример #6
0
 def setUp(self):
     self.project = Project.from_path(
         os.path.join(os.path.dirname(__file__), 'demo-project'))
     self.env = Environment(self.project)
     self.pad = Database(self.env).new_pad()
     self.out = tempfile.mkdtemp()
     self.builder = Builder(self.pad, self.out)
Пример #7
0
def release(ctx, path_to_info):
    project = Project.discover()
    env = project.make_env()
    pad = env.new_pad()

    later = datetime.datetime.now() + datetime.timedelta(hours=1)

    with io.open(path_to_info, encoding='utf8') as f:
        info = json.load(f)
    info.setdefault('min_sysver', '10.8')
    info.setdefault('pub_datetime', later.strftime(r'%Y-%m-%d %H:%M:%S'))
    info.setdefault(
        'download_url',
        'https://github.com/MacDownApp/macdown/releases/download/'
        'v{version}/MacDown.app.zip'.format(version=info['version']),
    )

    download = pad.get('/download')

    new_dirname = os.path.join(
        ROOT_DIR,
        os.path.dirname(download.source_filename),
        info['build_number'],
    )
    os.mkdir(new_dirname)

    contents_fn = os.path.join(new_dirname, 'contents.lr')
    with io.open(contents_fn, mode='w', encoding='utf8') as f:
        f.write(release_template.format(**info))
Пример #8
0
def project(tmp_path_factory):
    site_path = tmp_path_factory.mktemp('site')
    project_file = site_path / 'site.lektorproject'
    project_file.write_text(u"""
    [project]
    name = Test Project
    """)
    return Project.from_file(str(project_file))
Пример #9
0
 def list_local(self):
     all_records = []
     project = Project.discover()
     env = project.make_env()
     pad = env.new_pad()
     root = pad.root
     all_records = self.add_index_children_json(pad, root)
     return all_records
Пример #10
0
 def list_local(self):
     all_records = []
     project = Project.discover()
     env = project.make_env()
     pad = env.new_pad()
     root = pad.root
     all_records = self.add_index_children_json(pad, root)
     return all_records
Пример #11
0
 def get_project(self, silent=False):
     if self._project is not None:
         return self._project
     if self._project_path is not None:
         rv = Project.from_path(self._project_path)
     else:
         rv = Project.discover()
     if rv is None:
         if silent:
             return None
         if self._project_path is None:
             raise click.UsageError("Could not automatically discover "
                                    "project.  A Lektor project must "
                                    "exist in the working directory or "
                                    "any of the parent directories.")
         raise click.UsageError('Could not find project "%s"' %
                                self._project_path)
     self._project = rv
     return rv
Пример #12
0
def child_sources_test_project_builder(request):
    from lektor.db import Database
    from lektor.environment import Environment
    from lektor.project import Project

    project = Project.from_path(os.path.join(os.path.dirname(__file__), "child-sources-test-project"))
    env = Environment(project)
    pad = Database(env).new_pad()

    return make_builder(request, pad)
Пример #13
0
def child_sources_test_project_builder(request):
    from lektor.db import Database
    from lektor.environment import Environment
    from lektor.project import Project

    project = Project.from_path(
        os.path.join(os.path.dirname(__file__), 'child-sources-test-project'))
    env = Environment(project)
    pad = Database(env).new_pad()

    return make_builder(request, pad)
Пример #14
0
def child_sources_test_project_builder(tmpdir):
    from lektor.db import Database
    from lektor.environment import Environment
    from lektor.project import Project
    from lektor.builder import Builder

    project = Project.from_path(
        os.path.join(os.path.dirname(__file__), 'child-sources-test-project'))
    env = Environment(project)
    pad = Database(env).new_pad()

    return Builder(pad, str(tmpdir.mkdir("output")))
Пример #15
0
def get_unicode_builder(tmpdir):
    from lektor.project import Project
    from lektor.environment import Environment
    from lektor.db import Database
    from lektor.builder import Builder

    proj = Project.from_path(os.path.join(os.path.dirname(__file__),
                                          u'ünicöde-project'))
    env = Environment(proj)
    pad = Database(env).new_pad()

    return pad, Builder(pad, str(tmpdir.mkdir('output')))
Пример #16
0
def child_sources_test_project_builder(tmpdir):
    from lektor.db import Database
    from lektor.environment import Environment
    from lektor.project import Project
    from lektor.builder import Builder

    project = Project.from_path(os.path.join(os.path.dirname(__file__),
                                             'child-sources-test-project'))
    env = Environment(project)
    pad = Database(env).new_pad()

    return Builder(pad, str(tmpdir.mkdir("output")))
Пример #17
0
def get_unicode_builder(tmpdir):
    from lektor.project import Project
    from lektor.environment import Environment
    from lektor.db import Database
    from lektor.builder import Builder

    proj = Project.from_path(os.path.join(os.path.dirname(__file__),
                                          u'ünicöde-project'))
    env = Environment(proj)
    pad = Database(env).new_pad()

    return pad, Builder(pad, str(tmpdir.mkdir('output')))
Пример #18
0
def content_file_info_cmd(ctx, files, as_json):
    """Given a list of files this returns the information for those files
    in the context of a project.  If the files are from different projects
    an error is generated.
    """
    project = None

    def fail(msg):
        if as_json:
            echo_json({"success": False, "error": msg})
            sys.exit(1)
        raise click.UsageError("Could not find content file info: %s" % msg)

    for filename in files:
        this_project = Project.discover(filename)
        if this_project is None:
            fail("no project found")
        if project is None:
            project = this_project
        elif project.project_path != this_project.project_path:
            fail("multiple projects")

    if project is None:
        fail("no file indicated a project")

    project_files = []
    for filename in files:
        content_path = project.content_path_from_filename(filename)
        if content_path is not None:
            project_files.append(content_path)

    if not project_files:
        fail("no files resolve in project")

    if as_json:
        echo_json(
            {
                "success": True,
                "project": project.to_json(),
                "paths": project_files,
            }
        )
    else:
        click.echo("Project:")
        click.echo("  Name: %s" % project.name)
        click.echo("  File: %s" % project.project_file)
        click.echo("  Tree: %s" % project.tree)
        click.echo("Paths:")
        for project_file in project_files:
            click.echo("  - %s" % project_file)
Пример #19
0
def scratch_project(request):
    base = tempfile.mkdtemp()
    with open(os.path.join(base, 'Scratch.lektorproject'), 'w') as f:
        f.write(
            '[project]\n'
            'name = Scratch\n\n'
            '[alternatives.en]\n'
            'primary = yes\n'
            '[alternatives.de]\n'
            'url_prefix = /de/\n'
            '[servers.production]\n'
            'enabled = yes\n'
            'name = Production\n'
            'target = rsync://example.com/path/to/website\n'
            'name[de] = Produktion\n'
            'extra_field = extra_value\n'
        )

    os.mkdir(os.path.join(base, 'content'))
    with open(os.path.join(base, 'content', 'contents.lr'), 'w') as f:
        f.write(
            '_model: page\n'
            '---\n'
            'title: Index\n'
            '---\n'
            'body: Hello World!\n'
        )
    os.mkdir(os.path.join(base, 'templates'))
    with open(os.path.join(base, 'templates', 'page.html'), 'w') as f:
        f.write('<h1>{{ this.title }}</h1>\n{{ this.body }}\n')
    os.mkdir(os.path.join(base, 'models'))
    with open(os.path.join(base, 'models', 'page.ini'), 'w') as f:
        f.write(
            '[model]\n'
            'label = {{ this.title }}\n\n'
            '[fields.title]\n'
            'type = string\n'
            '[fields.body]\n'
            'type = markdown\n'
        )

    def cleanup():
        try:
            shutil.rmtree(base)
        except (OSError, IOError):
            pass
    request.addfinalizer(cleanup)

    from lektor.project import Project
    return Project.from_path(base)
Пример #20
0
def get_meetup_groups():
    """
    Loads meetup groups from the Python Colombia lektor database.

    This returns only communities that are displayed on the map.
    """
    project = Project.discover()
    env = project.make_env()
    pad = env.new_pad()
    groups = [
        g for g in pad.query('/usuarios/') if g['type'] == 'comunidad'
        and g['map'] and not isinstance(g['meetup_handle'], Undefined)
    ]
    groups = {g['meetup_handle']: g['username'] for g in groups}
    return groups
Пример #21
0
def scratch_project(tmpdir):
    base = tmpdir.mkdir("scratch-proj")
    lektorfile_text = textwrap.dedent(u"""
        [project]
        name = Scratch

        [alternatives.en]
        primary = yes
        [alternatives.de]
        url_prefix = /de/
    """)
    base.join("Scratch.lektorproject").write_text(lektorfile_text,
                                                  "utf8",
                                                  ensure=True)
    content_text = textwrap.dedent(u"""
        _model: page
        ---
        title: Index
        ---
        body: Hello World!
    """)
    base.join("content", "contents.lr").write_text(content_text,
                                                   "utf8",
                                                   ensure=True)
    template_text = textwrap.dedent(u"""
        <h1>{{ this.title }}</h1>
        {{ this.body }}
    """)
    base.join("templates", "page.html").write_text(template_text,
                                                   "utf8",
                                                   ensure=True)
    model_text = textwrap.dedent(u"""
        [model]
        label = {{ this.title }}

        [fields.title]
        type = string
        [fields.body]
        type = markdown
    """)
    base.join("models", "page.ini").write_text(model_text, "utf8", ensure=True)

    from lektor.project import Project
    return Project.from_path(str(base))
Пример #22
0
def demo_output(site_path, my_plugin_id, my_plugin_cls, tmp_path_factory):
    """ Build the demo site.

    Return path to output directory.

    """
    project = Project.from_path(str(site_path))
    env = Environment(project, load_plugins=False)

    # Load our plugin
    env.plugin_controller.instanciate_plugin(my_plugin_id, my_plugin_cls)
    env.plugin_controller.emit('setup-env')

    pad = Database(env).new_pad()
    output_path = tmp_path_factory.mktemp('demo-site')
    builder = Builder(pad, str(output_path))
    with CliReporter(env):
        failures = builder.build_all()
        assert failures == 0
    return output_path
Пример #23
0
def no_alt_pad(tmp_path_factory):
    no_alt_project = tmp_path_factory.mktemp("no-alts") / "demo-project"
    demo_project = Path(__file__).parent / "demo-project"
    shutil.copytree(demo_project, no_alt_project)

    project_file = no_alt_project / "Website.lektorproject"
    alt_section_re = r"(?ms)^\[alternatives\.\w+\].*?(?=^\[)"
    project_file.write_text(
        re.sub(alt_section_re, "", project_file.read_text()))

    dirs = [no_alt_project]
    while dirs:
        for child in dirs.pop().iterdir():
            if child.is_dir():
                dirs.append(child)
            elif child.match("contents+*.lr"):
                child.unlink()

    project = Project.from_path(no_alt_project)
    return project.make_env().new_pad()
Пример #24
0
def scratch_project(request):
    base = tempfile.mkdtemp()
    with open(os.path.join(base, "Scratch.lektorproject"), "w") as f:
        f.write(
            "[project]\n"
            "name = Scratch\n\n"
            "[alternatives.en]\n"
            "primary = yes\n"
            "[alternatives.de]\n"
            "url_prefix = /de/\n"
        )

    os.mkdir(os.path.join(base, "content"))
    with open(os.path.join(base, "content", "contents.lr"), "w") as f:
        f.write("_model: page\n" "---\n" "title: Index\n" "---\n" "body: Hello World!\n")
    os.mkdir(os.path.join(base, "templates"))
    with open(os.path.join(base, "templates", "page.html"), "w") as f:
        f.write("<h1>{{ this.title }}</h1>\n{{ this.body }}\n")
    os.mkdir(os.path.join(base, "models"))
    with open(os.path.join(base, "models", "page.ini"), "w") as f:
        f.write(
            "[model]\n"
            "label = {{ this.title }}\n\n"
            "[fields.title]\n"
            "type = string\n"
            "[fields.body]\n"
            "type = markdown\n"
        )

    def cleanup():
        try:
            shutil.rmtree(base)
        except (OSError, IOError):
            pass

    request.addfinalizer(cleanup)

    from lektor.project import Project

    return Project.from_path(base)
Пример #25
0
def scratch_project(tmpdir):
    base = tmpdir.mkdir("scratch-proj")
    lektorfile_text = textwrap.dedent(u"""
        [project]
        name = Scratch

        [alternatives.en]
        primary = yes
        [alternatives.de]
        url_prefix = /de/
    """)
    base.join("Scratch.lektorproject").write_text(lektorfile_text, "utf8", ensure=True)
    content_text = textwrap.dedent(u"""
        _model: page
        ---
        title: Index
        ---
        body: Hello World!
    """)
    base.join("content", "contents.lr").write_text(content_text, "utf8", ensure=True)
    template_text = textwrap.dedent(u"""
        <h1>{{ this.title }}</h1>
        {{ this.body }}
    """)
    base.join("templates", "page.html").write_text(template_text, "utf8", ensure=True)
    model_text = textwrap.dedent(u"""
        [model]
        label = {{ this.title }}

        [fields.title]
        type = string
        [fields.body]
        type = markdown
    """)
    base.join("models", "page.ini").write_text(model_text, "utf8", ensure=True)

    from lektor.project import Project
    return Project.from_path(str(base))
Пример #26
0
def theme_project(theme_project_tmpdir, request):
    """Return the theme project created in a temp dir.

    Could be parametrize, if request.param=False themes variables won't be set
    """
    try:
        with_themes_var = request.param
    except AttributeError:
        with_themes_var = True

    from lektor.project import Project

    # Create the .lektorproject file
    lektorfile_text = textwrap.dedent(u"""
        [project]
        name = Themes Project
        {}
    """.format("themes = blog_theme, project_theme"
               if with_themes_var else ""))

    theme_project_tmpdir.join("themes.lektorproject").write_text(
        lektorfile_text, "utf8", ensure=True)
    return Project.from_path(str(theme_project_tmpdir))
def demo_output(tmp_path_factory):
    """ Build the demo site.

    Return path to output director.

    """
    site_dir = os.path.join(os.path.dirname(__file__), 'test-site')

    project = Project.from_path(site_dir)

    env = project.make_env(load_plugins=False)
    # Load our plugin
    env.plugin_controller.instanciate_plugin('polymorphic-type',
                                             PolymorphicTypePlugin)
    env.plugin_controller.emit('setup-env')

    output_path = tmp_path_factory.mktemp('output')
    builder = Builder(env.new_pad(), str(output_path))
    with CliReporter(env):
        failures = builder.build_all()
        assert failures == 0

    return output_path
Пример #28
0
def project():
    from lektor.project import Project
    return Project.from_path(
        os.path.join(os.path.dirname(__file__), 'demo-project'))
import imghdr
from os.path import abspath, dirname, join, isfile

import pyimagediet

# Lektor stuff
from lektor.pluginsystem import Plugin
from lektor.build_programs import FileAssetBuildProgram, AttachmentBuildProgram, BuildProgram
from lektor.assets import File
from lektor.sourceobj import VirtualSourceObject
from lektor.project import Project
from lektor.db import Image
from werkzeug._internal import _log

# Load and parse the pyimagediet configuration
config_filename = abspath(join(Project.discover().project_path, '..', 'configs', 'minification.yml'))

if not isfile(config_filename):
    from pyimagediet.process import DEFAULT_CONFIG as DIET_CONFIG
else:
    DIET_CONFIG = pyimagediet.read_yaml_configuration(config_filename)

try:
    DIET_CONFIG = pyimagediet.parse_configuration(DIET_CONFIG)
except pyimagediet.ConfigurationErrorDietException, e:
    raise Exception(e.msg)


def copy_and_optimize(src, dst):
    """Make sure it's an image, and then optimize on place"""
    img_type = imghdr.what(src)
Пример #30
0
def project():
    from lektor.project import Project
    return Project.from_path(os.path.join(os.path.dirname(__file__),
                                          'demo-project'))
Пример #31
0
def scratch_project(scratch_project_data):
    base = scratch_project_data
    return Project.from_path(str(base))
Пример #32
0
def scratch_project(scratch_project_data):
    from lektor.project import Project

    base = scratch_project_data
    return Project.from_path(str(base))
def project():
    project = Project.from_path(str(ROOT / "example-project"))
    assert project
    return project
Пример #34
0
 def project(self):
     return Project.discover()
Пример #35
0
def lektor_env():
    site_path = os.path.join(os.path.dirname(__file__), 'test-site')
    return Project.from_path(site_path).make_env(load_plugins=False)
import os
import sys

# Third party imports
from PIL import Image as ImagePIL
from jinja2 import Undefined

# Local imports
from lektor.db import Image
from lektor.pluginsystem import Plugin
from lektor.project import Project
from lektor.reporter import reporter
from lektor.utils import portable_popen

PY3 = sys.version_info[0] == 3
PROJECT = Project.discover()
ROOT_PATH = os.path.abspath(os.path.dirname(PROJECT.project_path))
CONTENT_PATH = os.path.join(ROOT_PATH, 'content')


class PythonColombiaPlugin(Plugin):
    name = 'Python Colombia Custom Lektor Plugin'
    description = 'This is a custom local plugin to add extra functionality.'

    def on_after_build(self, builder, build_state, source, prog):
        if isinstance(source, Image) and source.parent['_model'] == 'user':
            w, h = source.width, source.height
            fpath = CONTENT_PATH + source.path
            if isinstance(w, Undefined):
                with ImagePIL.open(fpath) as img:
                    w, h = img.size
Пример #37
0
def project(request):
    from lektor.project import Project

    return Project.from_path(
        os.path.join(os.path.dirname(__file__), "demo-project"))
Пример #38
0
def pntest_project(request):
    from lektor.project import Project

    return Project.from_path(
        os.path.join(os.path.dirname(__file__), "dependency-test-project"))
Пример #39
0
def pntest_project(request):
    from lektor.project import Project
    return Project.from_path(os.path.join(os.path.dirname(__file__),
                                          'dependency-test-project'))
Пример #40
0
def list_local() -> List[Dict[str, Any]]:
    project = Project.discover()
    env = project.make_env()
    pad = env.new_pad()
    root = pad.root
    return get_all_records(pad, root)
Пример #41
-1
def project(request):
    from lektor.project import Project

    return Project.from_path(os.path.join(os.path.dirname(__file__), "demo-project"))