How to use the black.InvalidInput function in black

To help you get started, we’ve selected a few black examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github psf / black / tests / test_black.py View on Github external
def test_lib2to3_parse(self) -> None:
        with self.assertRaises(black.InvalidInput):
            black.lib2to3_parse("invalid syntax")

        straddling = "x + y"
        black.lib2to3_parse(straddling)
        black.lib2to3_parse(straddling, {TargetVersion.PY27})
        black.lib2to3_parse(straddling, {TargetVersion.PY36})
        black.lib2to3_parse(straddling, {TargetVersion.PY27, TargetVersion.PY36})

        py2_only = "print x"
        black.lib2to3_parse(py2_only)
        black.lib2to3_parse(py2_only, {TargetVersion.PY27})
        with self.assertRaises(black.InvalidInput):
            black.lib2to3_parse(py2_only, {TargetVersion.PY36})
        with self.assertRaises(black.InvalidInput):
            black.lib2to3_parse(py2_only, {TargetVersion.PY27, TargetVersion.PY36})
github Nikoleta-v3 / blackbook / src / blackbook / main.py View on Github external
def format_notebook_content(path: pathlib.Path) -> dict:
    content = path.read_text()
    nb = json.loads(content)

    for cell in nb["cells"]:
        try:
            string = "".join(cell["source"])
            formatted_string = black.format_str(string, line_length=black.DEFAULT_LINE_LENGTH)
            cell["source"] = [s + "\n" for s in formatted_string.split("\n")][:-1]
        except black.InvalidInput:
            pass

    return nb
github tomcatling / black-nb / black_nb / cli.py View on Github external
src: Path,
    write_back: black.WriteBack,
    mode: black.FileMode,
    clear_output: bool,
    sub_report: "SubReport",
) -> "SubReport":
    """
    Format file under `src` path. Return True if changed.
    If `write_back` is YES, write reformatted code to the file.
    """
    try:
        src_contents = nbformat.read(str(src), as_version=nbformat.NO_CONVERT)
    except nbformat.reader.NotJSONError:
        raise black.InvalidInput("Not JSON")
    except AttributeError:
        raise black.InvalidInput("No cells")

    dst_cells: List[Dict[Any, Any]] = []
    for cell in src_contents["cells"]:
        if cell["cell_type"] == "code":
            try:
                cell["source"] = format_cell_source(cell["source"], mode=mode)
                sub_report.done(black.Changed.YES)
            except black.NothingChanged:
                sub_report.done(black.Changed.NO)
            except black.InvalidInput:
                sub_report.failed()
            if clear_output:
                try:
                    (
                        cell["outputs"],
                        cell["execution_count"],
github stellargraph / stellargraph / scripts / format_notebooks.py View on Github external
def preprocess_cell(self, cell, resources, cell_index):
        mode = FileMode(line_length=self.linelength)

        if cell.cell_type == "code":
            try:
                formatted = format_str(src_contents=cell["source"], mode=mode)
            except InvalidInput as err:
                print(f"Formatter error: {err}")
                formatted = cell["source"]

            if formatted and formatted[-1] == "\n":
                formatted = formatted[:-1]

            if cell["source"] != formatted:
                self.notebook_cells_changed += 1

            cell["source"] = formatted
        return cell, resources
github peterjc / flake8-black / flake8_black.py View on Github external
msg = "900 Failed to load file: %s" % e

        if not source and not msg:
            # Empty file (good)
            return
        elif source:
            # Call black...
            try:
                file_mode = self._file_mode
                file_mode.is_pyi = self.filename and self.filename.endswith(".pyi")
                new_code = black.format_file_contents(
                    source, mode=file_mode, fast=False
                )
            except black.NothingChanged:
                return
            except black.InvalidInput:
                msg = "901 Invalid input."
            except BadBlackConfig as err:
                msg = "997 Invalid TOML file: %s" % err
            except Exception as err:
                msg = "999 Unexpected exception: %s" % err
            else:
                assert (
                    new_code != source
                ), "Black made changes without raising NothingChanged"
                line, col = find_diff_start(source, new_code)
                line += 1  # Strange as col seems to be zero based?
                msg = "100 Black would make changes."
        # If we don't know the line or column numbers, leaving as zero.
        yield line, col, black_prefix + msg, type(self)
github Nikoleta-v3 / blackbook / src / blackbook / __init__.py View on Github external
for cell in nb["cells"]:

                try:  # Some ipynb files will not have valid source code
                    string = "".join(cell["source"])
                    formatted_string = black.format_str(
                        string, mode=black.FileMode()
                    ).strip()  # Remove trailing newlines
                    if formatted_string != string:
                        modification_found = True
                        cell["source"] = formatted_string.splitlines()
                        cell["source"][:-1] = [
                            line + "\n" for line in cell["source"][:-1]
                        ]

                except black.InvalidInput:
                    pass

            if modification_found:
                return nb

        except KeyError:
            pass

    except json.JSONDecodeError:
        pass

    return None
github psf / black / black.py View on Github external
src_txt += "\n"

    for grammar in get_grammars(set(target_versions)):
        drv = driver.Driver(grammar, pytree.convert)
        try:
            result = drv.parse_string(src_txt, True)
            break

        except ParseError as pe:
            lineno, column = pe.context[1]
            lines = src_txt.splitlines()
            try:
                faulty_line = lines[lineno - 1]
            except IndexError:
                faulty_line = "
github tomcatling / black-nb / black_nb / cli.py View on Github external
try:
        src_contents = nbformat.read(str(src), as_version=nbformat.NO_CONVERT)
    except nbformat.reader.NotJSONError:
        raise black.InvalidInput("Not JSON")
    except AttributeError:
        raise black.InvalidInput("No cells")

    dst_cells: List[Dict[Any, Any]] = []
    for cell in src_contents["cells"]:
        if cell["cell_type"] == "code":
            try:
                cell["source"] = format_cell_source(cell["source"], mode=mode)
                sub_report.done(black.Changed.YES)
            except black.NothingChanged:
                sub_report.done(black.Changed.NO)
            except black.InvalidInput:
                sub_report.failed()
            if clear_output:
                try:
                    (
                        cell["outputs"],
                        cell["execution_count"],
                    ) = clear_cell_outputs(
                        cell["outputs"], cell["execution_count"]
                    )
                    sub_report.done_output(black.Changed.YES)
                except black.NothingChanged:
                    sub_report.done_output(black.Changed.NO)
        dst_cells.append(cell)
    src_contents["cells"] = dst_cells

    if write_back is black.WriteBack.YES:
github tomcatling / black-nb / black_nb / cli.py View on Github external
def format_file_in_place(
    src: Path,
    write_back: black.WriteBack,
    mode: black.FileMode,
    clear_output: bool,
    sub_report: "SubReport",
) -> "SubReport":
    """
    Format file under `src` path. Return True if changed.
    If `write_back` is YES, write reformatted code to the file.
    """
    try:
        src_contents = nbformat.read(str(src), as_version=nbformat.NO_CONVERT)
    except nbformat.reader.NotJSONError:
        raise black.InvalidInput("Not JSON")
    except AttributeError:
        raise black.InvalidInput("No cells")

    dst_cells: List[Dict[Any, Any]] = []
    for cell in src_contents["cells"]:
        if cell["cell_type"] == "code":
            try:
                cell["source"] = format_cell_source(cell["source"], mode=mode)
                sub_report.done(black.Changed.YES)
            except black.NothingChanged:
                sub_report.done(black.Changed.NO)
            except black.InvalidInput:
                sub_report.failed()
            if clear_output:
                try:
                    (