Commit Graph

651 Commits

Author SHA1 Message Date
KotlinIsland
0359b85b58
Preserve crlf line endings in blackd (#3257)
Co-authored-by: KotlinIsland <kotlinisland@users.noreply.github.com>
2022-10-04 13:10:11 -07:00
Yilei "Dolee" Yang
55db05519e
Fix a crash when # fmt: on is used on a different block level than # fmt: off (#3281)
Previously _Black_ produces invalid code because the `# fmt: on` is used on a different block level.

While _Black_ requires `# fmt: off` and `# fmt: on` to be used at the same block level, incorrect usage shouldn't cause crashes.

The formatting behavior this PR introduces is, the code below the initial `# fmt: off` block level will be turned off for formatting, when `# fmt: on` is used on a different level or there is no `# fmt: on`. This also matches the current behavior when `# fmt: off` is used at the top-level without a matching `# fmt: on`, it turns off formatting for everything below `# fmt: off`.

- Fixes #2567
- Fixes #3184
- Fixes #2985
- Fixes #2882
- Fixes #2232
- Fixes #2140
- Fixes #1817
- Fixes #569
2022-09-23 20:37:22 -07:00
Yilei "Dolee" Yang
e2adcd7de1
Fix a crash on dicts with paren-wrapped long string keys (#3262)
Fix a crash when formatting some dicts with parenthesis-wrapped long
string keys. When LL[0] is an atom string, we need to check the atom
node's siblings instead of LL[0] itself, e.g.:

    dictsetmaker
      atom
        STRING '"This is a really long string that can\'t be expected to fit in one line and is used as a nested dict\'s key"'
      /atom
      COLON ':'
      atom
        LSQB ' ' '['
        listmaker
          STRING '"value"'
          COMMA ','
          STRING ' ' '"value"'
        /listmaker
        RSQB ']'
      /atom
      COMMA ','
    /dictsetmaker
2022-09-13 23:23:51 -04:00
Cooper Lees
383b228a16
Move 3.11 tests to install aiohttp without C extensions (#3258)
* Move 311 tests to install aiohttp without C extensions

- Configure tox to install aiohttp without extensions
  - i.e. use `AIOHTTP_NO_EXTENSIONS=1` for pip install
  - This allows us to reenable blackd tests that use aiohttp testing helpers etc.
- Had to ignore `cgi` module deprecation warning
  - Filed issue for aiohttp to fix: https://github.com/aio-libs/aiohttp/issues/6905

Test:
- `/tmp/tb/bin/tox -e 311`

* Fix formatting + linting

* Add latest aiohttp for loop fix + Try to exempt deprecation warning but failed - will ask for help

* Remove unnecessary warning ignore

Co-authored-by: Cooper Ry Lees <me@wcooperlees.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-09-06 08:27:39 +10:00
Martin de La Gorce
767604e03f
Use .gitignore files in the initial source directories (#3237)
Solves https://github.com/psf/black/issues/2598 where Black wouldn't
use .gitignore at folder/.gitignore if you ran `black folder` for
example.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-31 15:47:42 -04:00
Shantanu
2c90480e1a
Use strict mypy checking (#3222)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-30 20:46:46 -07:00
Yilei "Dolee" Yang
ba618a307a
Add parens around implicit string concatenations where it increases readability (#3162)
Adds parentheses around implicit string concatenations when it's inside
a list, set, or tuple. Except when it's only element and there's no trailing
comma.

Looking at the order of the transformers here, we need to "wrap in
parens" before string_split runs. So my solution is to introduce a
"collaboration" between StringSplitter and StringParenWrapper where the
splitter "skips" the split until the wrapper adds the parens (and then
the line after the paren is split by StringSplitter) in another pass.

I have also considered an alternative approach, where I tried to add a
different "string paren wrapper" class, and it runs before string_split.
Then I found out it requires a different do_transform implementation
than StringParenWrapper.do_transform, since the later assumes it runs
after the delimiter_split transform. So I stopped researching that
route.

Originally function calls were also included in this change, but given
missing commas should usually result in a runtime error and the scary
amount of changes this cause on downstream code, they were removed in
later revisions.
2022-08-30 22:52:00 -04:00
Richard Si
e269f44b25 Lazily import parallelized format modules
`black.reformat_many` depends on a lot of slow-to-import modules. When
formatting simply a single file, the time paid to import those modules
is totally wasted. So I moved `black.reformat_many` and its helpers
to `black.concurrency` which is now *only* imported if there's more
than one file to reformat. This way, running Black over a single file
is snappier

Here are the numbers before and after this patch running `python -m
black --version`:

- interpreted: 411 ms +- 9 ms -> 342 ms +- 7 ms: 1.20x faster
- compiled: 365 ms +- 15 ms -> 304 ms +- 7 ms: 1.20x faster

Co-authored-by: Fabio Zadrozny <fabiofz@gmail.com>
2022-08-26 21:11:00 -04:00
Shantanu
c47b91f513
Fix misdetection of project root with --stdin-filename (#3216)
There are a number of places this behaviour could be patched, for
instance, it's quite tempting to patch it in `get_sources`. However
I believe we generally have the invariant that project root contains all
files we want to format, in which case it seems prudent to keep that
invariant.

This also improves the accuracy of the "sources to be formatted" log
message with --stdin-filename.

Fixes GH-3207.
2022-08-26 17:07:25 -04:00
Yilei "Dolee" Yang
21218b666a
Fix a string merging/split issue caused by standalone comments. (#3227)
Fixes #2734: a standalone comment causes strings to be merged into one far too long (and requiring two passes to do so).

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-22 20:40:38 -07:00
Cooper Lees
59acf8af38
Add passing 3.11 CI by exempting blackd tests (#3234)
- Had to exempt blackd tests for now due to aiohttp
  - Skip by using `sys.version_info` tuple
  - aiohttp does not compile in 3.11 yet - refer to #3230
- Add a deadsnakes ubuntu workflow to run 3.11-dev to ensure we don't regress
  - Have it also format ourselves

Test:
- `tox -e 311`

Co-authored-by: Cooper Ry Lees <me@wcooperlees.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-22 20:39:48 -07:00
Shantanu
4ebf14d17e
Strip trailing commas in subscripts with -C (#3209)
Fixes #2296, #3204
2022-08-13 06:41:34 -07:00
Alexandr Artemyev
07b68e2425
add preview option support for blackd (#3217)
Fixes #3195

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-12 20:23:02 -07:00
Shantanu
6064a43545
Use debug f-strings for feature detection (#3215)
Fixes GH-2907.
2022-08-10 17:29:47 -04:00
Tom Fryers
507234c47d
Remove invalid syntax in docstrings -S --preview test (#3205)
uR is not a legal string prefix, so this test breaks (AssertionError:
cannot use --safe with this file; failed to parse source file AST:
invalid syntax) if changed to one in which the file is changed. I've
changed the last test to have u alone, and added an R to the test above
instead.
2022-08-02 17:22:04 -04:00
Richard Si
44d5da00b5 Reformat codebase with isort 2022-07-27 17:19:28 -04:00
Yilei "Dolee" Yang
b4dc40bf7a
Use underscores instead of a space in a test file's name (#3180)
... for *consistency*
2022-07-19 21:33:00 -04:00
Yilei "Dolee" Yang
249c6536c4
Fix an infinite loop when using # fmt: on/off ... (#3158)
... in the middle of an expression or code block by adding a missing return.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-07-19 20:57:23 -04:00
Yilei "Dolee" Yang
6ea4eddf93
Fix the handling of # fmt: skip when it's at a colon line (#3148)
When the Leaf node with `# fmt: skip` is a NEWLINE inside a `suite`
Node, the nodes to ignore should be from the siblings of the parent
`suite` Node.

There is a also a special case for the ASYNC token, where it expands
to the grandparent Node where the ASYNC token is.

This fixes GH-2646, GH-3126, GH-2680, GH-2421, GH-2339, and GH-2138.
2022-07-19 17:26:11 -04:00
Thomas Grainger
1b6de7b0a3
Improve warning filtering in tests (#3175) 2022-07-18 19:17:13 -07:00
Richard Si
ad5c315dda
Actually disable docstring prefix normalization with -S + fix instability (#3168)
The former was a regression I introduced a long time ago. To avoid
changing the stable style too much, the regression is only fixed if
--preview is enabled

Annoyingly enough, as we currently always enforce a second format pass if
changes were made, there's no good way to prove the existence of the
docstring quote normalization instability issue. For posterity, here's
one failing example:

    --- source
    +++ first pass
    @@ -1,7 +1,7 @@
     def some_function(self):
    -    ''''<text here>
    +    """ '<text here>

         <text here, since without another non-empty line black is stable>

    -    '''
    +    """
         pass
    --- first pass
    +++ second pass
    @@ -1,7 +1,7 @@
     def some_function(self):
    -    """ '<text here>
    +    """'<text here>

         <text here, since without another non-empty line black is stable>

         """
         pass

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-07-14 19:47:33 -04:00
Richard Si
4f0532d6f0
Don't (ever) put a single-char closing docstring quote on a new line (#3166)
Doing so is invalid. Note this only fixes the preview style since the
logic putting closing docstring quotes on their own line if they violate
the line length limit is quite new.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-07-13 22:26:05 -04:00
Richard Si
18c17bea75
Copy over comments when hugging power ops (#2874)
Otherwise they'd be deleted which was a regression in 22.1.0 (oops! my
bad!). Also type comments are now tracked in the AST safety check on all
compatible platforms to error out if this happens again.

Overall the line rewriting code has been rewritten to do "the right
thing (tm)", I hope this fixes other potential bugs in the code (fwiw I
got to drop the bugfix in blib2to3.pytree.Leaf.clone since now bracket
metadata is properly copied over).

Fixes #2873
2022-07-13 17:02:51 -07:00
Sagi Shadur
6c1bd08f16
Test run black on self (#3114)
* Add run_self environment in tox

* Add run_self task as part of the lint CI flow

* Remove hard coded sources list

* Remove black from pre-commit

Co-authored-by: Cooper Lees <me@cooperlees.com>
2022-06-14 09:08:36 -07:00
Sagi Shadur
4bb7bf2bdc
Remove newline after code block open (#3035)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-06-11 09:55:01 +03:00
Batuhan Taskaya
1e557184b0
Implement support for PEP 646 (#3071) 2022-05-26 09:45:22 -07:00
Sagi Shadur
2893c42176
Remove hard coded test cases (#3062) 2022-05-18 12:11:37 -07:00
Sagi Shadur
fc2a16433e
Read simple data cases automatically (#3034)
Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
2022-05-08 12:27:40 -07:00
Iain Dorrington
20d8ccb542
Put closing quote on a separate line if docstring is too long (#3044)
Fixes #1632

Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
2022-05-07 21:34:28 -07:00
Zac Hatfield-Dodds
9ce100ba61
Move imports of ThreadPoolExecutor into reformat_many(), allowing Black-in-the-browser (#3046)
This is a slight perf win for use-cases that don't invoke `reformat_many()`, but more importantly to me today it means I can use Black in pyscript.
2022-05-06 07:06:27 -07:00
Batuhan Taskaya
7f7673d941
Support 3.11 / PEP 654 syntax (#3016) 2022-04-15 12:25:07 -04:00
Marco Edward Gorelli
712f8b37fb
Make ipynb tests compatible with ipython 8.3.0+ (#3008) 2022-04-13 19:13:33 -04:00
Ryan Siu
431bd09e15
Correctly handle fmt: skip comments without internal spaces (#2970)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-04-09 16:52:45 -04:00
Joe Young
75f99bded3
Remove redundant parentheses around awaited coroutines/tasks (#2991)
This is a tricky one as await is technically an expression and therefore
in certain situations requires brackets for operator precedence.
However, the vast majority of await usage is just await some_coroutine(...)
and similar in format to return statements. Therefore this PR removes
redundant parens around these await expressions.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-04-09 16:49:40 -04:00
Joe Young
98fcccee55
Better manage return annotation brackets (#2990)
Allows us to better control placement of return annotations by:

a) removing redundant parens
b) moves very long type annotations onto their own line

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-04-09 10:36:05 -04:00
Richard Si
fa5fd262ff
Update test_black.shhh_click test for click 8+ (#2993)
The 8.0.x series renamed its "die on LANG=C" function and the 8.1.x
series straight up deleted it.

Unfortunately this makes this test type check cleanly hard, so we'll
just lint with click 8.1+ (the pre-commit hook configuration was changed
mostly to just evict any now unsupported mypy environments)
2022-04-04 18:23:30 -07:00
Joe Young
24c708eb37
Remove unnecessary parentheses from with statements (#2926)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-04-02 20:27:33 -07:00
Richard Si
82e150a13a
Keep tests working w/ upcoming aiohttp 4.0.0 (#2974)
aiohttp.test_utils.unittest_run_loop was deprecated since aiohttp 3.8
and aiohttp 4 (which isn't a thing quite yet) removes it. To maintain
compatibility with the full range of versions we declare to support,
test_blackd.py will now define a no-op replacement if it can't be
imported.

Also, mypy is painfully slow to use without a cache, let's reenable it.
2022-03-30 13:40:50 -07:00
Jelle Zijlstra
e9681a40dc
Fix _unicodefun patch code for Click 8.1.0 (#2966)
Fixes #2964
2022-03-28 12:01:13 -07:00
Joe Young
bd1e980349
Remove unnecessary parentheses from except clauses (#2939)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-03-26 09:56:50 -07:00
Joe Young
14e5ce5412
Remove unnecessary parentheses from tuple unpacking in for loops (#2945) 2022-03-24 07:59:54 -07:00
Joe Young
3800ebd81d
Avoid magic-trailing-comma in single-element subscripts (#2942)
Closes #2918.
2022-03-23 19:16:09 -07:00
Marco Edward Gorelli
f87df0e3c8
dont skip formatting #%% (#2919)
Fixes #2588
2022-03-21 14:51:07 -07:00
Richard Si
a57ab326b2
Farewell black-primer, it was nice knowing you (#2924)
Enjoy your retirement at https://github.com/cooperlees/black-primer
2022-03-15 12:57:59 -07:00
yoerg
24ffc54a53
Fix handling of Windows junctions in normalize_path_maybe_ignore (#2904)
Fixes #2569
2022-03-08 07:28:13 -08:00
Batuhan Taskaya
6f4976a7ac
Allow for's target expression to be starred (#2879)
Fixes #2878
2022-03-04 17:37:16 -08:00
Jelle Zijlstra
2918ea3b07
Format ourselves in preview mode (#2889) 2022-02-23 18:20:59 -08:00
Frédérik Paradis
50a856970d
Isolate command line tests for notebooks from user-level config (#2854) 2022-02-20 17:17:01 -08:00
Joachim Jablon
b4a6bb08fa
Avoid crashing when the user has no homedir (#2814) 2022-02-08 12:13:58 -08:00
Richard Si
fb9fe6b565
Isolate command line tests from user-level config (#2851) 2022-01-31 21:29:01 -08:00
Frédérik Paradis
cae7ae3a4d
Soft comparison of --required-version (#2832)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
2022-01-30 13:42:56 -08:00
Shantanu
a4992b4d50
Add a test case to torture.py (#2822)
Co-authored-by: hauntsaninja <>
2022-01-28 19:38:50 -08:00
Nipunn Koorapati
a24e1f7959
Fix instability due to trailing comma logic (#2572)
It was causing stability issues because the first pass
could cause a "magic trailing comma" to appear, meaning
that the second pass might get a different result. It's
not critical.

Some things format differently (with extra parens)
2022-01-28 18:13:18 -08:00
Jelle Zijlstra
4ce049dbfa
torture test (#2815)
Fixes #2651. Fixes #2754. Fixes #2518. Fixes #2321.

This adds a test that lists a number of cases of unstable formatting
that we have seen in the issue tracker. Checking it in will ensure
that we don't regress on these cases.
2022-01-28 16:48:38 -08:00
Shantanu
343795029f
Treat blank lines in stubs the same inside top-level if statements (#2820) 2022-01-28 16:29:07 -08:00
Shantanu
fda2561f79
Tests for unicode identifiers (#2816) 2022-01-28 10:16:25 +02:00
Shivansh-007
777cae55b6
Use parentheses on method access on float and int literals (#2799)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
2022-01-27 21:31:50 -08:00
Jelle Zijlstra
b92822afee
more trailing comma tests (#2810) 2022-01-26 19:44:39 -08:00
Jelle Zijlstra
889a8d5dd2
Fix crash on some power hugging cases (#2806)
Found by the fuzzer. Repro case:

	python -m black -c 'importA;()<<0**0#'
2022-01-26 16:47:36 -08:00
Jelle Zijlstra
32dd9ecb2e
properly run ourselves twice (#2807)
The previous run-twice logic only affected the stability checks but not the output. Now, we actually output the twice-formatted code.
2022-01-25 15:58:58 -08:00
Richard Si
6417c99bfd
Hug power operators if its operands are "simple" (#2726)
Since power operators almost always have the highest binding power in expressions, it's often more readable to hug it with its operands. The main exception to this is when its operands are non-trivial in which case the power operator will not hug, the rule for this is the following:

> For power ops, an operand is considered "simple" if it's only a NAME, numeric CONSTANT, or attribute access (chained attribute access is allowed), with or without a preceding unary operator. 

Fixes GH-538.
Closes GH-2095.

diff-shades results: https://gist.github.com/ichard26/ca6c6ad4bd1de5152d95418c8645354b

Co-authored-by: Diego <dpalma@evernote.com>
Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-01-24 19:13:34 -08:00
Felix Hildén
73cb6e7734
Make SRC or code mandatory and mutually exclusive (#2360) (#2804)
Closes #2360: I'd like to make passing SRC or `--code` mandatory and the arguments mutually exclusive. This will change our (partially already broken) promises of CLI behavior, but I'll comment below.
2022-01-24 07:35:56 -08:00
Batuhan Taskaya
022f89625f
Enable pattern matching by default (#2758)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-01-22 12:05:26 -08:00
Perry Vargas
10677baa40
Allow setting custom cache directory on all platforms (#2739)
Fixes #2506

``XDG_CACHE_HOME`` does not work on Windows. To allow for users to set a custom cache directory on all systems I added a new environment variable ``BLACK_CACHE_DIR`` to set the cache directory. The default remains the same so users will only notice a change if that environment variable is set.

The specific use case I have for this is I need to run black on in different processes at the same time. There is a race condition with the cache pickle file that made this rather difficult. A custom cache directory will remove the race condition.

I created ``get_cache_dir`` function in order to test the logic. This is only used to set the ``CACHE_DIR`` constant.
2022-01-21 22:00:33 -08:00
Michael Marino
4ea75cd495
Add support for custom python cell magics (#2744)
Fixes #2742.

This PR adds the ability to configure additional python cell magics. This
will allow formatting cells in Jupyter Notebooks that are using custom (python)
magics.
2022-01-20 16:45:28 -08:00
Felix Hildén
6e97c5f47c
Deprecate ESP and move the functionality under --preview (#2789) 2022-01-20 15:42:07 -08:00
Felix Hildén
8c22d232b5
Create --preview CLI flag (#2752) 2022-01-19 17:34:52 -08:00
Batuhan Taskaya
33e3bb1e4e
[trivial] Use proper test cases on unittest (#2775) 2022-01-15 14:19:37 -08:00
Felix Hildén
799f76f537
Normalise string prefix order (#2297)
Closes #2171
2022-01-13 09:59:43 -08:00
Batuhan Taskaya
0f26a0369e
Fix handling of standalone match/case with newlines/comments (#2760)
Resolves #2759
2022-01-10 12:22:07 -08:00
Batuhan Taskaya
3e731527e4
Speed up new backtracking parser (#2728) 2022-01-10 10:22:00 -08:00
Shivansh-007
521d1b8129
Enhance --verbose (#2526)
Black would now echo the location that it determined as the root path
for the project if `--verbose` is enabled by the user, according to
which it chooses the SRC paths, i.e. the absolute path of the project
is `{root}/{src}`.

Closes #1880
2022-01-10 05:58:35 -08:00
Richard Si
e401b6bb1e
Remove Python 2 support (#2740)
*blib2to3's support was left untouched because: 1) I don't want to touch
parsing machinery, and 2) it'll allow us to provide a more useful error
message if someone does try to format Python 2 code.
2022-01-10 04:16:30 -08:00
Batuhan Taskaya
e64949ee69
Fix call patterns that contain as-expression on the kwargs (#2749) 2022-01-07 18:51:36 +02:00
Richard Si
05e1fbf27d
Stubs: preserve blank line between attributes and methods (#2736) 2022-01-07 18:38:03 +02:00
Miro Hrončok
092959ff1f
Support pytest 7 by fixing broken imports (GH-2705)
The tmp_path related changes are not necessary to make pytest 7 work,
but it feels more complete this way.
2021-12-24 22:28:43 -05:00
Batuhan Taskaya
3fafd806b3
Support multiple top-level as-expressions on case statements (#2716) 2021-12-21 10:16:55 -08:00
Batuhan Taskaya
b97ec62368
Imply 3.8+ when annotated assigments used with unparenthesized tuples (#2708) 2021-12-17 13:43:14 -08:00
Batuhan Taskaya
dc90d4951f
Unpacking on flow constructs (return/yield) now implies 3.8+ (#2700) 2021-12-15 16:17:33 -08:00
Richard Si
3501cefb09
Include underlying error when AST safety check parsing fails (#2693) 2021-12-14 18:21:28 -08:00
Richard Si
3083f4470b
Don't colour diff headers white, only bold (GH-2691)
So people with light themed terminals can still read 'em.
2021-12-14 19:32:14 -05:00
Batuhan Taskaya
ab86513710
from __future__ import annotations now implies 3.7+ (#2690) 2021-12-14 15:22:56 -08:00
Batuhan Taskaya
1c6b3a3a6f
Support as-expressions on dict items (GH-2686) 2021-12-12 16:10:22 -05: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
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
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
Jelle Zijlstra
17e42cb94b
fix regex (#2643) 2021-11-25 18:34:19 -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
Richard Si
117891878e
Implementing mypyc support pt. 2 (#2431) 2021-11-15 20:24:16 -08:00
Batuhan Taskaya
d7b091e762
black/parser: optimize deepcopying nodes (#2611)
The implementation of the new backtracking logic depends heavily on deepcopying the current state of the parser before seeing one of the new keywords, which by default is an very expensive operations. On my system, formatting these 3 files takes 1.3 seconds.

```
 $ touch tests/data/pattern_matching_*; time python -m black -tpy310 tests/data/pattern_matching_*             19ms
All done!  🍰 
3 files left unchanged.
python -m black -tpy310 tests/data/pattern_matching_*  2,09s user 0,04s system 157% cpu 1,357 total
```

which can be optimized 3X if we integrate the existing copying logic (`clone`) to the deepcopy system;
```
 $ touch tests/data/pattern_matching_*; time python -m black -tpy310 tests/data/pattern_matching_*              1ms
All done!  🍰 
3 files left unchanged.
python -m black -tpy310 tests/data/pattern_matching_*  0,66s user 0,02s system 147% cpu 0,464 total
```

This still might have some potential, but that would be way trickier than this initial patch.
2021-11-15 18:38:40 -08:00
Batuhan Taskaya
147d075a4c
black/parser: support as-exprs within call args (#2608) 2021-11-14 06:04:31 -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
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
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
Nipunn Koorapati
92eeacc2e3
Use STDIN project in test_projects to ensure it runs quickly (#2575)
Existing test was actually running a full black-primer
run which could be slow. This goes from 8 seconds to
0.4 seconds on my machine.

Needed to move to top level scope to leverage the caplog
feature of pytest in order to test that the command line
was parsing the bogus arguments and dumping to stderr.
2021-10-30 11:54:43 -07:00
dawn
cbf5401eff
fix: allow tests to be run from (hopefully) any directory (GH-2574)
* fix: allow tests to be run from the tests/ directory
* fix: try fixing windows build with MarcoGorelli's suggestion
* Windows hotfix + better respect test's spirit

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-10-30 11:50:45 -04: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
Nipunn Koorapati
aedb4ff7f0
Print out line diff on test failure (#2552)
It currently prints both ASTs - this also
adds the line diff, making it much easier to visualize
the changes as well. Not too verbose since it's only a diff.
2021-10-27 07:37:20 -07:00
Nipunn Koorapati
da8a5bb189
Disallow any Generics on mypy except in black_primer (#2556)
Only black_primer needs the disallowal - means we'll
get better typing everywhere else.
2021-10-21 19:38:39 -07: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
3500e1cda5
MNT: remove unnecessary test deps + some refactoring (GH-2510)
The main goals of this commit include:

* improving consistency on how strict the test suite is -- Jelle has
  seen cases where a test did not fail to an incomplete test setup
  even though it should've
* simplifying tests for both ease of creation and reading via
  parametrization and helpers
* reorganizing the test suite by grouping more tests
* dropping test suite dependencies that aren't strictly necessary

The test suite could definitely do with more refactoring, but this is a
good first pass. Anyway it would've gotten too big to review effectively
if I did continue on this PR.

Commit history before squash merge:

* Drop parameterized dep and refactor format tests

Since the test suite is already using pytest-only features we can drop
the parameterized test dependency in favour of pytest's own offering.

I also added an utility function called assert_format that makes it
even easier to verify Black formats some code correctly. We already
have great tooling if the case is very simple in test_format.py but
any sort of complication makes it hard to use. Also if you're writing
a non-standard test case, you have to be careful to include all of
the steps so issues don't go undetected. assert_format aims to
1) improve consistency, 2) avoid wasted CPU cycles, and 3) avoid
logical errors that hide issues.

Finally, quite a few tests were either moved and/or simplified with
the new setup.

* Move file collection tests
* Add assert_collected_sources helper function

Testing source collection involves a lot of repetitive boilerplate,
something that black.files.get_sources's signature does not help with.
So to cut down on boilerplate like `report=black.Report()` I added
a convenience function to tests/test_black.py which wraps
black.get_sources. Its signature is designed to be much more lax to
make it much easier to use. Somehow this leads to cutting 100 lines!

Also IMO the test cases are much easier to read since it's more
declarative than really procedural now.

* Run isort on some test files
* Move cache tests
* Use pytest-style asserts & add parametrization
* Drop now unnecessary test dependencies

*pytest-cases might be interesting for further refactoring but I
haven't been able to wrap my head around it for the time being. We
can always revisit anyway.
2021-10-02 19:37:32 -04:00
Marco Edward Gorelli
39b55f787c
Add test to cover when unable to replace magics (#2471)
Another follow-up from #2357, adding a test for uncovered code.
2021-09-25 15:46:36 -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
Marco Edward Gorelli
7a093f0303
add test which covers stdin filename ipynb (#2454) 2021-08-28 08:27:55 -07: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
Cooper Lees
5bb4da02c2
Add cpython Lib/ repository config into primer config - Disabled (#2429)
* Add CPython repository into primer runs

- CPython tests is probably the best repo for black to test on as the stdlib's unittests should use all syntax
  - Limit to running in recent versions of the python runtime - e.g. today >= 3.9
    - This allows us to parse more syntax
- Exclude all failing files for now
  - Definitely have bugs to explore there - Refer to #2407 for more details there
  - Some test files on purpose have syntax errors, so we will never be able to parse them
- Add new black command arguments logging in debug mode; very handy for seeing how CLI arguments are formatted

CPython now succeeds ignoring 16 files:
```
Oh no! 💥 💔 💥
1859 files would be reformatted, 148 files would be left unchanged.
```

Testing
- Ran locally with and without string processing - Very little runtime difference BUT 3 more failed files
```
time /tmp/tb/bin/black --experimental-string-processing --check . 2>&1 | tee /tmp/black_cpython_esp
...
Oh no! 💥 💔 💥
1859 files would be reformatted, 148 files would be left unchanged, 16 files would fail to reformat.

real	4m8.563s
user	16m21.735s
sys	0m6.000s
```
- Add unittest for new covienence config file flattening that allows long arguments to be broke up into an array/list of strings

Addresses #2407

---

Commit history before merge:

* Add new `timeout_seconds` support into primer.json
- If present, will set forked process limit to that value in seconds
- Otherwise, stay with default 10 minutes (600 seconds)

* Add new "base_path" concept to black-primer
- Rather than start at the repo root start at a configured path within the repository
  - e.g. for cpython only run black on `Lib`

* Disable by default - It's too much for GitHub Actions. But let's leave config for others to use
* Minor tweak to _flatten_cli_args

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-08-24 17:29:49 -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
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
Jelle Zijlstra
65abd1006b
add context manager to temporarily change the cwd (#2377)
Commit history before merge:

* add context manager to temporarily change the cwd
* Iterator, not Iterable
2021-07-16 22:21:34 -04: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
Felix Hildén
dd6c674e3a
Use setuptools.find_packages in setup (#2363)
* Use setuptools.find_packages in setup

* Address mypy errors
2021-07-09 17:09:29 -07: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
Taneli Hukkinen
be16cfa035
Get click types from main repo (#2344)
Click types have been moved to click repo itself. See pallets/click#1856

I've had some issues with typeshed types being outdated in another project
so might be good to avoid that here.

Commit history before merge:

* Get `click` types from main repo
* Fix mypy errors
* Require click v8 for type annotations
* Update Pipfile
2021-06-22 11:58:49 -04:00
jack1142
52f402dcfb
Add EOF and trailing whitespace fixer to pre-commit config (#2330) 2021-06-13 10:22:46 -07: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
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
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
Felix Hildén
a9eab85f22
Mention comment non-processing in documentation (#2306)
This commit adds a short section discussing the non-processing of docstrings
besides spacing improvements, mentions comment moving and links to the
AST equivalence discussion. I also added a simple spacing test for good
measure.

Commit history before merge:

* Mention comment non-processing in documentation, add spacing test
* Mention special cases for comment spacing
* Add all special cases, improve wording
2021-06-08 17:57:23 -04: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
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
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
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
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
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
Christian Clauss
445f094f1f
Use codespell to find typos (#2228) 2021-05-13 10:28:41 -07:00
Richard Si
94a0b07dbe
Remove useless flake8 config + test support code (#2221)
We've depended on Click 7.x ever since we broke CI systems across the
world (oops lol) and flake8-mypy was purged a fair bit back: #1867

Also remove the primer tests import in tests/test_black.py because it's
annoying when just trying to actually target tests/test_black.py tests.
`pytest -k test_black.py` doesn't do what you expect due to that import.
2021-05-11 14:09:33 -04:00
Richard Si
036bea4aa0
Speed up tests even more (#2205)
There's three optimizations in this commit:

1. Don't check if Black's output is stable or equivalant if no changes
   were made in the first place. It's not like passing the same code
   (for both source and actual) through black.assert_equivalent or
   black.assert_stable is useful. It's not a big deal for the smaller
   tests, but it eats a lot of time in tests/test_format.py since
   its test cases are big. This is also closer to how Black works IRL.

2. Use a smaller file for `test_root_logger_not_used_directly` since
   the logging it's checking happens during blib2to3's startup so the
   file doesn't really matter.

3. If we're checking a file is formatting (i.e. test_source_is_formatted)
   don't run Black over it again with `black.format_file_in_place`.
   `tests/test_format.py::TestSimpleFormat.check_file` is good enough.
2021-05-08 11:34:25 +02: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
Łukasz Langa
d0e06b53b0
Mark blackd tests with the blackd optional marker (#2204)
This is a follow-up of #2203 that uses a pytest marker instead of a bunch of
`skipUnless`.  Similarly to the Python 2 tests, they are running by default and
will crash on an unsuspecting contributor with missing dependencies.  This is
by design, we WANT contributors to test everything.  Unless we actually don't
and then we can run:

  pytest --run-optional=no_blackd

Relatedly, bump required aiohttp to 3.6.0 at least to get rid of expected
failures on Python 3.8 (see 6b5eb7d465).
2021-05-07 16:33:36 +02:00
Łukasz Langa
e4b4fb02b9
Use optional tests for "no_python2" to simplify local testing (#2203) 2021-05-07 15:03:13 +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
KotlinIsland
204f76e0c0
add test configurations that don't contain python2 optional install (#2190)
add test for negative scenario: formatting python2 code
tag python2 only tests

Co-authored-by: KotlinIsland <kotlinisland@users.noreply.github.com>
2021-05-04 10:47:22 +02: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
Richard Si
b55ea63ff4
Stop stripping parens in even more illegal spots (#2148)
We're only fixing them so fuzzers don't yell at us when we break "valid"
code. I mean "valid" because some of the examples aren't even accepted by
Python.
2021-04-26 22:26:43 +02: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
Ł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
Łukasz Langa
773e4a22d5
Revert "Use lowercase hex numbers fixes #1692 (#1775)"
This reverts commit 7d032fa848.
2021-04-25 19:13:23 +02:00
Felix Hildén
368f043f13
Document experimental string processing and docstring indentation (#2106) 2021-04-22 10:37:27 -07: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
Harish Rajagopal
9451c57d1c
Support for top-level user configuration (#1899)
* Added support for top-level user configuration

At the user level, a TOML config can be specified in the following locations:
* Windows: ~\.black
* Unix-like: $XDG_CONFIG_HOME/black (~/.config/black fallback)

Instead of changing env vars for the entire black-primer process, they
are now changed only for the black subprocess, using a tmpdir.
2021-04-01 18:39:18 +02:00
Joshua Cannon
e3c71c3a47
Turn test_regex into a click callback (#2016)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-03-02 17:21:50 -08:00
Joshua Cannon
beecd6fd0a
Add --extend-exclude parameter (#2005)
Look ma! I contribute to open source!

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-03-01 14:07:36 -08:00
Rishav Kundu
858225d34d
Strip redundant parentheses from assignment exprs (#1906)
Fixes #1656
2021-02-27 17:20:23 -08:00
tpilewicz
b06cd15666
Wrap arithmetic and binary arithmetic expressions in invisible parentheses (#2001) 2021-02-24 03:56:56 -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
Sagi Shadur
6a105e019f
Add "# fmt: skip" directive to black (#1800)
Fixes #1162
2021-02-15 08:02:48 -08:00
James Addison
b8c1020b52
Stability fixup: interaction between newlines and comments (#1975)
* Add test case to illustrate the issue

* Accept carriage returns as valid separators while enumerating comments

Without this acceptance, escaped multi-line statments that use carriage returns will not be counted into the 'ignored_lines' variable since the emitted line values will end with a CR and not an escape character.  That leads to comments associated with the line being incorrectly labeled with the STANDALONE_COMMENT type, affecting comment placement and line space management.

* Remove comment linking to ephemeral build log
2021-02-11 12:11:42 -08:00
Anthony Sottile
3fca540d05
speed up cache by approximately 42x by avoiding pathlib (#1953) 2021-02-04 13:03:42 -08:00
Shantanu
692c0f50d9
Add --skip-magic-trailing-comma (#1824) 2021-01-17 16:59:06 -08:00
Bryan Bugyi
e912c7ff54
Fix INTERNAL ERROR caused by removing parens from pointless string (#1888)
Fixes #1846.
2020-12-28 12:30:23 -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
Thiago Bellini Ribeiro
dea81b7ad5
Provide a stdin-filename to allow stdin to respect force-exclude rules (#1780)
* Provide a stdin-filename to allow stdin to respect exclude/force-exclude rules

This will allow automatic tools to enforce the project's
exclude/force-exclude rules even if they pass the file through stdin to
update its buffer.

This is a similar solution to --stdin-display-name in flake8.

* Update src/black/__init__.py

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

* --stdin-filename should only respect --exclude-filename

* Update README with the new --stdin-filename option

* Write some tests for the new stdin-filename functionality

* Apply suggestions from code review

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

* Force stdin output when we asked for stdin even if the file exists

* Add an entry in the changelog regarding --stdin-filename

* Reduce disk reads if possible

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

* Check for is_stdin and p.is_file before checking for p.is_dir()

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
2020-11-13 07:26:07 -08: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
Justin Prieto
1d8b4d766d
Correctly handle inline tabs in docstrings (#1810)
The `fix_docstring` function expanded all tabs, which caused a
difference in the AST representation when those tabs were inline and not
leading. This changes the function to only expand leading tabs so inline
tabs are preserved.

Fixes #1601.
2020-11-09 11:58:23 -08:00
Bryan Bugyi
edf1c9dc0f
Fix bug which causes f-expressions to be split (#1809)
Closes #1807.
2020-11-06 16:17:23 -08:00
Bryan Bugyi
6c3f818185
Fix bug where black tries to split string on escaped space (#1799)
Closes #1505.
2020-10-31 10:42:36 -07:00
Sagi Shadur
e6cd10e761
Extract formatting tests (#1785)
* Update test versions

* Use parametrize to remove tests duplications

* Extract sources format tests

* Fix mypy errors

* Fix .travis.yml
2020-10-30 08:12:04 -07:00
Sagi Shadur
407052724f
Switch to pytest and tox (#1763)
* Add venv to .gitignore

* Use tox to run tests

* Make fuzz run in tox

* Split tests files

* Fix import error
2020-10-19 10:35:26 -07: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
Bryan Bugyi
cd055efd7d
Fix unstable subscript assignment string wrapping (#1678)
Fixes #1598
2020-09-10 09:24:01 -07:00
Bryan Bugyi
6284953d07
Fix crash on assert and parenthesized % format (fixes #1597, fixes #1605) (#1681) 2020-09-06 09:15:40 -07:00
Bryan Bugyi
7bca930ca3
Fix crash on concatenated string + comment (fixes #1596) (#1677)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2020-09-06 08:02:57 -07:00
Bryan Bugyi
e3ccabb23c
Fix unstable formatting on string split + % formatting (#1680)
Fixes #1595
2020-09-05 17:24:00 -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
ceeb1d9a2e Add expected failure tests with the unstable formattings 2020-08-26 16:55:05 +02:00
Łukasz Langa
9270a10f6f Improve docstring re-indentation handling
This addresses a few crashers, namely:

* producing non-equivalent code due to mangling escaped newlines,

* invalid hugging quote characters in the docstring body to the docstring outer
  triple quotes (causing a quadruple quote which is a syntax error),

* lack of handling for docstrings that start on the same line as the `def`, and

* invalid stripping of outer triple quotes when the docstring contained
  a string prefix.

As a bonus, tests now also run when string normalization is disabled.
2020-08-25 23:14:39 +02:00
Łukasz Langa
586d24236e Address pre-existing trailing commas when not in the rightmost bracket pair
This required some hackery.  Long story short, we need to reuse the ability to
omit rightmost bracket pairs (which glues them together and splits on something
else instead), for use with pre-existing trailing commas.

This form of user-controlled formatting is brittle so we have to be careful not
to cause a scenario where Black first formats code without trailing commas in
one way, and then looks at the same file with pre-existing trailing commas
(that it itself put on the previous run) and decides to format the code again.

One particular ugly edge case here is handling of optional parentheses.  In
particular, the long-standing `line_length=1` hack got in the way of
pre-existing trailing commas and had to be removed.  Instead, a more
intelligent but costly solution was put in place: a "second opinion" if the
formatting that omits optional parentheses ended up causing lines to be too
long.  Again, for efficiency purposes, Black reuses Leaf objects from blib2to3
and modifies them in place, which was invalid for having two separate
formattings.  Line cloning was used to mitigate this.

Fixes #1619
2020-08-25 22:10:05 +02:00
Łukasz Langa
d46268cd67
Run trailing comma tests with TargetVersion.PY38 2020-08-24 21:33:51 +02:00
Łukasz Langa
292bceb9fd
Add more trailing comma test variants 2020-08-24 18:48:11 +02:00
Łukasz Langa
bc71685d22 Open file explicitly with UTF-8 so it works on Windows, too 2020-08-21 16:45:30 +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
Jelle Zijlstra
e5bb92f53c
Disable string splitting/merging by default (#1609)
* put experimental string stuff behind a flag
* update tests
* don't need an output section if it's the same as the input
* Primer: Expect no formatting changes in attrs, hypothesis and poetry with --experimental-string-processing off

Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
2020-08-20 14:23:28 +02:00
David Szotten
820f38708f
fix unary op detection (#1600) 2020-08-14 09:17:56 -07:00
David Szotten
d1ad8730e3
don't strip brackets before lsqb (#1575) (#1590)
if the string contains a PERCENT, it's not safe to remove brackets that
follow and operator with the same or higher precedence than PERCENT
2020-08-13 19:20:46 -07:00
Jelle Zijlstra
5e1f620af7
fix some docstring crashes (#1593)
Allow removing some trailing whitespace
2020-08-13 16:40:45 -07:00
Richard Si
97c11f22aa
Make --exclude only apply to recursively found files (#1591)
Ever since --force-exclude was added, --exclude started to touch files
that were given to Black through the CLI too. This is not documented
behaviour and neither expected as --exclude and --force-exclude now
behave the same!

Before this commit, get_sources() when encountering a file that was passed
explicitly through the CLI would pass a single Path object list to
gen_python_files(). This causes bad behaviour since that function
doesn't treat the exclude and force_exclude regexes differently. Which
is fine for recursively found files, but *not* for files given through
the CLI.

Now when get_sources() iterates through srcs and encounters
a file, it checks if the force_exclude regex matches, if not, then the
file will be added to the computed sources set.

A new function had to be created since before you can do regex matching,
the path must be normalized. The full process of normalizing the path is
somewhat long as there is special error handling. I didn't want to
duplicate this logic in get_sources() and gen_python_files() so that's
why there is a new helper function.
2020-08-12 20:07:19 -07:00
Lihu Ben-Ezri-Ravin
2471b9256d
Find project root correctly (#1518)
Ensure root dir is a common parent of all inputs
Fixes #1493
2020-06-24 10:09:07 +01:00
Richard Si
6ebdc5a644
Fix toml parsing and bump toml from 0.10.0 to 0.10.1 (#1501)
* Bump toml from 0.10.0 to 0.10.1 to fix a bug

* Add tests for TOML parsing and reading

* Fix configuration bug affecting vim plugin

The vim plugin directly calls parse_pyproject and skips the Click processing
, but parse_pyproject assumed that it would only be used before Click processing
and therefore made the config values click friendly. This moves the "make the values
click friendly processing" into read_pyproject_toml which is only called by a Click
callback.

* Please mypy and flake8
2020-06-16 11:58:33 -07:00
Adam Williamson
88d12f88a9
expression tests: adjust starred expression for Python 3.9 (#1441) (#1477)
As discussed in #1441, Python 3.9's new parser will not parse
`(*starred)` even using `compile()` with the `PyCF_ONLY_AST`
flag (as `ast.parse()` does), it raises a `SyntaxError`. This
breaks the four tests that use this file with Python 3.9.
Upstream does not consider this to be a bug - see
https://bugs.python.org/issue40848#msg370643 - so we must
adjust the expression. As suggested by @JelleZijlstra, this just
adds a comma, which makes the new parser happy with it (the old
parser is fine with this form also).

Signed-off-by: Adam Williamson <awilliam@redhat.com>
2020-06-03 15:15:54 -07:00
Cooper Lees
ff6bbd5d96
Capture CalledProcessError for any postitive returncode (#1450)
- Leave logic to still allow for formatting changes to be ignored
- Now just capture the output of any other error that has a > 1 returncode
- Raise on anything else

Test: Add unit test to exercise this new logic
2020-05-22 12:16:31 -07:00
Hugo van Kemenade
a2408b3cb2
black-primer: handle singular and plural in output messages (#1432)
* Handle singular and plural in output messages
2020-05-20 21:03:51 -07:00
Cooper Lees
8acc22f114
Add black-primer unittests (#1426)
* Add black-primer unittests

- Get this tool covered with some decent unittests for all unittests wins
- Have a CLI and lib test class
- Import it from `test_black.py` so we always run tests
- Revert typing asyncio.Queue as Queue[str] so we can work in 3.6
- **mypy**: Until black > 3.6 disallow_any_generics=False for primer code

Test:
- Run tests: `coverage run tests/test_primer.py` or `coverage run -m unittest`
```
(b) cooper-mbp1:black cooper$ coverage report
Name                      Stmts   Miss  Cover
---------------------------------------------
src/black_primer/cli.py      49      8    84%
src/black_primer/lib.py     148     28    81%
tests/test_primer.py        114      1    99%
---------------------------------------------
TOTAL                       311     37    88%
```

* Use ProactorEventLoop for Windows + fix false path for Linux

* Set Windows to use ProactorEventLoop in  to benefit all callers

* sys.platform seems to not having the loop applied - So type ignore and use platform.system() gate

* Have each test loop correctly set to ProactorEventLoop on Windows for < 3.8 too
2020-05-17 12:18:49 -07:00
Hugo van Kemenade
03b8304abd
Update and fix Flake8 (#1424)
* Update pre-commit

* Fix F541 f-string is missing placeholders

* Fix E741 ambiguous variable name 'l'

* Update actions to v2
2020-05-17 07:18:45 -07:00
Jelle Zijlstra
c7da3482c7
fix crashes on docstring whitespace changes (#1417)
Fixes #1415
2020-05-15 20:47:21 -07:00
Cooper Lees
2082a325fd
Refactor black into packages in src/ dir (#1376)
- Move black.py to src/black/__init__.py
- Have setuptools_scm make src/_black_version.py and exclude from git
- Move blackd.py to src/blackd/__init__.py
- Move blib2to3/ to src/
- Update `setup.py`
- Update unittests to pass
  - Mostly path fixing + resolving
- Update CI
  - pre-commit config
  - appveyor + travis

Tested on my mac with python 3.7.5 via:
```
python3 -m venv /tmp/tb3
/tmp/tb3/bin/pip install --upgrade setuptools pip coverage pre-commit
/tmp/tb2/bin/pip install ~/repos/black/
cd ~/repos/black/
/tmp/tb2/bin/coverage run tests/test_black.py
/tmp/tb3/bin/pre-commit run -a
/tmp/tb3/bin/black --help
/tmp/tb3/bin/black ~/repos/ptr/ptr.py
```
2020-05-08 08:50:50 -07:00
Zsolt Dollenstein
7f4b275413
close event loop for all tests (#1394) 2020-05-08 16:27:50 +01:00
Zsolt Dollenstein
703faa3233 Fix mono test 2020-05-08 16:15:31 +01:00
Zsolt Dollenstein
6ea76e9b4f Improve error messages from BlackRunner 2020-05-08 16:15:31 +01:00
Giacomo Tagliabue
89c87d22e7
add --force-exclude argument (#1032)
Co-authored-by: Peter Yu <2057325+yukw777@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2020-05-08 07:47:26 -07:00
Zsolt Dollenstein
67726a7cf3
skip mono test while im working on it 2020-05-08 15:37:08 +01:00
Zsolt Dollenstein
9104ebe5ae
better test for mono executor 2020-05-08 14:57:32 +01:00
Allan Simon
c0a7582e3d
permits black to run in AWS Lambda: (#1141)
AWS Lambda and some other virtualized environment may not permit access
to /dev/shm on Linux and as such, trying to use ProcessPoolExecutor will
fail.

As using parallelism is only a 'nice to have' feature of black, if it fails
we gracefully fallback to a monoprocess implementation, which permits black
to finish normally.

Co-authored-by: Allan Simon <asimon@yolaw.fr>
2020-05-08 15:46:07 +02:00
Douglas Thor
8d6d92aa5b
Add option for printing a colored diff (#1266) 2020-05-08 14:30:10 +01:00
Jon Dufresne
1382eabb3f
Remove deprecated use of 'setup.py test' (#1275)
Since setuptools v41.5.0 (27 Oct 2019), the 'test' command is formally
deprecated and should not be used. Now use unittest as the test entry
point.
2020-05-08 06:23:50 -07:00
williamfzc
92c611cfdf
add bracket check in split_line (#1315) 2020-05-08 06:16:57 -07:00
Alex Vandiver
a4c11a75e1
Re-indent the contents of docstrings (#1053)
* Re-indent the contents of docstrings when indentation changes

Keeping the contents of docstrings completely unchanged when
re-indenting (from 2-space intents to 4, for example) can cause
incorrect docstring indentation:

```
class MyClass:
  """Multiline
  class docstring
  """

  def method(self):
    """Multiline
    method docstring
    """
    pass
```
...becomes:
```
class MyClass:
    """Multiline
  class docstring
  """

    def method(self):
        """Multiline
    method docstring
    """
        pass
```

This uses the PEP 257 algorithm for determining docstring indentation,
and adjusts the contents of docstrings to match their new indentation
after `black` is applied.

A small normalization is necessary to `assert_equivalent` because the
trees are technically no longer precisely equivalent -- some constant
strings have changed.  When comparing two ASTs, whitespace after
newlines within constant strings is thus folded into a single space.

Co-authored-by: Luka Zakrajšek <luka@bancek.net>

* Extract the inner `_v` method to decrease complexity

This reduces the cyclomatic complexity to a level that makes flake8 happy.

* Blacken blib2to3's docstring which had an over-indent

Co-authored-by: Luka Zakrajšek <luka@bancek.net>
Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
2020-05-08 14:08:15 +01:00
Bryan Bugyi
544ea9c217
Improve String Handling (#1132)
This pull request's main intention is to wraps long strings (as requested by #182); however, it also provides better string handling in general and, in doing so, closes the following issues:

Closes #26
Closes #182
Closes #933
Closes #1183
Closes #1243
2020-05-08 14:56:21 +02:00
otstrel
892eddacd2
Fix for "# fmt: on" with decorators (#1325) 2020-05-08 14:37:17 +02:00
Toby Fleming
7a14a37981
Change exit code to 2 when config file doesn't exist (#1361)
Fixes #1360, where an invalid config file causes a return/exit code of 1. This
change means this case is caught earlier, treated like any other bad
parameters, and results in an exit code of 2.

Co-authored-by: Toby Fleming <tobywf@users.noreply.github.com>
2020-04-30 08:47:52 +01:00
Rémi Verschelde
959848c176
Fix --diff output when encountering EOF (#1328)
`split("\n")` includes a final empty element `""` if the final line
ends with `\n` (as it should for POSIX-compliant text files), which
then became an extra `"\n"`.

`splitlines()` solves that, but there's a caveat, as it will split
on other types of line breaks too (like `\r`), which may not be
desired.

Fixes #526.
2020-04-04 22:02:57 -07:00
Shantanu
6d8b90167b
string prefixes: don't normalise capital R-strings (#1271)
Resolves #1244

Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2020-03-03 14:55:14 +01:00
Vlad Emelianov
be49ac72a0 Support py38-style starred expressions in return statement (#1121) 2020-01-18 07:21:46 -08:00
kyle hausmann
a02829bea1 Use conditional case for diff reports (#1226)
When --diff flag is used, black will now use the
conditional case in the Report output: eg "would
be reformatted"
2020-01-18 07:13:15 -08:00
Michael J. Sullivan
4b449e7471 Fix unstable formatting with some # type: ignores (#1113)
`type: ignore` shouldn't block collapsing a line, since it will still
apply fine to the merged line. This prevents an issue where a reformat
causes it to shift lines and then be merged on a subsequent pass.

There is a downside to this, which is that it can cause a `type:
ignore` to apply to more code than was originally intended. There
might be a way to apply this in a more limited situation, but I'm not
sure what it is.

Fixes #1061.
2019-11-25 14:16:00 -08:00
Michael J. Sullivan
3e60f6d454 Support compilation with mypyc (#1009)
* Make most of blib2to3 directly typed and mypyc-compatible

This used a combination of retype and pytype's merge-pyi to do the
initial merges of the stubs, which then required manual tweaking to
make actually typecheck and work with mypyc.

Co-authored-by: Sanjit Kalapatapu <sanjitkal@gmail.com>
Co-authored-by: Michael J. Sullivan <sully@msully.net>

* Make black able to compile and run with mypyc

The changes made fall into a couple categories:
 * Fixing actual type mistakes that slip through the cracks
 * Working around a couple mypy bugs (the most annoying of which being
   that we need to add type annotations in a number of places where
   variables are initialized to None)

Co-authored-by: Sanjit Kalapatapu <sanjitkal@gmail.com>
Co-authored-by: Michael J. Sullivan <sully@msully.net>
2019-10-30 07:29:29 -07:00
Lawrence Chan
23fec8b0f7 Fix fmt on/off when multiple exist in leaf prefix (#1086)
The old behavior would detect the existence of a `# fmt: on` in a leaf
node's comment prefix and immediately mark the node as formatting-on,
even if a subsequent `# fmt: off` in the same comment prefix would turn
it back off. This change modifies that logic to track the state through
the entire prefix and take the final state.

Note that this does not fully solve on/off behavior, since any _comment_
lines between the off/on are still formatted. We may need to add
virtual leaf nodes to truly solve that. I will leave that for a separate
commit/PR.

Fixes #1005
2019-10-28 20:51:45 +01:00
Łukasz Langa
f99fad1b78
Always move the prefix out when wrapping with parentheses (#1103)
Fixes #1097
2019-10-28 20:34:37 +01:00
Jelle Zijlstra
e027fc9e75 line_length=1 to reduce churn (#1092) 2019-10-28 15:25:42 +01:00
Łukasz Langa
6dca5278a3
Fix regression: unexpected parentheses around non-mathematical powers
This was caused by an overly liberal application of parentheses in #909 that
fixed #646.

Fixes #1041
2019-10-28 14:55:24 +01:00
Joe Antonakakis
df6e1a41f7 Add diff support to blackd (#969) 2019-10-28 14:25:26 +01:00
Jelle Zijlstra
53808e3902 fix crash with long type annotations (#1093) 2019-10-27 11:31:10 +00:00
jgirardet
e9d4e7b67f add gitignore support using pathspec (#878) 2019-10-21 11:44:53 +02:00
Jelle Zijlstra
14b28c89c2
Back out #850 (#1079)
Fixes #1042 (and probably #1044 which looks like the same thing).

The issue with the "obviously unnecessary" parentheses that #850 removed is that sometimes they're necessary to help Black fit something in one line. I didn't see an obvious solution that still removes the parens #850 was intended to remove, so let's back out this change for now in the interest of unblocking a release.

This PR also adds a test adapted from the failing example in #1042, so that if we try to reapply the #850 change we don't break the same case again.
2019-10-20 09:02:17 -07:00
Jelle Zijlstra
a73d25883a
fix CI (#1078) 2019-10-20 08:35:57 -07:00
Augie Fackler
9854d4b375 Tweak collection literals to explode with trailing comma (#826) 2019-10-20 16:08:34 +02:00
Michael J. Sullivan
0ff718e1e2 Blacken .py files in blib2to3 (#1011)
* Blacken .py files in blib2to3

This is in preparation for adding type annotations to blib2to3 in
order to compiling it with mypyc (#1009, which I can rebase on top of
this).

To enforce that it stays blackened, I just cargo-culted the existing
test code used for validating formatting. It feels pretty clunky now,
though, so I can abstract the common logic out into a helper if that
seems better. (But error messages might be less clear then?)

* Tidy up the tests
2019-10-20 15:55:31 +02:00
Michael J. Sullivan
7b11f04d54 Fix type: ignore line breaking when there is a destructuring assignment (#1065)
It turns out we also need to handle invisible *left* parens added at
the *start* of a line. Refactor `contains_unsplittable_type_ignore` to
handle this more cleanly.
2019-10-14 18:15:18 -07:00
Linus Groh
73bd7038fb Add black version header to blackd responses (#1046) 2019-10-13 11:35:31 -07:00
Andrey
6aef6c9d45 #455 Fix bug with tricky unicode symbols (#1047)
* add test for special unicode symbol which usual re can not process correctly
add regex lib which supports unicode 12.1.0 standard
replace re usage in project in favor to regex

* #455 fix dependency
2019-10-13 10:21:15 -07:00