Repository: psf/black
File: black.py (Python)

Code before:
            dst_name = f"STDOUT\t{now} +0000"
            d = diff(src, dst, src_name, dst_name)
            if write_back == WriteBack.COLOR_DIFF:
                d = color_diff(d)
                f = wrap_stream_for_windows(f)
            f.write(d)
        f.detach()


def format_file_contents(
    src_contents: str, *, fast: bool, mode: FileMode
) -> FileContent:
    """Reformat contents a file and return new contents.

    If `fast` is False, additionally confirm that the reformatted code is
    valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
    `mode` is passed to :func:`format_str`.
    """
    if src_contents.strip() == "":
        raise NothingChanged

    dst_contents = format_str(src_contents, mode=mode)
    if src_contents == dst_contents:
        raise NothingChanged

    if not fast:
        assert_equivalent(src_contents, dst_contents)
        assert_stable(src_contents, dst_contents, mode=mode)
    return dst_contents


def format_str(src_contents: str, *, mode: FileMode) -> FileContent:
    """Reformat a string and return new contents.

    `mode` determines formatting options, such as how many characters per line are
    allowed.
    """
    src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
    dst_contents = []
    future_imports = get_future_imports(src_node)
    if mode.target_versions:
        versions = mode.target_versions
    else:
        versions = detect_target_versions(src_node)
    normalize_fmt_off(src_node)
    lines = LineGenerator(
        remove_u_prefix="unicode_literals" in future_imports
        or supports_feature(versions, Feature.UNICODE_LITERALS),
        is_pyi=mode.is_pyi,
        normalize_strings=mode.string_normalization,
    )

Review comment (suggestion):
I don't like this, but I don't fully understand what `detach` does or why it's needed, so this is the best I could come up with.

Code after:
        lines[i] = line
    return "\n".join(lines)


def wrap_stream_for_windows(
    f: io.TextIOWrapper,
) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32.AnsiToWin32"]:
    """
    Wrap the stream in colorama's wrap_stream so colors are shown on Windows.

    If `colorama` is not found, then no change is made. If `colorama` does
    exist, then it handles the logic to determine whether or not to change
    things.
    """
    try:
        from colorama import initialise

        # We set `strip=False` so that we can don't have to modify
        # test_express_diff_with_color.
        f = initialise.wrap_stream(
            f, convert=None, strip=False, autoreset=False, wrap=True
        )

        # wrap_stream returns a `colorama.AnsiToWin32.AnsiToWin32` object
        # which does not have a `detach()` method. So we fake one.
        f.detach = lambda *args, **kwargs: None  # type: ignore
    except ImportError:
        pass

    return f


def format_stdin_to_stdout(
    fast: bool, *, write_back: WriteBack = WriteBack.NO, mode: Mode
) -> bool:
    """Format file on stdin. Return True if changed.

    If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
    write a diff to stdout. The `mode` argument is passed to
    :func:`format_file_contents`.
    """
    then = datetime.utcnow()
    src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
    dst = src
    try:
        dst = format_file_contents(src, fast=fast, mode=mode)
        return True

    except NothingChanged:
        return False