def format_file_in_place( src: Path, line_length: int, 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"], line_length=line_length, 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: with src.open("w") as fp: nbformat.write(src_contents, fp) return sub_report
def blacken(lines, mode=None): for original_line_range, code_format, line_unit in lines: if code_format == "none": yield line_unit continue indentation_depth, parameters, code = extract_code( line_unit, code_format) current_mode = black.FileMode() if mode is None else copy.copy(mode) current_mode.line_length -= indentation_depth + parameters.pop( "prompt_length", 0) original_line_number, _ = original_line_range original_line_number += parameters.pop("n_header_lines", 0) try: blackened = black.format_str(code, mode=current_mode).rstrip() except TokenError as e: message, (apparent_line_number, column) = e.args lineno = original_line_number + (apparent_line_number - 1) faulty_line = code.split("\n")[(apparent_line_number - 1) - 1] raise black.InvalidInput( f"Cannot parse: {lineno}:{column}: {message}: {faulty_line}") except black.InvalidInput as e: message, apparent_line_number, column, faulty_line = parse_message( str(e)) lineno = original_line_number + (apparent_line_number - 1) raise black.InvalidInput( f"{message}: {lineno}:{column}: {faulty_line}") except IndentationError as e: lineno = original_line_number + (e.lineno - 1) line = e.text.rstrip() # TODO: try to find the actual line, this exception is # only raised when the indentation causes the code to # become ambiguous raise black.InvalidInput(f"Invalid indentation: {lineno}: {line}") reformatted = reformat_code(blackened, code_format, indentation_depth, **parameters) yield reformatted