Exemple #1
0
def test_reference():
    ref = [
        ("1 + 2 + 3\n2 + 5\n", 2),
        ("import exdown\n\nexdown.from_buffer\n", 7),
        ("# ```import math```\n", 23),
        ("1 + 1 == 2\n", 28),
        ("1 + 1 == 2\n", 33),
    ]
    lst = exdown.extract(this_dir / "example.md", syntax_filter="python")
    for r, obj in zip(ref, lst):
        assert r == obj
Exemple #2
0
def _format_path(path: Path, *, check: bool) -> Tuple[str, bool, list]:
    content = path.read_text("utf-8")
    lines = content.splitlines()
    errors = []
    offset = 0
    changed = False

    for source, lineno in exdown.extract(path, syntax_filter="python"):
        sourcelines = source.splitlines()
        try:
            outputlines = black.format_str(
                source,
                mode=black.FileMode(
                    target_versions={black.TargetVersion.PY37}),
            ).splitlines()
        except black.InvalidInput as exc:
            if source.startswith(">>> "):
                # Probably a Python shell snippet. Skip it since Black can't read those.
                continue
            errors.append(_danger(f"ERROR: at {path}:{lineno}: {exc}"))
            continue

        if sourcelines == outputlines:
            continue

        changed = True

        if check:
            continue

        lines_before = lines[:lineno + offset]
        lines_after = lines[lineno + offset + len(sourcelines):]
        lines = lines_before + outputlines + lines_after

        offset += len(outputlines) - len(sourcelines)

    if check and changed:
        errors.append(_warn(f"Needs formatting: {path}"))

    lines.append("")  # Final newline.
    if not content.endswith("\n"):
        changed = True

    output = "\n".join(lines)

    return output, changed, errors
Exemple #3
0
import io
import pathlib

import pytest

import exdown

this_dir = pathlib.Path(__file__).resolve().parent
inp = io.StringIO("""
Lorem ipsum
```python
1 + 2 + 3
```
dolor sit amet
""")


@pytest.mark.parametrize("string,lineno", exdown.from_buffer(inp))
def test_string(string, lineno):
    exec(string)


@pytest.mark.parametrize(
    "string, lineno",
    exdown.extract(this_dir / "example.md", syntax_filter="python"),
)
def test_file(string, lineno):
    exec(string)
Exemple #4
0
import pathlib

import exdown
import pytest

this_dir = pathlib.Path(__file__).resolve().parent


@pytest.mark.parametrize(
    "string,lineno",
    exdown.extract(this_dir.parent / "README.md", syntax_filter="python"),
)
def test_readme(string, lineno):
    try:
        # https://stackoverflow.com/a/62851176/353337
        exec(string, {"__MODULE__": "__main__"})
    except Exception:
        print(f"README.md (line {lineno}):\n```\n{string}```")
        raise
Exemple #5
0
import pathlib
import zipfile

import exdown
import pytest
import requests

this_dir = pathlib.Path(__file__).resolve().parent


@pytest.mark.parametrize(
    "string,lineno",
    exdown.extract(this_dir.parent / "README.md",
                   syntax_filter="python",
                   max_num_lines=100000),
)
def test_readme(string, lineno):

    # download
    url = "http://www.soest.hawaii.edu/pwessel/gshhg/gshhg-shp-2.3.7.zip"
    filename = url.split("/")[-1]
    with open(filename, "wb") as f:
        r = requests.get(url)
        f.write(r.content)

    # un-compress
    with zipfile.ZipFile("gshhg-shp-2.3.7.zip", "r") as zip_ref:
        zip_ref.extractall("gshhg-shp-2.3.7")

    try:
        # https://stackoverflow.com/a/62851176/353337
Exemple #6
0
import exdown
import tempfile
import os

def audited_execute(command):
    assert os.EX_OK == os.system(command)

for snippet, __ in exdown.extract('README.md', syntax_filter='cpp'):
    with tempfile.TemporaryDirectory() as tmpdirname:

        source = f'{tmpdirname}/native.cpp'
        out = f'{tmpdirname}/a.out'

        with open(f'{source}', 'w') as file:
            file.write(snippet)

        audited_execute(
            f'mpicxx --std=c++2a -Iinclude/ -Ithird-party/ {source} -lpthread -o {out}'
        )
        audited_execute(f'script/uitexec -n 2 script/uitwrap {out}')
Exemple #7
0
import os
import exdown

for root, dirs, files in os.walk("."):
    for file in files:
        if file.lower().endswith(".md"):
            filename = os.path.join(root, file)
            print(filename)
            blocks = exdown.extract(filename,
                                    encoding=None,
                                    syntax_filter="python")
            for code, line in blocks:
                try:
                    exec(code)
                except Exception:
                    print(f"{filename} (line {line}) failed")
                    raise
Exemple #8
0
import pytest

import exdown


@pytest.mark.parametrize(
    "string, lineno", exdown.extract("README.md", syntax_filter="python")
)
def test_readme(string, lineno):
    try:
        # https://stackoverflow.com/a/62851176/353337
        exec(string, {"__MODULE__": "__main__"})
    except Exception:
        print(f"README.md (line {lineno}):\n```\n{string}```")
        raise