Commit Graph

272 Commits

Author SHA1 Message Date
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
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
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
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
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
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
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
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
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
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
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
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
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
Tom Saunders
6b5753a417
Handle .COLOR_DIFF in the same way as .DIFF (#1673) 2020-09-05 12:15:28 -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
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
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
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
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
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
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
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
Joe Antonakakis
df6e1a41f7 Add diff support to blackd (#969) 2019-10-28 14:25:26 +01:00
jgirardet
e9d4e7b67f add gitignore support using pathspec (#878) 2019-10-21 11:44:53 +02: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
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
vezeli
c4d2db4323 Change variable in README according to the PEP8 (#1002)
* Change variable in README according to the PEP8
* Change variable in tests according to the PEP8
2019-09-04 09:11:07 +01:00
Zsolt Dollenstein
40e8b3a231 [blackd] Support py36-style values in X-Python-Variant header (#979) 2019-08-13 08:26:01 -07:00
Zsolt Dollenstein
bd0ab3cba2
Reraise exception in skip_if_exception decorator 2019-08-05 10:07:43 +01:00
Joe Antonakakis
154b98579d Fix async blackd tests which won't fail currently (#966) 2019-08-05 10:06:12 +01:00
Joe Antonakakis
c7495b9aa0 Fix unstable format involving backslash + whitespace at beginning of file (#948) 2019-08-04 10:03:19 +01:00
Zsolt Dollenstein
e66451761f appease flake8... 2019-07-28 16:40:04 +01:00
Zsolt Dollenstein
6b5eb7d465 skip tests touching aiohttp when known exception occurs 2019-07-28 16:35:10 +01:00
Zsolt Dollenstein
2848e2e1d6
Support PEP-570 (positional only arguments) (#946)
Code using positional only arguments is considered >= 3.8
2019-07-28 16:17:33 +01:00
Zsolt Dollenstein
d8fa8df052
Add support for walrus operator (#935)
* Parse `:=` properly
* never unwrap parenthesis around `:=`
* When checking for AST-equivalence, use `ast` instead of `typed-ast` when running on python >=3.8
* Assume code that uses `:=` is at least 3.8
2019-07-28 16:03:23 +01:00
dylanjblack
9394de150e Fix trailing comma for function with one arg (#880) (#891)
Modified maybe_remove_trailing_comma to remove trailing commas for
typedarglists (in addition to arglists), and updated line split logic
to ensure that all lines in a function definition that contain only one
arg have a trailing comma.
2019-06-14 21:49:49 -07:00
Jelle Zijlstra
957ba24bb6
remove obviously unnecessary parentheses (#850)
Fixes #548
2019-05-15 21:11:04 -07:00
Benjamin Woodruff
f8617f975d
Add support for always tokenizing async/await as keywords
Fixes #593

I looked into this bug with @ambv and @carljm, and we reached the
conclusion was that it's not possible for the tokenizer to determine if
async/await is a keyword inside all possible generators without breaking
the grammar for older versions of Python.

Instead, we introduce a new tokenizer mode for Python 3.7+ that will
cause all async/await instances to get parsed as a reserved keyword,
which should fix async/await inside generators.
2019-05-09 17:59:29 +02:00
Jason Fried
866be06646 Make --safe work for Python2.7 syntax, by using typed_ast for safe validation (#840) 2019-05-08 07:45:59 -07:00
Carl Meyer
6fdbdb4ee3
Avoid unstable formatting when comment follows escaped newline. (#839). Fixes #767. 2019-05-08 09:53:20 -04:00
Jelle Zijlstra
de806405d2 Add parentheses around tuple unpack assignment (#832)
Fixes #656
2019-05-07 09:51:28 -04:00
Jelle Zijlstra
6b994fdb8a
fix handling of comments in from imports (#829)
Fixes #671
2019-05-06 09:13:25 -04:00
Jelle Zijlstra
cea13f4984
Split the TRAILING_COMMA feature (#763) 2019-03-25 08:22:02 -07:00
Jelle Zijlstra
ba64fc757c
redo grammar selection, add test (#765) 2019-03-16 11:35:18 -07:00
Andy Freeland
d6db1c12a8 Fix print() function on Python 2 (#754)
Fixes #752
2019-03-14 16:42:54 -07:00
Łukasz Langa
6af55d8851
Mention tab comment fixes, extend tests 2019-03-14 17:17:50 +01:00
Anders-Petter Ljungquist
227c2d77b4 Changes default logger used by blib2to3 Driver (#732)
... to stop it from spamming the log when black is used as a library in another
    python application.

When used indirectly by black the logger initiated in `driver.py` will emit
thousands of debug messages making the debug level of the root logger virtually
useless. By getting a named logger instead the verbosity of logging from this
module can easily be controlled by setting its log level.

Fixes #715
2019-03-14 13:39:42 +01:00
Jelle Zijlstra
ea55ff2878
remove Python implementation-specific versions (#736) 2019-03-07 16:34:34 -08:00
Jelle Zijlstra
21ab37a5d9
remove --py36 (#724)
Fixes #703.
2019-02-24 09:15:03 -08:00
Zsolt Dollenstein
250ba7f04b Remove numeric underscore normalization (#696) 2019-02-06 19:16:49 -08:00
Jelle Zijlstra
36d3c516d3
Add --target-version option to allow users to choose targeted Python versions (#618) 2019-02-06 18:43:50 -08:00
Samuel Cormier-Iijima
66aa676278 Fix indent calculation with tabs when computing prefixes (#595)
Closes #262
2019-02-04 18:55:01 -08:00
Jan Hnátek
f6643c4f0c Fix location of expression.diff in the change notification message (#670) 2019-02-04 18:42:42 -08:00
Utsav Shah
024c9cab55 Add support for special comments in multiline functions (#642) 2019-01-05 11:20:12 -08:00
Jim Brännlund
4809e365d4 Silence expected stderr (#621)
* Silence expected stderr output during test

* Change based on PR comment
2018-11-29 21:43:22 +00:00
Jelle Zijlstra
8d58827376
Refactor Travis (#614)
Fixes #305 

- Run separate jobs for mypy, self-formatting, flake8, and test runs.
- Don't run flake8 in 3.8 because it is broken (and we can't really expect flake8 to always keep up with 3.8 development).
- Fix unused variable in test
2018-11-20 08:42:43 -08:00
Zsolt Dollenstein
5f9eb9e4f7 Add underscores to numeric literals with more than six digits (#529) 2018-09-26 12:32:11 +01:00
Zsolt Dollenstein
a82f186787 blackd: a HTTP server for blackening (#460) 2018-09-17 10:02:25 -07:00
Zsolt Dollenstein
66a6be642c fix lint errors 2018-08-26 21:27:33 +01:00
Zsolt Dollenstein
401836d02e add test case for preserving newlines from stdin 2018-08-26 21:19:22 +01:00
Jelle Zijlstra
b53cb94743 fix bracket match bug (#470)
* fix bracket match bug

* add missing test file
2018-08-23 12:52:07 +01:00
Zsolt Dollenstein
883689366c Support parsing of async generators in non-async functions (#165)
This is a new syntax added in python3.7, so black can't verify that reformatting will not change the ast unless black itself is run with 3.7. We'll need to change the error message black gives in this case. @ambv any ideas?

Fixes #125.
2018-08-20 14:47:58 +01:00
Jelle Zijlstra
b719d85ccc
autodetect Python 3.6 on the basis of underscores (#461) 2018-08-19 21:02:06 -07:00
Jelle Zijlstra
cc48bc56ca normalize numeric literals (#454)
Fixes #452

I ended up making a couple of other normalizations to numeric literals
too (lowercase everything, don't allow leading or trailing . in floats,
remove redundant + sign in exponent). I don't care too much about those,
so I'm happy to change the behavior there.

For reference, here is Python's grammar for numeric literals:
https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
2018-08-17 15:03:58 +01:00
Zsolt Dollenstein
df965b0558 update to mypy 0.620 and make tests pass again
Fixes #408
2018-07-18 22:10:52 +01:00
Zsolt Dollenstein
dd8bde6d2f Improve get_future_imports implementation.
Closes #389.
2018-07-02 17:49:47 +01:00
Łukasz Langa
048efa7476 Trivial nits 2018-06-19 23:08:10 -07:00
Łukasz Langa
2dfa69bb7f Stop Click from crashing Black on invalid environments
Fixes #277
2018-06-19 22:55:57 -07:00
Łukasz Langa
df2ae3bbe6 Use the separate pass for # fmt: off on all code
This removes the hacky exception-based handling that didn't work across
statement boundaries.

Fixes #335
2018-06-19 17:32:41 -07:00
Neraste
42a3fe5331 Ignore symbolic links pointing outside of the root directory (#339)
Fixes #338
2018-06-13 00:07:04 -07:00
Łukasz Langa
ec31ee967d Make test_black.py work in profilers 2018-06-09 18:49:39 -07:00
Łukasz Langa
489d00ed8f Support pyproject.toml
Fixes #65
2018-06-06 17:02:10 -07:00
Łukasz Langa
f71db23824 Move test data to data 2018-06-06 15:48:38 -07:00
Zsolt Dollenstein
33baccd88e Change tests with stdin/out to exercise black.main (#307) 2018-06-06 15:42:50 -07:00
Łukasz Langa
7fc6ce9906 Fix handling of empty files 2018-06-04 19:04:29 -07:00
Łukasz Langa
728e5a2f1e Properly format unified diff
Previously we weren't using timestamps.
2018-06-04 18:07:03 -07:00
Łukasz Langa
ed91dd4de6 Make source handling use sets instead of lists
Also, sort cached file output to be (more) deterministic.
2018-06-04 15:53:37 -07:00
Zsolt Dollenstein
00a302560b Preserve line endings when formatting a file in place (#288) 2018-06-04 15:52:06 -07:00
Łukasz Langa
4c352ad4be Add --verbose and report excluded paths in it, too
Fixes #283
2018-06-04 12:09:18 -07:00
Łukasz Langa
36bed855e1 Introduce "project root" as a concept
This is required for regular expressions in `--include=` and `--exclude=` not
to catch false positives from directories outside of the project.
2018-06-04 11:03:18 -07:00
Zsolt Dollenstein
ef903ecd46 Skip symlink test if can't create one (#287) 2018-06-01 14:47:07 -07:00
Łukasz Langa
8a82e0bf9a Make empty --include mean "anything goes", simplify gen_python_files_in_dir 2018-05-31 19:40:07 -07:00
Mika⠙
51756a405c Added --include and --exclude cli options (#281)
These 2 options allow you to pass in regular expressions that determine
whether files/directories are included or excluded in the recursive file
search.

Fixes #270
2018-05-31 17:51:15 -07:00
Łukasz Langa
8ebbd26888 Add --skip-string-normalization
Fixes #118
2018-05-30 12:56:16 -07:00
Łukasz Langa
023e61a254 Refactor --pyi and --py36 into FileMode 2018-05-29 01:53:54 -07:00
Luka Sterbic
e818260f1a Class new line between docstrings / vars / methods (#219)
Partially addresses #144
2018-05-28 23:48:59 -07:00
Carl Meyer
07b1b2f3dd Add --pyi and --py36 flags (#249)
Fixes #244.
2018-05-23 11:01:26 -07:00
Jelle Zijlstra
14ba1bf8b6 Add support for pyi files (#210)
Fixes #207
2018-05-15 15:09:35 -04:00
Miguel Gaiowski
c667b85a7f Check for broken symlinks before checking file data (#202) 2018-05-15 01:13:48 -04:00
Jelle Zijlstra
21c8dc85f5 Remove u prefix if unicode_literals is present (#199) 2018-05-09 18:26:41 -04:00
Łukasz Langa
1747c388bb Discover whether a file is Python 3.6+ also by stars in calls
Fixes a pathological situation where if a function signature used a trailing
comma but was later reformatted to a single line (with the trailing comma
removed), Black would change its mind whether a file is Python
3.6-compatible between runs.
2018-05-08 21:57:09 -07:00
snlkapil
6dbb657681 Removing empty parentheses after class name (#180) 2018-05-07 10:15:24 -07:00
Christian Heimes
2d9eaafa97 Output something when no files are reformatted (#190)
Just executing ``black`` without any argument does not print any message
to stdout or stderr. It's rather confusing, because the user doesn't
know what happened.

In ``len(sources) == 0`` case, black now prints ``No paths given. Nothing to
do``.

Signed-off-by: Christian Heimes <christian@python.org>
2018-05-07 10:12:47 -07:00
Zsolt Dollenstein
9f096d5536 Format subscriptions in a PEP-8 compliant way (#178)
Fixes #157
2018-04-30 22:49:30 -07:00
Jonas Obrist
92957a41e3 Make cache work with non-default line lenghts (#163) 2018-04-24 11:56:50 -07:00
Łukasz Langa
52fda8b0e9 Support sticky standalone comments (comments preceding defs, classes, and decorators)
Fixes #56
Fixes #154
2018-04-24 11:50:31 -07:00
Vishwas B Sharma
29e97d1d4a [#154] Handle comments between decorators properly (#166) 2018-04-24 09:38:12 -07:00
Łukasz Langa
54d707e10a Allow standalone comments to close code blocks
Fixes #16
Fixes #32
2018-04-23 16:17:12 -07:00
Łukasz Langa
06e95b1e9b Show full path on diffs
Fixes #130
2018-04-23 12:00:03 -07:00
Zsolt Dollenstein
c012c70176 Fix tests on windows (#159) 2018-04-23 11:23:36 -07:00
Vishwas B Sharma
5e1e1a1820 [#149] Make check and diff not mutually exclusive (#161)
Fixes #149.
2018-04-23 11:23:11 -07:00
Łukasz Langa
8429f3a63b Revert format_file_in_place() and format_stdin_to_stdout() to return bools
`Changed.CACHED` is meaningless for those two functions.
2018-04-18 17:46:03 -07:00