Commit Graph

303 Commits

Author SHA1 Message Date
Jelle Zijlstra
e7ddf524b0
Show details when a regex fails to compile (GH-2678) 2021-12-07 22:13:05 -05:00
Richard Si
f1d4e742c9
Prepare for release 21.12b0 (GH-2673)
Let's do this!
2021-12-05 16:39:34 -05:00
Batuhan Taskaya
28ab82aab0
perf: drop the initial stack copy (#2670)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-05 13:03:48 -08:00
Jelle Zijlstra
9424e795bf
Reorganize changelog (#2669)
I believe it would be useful to split up the long list of changes a bit more.

Specific changes:
- Removed the entry for new flake8 plugins; this is purely internal and not of interest to users
- Put regex in the packaging section
- New section for Jupyter Notebook
- New section for Python 3.10, mostly match/case stuff
2021-12-04 15:57:40 -08:00
Jelle Zijlstra
dc8cdda8fd
tell users to use -t py310 (#2668) 2021-12-04 15:30:23 -08:00
Tanvi Moharir
f52cb0fe37
Don't let TokenError bubble up from lib2to3_parse (GH-2343)
error: cannot format <string>: ('EOF in multi-line statement', (2, 0))
   
 ▲ before ▼ after

error: cannot format <string>: Cannot parse: 2:0: EOF in multi-line statement

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-04 15:21:26 -05:00
Batuhan Taskaya
136930fccb
Make star-expression spacing consistent in match/case (#2667) 2021-12-03 06:49:33 -08:00
Jelle Zijlstra
bd9d52b52d
Remove regex dependency (GH-2663)
We were no longer using it since GH-2644 and GH-2654. This should hopefully
make using Black easier to use as there's one less compiled dependency.
The core team also doesn't have to deal with the surprisingly frequent fires
the regex packaging setup goes through.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-02 17:35:02 -05:00
Batuhan Taskaya
20d7ae0676
Ensure match/case are recognized as statements (#2665) 2021-12-02 09:58:22 -08:00
Richard Si
b0c2bcc953
Treat functions/classes in blocks as if they're nested (GH-2472)
* Treat functions/classes in blocks as if they're nested

One curveball is that we still want two preceding newlines before blocks
that are probably logically disconnected. In other words:

    if condition:

        def foo():
            return "hi"
                             # <- aside: this is the goal of this commit
    else:

        def foo():
            return "cya"
                             # <- the two newlines spacing here should stay
                             #    since this probably isn't related
    with open("db.json", encoding="utf-8") as f:
        data = f.read()

Unfortunately that means we have to special case specific clause types
instead of just being able to just for a colon leaf. The hack used here
is to check whether we're adding preceding newlines for a standalone or
dependent clause. "Standalone" being a clause that doesn't need another
clause to be valid (eg. if) and vice versa.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-12-01 18:05:59 -05:00
Shantanu
f1813e31b6
Fix determination of f-string expression spans (#2654)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-12-01 09:52:24 -08:00
Jelle Zijlstra
0f7cf9187f
fix error message for match (#2649)
Fixes #2648.

Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
2021-11-30 18:39:39 -08:00
Jelle Zijlstra
5e2bb528e0
Reduce usage of regex (#2644)
This removes all but one usage of the `regex` dependency. Tricky bits included:
- A bug in test_black.py where we were incorrectly using a character range. Fix also submitted separately in #2643.
- `tokenize.py` was the original use case for regex (#1047). The important bit is that we rely on `\w` to match anything valid in an identifier, and `re` fails to match a few characters as part of identifiers. My solution is to instead match all characters *except* those we know to mean something else in Python: whitespace and ASCII punctuation. This will make Black able to parse some invalid Python programs, like those that contain non-ASCII punctuation in the place of an identifier, but that seems fine to me.
- One import of `regex` remains, in `trans.py`. We use a recursive regex to parse f-strings, and only `regex` supports that. I haven't thought of a better fix there (except maybe writing a manual parser), so I'm leaving that for now.

My goal is to remove the `regex` dependency to reduce the risk of breakage due to dependencies and make life easier for users on platforms without wheels.
2021-11-30 18:01:36 -08:00
Batuhan Taskaya
b336b390d0
Fix line generation for match match: / case case: (GH-2661) 2021-11-30 15:56:38 -05:00
Batuhan Taskaya
8cdac18a04
Allow top-level starred expression on match (#2659)
Fixes #2647
2021-11-30 07:52:25 -08:00
Daniel Sparing
a066a2bc8b
Return NothingChanged if non-Python cell magic is detected, to avoid tokenize error (#2630)
Fixes https://github.com/psf/black/issues/2627 , a non-Python cell magic such as `%%writeline` can legitimately contain "incorrect" indentation, however this causes `tokenize-rt` to return an error. To avoid this, `validate_cell` should early detect cell magics (just like it detects `TransformerManager` transformations).

Test added too, in the shape of a "badly indented" `%%writefile` within `test_non_python_magics`.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Marco Edward Gorelli <marcogorelli@protonmail.com>
2021-11-29 15:07:35 -08:00
danieleades
a18ee4018f
add more flake8 lints (#2653) 2021-11-28 18:20:52 -08:00
Marco Edward Gorelli
e0253080b0
Assignment to env var in Jupyter Notebook doesn't round-trip (#2642)
closes #2641
2021-11-26 08:14:57 -08:00
Batuhan Taskaya
dfa45cec9e
grammar: accept open sequences on match subject (GH-2639)
* grammar: accept open sequences on match subject
* give an example about the fixed match subject
2021-11-24 20:21:36 -05:00
Matthew D. Scholefield
05954c0950
Fix process pool fallback on Python 3.10 (GH-2631)
In Python 3.10 the exception generated by creating a process pool on
a Python build that doesn't support this is now `NotImplementedError`

Commit history before merge:

* Fix process pool fallback on Python 3.10
* Update CHANGES.md
* Update CHANGES.md

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-11-20 14:25:30 -05:00
Jelle Zijlstra
19f6aa8208
prepare release 2021.11b1 (#2622) 2021-11-17 19:51:49 -08:00
Rowan Seymour
ecf8c74481
Bump regex dependency to 2021.4.4 to fix import of Pattern class (#2621)
Fixes #2620
2021-11-17 19:46:28 -08:00
Jelle Zijlstra
d0b04d9f21
prepare release 21.11b0 (#2616) 2021-11-16 18:30:19 -08:00
Jelle Zijlstra
1d7260050d
vim: Parse skip_magic_trailing_comma from pyproject.toml (#2613)
Co-authored-by: Kyle Kovacs <kkovacs@diconfiberoptics.com>
2021-11-15 19:03:47 -08:00
Michal Siska
78317a4cfb
Removed distutils import from autoload/black.vim (#2607) (#2610) 2021-11-15 08:51:56 -08:00
Hugo van Kemenade
3cb010ec8e
Declare support for Python 3.10 (#2562) 2021-11-14 06:37:06 -08:00
Oliver Margetts
eb9d0396cd
Allow install under pypy (#2559)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-11-13 19:46:15 -08:00
Batuhan Taskaya
1e0ec543ff
black/parser: partial support for pattern matching (#2586)
Partial implementation for #2242. Only works when explicitly stated -t py310.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-11-13 19:15:31 -08:00
Kian Meng Ang
53cabe7265
Fix typos (#2603) 2021-11-11 19:02:43 -08:00
Richard Si
0753d99519
Improve Python 2 only syntax detection (GH-2592)
* Improve Python 2 only syntax detection

First of all this fixes a mistake I made in Python 2 deprecation PR
using token.* to check for print/exec statements. Turns out that
for nodes with a type value higher than 256 its numeric type isn't
guaranteed to be constant. Using syms.* instead fixes this.

Also add support for the following cases:

    print "hello, world!"

    exec "print('hello, world!')"

    def set_position((x, y), value):
        pass

    try:
        pass
    except Exception, err:
        pass

    raise RuntimeError, "I feel like crashing today :p"

    `wow_these_really_did_exist`

    10L

* Add octal support, more test cases, and fixup long ints

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-11-11 20:28:48 -05:00
Cooper Lees
64c8be01f0
Update CHANGES.md for 21.10b0 release (#2583)
* Update CHANGES.md for 21.10b0 release

* Update version in docs/usage_and_configuration/the_basics.md

* Also update docs/integrations/source_version_control.md ...
2021-10-31 17:59:39 -07:00
Vincent Barbaresi
bd961304b6
install build-essential to compile dependencies and use multi-stage build (#2582)
- Install build-essential to avoid build issues like #2568 when dependencies don't have prebuilt wheels available
- Use multi-stage build instead of trying to purge packages and cache from the image
  Copying `/root/.local/` installs only black's built Python dependencies (< 20 MB).
  So the image is barely larger than python:3-slim base image
2021-10-31 17:43:34 -07:00
Richard Si
b21c0c3d28
Deprecate Python 2 formatting support (#2523)
* Prepare for Python 2 depreciation

- Use BlackRunner and .stdout in command line test

So the next commit won't break this test. This is in its own commit so
we can just revert the depreciation commit when dropping Python 2
support completely.

* Deprecate Python 2 formatting support
2021-10-31 16:46:12 -07:00
Cooper Lees
7bf233a944
Pin regex in docker to 2021.10.8 (GH-2579)
* Pin regex in docker to 2021.10.8
- This is due to 2021.10.8 having arm wheels and newer versions not

I will go see if I can help restore arm build @ https://bitbucket.org/mrabarnett/mrab-regex/issues/399/missing-wheel-for-macosx-and-the-new-m1 soon.

Test: Build on my M1 mac: `docker build -t cooperlees/black .`

* Add in that the pin is only for docker
2021-10-31 13:41:12 -04:00
Richard Si
9afffacaa0
Address mypy errors on 3.10 w/ asyncio loop parameter (#2580) 2021-10-30 15:35:55 -07:00
Nipunn Koorapati
5434407af7
black-primer: Print summary after individual failures (#2570)
If the individual failures are verbose, it's useful to have
the summary at the end. Otherwise, it can be really difficult
to figure out which projects have an issue.
2021-10-28 10:35:37 -07:00
Nipunn Koorapati
467efe1556
Add --projects cli flag to black-primer (#2555)
* Add --projects cli flag to black-primer

Makes it possible to run a subset of projects on black primer

* Refactor into click callback
2021-10-27 11:31:34 -07:00
Jelle Zijlstra
c75abed63e
Define a stability policy (#2529)
Fixes #2394. Eventually fixes #517.

This is essentially @pradyunsg's suggestion from #2394. I suggest that at the
same time we start the formal stability policy, we take a few other disruptive steps
and drop Python 2 and the "b" marker.

Co-authored-by: Pradyun Gedam <pradyunsg@gmail.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2021-10-21 17:02:38 +02:00
Zac Hatfield-Dodds
2f3fa1f6d0
Fix feature detection for positional-only arguments in lambdas (#2532) 2021-10-11 21:45:58 -07:00
Richard Si
872bb9474e
Bump typed-ast minimum to 1.4.3 for 3.10 compat (#2519) 2021-10-04 17:36:57 -07:00
Fergus Mitchell
0fd353f163
Add --workers CLI parameter (fixes #2513) (#2514)
Fixes #2513
2021-09-29 09:50:44 -07:00
shaoran
09915f4bd2
Allow to pass the FileMode options in the vim plugin (#1319) 2021-09-28 17:31:29 -07:00
Zsolt Dollenstein
1af5331089
Bump required aiohttp version to 3.7.4 (#2509)
Commit history before merge:

* Bump required aiohttp version to 3.7.4

This release includes an important security fix
(https://github.com/aio-libs/aiohttp/security/advisories/GHSA-v6wp-4m6f-gcjg) and many
other improvements.

* add changelog entry
* Let's not forget about Pipfile

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-09-25 15:45:13 -04:00
Zsolt Dollenstein
a5381ba764
re-implement simple CORS middleware for blackd (#2500)
* re-implement simple CORS middleware for blackd
* remove aiohttp-cors from setup.py
* Remove aiohttp-cors from Pipfile.lock

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-09-25 12:58:44 +01:00
Jelle Zijlstra
911470a610
Update CHANGES.md for 21.9b0 release (#2494) 2021-09-13 19:23:11 -07:00
Sorin Sbarnea
41e6700640
Fix missing toml extra w/ setuptools-scm (GH-2475)
Project packaging is using TOML due to pyproject.toml but fails to
mention it, causing installation failures with newer setuptools-scm 6.3.0.

Commit history before merge:

* Fix missing toml extra

Fixed breakage uncovered by setuptools-scm 6.3.0 where installation
would fail for project that missed to mention the toml extra.

* Bump setuptools[-scm] to avoid toml extra

https://github.com/psf/black/pull/2475#issuecomment-912730714

> If you constraint greater than 6.3.0 and setuptools greater than 45
> you can skip the extra,

* Actually for safety reasons, just use the extra

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-09-06 17:10:39 -04:00
Jameel Al-Aziz
72de89f54e
Add hidden import to PyInstaller build (GH-2466)
Add new platformdirs dependencies as hidden imports when creating
PyInstaller-based binaries.

platformdirs imports the module for each platform dynamically, which
PyInstaller is unable to correctly detect for packing. By adding the
modules as hidden imports, we are telling PyInstaller to include the
modules in the packaged binary.

This issue seems to have been introduce when switching to platformdirs
in #2375. fixes #2464

Commit history before merge:

* Add hidden import to PyInstaller build

Add new platformdirs dependency as a hidden import when creating
PyInstaller based binaries.

* Only include the platformdirs for the relevant os
2021-09-01 18:05:11 -04:00
Richard Si
a8b4665e7d
Exclude broken typing-extensions version + fix import (#2460)
re. import, the ipynb code was assuming that typing-extensions would
always be available, but that's not the case! There's an environment
marker on the requirement meaning it won't get installed on 3.10 or
higher. The test suite didn't catch this issue since aiohttp pulls in
typing-extensions unconditionally.
2021-08-29 17:04:49 -04:00
Richard Si
16275d24e3
Prepare CHANGES.md for release 21.8b0 (#2458)
Hopefully my first release doesn't end up in flames 🔥

Commit history before merge:

* Prepare CHANGES.md for release 21.8b0
* I need to add a check for this too.
2021-08-29 14:56:22 -04:00
Richard Si
a5bb6e0a32
Pin setuptools-scm build time dependency (#2457)
The setuptools-scm dependency in setup.cfg did not have a version
specified, leading to the issues described in #2449 after a faulty release
of setuptools-scm was published. To avoid this issue in the future, the
last version before that faulty update is now pinned.

Commit history before merge:

* Pin setuptools-scm dependency version (#2449)
* Update CHANGES.md
* Let's pin in pyproject.toml too

Mostly since it's non-build-backend specific configuration and more
widely standardized file. Not sure what benefits pinning in setup.cfg
gives us on top of pyproject.toml but I'd rather not find out during
the release that is supposed to happen today 😉

Co-authored-by: FiNs <24248249+FabianNiehaus@users.noreply.github.com>
2021-08-28 15:37:53 -04:00
Richard Si
366a0806eb
blib2to3: support unparenthesized wulruses in more places (#2447)
Implementation stolen from PR davidhalter/parso#162. Thanks parso!

I could add support for these newer syntactical constructs in the
target version detection logic, but until I get diff-shades up
and running I don't feel very comfortable adding the code.
2021-08-26 13:59:01 -07:00
Richard Si
8a59528c2d
Stop changing return type annotations to tuples (#2384)
This fixes a bug where a trailing comma would be added to a
parenthesized return annotation changing its type to a tuple.
Here's one case where this bug shows up:

```
def spam() -> (
    this_is_a_long_type_annotation_which_should_NOT_get_a_trailing_comma
):
    pass
```

The root problem was that the type annotation was treated as if it was
a parameter & import list (is_body=True to linegen::bracket_split_build_line)
where a trailing comma is usually fine. Now there's another check in the
aforementioned function to make sure the body it's operating on isn't
a return annotation before truly adding a trailing comma.
2021-08-25 18:32:27 -07:00
erykoff
0969ca4a46
Change sys.exit to raise ImportError (#2440)
The fix for #1688 in #1761 breaks help("modules") introspection and also leads
to unhappy results when inadvertently importing blackd from Python. Basically
the sys.exit(-1) causes the whole Python REPL to exit -- not great to suffice.

Commit history before merge:

* Change sys.exit to Raise.
* Add #2440 to changelog.
* Fix lint error from prettier
* Remove exception chain for more helpful user message.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-08-24 16:59:24 -04:00
Richard Si
8c04847aa2
Improve f-string expression detection regex so ... (#2437)
we don't accidentally add backslashes to them when normalizing quotes
because that's invalid syntax!

The problem this commit fixes is that matches would eat too much
blocking important matches to occur. For example, here's one f-string
body:

    {a}{b}{c}

I know there's no risk of introducing backslashes here, but the regex
already goes sideways with this. Throwing this example at regex101
I get:

    {a}{b}{c}   # The As and Bs are the two matches, and the upper
    ---- ----   # case letters are the groups with those matches.
    aAaa bbBb

... we've missed the middle expression (so if any backslashes in a
more complex example were introduced there we wouldn't bail out
even though we should -- hence the bug). As it stands the regex
needs somesort of extra character (or the start/end of the body)
around the expressions but that isn't always the case as shown
above.

The fix implemented here is to turn the "eat a surrounding non-curly
bracket character" groups ie. `(?:[^{]|^)` and `(?:[^}]|$)` into
negative lookaheads and lookbehinds. This still guarantees the
already specified rules but without problematically eating extra
characters ^^
2021-08-22 19:52:19 -07:00
Nipunn Koorapati
104aec555f
Present a more user-friendly error if .gitignore is invalid (#2414)
Fixes #2359.

This commit now makes Black exit with an user-friendly error message if a
.gitignore file couldn't be parsed -- a massive improvement over an opaque
traceback!
2021-08-20 19:54:53 -04:00
Aneesh Agrawal
ef7c45f281
Remove language_version for pre-commit (#2430)
* Remove `language_version` for pre-commit

At my company, we set the Python version in `default_language_version`
in each repo's `.pre-commit-config.yaml`,
so that all hooks are running with the same Python version.

However, this currently doesn't work for black,
as the `language_version` specified here
in the upstream `.pre-commit-hooks.yaml` takes precedence.
Currently, this requires us to manually set `language_version`
specifically for black,
duplicating the value from `default_language_version`.
The failure mode otherwise is subtle -
black works most of the time,
but try to add a walrus operator and it suddenly breaks!

Given that black's `setup.py` already has `python_requires>=3.6.2`,
specifying that `python3` must be used here isn't needed
as folks inadvertently using Python 2 will get hook-install-time failures anyways.
Remove the `language_version` from these upstream hook configs
so that users of black are able to use `default_language_version`
and have it apply to all their hooks, black included.

Example `.pre-commit-config.yaml` before:
```
default_language_version:
  python: python3.8
repos:
-   repo: https://github.com/psf/black
    rev: 21.7b0
    hooks:
    -   id: black
        language_version: python3.8
```

After:
```
default_language_version:
  python: python3.8
repos:
-   repo: https://github.com/psf/black
    rev: 21.7b0
    hooks:
    -   id: black
```

* Add changelog entry
2021-08-18 12:24:14 -04:00
Marco Edward Gorelli
b1d0601016
Jupyter notebook support (#2357)
To summarise, based on what was discussed in that issue:

due to not being able to parse automagics (e.g. pip install black)
without a running IPython kernel, cells with syntax which is parseable
by neither ast.parse nor IPython will be skipped cells with multiline
magics will be skipped trailing semicolons will be preserved, as they
are often put there intentionally in Jupyter Notebooks to suppress
unnecessary output

Commit history before merge (excluding merge commits):

* wip
* fixup tests
* skip tests if no IPython
* install test requirements in ipynb tests
* if --ipynb format all as ipynb
* wip
* add some whole-notebook tests
* docstrings
* skip multiline magics
* add test for nested cell magic
* remove ipynb_test.yml, put ipynb tests in tox.ini
* add changelog entry
* typo
* make token same length as magic it replaces
* only include .ipynb by default if jupyter dependencies are found
* remove logic from const
* fixup
* fixup
* re.compile
* noop
* clear up
* new_src -> dst
* early exit for non-python notebooks
* add non-python test notebook
* add repo with many notebooks to black-primer
* install extra dependencies for black-primer
* fix planetary computer examples url
* dont run on ipynb files by default
* add scikit-lego (Expected to change) to black-primer
* add ipynb-specific diff
* fixup
* run on all (including ipynb) by default
* remove --include .ipynb from scikit-lego black-primer
* use tokenize so as to mirror the exact logic in IPython.core.displayhooks quiet
* fixup
* 🎨
* clarify docstring
* add test for when comment is after trailing semicolon
* enumerate(reversed) instead of [::-1]
* clarify docstrings
* wip
* use jupyter and no_jupyter marks
* use THIS_DIR
* windows fixup
* perform safe check cell-by-cell for ipynb
* only perform safe check in ipynb if not fast
* remove redundant Optional
* 🎨
* use typeguard
* dont process cell containing transformed magic
* require typing extensions before 3.10 so as to have TypeGuard
* use dataclasses
* mention black[jupyter] in docs as well as in README
* add faq
* add message to assertion error
* add test for indented quieted cell
* use tokenize_rt else we cant roundtrip
* fmake fronzet set for tokens to ignore when looking for trailing semicolon
* remove planetary code examples as recent commits result in changes
* use dataclasses which inherit from ast.NodeVisitor
* bump typing-extensions so that TypeGuard is available
* bump typing-extensions in Pipfile
* add test with notebook with empty metadata
* pipenv lock
* deprivative validate_cell
* Update README.md
* Update docs/getting_started.md
* dont cache notebooks if jupyter dependencies arent found
* dont write to cache if jupyter deps are not installed
* add notebook which cant be parsed
* use clirunner
* remove other subprocess calls
* add docstring
* make verbose and quiet keyword only
* 🎨
* run second many test on directory, not on file
* test for warning message when running on directory
* early return from non-python cell magics
* move NothingChanged to report to avoid circular import
* remove circular import
* reinstate --ipynb flag

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-08-06 16:57:46 -04:00
Bernát Gábor
4dd100bff2
Use platformdirs over appdirs (#2375)
Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
Signed-off-by: Bernát Gábor <gaborjbernat@gmail.com>
2021-07-16 13:45:47 -04:00
Cooper Lees
e3000ace2f
Update CHANGES.md for 21.7b0 release (#2376)
* Update CHANGES.md for 21.7b0 release

* move some changes to the right section

* another one

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-07-16 07:42:47 -07:00
Felix Hildén
91773b8909
Improve AST safety parsing error message (#2304)
Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2021-07-13 10:24:55 -07:00
Richard Si
2946d3b03d
Switch toml TOML library for tomli (#2301)
toml unfortunately has a lack of maintainership issue right now. It's
evident by the fact toml only supports TOML v0.5.0. TOML v1.0.0 has
been recently released and right now Black crashes hard on its usage.

tomli is a brand new parse only TOML library. It supports TOML
v1.0.0. Although TBH we're switching to this one mostly because
pip is doing the same.

*The upper bound was included at the library maintainer's request.

Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Co-authored-by: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com>
2021-07-12 16:01:38 -04:00
simaki
017aafea99
Accept empty stdin (close #2337) (#2346)
Commit history before merge:

* Accept empty stdin (close #2337)
* Update tests/test_black.py
* Add changelog
* Assert Black reformats an empty string to an empty string (#2337) (#2346)
* fix
2021-06-23 15:11:23 -04:00
Bryan Bugyi
e2fd914dc1
Fix internal error when FORCE_OPTIONAL_PARENTHESES feature is enabled (#2332)
Fixes #2313.
2021-06-13 10:20:50 -07:00
Bartosz Telenczuk
52384bf0a3
Vim plugin fix string normalization option (#1869)
This commit fixes parsing of the skip-string-normalization option in vim
plugin. Originally, the plugin read the string-normalization option,
which does not exist in help (--help) and it's not respected by black
on command line.

Commit history before merge:

* fix string normalization option in vim plugin
* fix string normalization option in vim plugin
* Finish and fix patch (thanks Matt Wozniski!)

FYI: this is totally the work and the comments below of Matt (AKA godlygeek)

This fixes two entirely different problems related to how pyproject.toml
files are handled by the vim plugin.

=== Problem #1 ===

The plugin fails to properly read boolean values from pyproject.toml.
For instance, if you create this pyproject.toml:

```
[tool.black]
quiet = true
```

the Black CLI is happy with it and runs without any messages, but the
:Black command provided by this plugin fails with:

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 102, in Black
  File "<string>", line 150, in get_configs
  File "<string>", line 150, in <dictcomp>
  File "/usr/lib/python3.6/distutils/util.py", line 311, in strtobool
    val = val.lower()
AttributeError: 'bool' object has no attribute 'lower'
```

That's because the value returned by the toml.load() is already a
bool, but the vim plugin incorrectly tries to convert it from a str to a bool.

The value returned by toml_config.get() was always being passed to
flag.cast(), which is a function that either converts a string to an
int or a string to a bool, depending on the flag. vim.eval()
returns integers and strings all as str, which is why we need the cast,
but that's the wrong thing to do for values that came from toml.load().
We should be applying the cast only to the return from vim.eval()
(since we know it always gives us a string), rather than casting the
value that toml.load() found - which is already the right type.

=== Problem #2 ===

The vim plugin fails to take the value for skip_string_normalization
from pyproject.toml. That's because it looks for a string_normalization
key instead of a skip_string_normalization key, thanks to this line
saying the name of the flag is string_normalization:

black/autoload/black.vim (line 25 in 05b54b8)
```
 Flag(name="string_normalization", cast=strtobool),
```

and this dictcomp looking up each flag's name in the config dict:

black/autoload/black.vim (lines 148 to 151 in 05b54b8)
```
 return {
   flag.var_name: flag.cast(toml_config.get(flag.name, vim.eval(flag.vim_rc_name)))
   for flag in FLAGS
 }
```

For the second issue, I think I'd do a slightly different patch. I'd
keep the change to invert this flag's meaning and change its name that
this PR proposes, but I'd also change the handling of the
g:black_skip_string_normalization and g:black_string_normalization
variables to make it clear that g:black_skip_string_normalization is
the expected name, and g:black_string_normalization is only checked
when the expected name is unset, for backwards compatibility.

My proposed behavior is to check if g:black_skip_string_normalization
is defined and to define it if not, using the inverse of
g:black_string_normalization if that is set, and otherwise to the
default of 0. The Python code in autoload/black.vim runs later, and
will use the value of g:black_skip_string_normalization (and ignore
g:black_string_normalization; it will only be used to set
g:black_skip_string_normalization if it wasn't already set).

---

Co-authored-by: Matt Wozniski <mwozniski@bloomberg.net>

* Fix plugin/black.vim (need to up my vim game)

Co-authored-by: Matt Wozniski <godlygeek@gmail.com>

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Matt Wozniski <mwozniski@bloomberg.net>
Co-authored-by: Matt Wozniski <godlygeek@gmail.com>
2021-06-12 15:55:10 -04:00
Austin Glaser
4a007a881f
Find pyproject from vim relative to current file (#1871)
Commit history before merge:

* Find pyproject from vim relative to current file
* Merge remote-tracking branch 'upstream/main' into find-pyproject-vim
* Finish and fix this patch (thanks Matt Wozniski!)

Both the existing code and the proposed code are broken.
The vim.eval() call (whether it's vim.eval("@%") or
vim.eval("fnamemodify(getcwd(), ':t')) returns a string, and it passes
that string to find_pyproject_toml, which expects a sequence of strings,
not a single string, and - since a string is a sequence of single
character strings - it gets turned into a list of ridiculous paths. I
tested with a file called foo.py, and added a print(path_srcs) into
find_project_root, which printed out:

[
  PosixPath('/home/matt/f'),
  PosixPath('/home/matt/o'),
  PosixPath('/home/matt/o'),
  PosixPath('/home/matt'),
  PosixPath('/home/matt/p'),
  PosixPath('/home/matt/y')
]

This does work for an unnamed buffer, too - we wind up calling
black.find_pyproject_toml(("",)), and that winds up prepending the
working directory to any relative paths, so "" just gets turned into
the current working directory.

Note that find_pyproject_toml needs to be passed a 1-tuple, not a
list, because it requires something hashable (thanks to
functools.lru_cache being used)

Co-authored-by: Matt Wozniski <mwozniski@bloomberg.net>

* I forgot the CHANGELOG entry ... again
* I'm really bad at dealing with merge conflicts sometimes
* Be more correct describing search behaviour

Co-authored-by: Austin Glaser <austin.glaser@spacex.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Matt Wozniski <mwozniski@bloomberg.net>
2021-06-12 15:52:49 -04:00
Cooper Lees
aa31a117b1
Add STDIN test to primer (#2315)
* Add STDIN test to primer

- Check that out STDIN black support stays working
- Add asyncio.subprocess STDIN pip via communicate
- We just check we format python code from primer's `lib.py`

Fixes #2310
2021-06-10 21:06:50 -07:00
Cooper Lees
93c10bf9eb
Update CHANGES.md for 21.6b0 release (#2325) 2021-06-10 15:25:47 -07:00
jack1142
62402a3261
Support named escapes (\N{...}) in string processing (#2319)
Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-06-09 12:29:32 -07:00
Richard Si
00e7e12a3a
Regression fix: leave R prefixes capitalization alone (#2285)
`black.strings.get_string_prefix` used to lowercase the extracted
prefix before returning it. This is wrong because 1) it ignores the
fact we should leave R prefixes alone because of MagicPython, and 2)
there is dedicated prefix casing handling code that fixes issue 1.
`.lower` is too naive.

This was originally fixed in 20.8b0, but was reintroduced since 21.4b0.

I also added proper prefix normalization for docstrings by using the
`black.strings.normalize_string_prefix` helper.

Some more test strings were added to make sure strings with capitalized
prefixes aren't treated differently (actually happened with my original
patch, Jelle had to point it out to me).
2021-06-08 17:46:09 -07:00
Sergey Vartanov
40fae18134
Possible fix for issue with indentation and fmt: skip (#2281)
Not sure the fix is right.  Here is what I found: issue is connected
with line

    first.prefix = prefix[comment.consumed :]

in `comments.py`.  `first.prefix` is a prefix of the line, that ends
with `# fmt: skip`, but `comment.consumed` is the length of the
`"  # fmt: skip"` string.  If prefix length is greater than 14,
`first.prefix` will grow every time we apply formatting.

Fixes #2254
2021-06-08 14:37:34 -07:00
Bryan Bugyi
99b68e59ce
Fix incorrect custom breakpoint indices when string group contains fake f-strings (#2311)
Fixes #2293
2021-06-07 07:03:39 -07:00
Bryan Bugyi
6380b9f2f6
Account for += assignment when deciding whether to split string (#2312)
Fixes #2294
2021-06-07 07:01:57 -07:00
Felix Hildén
a2b5ba2a3a
Add option to require a specific version to be running (#2300)
Closes #1246: This PR adds a new option (and automatically a toml entry, hooray for existing configuration management 🎉) to require a specific version of Black to be running.

For example: `black --required-version 20.8b -c "format = 'this'"`

Execution fails straight away if it doesn't match `__version__`.
2021-06-03 13:09:41 -07:00
Jelle Zijlstra
df1c86cbe7
don't uvloop.install on import (#2303) 2021-06-03 19:13:55 +02:00
Jelle Zijlstra
f2a3fee15c
remove unnecessary docs changelog 2021-06-01 20:01:02 -07:00
Cooper Ry Lees
5de8c5f2f7 Move --code #2259 change log to correct unlreased section of CHANGES.md 2021-06-01 19:45:03 -07:00
Hassan Abouelela
7567cdf3b4
Code Flag Options (#2259)
Properly handles the diff, color, and fast option when black is run with
 the `--code` option.

Closes #2104, closes #1801.
2021-06-01 18:55:21 -07:00
Stefan Foulis
4005246f86
Add version to github action (and rewrite the whole thing while at it) (#1940)
Commit history before merge:

* Add black_version to github action
* Merge upstream/main into this branch
* Add version support for the Black action pt.2

  Since we're moving to a composite based action, quite a few changes
  were made. 1) Support was added for all OSes (Windows was painful). 
  2) Isolation from the rest of the workflow had to be done manually
  with a virtual environment.

  Other noteworthy changes:

  - Rewrote basically all of the logic and put it in a Python script
    for easy testing (not doing it here tho cause I'm lazy and I can't
    think of a reasonable way of testing it).
  - Renamed `black_version` to `version` to better fit the existing
    input naming scheme.
  - Added support for log groups, this makes our action's output a
    bit more fancy (I may or may have not added some debug output too).

* Add more to and sorta rewrite the Action's docs

  Reflect compatability and gotchas.

* Add CHANGELOG entry
* Merge main into this branch
* Remove debug; address typos; clean up action.yml

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-05-31 21:45:50 -04:00
Bryan Bugyi
a4e35b3149
Correct max string length calculation when there are string operators (#2292)
PR #2286 did not fix the edge-cases (e.g. when the string is just long
enough to cause a line to be 89 characters long). This PR corrects that
mistake.
2021-05-31 17:57:23 -07:00
Cooper Lees
cf75673e1a
Update CHANGES.md for 21.5b2 release (#2290)
* Update CHANGES.md for 21.5b2 release
2021-05-31 07:25:54 -07:00
Bryan Bugyi
199e3eb76b
Fix regular expression that black uses to identify f-expressions (#2287)
Fixes #1469
2021-05-30 15:34:33 -07:00
Bryan Bugyi
4ca4407b4a
Make sure to split lines that start with a string operator (#2286)
Fixes #2284
2021-05-30 23:41:03 +02:00
Bryan Bugyi
eec44f5977
Fix --experiemental-string-processing crash when matching parens not found (#2283)
Fixes #2271
2021-05-30 12:32:28 -07:00
Jelle Zijlstra
519f807f87
add discussion of magic comments to FAQ (#2272)
Co-authored-by: Cooper Lees <me@cooperlees.com>
2021-05-29 19:16:33 +02:00
Jelle Zijlstra
33e2b44014
Add --experimental-string-processing to future changes (#2273)
* add esp to future style

* changelog

* fix label
2021-05-29 07:27:54 -07:00
Felix Hildén
d3670d9c65
Use latest Python in uploading binaries (#2260)
* Use latest Python in uploading binaries

* Don't pin version at all

* Add changelog entry
2021-05-27 06:58:06 -07:00
Richard Si
6613e76658
Fix and test docs on Windows (#2262)
There's some weird interaction between Click and
sphinxcontrib-programoutput on Windows that leads to an encoding error
during the printing of black-primer's help text.

Also symlinks aren't well supported on Windows so let's just use
includes which actually work because we now use MyST :D
2021-05-26 19:04:10 -07:00
Cooper Lees
754eecf69e
Add optional uvloop import (#2258)
* Add optional uvloop import

- If we find `uvloop` in the env for black, blackd or black-primer lets try and use it
- Add a uvloop extra install

Fixes #2257

Test:
- Add ci job to install black[uvloop] and run a primer run with uvloop
  - Only with latest python (3.9)
  - Will be handy to compare runtimes as a very unoffical benchmark

* Remove tox install

* Add to CHANGES/news
2021-05-26 05:52:09 -07:00
Mark Bell
92f20d7f84
Removed adding a space into empty docstrings. (#2249)
Resolves #2168 by disabling the insertion of a " " when the docstring is entirely empty.

Note that this PR is focussed only on the case of empty docstrings. In particular this does not make any changes to the behaviour that a " " is inserted if a non-empty docstring begins with the quoting character. That is, black still prefers:

    """ "something" """

to:

    """"something" """

and that:

    """"Something""""

is not a legal docstring.
2021-05-25 15:43:28 -07:00
Felix Hildén
04518c38c9
Create FAQ documentation (GH-2247)
This commit creates a Frequently Asked Questions document for our users
to read. Hopefully they actually read it too. Items included are:
Black's non-API, AST safety, style stability, file discovery, Flake8
disagreements and Python 2 support. Hopefully I've got the answers
down in general.

Commit history before merge:

* Create FAQ
* Address feedback
* Move to single markdown file
* Minor wording improvements
* Add changelog entry
2021-05-25 16:07:05 -04:00
temeddix
3759b856af
Solved Problem with Non-ASCII .gitignore Files (#2229)
* Solved Problem with non-alphabetical .gitignore files

When .gitignore file in the user's project directory contained non-alphabetical
characters(Japanese, Korean, Chinese, etc), Nothing works and printed this
weird message in the console('cp949' is the encoding for Korean characters
in this case). It even blocks VSCode's formatting from working. This commit
solves the problem.

Traceback (most recent call last):
  File "c:\users\username\anaconda3\envs\project-name\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\username\anaconda3\envs\project-name\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\username\anaconda3\envs\project-name\Scripts\black.exe\__main__.py", line 7, in <module>
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\black\__init__.py", line 1056, in patched_main      
    main()
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\click\core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\click\core.py", line 782, in main
    rv = self.invoke(ctx)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\click\core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\click\core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\click\decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\black\__init__.py", line 394, in main
    stdin_filename=stdin_filename,
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\black\__init__.py", line 445, in get_sources        
    gitignore = get_gitignore(root)
  File "c:\users\username\anaconda3\envs\project-name\lib\site-packages\black\files.py", line 122, in get_gitignore
    lines = gf.readlines()
UnicodeDecodeError: 'cp949' codec can't decode byte 0xb0 in position 13: illegal multibyte sequence

* Made .gitignore File Reader Detect Its Encoding
* Revert "Made .gitignore File Reader Detect Its Encoding"

  This reverts commit 6c3a7ea42b5b1e441cc0026c8205d1cee68c1bba.

* Revert "Solved Problem with non-alphabetical .gitignore files"

  This reverts commit b0100b5d91c2f5db544a60f34aafab120f0aa458.

* Made .gitignore Reader Open the File with Auto Encoding Detecting

  https://docs.python.org/3.8/library/tokenize.html#tokenize.open

* Revert "Made .gitignore Reader Open the File with Auto Encoding Detecting"

  This reverts commit 50dd80422938649ccc8c7f43aac752f9f6481779.

* Made .gitignore Reader Use UTF-8
* Updated CHANGES.md for #2229
* Updated CHANGES.md for #2229
* Update CHANGES.md
* Update CHANGES.md

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-05-23 22:19:03 -04:00
Salomon Popp
0b9b7dbdab
Build macOS releases (#2198)
* Add macOS release target
* Update ubuntu runner

Ubuntu 16.04 runner environment is deprecated
https://github.blog/changelog/2021-04-29-github-actions-ubuntu-16-04-lts-virtual-environment-will-be-removed-on-september-20-2021/
2021-05-23 18:59:03 -07:00
Hadi Alqattan
b8450b9fae
Fix: black only respects the root gitignore. (#2225)
Commit history before merge:

Black now respects .gitignore files in all levels, not only root/.gitignore file
(apply .gitignore rules like git does).

* Fix: typo
* Fix: respect .gitignore files in all levels.
* Add: CHANGELOG note.
* Fix: TypeError: unsupported operand type(s) for +: 'NoneType' and 'PathSpec'
* Update docs.
* Fix: no parent .gitignore
* Add a comment since the if expression is a bit hard to understand
* Update tests - conver no parent .gitignore case.
* Use main's Pipfile.lock instead

  The original changes in Pipfile.lock are whitespace only. The changes
  turned the JSON's file indentation from 4 to 2. Effectively this
  happened: `json.dumps(json.loads(old_pipfile_lock), indent=2) + "\n"`.

  Just using main's Pipfile.lock instead of undoing the changes because
  1) I don't know how to do that easily and quickly, and 2) there's a
  merge conflict.

  Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>

* Merge remote-tracking branch 'upstream/main' into i1730 …
  
  conflicts for days ay?
2021-05-16 13:51:27 -04:00
Łukasz Langa
60f8bd2c89
Include Jelle's review suggestions 2021-05-16 18:24:28 +02:00
Matthew Clapp
9704922cf9
Update vim plugin manual installation instructions. (#2235) 2021-05-16 18:10:59 +02:00
Richard Si
904fe94ceb
Add lower bound for aiohttp-cors + fix primer (#2231)
It appears sqlalchemy has recently reformatted their project with
Black 21.5b1.

Most of our dependencies have a lower bound and creating a test
environment with the oldest acceptable dependencies runs the full
Black test suite just fine. The only exception to this is aiohttp-cors.
It's unbounded and the oldest version 0.1.0 until 0.4.0 breaks the
test suite in such an old environment.

Failure with 0.1.0:

```
tests/test_blackd.py:10: in <module>
    import blackd
testenv/lib/python3.8/site-packages/blackd/__init__.py:12: in <module>
    import aiohttp_cors
testenv/lib/python3.8/site-packages/aiohttp_cors/__init__.py:29: in <module>
    from .urldispatcher_router_adapter import UrlDistatcherRouterAdapter
testenv/lib/python3.8/site-packages/aiohttp_cors/urldispatcher_router_adapter.py:27: in <module>
    class UrlDistatcherRouterAdapter(RouterAdapter):
testenv/lib/python3.8/site-packages/aiohttp_cors/urldispatcher_router_adapter.py:32: in UrlDistatcherRouterAdapter
    def route_methods(self, route: web.Route):
E   AttributeError: module 'aiohttp.web' has no attribute 'Route'
```

For 0.2.0:

```
tests/test_blackd.py:10: in <module>
    import blackd
testenv/lib/python3.8/site-packages/blackd/__init__.py:12: in <module>
    import aiohttp_cors
testenv/lib/python3.8/site-packages/aiohttp_cors/__init__.py:27: in <module>
    from .cors_config import CorsConfig
testenv/lib/python3.8/site-packages/aiohttp_cors/cors_config.py:24: in <module>
    from .urldispatcher_router_adapter import UrlDistatcherRouterAdapter
testenv/lib/python3.8/site-packages/aiohttp_cors/urldispatcher_router_adapter.py:27: in <module>
    class UrlDistatcherRouterAdapter(AbstractRouterAdapter):
testenv/lib/python3.8/site-packages/aiohttp_cors/urldispatcher_router_adapter.py:32: in UrlDistatcherRouterAdapter
    def route_methods(self, route: web.Route):
E   AttributeError: module 'aiohttp.web' has no attribute 'Route'
```

For 0.3.0:

```
ERROR: Cannot install aiohttp-cors==0.3.0 and aiohttp==3.6.0 because these package versions have conflicting dependencies.

The conflict is caused by:
    The user requested aiohttp==3.6.0
    aiohttp-cors 0.3.0 depends on aiohttp<=0.20.2 and >=0.18.0

To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies
```
2021-05-13 12:30:34 -07:00
Christian Clauss
445f094f1f
Use codespell to find typos (#2228) 2021-05-13 10:28:41 -07:00
Łukasz Langa
b2ee211b5a
Click 8.0 renamed its "die on LANG=C" function so we need to look for that one too (#2227) 2021-05-12 21:47:32 +02:00
Cooper Lees
f933e8a838
Update CHANGES.md for 21.5b1 release (#2215) 2021-05-10 07:59:32 -07:00
Panagiotis Vasilopoulos
06ccb88bf2
Replace references to master branch (#2210)
Commit history before merge:

* Replace references to master branch
* Update .flake8 to reference docs on RTD

  We're moving away from GitHub as a documentation host to only RTD because
  it's makes our lives easier creating good docs. I know this link is dead right now,
  but it won't be once we release a new version with the documentation reorganization
  changes (which should be soon!).

  Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-05-09 17:50:17 -04:00
Richard Si
62bfbd6a63
Reorganize docs v2 (GH-2174)
I know I know, this is the second reorganization of the docs. I'm not
saying the first one was bad or anything... but.. actually wait nah,
*it was bad*.

Anyway, welcome to probably my biggest commit. The main thing with this
reorganization was to introduce nesting to the documentation! Having
all of the docs be part of the main TOC was becoming too much. There
wasn't much room to expand either. Finally, the old setup required
a documentation generation step which was just annoying.

The goals of this reorganization was to:

1. Significantly restructure the docs to be discoverable and
   understandable

2. Add room for further docs (like guides or contributing docs)

3. Get rid of the doc generation step (it was slow and frustrating)

4. Unblock other improvements and also just make contributing to the
   docs easier

Another important change with this is that we are no longer using GitHub
as a documentation host. While GitHub does support Markdown based docs
actually pretty well, the lack of any features outside of GitHub Flavoured
Markdown is quite limiting. ReadTheDocs is just much better suited for
documentation. You can use reST, MyST, CommonMark, and all of their
great features like toctrees and admonitions.

Related to this change, we're adopting MyST as our flavour of Markdown.
MyST introduces neat syntax extensions to Markdown that pretty much
gives us the best of both worlds. The ease of use and simplicity of MD
and the flexibility and expressiveness of reST. Also recommonmark is
deprecated now. This switch was possible now we don't use GH as a docs
host. MyST docs have to be built to really be usable / pretty, so the MD
docs are going to look pretty bad on GH, but that's fine now!

Another thing that should be noted is that the README has been stripped
of most content since it was confusing. Users would read the README and
then think some feature or bug was fixed already and is available in a
release when in reality, they weren't. They were reading effectively
the latest docs without knowing.

See also: https://github.com/psf/black/issues/1759

FYI: CommonMark is a rationalized version of Markdown syntax

--

Commit history before merge:

* Switch to MyST-Parser + doc config cleanup

  recommonmark is being deprecated in favour of MyST-Parser. This change
  is welcomed, especially since MyST-Parser has syntax extensions for the
  Commonmark standard. Effectively we get to use a language that's powerful
  and expressive like ReST, but get the simplicity of Markdown.

  The rest of this effort will be using some MyST features.

  This reorganization efforts aims to remove as much duplication as possible.
  The regeneration step once needed is gone, significantly simplifing our
  Sphinx documentation configuration.

* Tell pipenv we replaced recommonmark for MyST-Parser

  Also update `docs/requirements.txt`

* Delete all auto generated content
* Switch prettier for mdformat (plus a few plugins)

  **FYI: THIS WAS EFFECTIVELY REVERTED, SEE THIRD TO LAST COMMIT**

  prettier doesn't support MyST's syntax extensions which are going to be
  used in this reorganization effort so we have to switch formatter.

  Unfortanately mdformat's style is different from prettier's so time to
  reformat the whole repo too.

  We're excluding .github/ISSUE_TEMPLATE because I have no idea whether
  its changes are safe, so let's play it safe.

* Fix the heading levels in CHANGES.md + a link

  MyST-Parser / sphinx's linkcheck complains otherwise.

* Move reference docs into a docs/contributing dir

  They're for contributors of Black anyway. Also added a note in the
  summary document warning about the lack of attention the reference has
  been dealing with.

* Rewrite and setup the new landing page + main TOC

  - add some more detail about Black's beta status
  - add licensing info
  - add external links in the main TOC for GitHub, PyPI, and IRC
  - prepare main TOC for new structure

* Break out AUTHORS into its own file

  Not only was the AUTHORS list quite long, this makes it easy to include
  it in the Sphinx docs with just a simple symlink.

* Add license to docs via a simple include

  Yes the document is orphaned but it is linked to in the landing page
  (docs/index.rst).

* Add "The Black Code Style" section

  This mostly was a restructuring commit, there has been a few updates but
  not many. The main goal was to split "current style" and "planned
  changes to the style that haven't happened yet" to avoid confusion.

* Add "Getting Started" page

  This is basically a quick start + even more. This commit is certainly
  one of most creatively involved in this effort.

* Add "Usage and Configuration" section

  This commit was as much restructuring as new content. Instead of being
  in one giant file, usage and configuration documentation can expand
  without bloating a single file.

* Add "Integrations" section

Just a restructuring commit ...

* Add "Guides" section

  This is a promising area of documentation that could easily grow in the
  future, let's prepare for that!

* Add "Contributing" section

  This is also another area that I expect to see significant growth in.
  Contributors to Black could definitely do with some more specific docs
  that clears up certain parts of our slightly confusing project (it's
  only confusing because we're getting big and old!).

* Rewrite CONTRIBUTING.md to just point to RTD
* Rewrite README.md to delegate most info to RTD
* Address feedback + a lot of corrections and edits

  I know I said I wanted to do these after landing this but given there's
  going to be no time between this being merged and a release getting
  pushed, I want these changes to make it in.

  - drop the number flag for mdformat - to reduce diffs, see also:
    https://mdformat.readthedocs.io/en/stable/users/style.html#ordered-lists
  - the GH issue templates should be safe by mdformat, so get rid of the
    exclude
  - clarify our configuration position - i.e. stop claiming we don't have
    many options, instead say we want as little formatting knobs as
    possible
  - lots and lots of punctuation, spelling, and grammar corrections (thanks
    Jelle!)
  - use RTD as the source for the CHANGELOG too
  - visual style cleanups
  - add docs about our .gitignore behaviour
  - expand GHA Action docs
  - clarify we want the PR number in the CHANGELOG entry
  - claify Black's behaviour for with statements post Python 3.9
  - italicize a bunch of "Black"s

  Thank you goes to Jelle, Taneli (hukkinj1 on GH), Felix
  (felix-hilden on GH), and Wouter (wbolster on GH) for the feedback!

* Merge remote-tracking branch 'upstream/master' into reorganize-docs-v2

  merge conflicts suck, although these ones weren't too bad.

* Add changelog entry + fix merge conflict resolution error

  I consider this important enough to be worthy of a changelog entry :)

* Merge branch 'master' into reorganize-docs-v2

  Co-authored-by: Łukasz Langa <lukasz@langa.pl>

* Actually let's continue using prettier

  Prettier works fine for all of the default MyST syntax so let's not
  rock the boat as much. Dropping the mdformat commit was merge-conflict
  filled so here's additional commit instead.

* Address Cooper's, Taneli's, and Jelle's feedback

  Lots of wording improvements by Cooper. Taneli suggested to disable the
  enabled by default MyST syntax not supported by Prettier and I agreed.
  And Jelle found one more spelling error!

* More minor fixes
2021-05-08 15:17:38 -04:00
Łukasz Langa
f2ea461e9e
Refactor src/black/__init__.py into many files (#2206)
* Move string-related utility to functions to strings.py, const.py
* Move Leaf/Node-related functionality to nodes.py
* Move comment-related functions to comments.py
* Move caching to cache.py and Mode/TargetVersion/Feature to mode.py
* Move some leftover functions to nodes.py, comments.py, strings.py
* Add missing files to source list for test runs
* Move line-related functionality into lines.py, brackets into brackets.py
* Move transformers to trans.py
* Move file handling, output, parsing, concurrency, debug, and report
* Move two more functions to nodes.py
* Add CHANGES
* Add numeric.py
* Add linegen.py
* More docstrings
* Include new files in tests

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-05-08 11:29:47 +02:00
Kaleb Barrett
1fe2efd857
Do not use gitignore if explicitly passing excludes (#2170)
Closes #2164.

Changes behavior of how .gitignore is handled. With this change, the rules in .gitignore are only used as a fallback if no exclusion rule is explicitly passed on the command line or in pyproject.toml. Previously they were used regardless if explicit exclusion rules were specified, preventing any overriding of .gitignore rules.

Those that depend only on .gitignore for their exclusion rules will not be affected. Those that use both .gitignore and exclude will find that exclude will act more like actually specifying exclude and not just another extra-excludes. If the previous behavior was desired, they should move their rules from exclude to extra-excludes.
2021-05-07 14:54:21 +02:00
Cooper Lees
d8a034f9b6
Update CHANGES.md for 21.5b0 release (#2192)
* Update CHANGES.md for 21.5b0 release

* Make prettier happy
2021-05-04 11:07:08 -07:00
Richard Si
e42f9921e2
Detect '@' dotted_name '(' ')' NEWLINE as a simple decorator (#2182)
Previously the RELAXED_DECORATOR detection would be falsely True on that
example. The problem was that an argument-less parentheses pair didn't
pass the `is_simple_decorator_trailer` check even it should. OTOH a
parentheses pair containing an argument or more passed as expected.
2021-05-04 10:46:46 +02:00
Cooper Lees
a18c7bc099
primer: Add --no-diff option (#2187)
- Allow runs with no code diff output
- This is handy for reducing output to see which file is erroring

Test:
- Edit config for 'channels' to expect no changes and run with `--no-diff` and see no diff output
2021-05-04 10:44:40 +02:00
Bryan Forbes
35e8d1560d
Set is_pyi if stdin_filename ends with .pyi (#2169)
Fixes #2167

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-05-02 14:48:54 +02:00
Łukasz Langa
b39999da7f
Elaborate on what AST changes Black might perform 2021-04-28 16:50:02 +02:00
Cooper Lees
682077c15e
Update CHANGELOG for 21.4b2 release (#2162) 2021-04-28 16:21:56 +02:00
Jelle Zijlstra
ad1696422b
Ignore inaccessible user config (#2158)
Fixes #2157
2021-04-27 14:16:35 -07:00
Jelle Zijlstra
807a65f9d5
Update discussion of AST safety check in README (#2159) 2021-04-27 14:00:17 -07:00
Miro Hrončok
76e1602d60
Install primer.json (used by black-primer by default) with black (#2154)
Fixes https://github.com/psf/black/issues/2153
2021-04-27 08:58:39 -07:00
Cooper Lees
1728bb441e
Update CHANGELOG for 21.4b1 release (#2151)
* Update CHANGELOG for 21.4b1 release

* Add pathspec minimum bump + update primer not to expect changes for virtualenv
2021-04-27 07:40:08 -07:00
Łukasz Langa
eaa337f176
Add more tests for fancy whitespace (#2147) 2021-04-26 20:24:06 +02:00
Jelle Zijlstra
557b54aa60
Fix crash on docstrings ending with "\ " (#2142)
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2021-04-26 19:42:16 +02:00
Richard Si
db30456916
Don't strip parens in assert / return with assign expr (#2143)
Black would previously strip the parenthesis away from statements like this these ones:

    assert (spam := 12 + 1)
    return (cheese := 1 - 12)

Which happens to be invalid code. Now before making the parenthesis invisible, Black
checks if the assignment expression's parent is an assert stamtment, aborting if True.

Raise, yield, and await are already handled fine.

I added a bunch of test cases from the PEP defining asssignment expressions (PEP 572).
2021-04-26 08:28:42 -07:00
Jelle Zijlstra
0a833b4b14
fix magic comma and experimental string cache flags (#2131)
* fix magic comma and experimental string cache flags

* more changelog

* Update CHANGES.md

Co-authored-by: Cooper Lees <me@cooperlees.com>

* fix tests

Co-authored-by: Cooper Lees <me@cooperlees.com>
2021-04-26 07:46:48 +02:00
Cooper Lees
65f0ea6159
Remove Lowercase Hex (PR #1692) from CHANGES.md (#2133)
- It was reverted to not cause so much diff churn on millions of lines of code
- Fix primer config for projects that should now pass
2021-04-25 20:48:04 -07:00
Cooper Lees
67d5532c33
Update CHANGES.md for release (#2129) 2021-04-25 15:12:27 -07:00
Richard Si
de7187a823
Issue 1629 has been closed, let's celebrate! (#2127) 2021-04-25 23:52:23 +02:00
Łukasz Langa
8672af35f0
Work around stability errors due to optional trailing commas (#2126)
Optional trailing commas put by Black become magic trailing commas on another
pass of the tool.  Since they are influencing formatting around optional
parentheses, on rare occasions the tool changes its mind in terms of putting
parentheses or not.

Ideally this would never be the case but sadly the decision to put optional
parentheses or not (which looks at pre-existing "magic" trailing commas) is
happening around the same time as the decision to put an optional trailing
comma.  Untangling the two proved to be impractically difficult.

This shameful workaround uses the fact that the formatting instability
introduced by magic trailing commas is deterministic: if the optional trailing
comma becoming a pre-existing "magic" trailing comma changes formatting, the
second pass becomes stable since there is no variable factor anymore on pass 3,
4, and so on.

For most files, this will introduce no performance penalty since `--safe` is
already re-formatting everything twice to ensure formatting stability.  We're
using this result and if all's good, the behavior is equivalent.  If there is
a difference, we treat the second result as the binding one, and check its
sanity again.
2021-04-25 20:15:54 +02:00
CiderMan
5316bbff0e
Handle Docstrings as bytes + strip all whitespace (#2037)
(fixes #1844, fixes #1923, fixes #1851, fixes #2002, fixes #2103)
2021-04-22 08:40:51 -07:00
Mark Bell
1fc3215e8c
Make black remove leading and trailing spaces from one-line docstrings (#1740)
Fixes #1738. Fixes #1812.

Previously, Black removed leading and trailing spaces in multiline docstrings but failed to remove them from one-line docstrings.
2021-04-22 08:23:41 -07:00
Pierre Sassoulas
d960d5d238
Remove NBSP at the beginning of comments (#2092)
Closes #2091
2021-04-11 14:41:22 -07:00
johnthagen
e4003c2c43
Exclude venv directory by default (#1683)
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2021-04-10 05:07:34 -07:00
KotlinIsland
ed9d58b741 don't require typed-ast 2021-04-01 17:38:04 +02:00
Shantanu
4218ae18c0
Add --skip-magic-trailing-comma to CHANGES.md (#2064) 2021-03-26 07:21:18 -07:00
Richard Si
580b4fe8bc
Add entry for --extend-exclude in the right place (#2061)
The PR author added the changelog entry for their `extend-exclude` addition
in `docs/change_log.md` which is understandable but incorrect as it will be
overwritten since it's autogenerated from the readme.
2021-03-24 16:38:07 -07:00
Richard Si
b332cfa655
Add missing changelog entry for fmt: skip (#2025) 2021-03-06 12:02:25 -08:00
Austin Pray
cac18293d5
Adds --stdin-filename back to changelog (#2017)
* Adds --stdin-filename back to changelog

Looks like this went missing dea81b7ad5 (diff-729efdd61772b108539268bdbfd7472521bdc05a7cae6113f62ed2649a3ad9c7)

* Update CHANGES.md

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>

* Update CHANGES.md

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-03-01 16:35:57 -08:00
Paul "TBBle" Hampson
cd4295dd98
Indicate that a final newline was added in --diff (#1897) (#1897)
Fixes: #1662

Work-around for https://bugs.python.org/issue2142

The test has to slightly mess with its input data, because the utility
functions default to ensuring the test data has a final newline, which
defeats the point of the test.

Signed-off-by: Paul "TBBle" Hampson <Paul.Hampson@Pobox.com>
2021-02-21 22:43:23 -08:00
Anthony Sottile
3fca540d05
speed up cache by approximately 42x by avoiding pathlib (#1953) 2021-02-04 13:03:42 -08:00
Richard Si
4d03716eae
Allow same RHS expressions in annotated assignments as in regular assignments (#1835) 2020-11-24 09:39:25 +00:00
Casper Weiss Bang
7d032fa848
Use lowercase hex numbers fixes #1692 (#1775)
* Made hex lower case

* Refactored numeric formatting section

* Redid some refactoring and removed bloat

* Removed additions from test_requirements.txt

* Primer now expects expected changes

* Undid some refactoring

* added to changelog

* Update src/black/__init__.py

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
Co-authored-by: Cooper Lees <me@cooperlees.com>
2020-11-13 07:25:17 -08:00
Richard Si
74e51e6a82
Automatically build and upload binaries on release (#1743)
This commit adds a new GitHub Actions workflow that builds self-contained
binaries / executables and uploads them as release assets to the triggering
release. Publishing a release, drafting one doesn't count, will trigger this
workflow.

I personally used GitHub Actions only because it's the CI/CD platform(?)
I am familiar with. Only Windows and Linux binaries are supported since
I don't have any systems running Mac OS.

For Linux, I had originally planned to use the manylinux2010 docker image
the PyPA provides for highly compatible wheel building, but unfortunately
it wasn't feasible due to GitHub Actions and PyInstaller incompatibilities.
As a stopgap the oldest versions of Linux and Windows are used although
Windows Server 2019 isn't that old nor is Ubuntu 16.04! I guess someone
(maybe me) could work out something else if compatibility is big problem.

A few things you should know about the workflow:
 - You don't need to set the `GITHUB_TOKEN` secret as it is automatically
   provided by GitHub.
 - matrix.pathsep is used because PyInstaller configuration's format is OS
   dependent for some reason ...

Also it's worth mentioning that Black once had Travis CI and AppVeyor
configuration that did the same thing as this commit. They were committed
in mid 2018 and worked (somewhat) well. Eventually we stopped using AppVeyor
and the refactor to packages broke the Travis CI config. This commit
replaces the still existing and broken Travis CI config wholesale.

Co-authored-by: Anders Fredrik Kiær <31612826+anders-kiaer@users.noreply.github.com>

 - Anders told me that I could get the release asset upload URL directly
   from the github.event.release payload. I originally planned to use
   bruceadams/get-release to get such URL.
2020-11-01 13:17:23 -08:00
Pete Grayson
4d71d74a44
Repair colorama wrapping on non-Windows platforms (#1670)
* Repair colorama wrapping on non-Windows platforms

The wrap_stream_for_windows() function calls
colorama.initialise.wrap_stream() function to apply colorama's magic to
wrapper to the output stream. Except this wrapper is only applied on
Windows platforms that need it, otherwise the original stream is
returned as-is.

The colorama wrapped stream lacks a detach() method, so a no-op lambda
was being assigned to the wrapped stream.

The problem is that the no-op lambda was being assigned unconditionally
whether or not colorama actually returns a wrapped stream, thus
replacing the original TextIOWrapper's detach() method. Replacing the
detach() method with a no-op lambda is the root cause of the problem
observed in #1664.

The solution is to only assign the no-op detach() method if the stream
lacks its own detach() method.

Repairs #1664
2020-09-27 22:41:11 +01:00
QuentinSoubeyran
6dddbd7241
PEP 614 support (#1717) 2020-09-19 20:33:10 +02:00
Richard Si
c0a8e42243
Fix empty line handling when formatting typing stubs (#1646)
Black used to erroneously remove all empty lines between non-function
code and decorators when formatting typing stubs. Now a single empty
line is enforced.

I chose for putting empty lines around decorated classes that have empty
bodies since removing empty lines around such classes would cause a
formatting issue that seems to be impossible to fix.

For example:

```
class A: ...
@some_decorator
class B: ...
class C: ...
class D: ...

@some_other_decorator
def foo(): -> None: ...
```

It is easy to enforce no empty lines between class A, B, and C.
Just return 0, 0 for a line that is a decorator and precedes an stub
class. Fortunately before this commit, empty lines after that class
would be removed already.

Now let's look at the empty line between class D and function foo. In
this case, there should be an empty line there since it's class code next
to function code. The problem is that when deciding to add X empty lines
before a decorator, you can't tell whether it's before a class or a
function. If the decorator is before a function, then an empty line
is needed, while no empty lines are needed when the decorator is
before a class.

So even though I personally prefer no empty lines around decorated
classes, I had to go the other way surrounding decorated classes with
empty lines.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2020-09-10 13:21:37 -07:00
Tom Saunders
6b5753a417
Handle .COLOR_DIFF in the same way as .DIFF (#1673) 2020-09-05 12:15:28 -07:00
Richard Si
1d2d7264ec
Fix incorrect space before colon in if/while stmts (#1655)
* Fix incorrect space before colon in if/while stmts

Previously Black would format this code

```
if (foo := True):
	print(foo)
```

as

```
if (foo := True) :
	print(foo)
```

adding an incorrect space after the RPAR. Buggy code in the
normalize_invisible_parens function caused the colon to be wrapped in
invisible parentheses. The LPAR of that pair was then prefixed with a
single space at the request of the whitespace function.

This commit fixes the accidental skipping of a pre-condition check
which must return True before parenthesis normalization of a specific
child Leaf or Node can happen. The pre-condition check being skipped
was why the colon was wrapped in invisible parentheses.

* Add an entry in CHANGES.md
2020-08-31 14:20:05 -07:00
mbarkhau
2b75f8870e
fix 1631 and add test (#1641) 2020-08-27 04:47:59 -07:00
Richard Si
7fe19fac5b Fix multiline docstring quote normalization
The quotes of multiline docstrings are now only normalized when string
normalization is off, instead of the string normalization setting being
ignored and the quotes being *always* normalized.

I had to make a new test case and data file since the current pair for
docstrings only worked when there is no formatting difference between the
formatting results with string normalization on and off. I needed to add
tests for when there *are* differences between the two. So I split
test_docstring's test code when string normalization is disabled into a
new test case along with a new data file.
2020-08-27 01:59:41 +02:00
Łukasz Langa
235412635e
v20.8b1 2020-08-26 17:50:44 +02:00
Łukasz Langa
824d06f720
v20.8b0 2020-08-26 16:00:55 +02:00
Łukasz Langa
fd5928c589
Update the changelog 2020-08-24 14:11:18 +02:00
Łukasz Langa
788268bc39 Re-implement magic trailing comma handling:
- when a trailing comma is specified in any bracket pair, that signals to Black
  that this bracket pair needs to be always exploded, e.g. presented as "one
  item per line";

- this causes some changes to previously formatted code that erroneously left
  trailing commas embedded into single-line expressions;

- internally, Black needs to be able to identify trailing commas that it put
  itself compared to pre-existing trailing commas. We do this by using/abusing
  lib2to3's `was_checked` attribute.  It's True for internally generated
  trailing commas and False for pre-existing ones (in fact, for all
  pre-existing leaves and nodes).

Fixes #1288
2020-08-21 16:45:30 +02:00
Hugo van Kemenade
4501f22fcb
README/CHANGES: Fix links (#1397)
* Replace relative README links with absolutes, so they work on PyPI

* CHANGES: Fix Spyder web link
2020-05-08 12:14:27 -07:00
Jelle Zijlstra
702e459176
Update changelog and README (#1392)
* add two CHANGELOG entries

* update README on command-line options
2020-05-08 07:55:57 -07:00
Cooper Lees
a904771093
Update CHANGELOG with some PRs merged (#1391)
* Update CHANGELOG with some PRs merged
- Add section for vim plugin
- Add vim plugin now prefering virtualenv
- Add py3 tagged wheels

* packges

* Update CHANGES.md _Black_

Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>

* Update CHANGES.md Vim

Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
2020-05-08 07:29:53 -07:00
Douglas Thor
8d6d92aa5b
Add option for printing a colored diff (#1266) 2020-05-08 14:30:10 +01:00
Zsolt Dollenstein
1d3fb871be add change log entry for #1053 2020-05-08 14:09:15 +01:00
Łukasz Langa
4eb822f20c
Run prettier and fix whitespace on CHANGES.md (#1296) 2020-03-04 19:10:17 +01:00
Cooper Lees
d29303c988
Split out Change Log (#1117)
* Split out Change Log
- Move to CHANGES.md to allow bots to see changes
- MANIFEST.in already includes *.md so CHANGES.md will be included
- THis maintains format but the change log will now be after acknowledgements
- This also ensure this gets added to pypi.org via setup.py function
2020-03-04 16:40:48 +01:00