Esempio n. 1
0
def parse_to_recipe(content: str) -> Recipe:
    """Parse a Markdown formatted string to a Recipe object

    Args:
        content (str): A Markdown formatted string

    Returns:
        Recipe: A Recipe object representing the given content
    """

    recipe_metadata = frontmatter.loads(content)

    document = marko.parse(content)
    recipe_name = get_recipe_name(document)
    quote = get_quote(document)
    ingredients = get_ingredients(document)
    instructions = get_instructions(document)

    return Recipe(
        name=recipe_metadata["name"],
        residence=recipe_metadata["residence"],
        category=RecipeCategory(recipe_metadata["category"].lower()),
        recipe_name=recipe_name,
        quote=quote,
        ingredients=ingredients,
        instructions=instructions,
    )
def pytest_generate_tests(metafunc):
    if 'example' in metafunc.fixturenames:
        modules = [x for x in MODULES_PATH.iterdir() if x.is_dir()]
        modules.sort()
        examples = []
        ids = []
        for module in modules:
            readme = module / 'README.md'
            if not readme.exists():
                continue
            doc = marko.parse(readme.read_text())
            index = 0
            last_header = None
            for child in doc.children:
                if isinstance(child,
                              marko.block.FencedCode) and child.lang == 'hcl':
                    index += 1
                    code = child.children[0].children
                    if 'tftest skip' in code:
                        continue
                    examples.append(code)
                    name = f'{module.stem}:{last_header}'
                    if index > 1:
                        name += f' {index}'
                    ids.append(name)
                elif isinstance(child, marko.block.Heading):
                    last_header = child.children[0].children
                    index = 0

        metafunc.parametrize('example', examples, ids=ids)
Esempio n. 3
0
def test_get_instructions():
    # Given
    expected = ["Instruction 1", "Instruction 2"]

    source = marko.parse(SOURCE_TEXT)

    # When
    actual = get_instructions(source)

    # Then
    assert expected == actual
Esempio n. 4
0
def test_get_ingredients():
    # Given
    expected = ["Ingredient 1", "Ingredient 2"]

    source = marko.parse(SOURCE_TEXT)

    # When
    actual = get_ingredients(source)

    # Then
    assert expected == actual
Esempio n. 5
0
def test_get_quote():
    # Given
    expected = "This is a test quote\nfor which this is the second line"

    source = marko.parse(SOURCE_TEXT)

    # When
    actual = get_quote(source)

    # Then
    assert expected == actual
Esempio n. 6
0
def test_get_recipe_name():
    # Given
    expected = "Recipe name"

    source = marko.parse(SOURCE_TEXT)

    # When
    actual = get_recipe_name(source)

    # Then
    assert expected == actual
Esempio n. 7
0
def extract_images(content: str) -> Iterator[Tuple[str, str]]:
    """
    Extract all images from a Markdown document.
    """
    tree = marko.parse(content)
    queue = [tree]
    while queue:
        element = queue.pop()

        if isinstance(element, marko.inline.Image):
            yield element.dest, element.children[0].children
        elif hasattr(element, "children"):
            queue.extend(element.children)
Esempio n. 8
0
def parse_to_recipe(content: str) -> Recipe:
    """Parse a Markdown formatted string to a Recipe object

    Args:
        content (str): A Markdown formatted string

    Returns:
        Recipe: A Recipe object representing the given content
    """

    recipe_metadata = frontmatter.loads(content)

    document = marko.parse(content)
    recipe_name = get_recipe_name(document)

    ingredients = list()
    instructions = list()
    in_ingredients = False
    in_instructions = False
    for line in content.splitlines():
        if line.strip().lower() == "## Ingredients".lower():
            in_ingredients = True
            in_instructions = False
        elif line.strip().lower() == "## Instructions".lower():
            in_ingredients = False
            in_instructions = True
        elif in_ingredients:
            ingredients.append(line)
        elif in_instructions:
            instructions.append(line)

    # quote = get_quote(document)
    # ingredients = get_ingredients(document)
    # instructions = get_instructions(document)

    category = RecipeCategory(recipe_metadata["category"].lower())
    cover_img = recipe_metadata[
        "cover_img"] if "cover_img" in recipe_metadata else (
            category.value.lower() + ".png")
    # print(recipe_name, cover_img)

    return Recipe(
        name=recipe_metadata["name"],
        residence=recipe_metadata["residence"],
        category=category,
        recipe_name=recipe_name,
        cover_img=cover_img,
        quote=recipe_metadata["quote"] if "quote" in recipe_metadata else "",
        ingredients="\n".join(ingredients),
        instructions="\n".join(instructions),
    )
Esempio n. 9
0
def extract_links(post: Post) -> Iterator[URL]:
    """
    Extract all links from a post.

    This includes links in the content, as well as metadata.
    """
    for key, value in post.metadata.items():
        if key.endswith("-url"):
            yield URL(value)

    tree = marko.parse(post.content)
    queue = [tree]
    while queue:
        element = queue.pop(0)

        if isinstance(element, marko.inline.Link):
            yield URL(element.dest)
        elif hasattr(element, "children"):
            queue.extend(element.children)
Esempio n. 10
0
def get_blocks(text):
    blocks = []
    subblock = []
    for element in marko.parse(text).children:
        if isinstance(element, marko.block.ThematicBreak) or isinstance(
                element, marko.block.Heading):
            if subblock != []:
                document = marko.block.Document("")
                document.children = subblock
                blocks.append(document)
                subblock = []
        if not isinstance(element,
                          marko.block.ThematicBreak) and not isinstance(
                              element, marko.block.BlankLine):
            subblock.append(element)
    if subblock != []:
        document = marko.block.Document("")
        document.children = subblock
        blocks.append(document)
    return blocks
Esempio n. 11
0
def markdown(root: Box, markup: str, escape_char="~") -> Box:
    """
    Render Markdown markup into the given box.

    The Markdown syntax has to adhere to the CommonMark spec, but only
    a subset of the Markdown syntax is supported (see user guide).

    Parameters
    ----------
    root: Box
        Parent box into which will the markup be rendered.
    markup: str
        Markdown markup.
    escape_char: str
        Escape character used for marking inline styles.
    """
    markup = trim_indent(markup).strip()
    document = marko.parse(markup)

    wrapper = create_root_md_box(root)

    ctx = MarkdownContext(wrapper, escape_char)
    build_children(ctx, document)
    return root