Unverified Commit 7567cdf3 authored by Hassan Abouelela's avatar Hassan Abouelela Committed by GitHub
Browse files

Code Flag Options (#2259)

Properly handles the diff, color, and fast option when black is run with
 the `--code` option.

Closes #2104, closes #1801.
parent fdc4b674
Loading
Loading
Loading
Loading
+1 −0
Changes for AUTHORS.md: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -68,6 +68,7 @@ Multiple contributions by:
- Gustavo Camargo
- hauntsaninja
- [Hadi Alqattan](mailto:alqattanhadizaki@gmail.com)
- [Hassan Abouelela](mailto:hassan@hassanamr.com)
- [Heaford](mailto:dan@heaford.com)
- [Hugo Barrera](mailto::hugo@barrera.io)
- Hugo van Kemenade
+2 −0
Changes for CHANGES.md: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -15,6 +15,7 @@
- Respect `.gitignore` files in all levels, not only `root/.gitignore` file (apply
  `.gitignore` rules like `git` does) (#2225)
- Restored compatibility with Click 8.0 on Python 3.6 when LANG=C used (#2227)
- Fixed option usage when using the `--code` flag (#2259)
- Add extra uvloop install + import support if in python env (#2258)
- Fix --experimental-string-processing crash when matching parens are not found (#2283)
- Make sure to split lines that start with a string operator (#2286)
@@ -43,6 +44,7 @@
- Fix typos discovered by codespell (#2228)
- Fix Vim plugin installation instructions. (#2235)
- Add new Frequently Asked Questions page (#2247)
- Removed safety checks warning for the `--code` option (#2259)
- Fix encoding + symlink issues preventing proper build on Windows (#2262)

## 21.5b1
+0 −7
Changes for docs/usage_and_configuration/the_basics.md: 0 added lines, 7 removed lines.
Original line number Diff line number Diff line
@@ -68,13 +68,6 @@ $ black --code "print ( 'hello, world' )"
print("hello, world")
```

```{warning}
--check, --diff, and --safe / --fast have no effect when using -c / --code. Safety
checks normally turned on by default that verify _Black_'s output are disabled as well.
This is a bug which we intend to fix eventually. More details can be found in this [bug
report](https://github.com/psf/black/issues/2104).
```

### Writeback and reporting

By default _Black_ reformats the files given and/or found in place. Sometimes you need
+55 −4
Changes for src/black/__init__.py: 55 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -384,10 +384,19 @@ def main(
    )
    if config and verbose:
        out(f"Using configuration from {config}.", bold=False, fg="blue")

    if code is not None:
        print(format_str(code, mode=mode))
        ctx.exit(0)
        # Run in quiet mode by default with -c; the extra output isn't useful.
        # You can still pass -v to get verbose output.
        quiet = True

    report = Report(check=check, diff=diff, quiet=quiet, verbose=verbose)

    if code is not None:
        reformat_code(
            content=code, fast=fast, write_back=write_back, mode=mode, report=report
        )
    else:
        sources = get_sources(
            ctx=ctx,
            src=src,
@@ -419,11 +428,16 @@ def main(
            )
        else:
            reformat_many(
            sources=sources, fast=fast, write_back=write_back, mode=mode, report=report
                sources=sources,
                fast=fast,
                write_back=write_back,
                mode=mode,
                report=report,
            )

    if verbose or not quiet:
        out("Oh no! 💥 💔 💥" if report.return_code else "All done! ✨ 🍰 ✨")
        if code is None:
            click.secho(str(report), err=True)
    ctx.exit(report.return_code)

@@ -512,6 +526,30 @@ def path_empty(
        ctx.exit(0)


def reformat_code(
    content: str, fast: bool, write_back: WriteBack, mode: Mode, report: Report
) -> None:
    """
    Reformat and print out `content` without spawning child processes.
    Similar to `reformat_one`, but for string content.

    `fast`, `write_back`, and `mode` options are passed to
    :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
    """
    path = Path("<string>")
    try:
        changed = Changed.NO
        if format_stdin_to_stdout(
            content=content, fast=fast, write_back=write_back, mode=mode
        ):
            changed = Changed.YES
        report.done(path, changed)
    except Exception as exc:
        if report.verbose:
            traceback.print_exc()
        report.failed(path, str(exc))


def reformat_one(
    src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
) -> None:
@@ -720,16 +758,27 @@ def format_file_in_place(


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

    If content is None, it's read from sys.stdin.

    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()

    if content is None:
        src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
    else:
        src, encoding, newline = content, "utf-8", ""

    dst = src
    try:
        dst = format_file_contents(src, fast=fast, mode=mode)
@@ -743,6 +792,8 @@ def format_stdin_to_stdout(
            sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
        )
        if write_back == WriteBack.YES:
            # Make sure there's a newline after the content
            dst += "" if dst[-1] == "\n" else "\n"
            f.write(dst)
        elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
            now = datetime.utcnow()
+1 −1
Changes for src/black/files.py: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -38,7 +38,7 @@ def find_project_root(srcs: Sequence[str]) -> Path:
    project root, the root of the file system is returned.
    """
    if not srcs:
        return Path("/").resolve()
        srcs = [str(Path.cwd().resolve())]

    path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]

Loading