Commit Graph

54 Commits

Author SHA1 Message Date
konsti
b40b01ffe3
Blank line between nested and function def in stub files. (#3862)
The idea behind this change is that we stop looking into previous body to determine if there should be a blank before a function or class definition.

Input:

```python
import sys

if sys.version_info > (3, 7):
    class Nested1:
        assignment = 1
        def function_definition(self): ...
    def f1(self) -> str: ...
    class Nested2:
        def function_definition(self): ...
        assignment = 1
    def f2(self) -> str: ...

if sys.version_info > (3, 7):
    def nested1():
        assignment = 1
        def function_definition(self): ...
    def f1(self) -> str: ...
    def nested2():
        def function_definition(self): ...
        assignment = 1
    def f2(self) -> str: ...
```

Stable style
```python
import sys

if sys.version_info > (3, 7):
    class Nested1:
        assignment = 1
        def function_definition(self): ...

    def f1(self) -> str: ...

    class Nested2:
        def function_definition(self): ...
        assignment = 1
    def f2(self) -> str: ...

if sys.version_info > (3, 7):
    def nested1():
        assignment = 1
        def function_definition(self): ...

    def f1(self) -> str: ...
    def nested2():
        def function_definition(self): ...
        assignment = 1
    def f2(self) -> str: ...
```

In the stable formatting, we have a blank line sometimes, not depending on the previous statement on the same level, but on the last (potentially nested) statement in the previous body.

#2783/#3564 fixes this for classes in preview style:

```python
import sys

if sys.version_info > (3, 7):
    class Nested1:
        assignment = 1
        def function_definition(self): ...

    def f1(self) -> str: ...

    class Nested2:
        def function_definition(self): ...
        assignment = 1

    def f2(self) -> str: ...

if sys.version_info > (3, 7):
    def nested1():
        assignment = 1
        def function_definition(self): ...

    def f1(self) -> str: ...
    def nested2():
        def function_definition(self): ...
        assignment = 1
    def f2(self) -> str: ...
```

This PR additionally fixes this for function definitions:

```python
if sys.version_info > (3, 7):
    if sys.platform == "win32":
        assignment = 1
        def function_definition(self): ...

    def f1(self) -> str: ...
    if sys.platform != "win32":
        def function_definition(self): ...
        assignment = 1

    def f2(self) -> str: ...

if sys.version_info > (3, 8):
    if sys.platform == "win32":
        assignment = 1
        def function_definition(self): ...

    class F1: ...
    if sys.platform != "win32":
        def function_definition(self): ...
        assignment = 1

    class F2: ...
```

You can see the effect of this change on typeshed in https://github.com/konstin/typeshed/pull/1/files. As baseline, the preview mode changes without this PR are at https://github.com/konstin/typeshed/pull/2.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-08 18:51:27 -07:00
Charlie Marsh
a20338cf10
Avoid removing whitespace for walrus operators within subscripts (#3823)
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-08 07:37:13 -07:00
Jelle Zijlstra
257d392217
Fix removed comments in stub files (#3745) 2023-07-09 15:52:41 -07:00
Jelle Zijlstra
3aad6e385b
Add support for PEP 695 syntax (#3703) 2023-06-01 18:37:08 -07:00
Tushar Sadhwani
53c23e62df
Support files with type comment syntax errors (#3594) 2023-03-19 18:52:06 -04:00
WMOkiishi
d7a28dd786
Enforce a blank line after a nested class in stubs (#3564) 2023-03-18 14:04:13 -07:00
Jelle Zijlstra
c4bd2e31ce
Draft for Black 2023 stable style (#3418) 2023-01-31 15:39:56 -08:00
Yilei "Dolee" Yang
91e1e1328a
Wrap multiple context managers in parentheses when targeting Python 3.9+ (#3489) 2023-01-20 04:14:05 -08:00
Jelle Zijlstra
60a2e8e2c2
Fix two docstring crashes (#3451) 2023-01-16 12:26:03 -08:00
Shantanu
4ebf14d17e
Strip trailing commas in subscripts with -C (#3209)
Fixes #2296, #3204
2022-08-13 06:41:34 -07:00
Richard Si
44d5da00b5 Reformat codebase with isort 2022-07-27 17:19:28 -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
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
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
Batuhan Taskaya
7f7673d941
Support 3.11 / PEP 654 syntax (#3016) 2022-04-15 12:25:07 -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
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
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
Batuhan Taskaya
6f4976a7ac
Allow for's target expression to be starred (#2879)
Fixes #2878
2022-03-04 17:37:16 -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
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
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
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
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
3e731527e4
Speed up new backtracking parser (#2728) 2022-01-10 10:22:00 -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
Jelle Zijlstra
dc8cdda8fd
tell users to use -t py310 (#2668) 2021-12-04 15:30:23 -08:00
Batuhan Taskaya
20d7ae0676
Ensure match/case are recognized as statements (#2665) 2021-12-02 09:58:22 -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
147d075a4c
black/parser: support as-exprs within call args (#2608) 2021-11-14 06:04:31 -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
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
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
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
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
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