Пример #1
0
    def process_file(self, filename):  # noqa: D102
        self.statements = []

        with fix_import_path([filename]):
            self._check_files(self.get_ast,
                              self._iterate_file_descrs([filename]))

        filename = PathPlus(filename)
        file_lines = filename.read_lines()

        for node in self.statements:

            if node.tolineno != node.lineno:
                warnings.warn("Currently unable to convert this statement")

            else:
                value = node.value.as_string()
                col = node.col_offset
                lineno = node.lineno - 1

                line = file_lines[lineno]
                line_pre_statement = line[:col]
                line_post_statement = line[col + len(value):]
                # print(f"{line_pre_statement}print({value}){line_post_statement}")
                file_lines[
                    lineno] = f"{line_pre_statement}print({value}){line_post_statement}"

        if file_lines[-1]:
            # ensure there's a newline at the end
            file_lines.append('')

        # print("\n".join(file_lines))
        filename.write_lines(file_lines)
Пример #2
0
def test_latex_output(app, latex_regression: LaTeXRegressionFixture):

    assert app.builder.name.lower() == "latex"

    with pytest.warns(UserWarning,
                      match="(No codes specified|No such code 'F401')"):
        app.build()

    output_file = PathPlus(app.outdir / "python.tex")
    latex_regression.check(StringList(output_file.read_lines()), jinja2=True)
def test_latex_output(app, advanced_file_regression: AdvancedFileRegressionFixture):
	random.seed("5678")

	assert app.builder.name.lower() == "latex"
	app.build()

	output_file = PathPlus(app.outdir / "sphinx-highlights-demo.tex")
	content = str(StringList(output_file.read_lines())).replace("\\sphinxAtStartPar\n", '')
	advanced_file_regression.check(
			re.sub(r"\\date{.*}", r"\\date{Mar 11, 2021}", content),
			extension=".tex",
			)
Пример #4
0
def test_latex_output_better_header_layout(
        app, latex_regression: LaTeXRegressionFixture):

    assert app.builder.name.lower() == "latex"

    better_header_layout(app.config, 9, 19)
    app.builder.context.update(app.config.latex_elements)

    with pytest.warns(UserWarning,
                      match="(No codes specified|No such code 'F401')"):
        app.build(force_all=True)

    output_file = PathPlus(app.outdir / "python.tex")
    latex_regression.check(StringList(output_file.read_lines()), jinja2=True)
Пример #5
0
def test_latex_output_latex_layout(app,
                                   latex_regression: LaTeXRegressionFixture):

    assert app.builder.name.lower() == "latex"

    app.setup_extension("sphinx_toolbox.tweaks.latex_layout")
    app.events.emit("config-inited", app.config)

    with pytest.warns(UserWarning,
                      match="(No codes specified|No such code 'F401')") as w:
        app.build(force_all=True)

    output_file = PathPlus(app.outdir / "python.tex")
    latex_regression.check(StringList(output_file.read_lines()), jinja2=True)
Пример #6
0
def is_docker() -> bool:
    """
	Is this current environment running in docker?

	>>> type(is_docker())
	<class 'bool'>

	.. versionadded:: 0.6.0
	"""  # noqa: D400

    if os.path.exists("/.dockerenv"):
        return True

    cgroup = PathPlus("/proc/self/cgroup")

    if cgroup.is_file():
        try:
            return any("docker" in line for line in cgroup.read_lines())
        except FileNotFoundError:
            return False

    return False
Пример #7
0
def test_latex_output(
    app,
    py_version: str,
    advanced_file_regression: AdvancedFileRegressionFixture,
):

    assert app.builder.name.lower() == "latex"

    app.build()

    output_file = PathPlus(app.outdir / "python.tex")
    content = str(StringList(output_file.read_lines())).replace(
        "\\sphinxAtStartPar\n", '').replace(". %\n", ".\n")
    content = re.sub(
        r"\\sphinxstepexplicit %\n(\\begin{footnote}\[1])\\phantomsection\\label{\\thesphinxscope\.1}%\n\\sphinxAtStartFootnote",
        "\n\\1\\\\sphinxAtStartFootnote",
        content,
    )

    advanced_file_regression.check(
        re.sub(r"\\date{.*}", r"\\date{Mar 11, 2021}", content),
        extension=".tex",
    )
Пример #8
0
def process_file(filename: PathLike) -> bool:
    """
	Augment Flake8 noqa comments with PyLint comments in the given file.

	:param filename:

	:return: :py:obj:`True` if the file contents were changed. :py:obj:`False` otherwise.
	"""

    file = PathPlus(filename)
    contents = file.read_lines()
    original_contents = contents[:]

    for idx, line in enumerate(contents):
        noqa = find_noqa(line)

        if noqa is None:
            continue

        if noqa.groupdict()["codes"] is None:
            continue

        # Line has one or more noqa codes
        flake8_codes = DelimitedList(
            filter(bool, re.split("[,; ]",
                                  noqa.groupdict()["codes"])))

        line_before_comment = line[:noqa.span()[0]].rstrip()
        line_after_comments = line[noqa.span()[1]:]

        # Search for pylint: disable= after the noqa comment
        disabled = find_pylint_disable(line[noqa.span()[1]:])
        disabled_checks = set()

        if disabled:
            line_after_comments = line[noqa.span()[1]:][disabled.span()[1]:]
            checks = disabled.groupdict()["checks"]

            if checks:
                disabled_checks = set(re.split("[,; ]", checks))

        for code in flake8_codes:
            disabled_checks.add(code_mapping.get(code, ''))

        disabled_checks = set(filter(bool, map(str.strip, disabled_checks)))

        if line_before_comment:
            buf = [line_before_comment, f"  # noqa: {flake8_codes:,}"]
        else:
            buf = [f"# noqa: {flake8_codes:,}"]

        if disabled_checks:
            buf.extend([
                "  # pylint: disable=",
                f"{DelimitedList(sorted(disabled_checks)):,}",
            ])

        buf.extend([
            "  ",
            line_after_comments.lstrip(),
        ])

        contents[idx] = ''.join(buf).rstrip()

    changed = contents != original_contents

    if changed:
        file.write_lines(contents, trailing_whitespace=True)

    return changed