Compare commits

...

948 Commits
21.6b0 ... main

Author SHA1 Message Date
GiGaGon
7987951e24
Convert legacy string formatting to f-strings (#4685)
* the changes

* Update driver.py
2025-06-05 18:51:26 -07:00
GiGaGon
e5e5dad792
Fix await ellipses and remove async/await soft keyword/identifier support (#4676)
* Update tokenize.py

* Update driver.py

* Update test_black.py

* Update test_black.py

* Update python37.py

* Update tokenize.py

* Update CHANGES.md

* Update CHANGES.md

* Update faq.md

* Update driver.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2025-06-05 18:50:42 -07:00
GiGaGon
24e4cb20ab
Fix backslash cr nl bug (#4673)
* Update tokenize.py

* Update CHANGES.md

* Update test_black.py

* Update test_black.py

* Update test_black.py
2025-06-05 18:49:15 -07:00
GiGaGon
e7bf7b4619
Fix CI mypyc 1.16 failure (#4671) 2025-05-29 14:10:29 -07:00
cobalt
71e380aedf
CI: Remove now-uneeded workarounds (#4665) 2025-05-25 18:23:42 -05:00
dependabot[bot]
2630801f95
Bump pypa/cibuildwheel from 2.22.0 to 2.23.3 (#4660)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.22.0 to 2.23.3.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.22.0...v2.23.3)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-version: 2.23.3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-15 07:22:11 -05:00
danigm
b0f36f5b42
Update test_code_option_safe to work with click 8.2.0 (#4666) 2025-05-15 07:04:00 -05:00
cobalt
314f8cf92b
Update Prettier pre-commit configuration (#4662)
* Update Prettier configuration

Signed-off-by: cobalt <61329810+cobaltt7@users.noreply.github.com>

* Update .github/workflows/diff_shades.yml

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

---------

Signed-off-by: cobalt <61329810+cobaltt7@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2025-05-11 19:21:50 -05:00
Pedro Mezacasa Muller
d0ff3bd6cb
Fix crash when a tuple is used as a ContextManager (#4646) 2025-04-08 21:42:17 -07:00
pre-commit-ci[bot]
a41dc89f1f
[pre-commit.ci] pre-commit autoupdate (#4644)
updates:
- [github.com/pycqa/isort: 5.13.2 → 6.0.1](https://github.com/pycqa/isort/compare/5.13.2...6.0.1)
- [github.com/pycqa/flake8: 7.1.1 → 7.2.0](https://github.com/pycqa/flake8/compare/7.1.1...7.2.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2025-04-07 14:45:01 -07:00
Tushar Sadhwani
950ec38c11
Disallow unwrapping tuples in an as clause (#4634) 2025-04-01 07:49:37 -07:00
Tushar Sadhwani
2c135edf37
Handle # fmt: skip followed by a comment (#4635) 2025-03-22 19:30:40 -07:00
Tushar Sadhwani
6144c46c6a
Fix parsing of walrus operator in complex with statements (#4630) 2025-03-20 14:00:11 -07:00
Tsvika Shapira
dd278cb316
update github-action to look for black version in "dependency-groups" (#4606)
"dependency-groups" is the mechanism for storing package requirements in `pyproject.toml`, recommended for formatting tools (see https://packaging.python.org/en/latest/specifications/dependency-groups/ )

this change allow the black action to look also in those locations when determining the version of black to install
2025-03-20 08:01:31 -07:00
Tushar Sadhwani
dbb14eac93
Recursively unwrap tuples in del statements (#4628) 2025-03-19 15:02:40 -07:00
Tushar Sadhwani
5342d2eeda
Replace the blib2to3 tokenizer with pytokens (#4536) 2025-03-15 17:41:19 -07:00
Glyph
9f38928414
github is deprecating the ubuntu 20.04 actions runner image (#4607)
see https://github.com/actions/runner-images/issues/11101
2025-03-05 18:26:00 -08:00
Pedro Mezacasa Muller
3e9dd25dad
Fix bug where # fmt: skip is not being respected with one-liner functions (#4552) 2025-03-03 15:11:21 -08:00
dependabot[bot]
bb802cf19a
Bump sphinx from 8.2.1 to 8.2.3 in /docs (#4603)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 8.2.1 to 8.2.3.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/master/CHANGES.rst)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v8.2.1...v8.2.3)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-03 06:24:03 -08:00
Jelle Zijlstra
5ae38dd370
Fix parser for TypeVar bounds (#4602) 2025-03-03 00:20:23 -08:00
rdrll
45cbe572ee
Add regression tests for Black’s previous inconsistent quote formatting with adjacent string literals (#4580) 2025-03-02 19:23:58 -08:00
Hugo van Kemenade
fccd70cff1
Update top-pypi-packages filename (#4598)
To stay within quota, it now has just under 30 days of data, so the filename has been updated. Both will be available for a while. See https://github.com/hugovk/top-pypi-packages/pull/46.
2025-03-02 08:09:40 -08:00
🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)
00c0d6d91a
📦 Tell git archive to include numbered tags (#4593)
The wildcard at the beginning used to match tags with arbitrary
prefixes otherwise. This patch corrects that making it more accurate.
2025-02-28 16:09:40 -08:00
🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)
0580ecbef3
📦 Make Git archives for tags immutable (#4592)
This change will help with reproducibility in downstreams.

Ref: https://setuptools-scm.rtfd.io/en/latest/usage/#git-archives
2025-02-27 09:08:50 -08:00
Michael R. Crusoe
ed64d89faa
additional fix for click 8.2.0 (#4591) 2025-02-27 08:46:59 -08:00
dependabot[bot]
452d3b68f4
Bump sphinx from 8.1.3 to 8.2.1 in /docs (#4587)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 8.1.3 to 8.2.1.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/v8.2.1/CHANGES.rst)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v8.1.3...v8.2.1)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-24 05:19:48 -08:00
sobolevn
256f3420b1
Add --local-partial-types and --strict-bytes to mypy (#4583) 2025-02-20 15:27:23 -08:00
dependabot[bot]
00cb6d15c5
Bump myst-parser from 4.0.0 to 4.0.1 in /docs (#4578)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v4.0.0...v4.0.1)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-18 21:16:59 -08:00
MeggyCal
14e1de805a
mix_stderr parameter was removed from click 8.2.0 (#4577) 2025-02-18 07:30:11 -08:00
GiGaGon
5f23701708
Fix diff shades CI (#4576) 2025-02-06 18:59:16 -08:00
GiGaGon
9c129567e7
Re-add packaging CHANGES.md comment (#4568) 2025-01-29 14:29:55 -08:00
Michał Górny
c02ca47daa
Fix mis-synced version check in black.vim (#4567)
The message has been updated to indicate Python 3.9+, but the check
still compares to 3.8
2025-01-29 12:25:00 -08:00
Jelle Zijlstra
edaf085a18 new changelog template 2025-01-28 21:55:27 -08:00
Jelle Zijlstra
b844c8a136
unhack pyproject.toml (#4566) 2025-01-28 21:54:46 -08:00
Jelle Zijlstra
d82da0f0e9
Fix hatch build (#4565) 2025-01-28 20:52:03 -08:00
Jelle Zijlstra
8a737e727a
Prepare release 25.1.0 (#4563) 2025-01-28 18:34:41 -08:00
Jelle Zijlstra
d330deea00
docs: We're not going to use backslashes for the with statement (#4564) 2025-01-28 18:29:05 -08:00
cobalt
3d8129001f
Move wrap_long_dict_values_in_parens to the preview style (#4561) 2025-01-27 17:46:13 -08:00
Pedro Mezacasa Muller
459562c71a
Improve function declaration wrapping when it contains generic type definitions (#4553)
---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2025-01-26 00:43:22 -08:00
Shantanu
99dbf3006b
Cache executor to avoid hitting open file limits (#4560)
Fixes #4504, fixes #3251
2025-01-25 09:28:06 -08:00
Jelle Zijlstra
c0b92f3888
Prepare the 2025 stable style (#4558) 2025-01-24 18:00:35 -08:00
GiGaGon
e58baf15b9
Add test for #1187 (#4559)
Closes #1187
2025-01-23 21:20:47 -08:00
GiGaGon
1455ae4731
Fix docs CI (#4555)
Update .readthedocs.yaml
2025-01-21 12:43:08 -08:00
cobalt
584d0331c8
fix: Don't remove parenthesis around long dictionary values (#4377) 2025-01-16 22:09:22 -08:00
Jelle Zijlstra
6e9654065c
Fix CI (#4551) 2025-01-16 21:21:08 -08:00
Cooper Lees
8dc912774e
Remove Facebook from users (#4548) 2025-01-09 19:22:59 -08:00
pre-commit-ci[bot]
40b73f2fb5
[pre-commit.ci] pre-commit autoupdate (#4547)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/pre-commit/mirrors-mypy: v1.13.0 → v1.14.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.13.0...v1.14.1)

* Fix wrapper's return types to be String or Text IO

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Cooper Ry Lees <me@cooperlees.com>
2025-01-07 11:42:27 -08:00
GiGaGon
e157ba4de5
Fix sus returns in strings.py (#4546) 2025-01-06 12:02:56 -08:00
Tony Wang
fdabd424e2
Speed up blib2to3 tokenization using startswith with a tuple (#4541) 2024-12-29 17:17:50 -08:00
GiGaGon
9431e98522
Fix integration between stdin filename and --force-exclude (#4539) 2024-12-27 16:48:23 -08:00
GiGaGon
3b00112ac5
Fix crash on formatting certain with statements (#4538)
Fixes #3678
2024-12-24 12:25:08 -08:00
GiGaGon
0aabac4fe0
Add regression test for #1765 (#4530) 2024-12-23 10:46:25 -08:00
cobalt
ed33205579
Fix type error (#4537) 2024-12-22 22:19:40 -08:00
Ac5000
6000d37f09
Add Clarification to Config File Location/Name (#4533) 2024-12-19 16:07:27 -08:00
GiGaGon
30759ca782
Add *.py diff=python to .gitattributes (#4531) 2024-12-11 11:35:20 -08:00
dependabot[bot]
84ac1a947d
Bump sphinxcontrib-programoutput from 0.17 to 0.18 in /docs (#4528)
Bumps [sphinxcontrib-programoutput](https://github.com/NextThought/sphinxcontrib-programoutput) from 0.17 to 0.18.
- [Changelog](https://github.com/OpenNTI/sphinxcontrib-programoutput/blob/master/CHANGES.rst)
- [Commits](https://github.com/NextThought/sphinxcontrib-programoutput/compare/0.17...0.18)

---
updated-dependencies:
- dependency-name: sphinxcontrib-programoutput
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-09 12:44:44 -08:00
mosfet80
0db1173bbc
Update libs into .pre-commit-config.yaml (#4521) 2024-12-07 19:53:22 -08:00
GiGaGon
3fab5ade71
Prevent f-string merge quote changes with nested quotes (#4498) 2024-12-03 20:44:26 -08:00
Owen Christie
e54f86bae4
Two blank lines after an import should be reduced to one (#4489)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-12-03 20:39:35 -08:00
cobalt
96ca1b6be3
fix: Remove parenthesis around sole list items (#4312) 2024-11-27 19:59:29 -08:00
Ярослав Бритов
17efac45f9
Update getting_started.md (#4518)
Update necessary python version to run black in docs.
2024-11-25 20:22:37 -08:00
dependabot[bot]
73f651f02f
Bump pypa/cibuildwheel from 2.21.2 to 2.22.0 (#4517)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.21.2 to 2.22.0.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.21.2...v2.22.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-25 08:54:00 -08:00
Shantanu
f6c7c98f34
Fix issue with newer upload-artifact in PyPI action (#4512)
Github is breaking older upload-artifact in a few weeks
2024-11-14 07:43:59 -08:00
dependabot[bot]
d670b0439c
Bump sphinx from 7.4.7 to 8.1.3 in /docs (#4483) 2024-11-14 04:27:54 +00:00
dependabot[bot]
56896264e4
Bump docutils from 0.20.1 to 0.21.2 in /docs (#4342) 2024-11-13 20:15:30 -08:00
dependabot[bot]
efd9778873
Bump myst-parser from 3.0.1 to 4.0.0 in /docs (#4434)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 3.0.1 to 4.0.0.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v3.0.1...v4.0.0)
2024-11-13 20:14:50 -08:00
GiGaGon
c472557ba8
Small improvements to the contributing basics (#4502) 2024-11-05 08:03:32 -08:00
Mattwmaster58
53a219056d
Note required python version for use_pyproject: true (#4503) 2024-10-24 18:58:24 -07:00
Matej Aleksandrov
c98fc0c128
Update deprecated type aliases (#4486) 2024-10-23 07:00:55 -07:00
Shantanu
f54f34799b
Use released mypy (#4490) 2024-10-19 18:01:05 -07:00
Matej Aleksandrov
484a669699
Replace remaining aliases to built-in types (#4485) 2024-10-14 16:37:58 -07:00
Matej Aleksandrov
fff747d61b
Fix formatting cells with magic methods and starting or trailing empty lines (#4484) 2024-10-14 06:55:59 -07:00
Marc Mueller
9995bffbe4
Store license identifier inside the License-Expression metadata field (#4479) 2024-10-11 14:40:49 -07:00
Jelle Zijlstra
7452902c77 New changelog 2024-10-11 14:21:07 -07:00
Jelle Zijlstra
32ebb93003
Clean up Python 3.8 remnants (#4473) 2024-10-08 19:11:22 -07:00
Shantanu
1b2427a2b7
Prepare release 24.10.0 (#4471) 2024-10-07 11:43:01 -07:00
Shantanu
a22b1ebbfd
Add mypyc 3.13 wheel build (#4449) 2024-10-07 07:32:53 -07:00
dependabot[bot]
b7d0e7212b
Bump AndreMiras/coveralls-python-action from 65c1672f0b8a201702d86c81b79187df74072505 to ac868b9540fad490f7ca82b8ca00480fd751ed19 (#4468)
Bumps [AndreMiras/coveralls-python-action](https://github.com/andremiras/coveralls-python-action) from 65c1672f0b8a201702d86c81b79187df74072505 to ac868b9540fad490f7ca82b8ca00480fd751ed19.
- [Release notes](https://github.com/andremiras/coveralls-python-action/releases)
- [Changelog](https://github.com/AndreMiras/coveralls-python-action/blob/develop/CHANGELOG.md)
- [Commits](65c1672f0b...ac868b9540)

---
updated-dependencies:
- dependency-name: AndreMiras/coveralls-python-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-30 08:00:31 -07:00
Jelle Zijlstra
f1a2f92bba
Include --unstable in cache key (#4466)
Fixes #4465
2024-09-27 13:41:29 -07:00
Matej Aleksandrov
8d9d18c033
Fix skipping Jupyter cells with unknown %% magic (#4462) 2024-09-19 19:35:46 -07:00
Hugo van Kemenade
bbfdba3a5e
Fix docs CI: use venv for uv to fix 'failed to create directory' (#4460)
Use venv for uv to fix 'failed to create directory'
2024-09-16 00:10:34 -07:00
Shantanu
8fb2add1f7
Use builtin generics (#4458)
uvx ruff check --output-format concise src --target-version py39 --select UP006 --fix --unsafe-fixes
uvx ruff check --output-format concise src --target-version py39 --select F401 --fix
plus some manual fixups
2024-09-15 20:10:07 -07:00
Shantanu
2a45cecf29
Fix crashes with comments in parentheses (#4453)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-09-15 19:34:02 -07:00
Shantanu
b4d6d8632d
Drop Python 3.8 support (#4452) 2024-09-15 18:21:21 -07:00
Shantanu
ac018c16ca
Require newer aiohttp for blackd (#4451) 2024-09-15 18:05:23 -07:00
Shantanu
058da5f81a
Report Black version on internal error (#4457) 2024-09-12 15:24:56 -07:00
Sam Burnett
98a580bbdc
Added Python and grammar versions to a parser error message (#4378)
---------

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: Shantanu Jain <hauntsaninja@gmail.com>
2024-09-08 14:24:54 -07:00
Matej Aleksandrov
f50aba4984
Fix broken GitHub link to black.schema.json (#4445) 2024-09-07 18:14:27 -07:00
Shantanu
6b27ef53e2
Caveat Python 3.13 support (#4448)
Note the actual release workflow will probably fail as it currently
stands, I anticipate we'd need to add CIBW_SKIP
2024-09-07 17:32:57 -07:00
Shantanu
26aeebe9fb
Update mypy/c (#4450) 2024-09-07 17:32:47 -07:00
Shantanu
9e13708be8
Prevent use on Python 3.12.5 (#4447)
Fixes #4446
See https://github.com/python/cpython/issues/123821

It's possible this is too strict? We could instead do this anytime the
AST safety check fails, but feels weird to have that happen
non-deterministically
2024-09-07 16:41:06 -07:00
Ewout ter Hoeven
ac28187bf4
Fully support Python 3.13, including CI testing and wheel building (#4436) 2024-08-26 10:07:54 -07:00
Terence Honles
823a7b0ff0
fix: fix PEP 646 support of tuple unpacking (#4440)
This change fixes unpacking a tuple or generic type when *args is a type
variable tuple.
2024-08-26 08:09:59 -07:00
Shantanu
699b45aef7
Fix type error in blackd (#4442) 2024-08-22 18:17:32 -07:00
dependabot[bot]
c20423249e
Bump furo from 2024.7.18 to 2024.8.6 in /docs (#4435)
Bumps [furo](https://github.com/pradyunsg/furo) from 2024.7.18 to 2024.8.6.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2024.07.18...2024.08.06)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-08 18:20:00 -07:00
Richard Si
5ec91686ff
Remove myself from docs dependency upgrade reviews (#4433) 2024-08-08 19:10:23 -04:00
Jelle Zijlstra
7e3e8f5bd9 Add new changelog 2024-08-05 10:33:28 -07:00
Jelle Zijlstra
b965c2a502
Prepare release 24.8.0 (#4426) 2024-08-02 09:38:22 -07:00
Michael Eliachevitch
9ccf279a17
Document find_project_root ignoring pyproject.toml without [tool.black] (#4425)
Extend the docstring of black's `find_project_root` to mention that it ignores
`pyproject.toml` files without a `[tool.black]` section.

This is relevant because that function is also used by other python packages
that use black. I found that e.g. datamodel-code-generator [1] uses that
function and that there the ignoring of the pyproject.toml files lead to
a degradation [2]. I think in that case it would be better to not use black's function
for finding the pyproject.toml, but in any case this behavior should be documented.

1: https://github.com/koxudaxi/datamodel-code-generator
2: https://github.com/koxudaxi/datamodel-code-generator/issues/2052

Co-authored-by: Michael Eliachevitch <Michael.Eliachevitch@blueyonder.com>
2024-08-02 09:38:07 -07:00
Kanishk Pachauri
14b6e61970
fix: Enhace black efficiently to skip directories listed in .gitignore (#4415) 2024-08-02 09:24:39 -07:00
Tushar Sadhwani
b1c4dd96d7
fix: respect braces better in f-string parsing (#4422) 2024-08-02 09:21:39 -07:00
Jelle Zijlstra
4b4ae43e8b
Fix incorrect linenos on fstring tokens with escaped newlines (#4423)
I don't think this can affect Black itself much (maybe for formatting
ranges), but I ran into this with https://github.com/JelleZijlstra/lib2toast
2024-08-01 11:54:15 -07:00
Kanishk Pachauri
7fa1faf83a
docs: fix the installation command of extra for blackd (#4413) 2024-07-24 21:40:26 -07:00
dependabot[bot]
8827accf56
Bump sphinx from 7.3.7 to 7.4.0 in /docs (#4404)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 7.3.7 to 7.4.0.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/master/CHANGES.rst)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v7.3.7...v7.4.0)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-22 07:06:49 -07:00
dependabot[bot]
b0da11d370
Bump furo from 2024.5.6 to 2024.7.18 in /docs (#4409)
Bumps [furo](https://github.com/pradyunsg/furo) from 2024.5.6 to 2024.7.18.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2024.05.06...2024.07.18)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-22 06:46:59 -07:00
Tushar Sadhwani
721dff5493
fix: avoid formatting backslash strings inside f-strings (#4401) 2024-07-10 19:52:37 -07:00
Oliver Sayers
7e2afc9bfd
Update actions/checkout to v4 to stop node deprecation warnings (#4379) 2024-07-04 16:50:26 -07:00
Shantanu
1ad5263f2f
Bump cibuildwheel to 2.19.2 (#4395)
Fixes #4383, fixes #4381
2024-07-04 16:45:53 -07:00
Shantanu
9ff047a957
Fix wheel build by using newer manylinux image (#4394) 2024-07-04 16:40:28 -07:00
Jelle Zijlstra
5e571ccbbe
Fix use of deprecated ast.Str (#4393) 2024-07-04 16:26:42 -07:00
pre-commit-ci[bot]
978bc505ac
[pre-commit.ci] pre-commit autoupdate (#4392) 2024-07-01 17:18:22 -07:00
dependabot[bot]
b1f7b9f87d
Bump docker/build-push-action from 5 to 6 (#4387)
* Bump docker/build-push-action from 5 to 6

Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 5 to 6.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-06-25 08:42:06 -07:00
Tushar Sadhwani
b677a643c5
tokenizer: skip lines that are just slash and whitespace (#4343) 2024-06-01 13:01:36 -07:00
dependabot[bot]
8447af4d8d
Bump pypa/cibuildwheel from 2.18.0 to 2.18.1 (#4373)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.18.0 to 2.18.1.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.18.0...v2.18.1)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-01 12:59:53 -07:00
Yilei Yang
9c1fd463e1
Make sure Black doesn't crash when fmt:off is used before a closing paren (#4363) 2024-05-15 20:32:27 -04:00
dependabot[bot]
b9c63230b4
Bump pypa/cibuildwheel from 2.17.0 to 2.18.0 (#4360)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.17.0 to 2.18.0.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.17.0...v2.18.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-13 05:32:40 -07:00
dependabot[bot]
4af12c499e
Bump furo from 2024.4.27 to 2024.5.6 in /docs (#4358)
Bumps [furo](https://github.com/pradyunsg/furo) from 2024.4.27 to 2024.5.6.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2024.04.27...2024.05.06)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-13 05:27:58 -07:00
dependabot[bot]
c827551b23
Bump AndreMiras/coveralls-python-action from 8799c9f4443ac4201d2e2f2c725d577174683b99 to 65c1672f0b8a201702d86c81b79187df74072505 (#4359)
Bump AndreMiras/coveralls-python-action

Bumps [AndreMiras/coveralls-python-action](https://github.com/andremiras/coveralls-python-action) from 8799c9f4443ac4201d2e2f2c725d577174683b99 to 65c1672f0b8a201702d86c81b79187df74072505.
- [Release notes](https://github.com/andremiras/coveralls-python-action/releases)
- [Changelog](https://github.com/AndreMiras/coveralls-python-action/blob/develop/CHANGELOG.md)
- [Commits](8799c9f444...65c1672f0b)

---
updated-dependencies:
- dependency-name: AndreMiras/coveralls-python-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-13 05:24:13 -07:00
Cooper Lees
3be19b306f
docker: Install the compiled wheel then install extras dependencies (#4357)
- Lets install black, then ask to install black with extrasC
  - pip sees black is installed and just installs extra dependencies

Test:
- Build local container
  - `docker build -t black_local .`
- Run blackd in container
  - `docker run -p 45484:45484 --rm black_local blackd --bind-host 0.0.0.0`
```
cooper@home1:~/repos/black$ docker run -p 45484:45484 --rm black_local blackd --bind-host 0.0.0.0
blackd version 24.4.3.dev11+gad60e62 listening on 0.0.0.0 port 45484
INFO:aiohttp.access:10.255.255.1 [10/May/2024:14:40:36 +0000] "GET / HTTP/1.1" 405 204 "-" "curl/8.5.0"

cooper@home1:~/repos/black$ curl http://10.6.9.2:45484
405: Method Not Allowed
```
- Test version is compiled
```
cooper@home1:~/repos/black$ docker run --rm black_local black --version
black, 24.4.3.dev11+gad60e62 (compiled: yes)
Python (CPython) 3.12.3
```

Fixes #4163
2024-05-10 08:23:10 -07:00
Jelle Zijlstra
f71925885c
Add caution to the playground mention (#4352) 2024-05-07 12:33:10 -07:00
Jelle Zijlstra
ccfb0db4d5
Extend link detection to links outside parens (#4347) 2024-05-04 16:14:13 -07:00
Jelle Zijlstra
c801cd60b1
Format docs/ and scripts/ in CI (#4348) 2024-05-04 13:26:36 -07:00
Samson Umezulike
f22b2437d5
Convert PR numbers in docs/change_log to clickable links (#4346)
Uses the sphinx include-read event to regex replace all occurrences of a PR number `(#X)` with a link `[(#X)](https://github.com/psf/black/pull/X)`.
2024-05-04 08:03:50 -07:00
Michael R. Crusoe
75eb55764e
packaging metadata: link to the docs, issue tracker (#4345)
See https://github.com/pypi/warehouse/issues/5947
https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#urls
2024-05-03 06:51:33 -07:00
dependabot[bot]
f2da85fe7f
Bump myst-parser from 2.0.0 to 3.0.1 in /docs (#4341)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 2.0.0 to 3.0.1.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v2.0.0...v3.0.1)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-29 06:17:24 -07:00
dependabot[bot]
0ab0b75717
Bump furo from 2024.1.29 to 2024.4.27 in /docs (#4340)
Bumps [furo](https://github.com/pradyunsg/furo) from 2024.1.29 to 2024.4.27.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2024.01.29...2024.04.27)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-29 06:16:28 -07:00
Tomasz Kłoczko
0c033f3eb7
Upgrade some old syntax (#4338)
Signed-off-by: Tomasz Kłoczko <kloczek@github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-04-27 07:54:18 -07:00
Jelle Zijlstra
455de7703e
Fix another f-string regression (#4339) 2024-04-27 01:24:20 -07:00
Jelle Zijlstra
dbb956b0d3 New changelog 2024-04-25 18:25:22 -07:00
Jelle Zijlstra
3702ba224e
Prepare release 24.4.2 (#4335)
* Prepare release 24.4.2

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-04-25 16:52:26 -07:00
Jelle Zijlstra
e4aaa8a994
Fix incorrect f-string tokenization (#4332) 2024-04-25 16:45:46 -07:00
Jelle Zijlstra
ba88fc372e
Simplify string tokenization regexes (#4331) 2024-04-24 23:11:31 -07:00
Jelle Zijlstra
5683242fd4 New release template 2024-04-24 20:22:56 -07:00
Jelle Zijlstra
e7fb048281
Prepare release 24.4.1 (#4328) 2024-04-24 07:23:25 -07:00
Jelle Zijlstra
3f0f8f1956
Support PEP 696 (#4327) 2024-04-23 22:08:37 -07:00
S.S
2f88085da5
Github Action: Directly install from repo if export-subst is skipped (#4313) 2024-04-23 20:01:53 -07:00
Shantanu
12ce3db077
Move changelog entry to right section (#4326)
Crashes are usually documented in the stable style portion of the
changelog. This patch doesn't affect the parser (e.g. blib2to3).
Noticed the second after I merged :-)
2024-04-23 19:26:49 -07:00
peterkra25
1354be2525
Add support to style function definitions with newlines before function stubs (#4318)
* Add support to style function definitions containing newlines before function stubs

* Relocated implementation for removal of newlines before function stubs with added tests for comments

---------

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2024-04-23 19:19:56 -07:00
Tushar Sadhwani
f4b644b82f
Prevent wrapping of multiline fstrings in parens (#4325) 2024-04-23 14:16:47 -07:00
Tushar Sadhwani
551ede2825
Add PEP 701 support (#3822)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-04-22 08:19:19 -07:00
dependabot[bot]
944b99aa91
Bump sphinx from 7.2.6 to 7.3.7 in /docs (#4322)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 7.2.6 to 7.3.7.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/master/CHANGES.rst)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v7.2.6...v7.3.7)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-22 00:01:38 -07:00
Shantanu
7134754ef4
Remove node-specific logic from visit_default (#4321)
This is the point of a visitor
2024-04-21 23:59:29 -07:00
Shantanu
7669381420
Pin to old flake8-bugbear (#4319)
See https://github.com/PyCQA/flake8-bugbear/issues/467 or https://github.com/psf/black/pull/4318
2024-04-21 20:19:47 -07:00
Shantanu
735733b205
Use uv in docs build (#4310)
Currently pip spends about 20s
2024-04-14 01:51:07 -07:00
Harsha S
9dc9114aef
Mention pipx installation 2024-04-14 01:11:24 -07:00
Shantanu
66e2b11571
Add new change template (#4308) 2024-04-12 13:25:36 -07:00
Shantanu
8fe627072f
Prepare release 24.4.0 (#4307) 2024-04-12 13:12:22 -07:00
dependabot[bot]
6b25e7cdab
Bump peter-evans/find-comment from 3.0.0 to 3.1.0 (#4304)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 3.0.0 to 3.1.0.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](d5fe37641a...3eae4d3798)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-08 09:40:15 -04:00
alwayshang
07fe1ca88a
docs: remove repetitive word (#4303)
Signed-off-by: alwayshang <zhanghonghao@outlook.com>
2024-04-07 00:18:00 -07:00
Sebastian Rittau
3383f531bc
GitHub Action: Allow reading version from pyproject.toml (#4294)
Closes #4285

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-04-05 08:40:40 -04:00
pre-commit-ci[bot]
c8f1a5542c
[pre-commit.ci] pre-commit autoupdate (#4297) 2024-04-01 15:51:24 -07:00
Shantanu
836acad863
Improve AST safety check (#4290)
Fixes #4288, regressed by #4270
2024-03-22 20:13:53 -06:00
cobalt
13bd0925eb
fix: Stop moving multiline strings to a new line unless inside brackets (#4289)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
2024-03-22 20:11:01 -06:00
Shantanu
c9d2635b55
Remove mocking from tests (#4287)
Fixes #4275
2024-03-20 18:15:42 -07:00
Yilei Yang
bf1195612c
Fix two logging calls in the test helper (#4286)
They were missing formatting interpolation operators.
2024-03-19 22:04:48 -07:00
dependabot[bot]
97993f997f
Bump pypa/cibuildwheel from 2.16.5 to 2.17.0 (#4283)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.16.5 to 2.17.0.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.16.5...v2.17.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-18 12:19:55 -06:00
rdrll
f78b15712a
Fix formatting for if clauses in match-case blocks (#4269)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-03-16 07:38:07 -07:00
Jelle Zijlstra
8332a75e82 Add new change template 2024-03-15 12:40:29 -07:00
Jelle Zijlstra
552baf8229
Prepare release 24.3.0 (#4279) 2024-03-15 12:17:00 -07:00
Jelle Zijlstra
f000936726
Fix catastrophic performance in lines_with_leading_tabs_expanded() (#4278) 2024-03-15 12:06:12 -07:00
Samson Umezulike
7b5a657285
Fix --line-ranges behavior when ranges are at EOF (#4273)
Fixes #4264
2024-03-15 11:18:47 -07:00
Kai Sforza
1abcffc818
Use regex where we ignore case on windows (#4252)
On windows the path `FoObAR` is the same as `foobar`, so the output
of `black` on a windows machine could output the path to `.gitignore`
with an upper or lower-case drive letter.
2024-03-12 21:22:10 -07:00
Daniel Krzeminski
719e67462c
Fix 4227: Improve documentation for --quiet --check (#4236)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-03-12 21:15:29 -07:00
Charpy
e5510afc06
update plugin url for Thonny (#4259) 2024-03-12 21:14:06 -07:00
Jelle Zijlstra
6af7d11096
Fix AST safety check false negative (#4270)
Fixes #4268

Previously we would allow whitespace changes in all strings, now
only in docstrings.

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2024-03-09 17:42:29 -08:00
Zac Hatfield-Dodds
f03ee113c9
Ensure blib2to3.pygram is initialized before use (#4224) 2024-03-02 19:31:02 -08:00
cobalt
e4bfedbec2
fix: Don't move comments while splitting delimiters (#4248)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
2024-03-01 07:02:56 -08:00
cobalt
d0287e1f75
Make trailing comma logic more concise (#4202)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
2024-02-28 13:20:46 -08:00
cobalt
0f18001abf
chore: Refactor delimiter_split() (#4257)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
2024-02-28 08:27:57 -08:00
Victorien
899002399a
Remove usage of pkg_resources in docs/conf.py (#4251) 2024-02-26 07:49:39 -08:00
Shantanu
ea66d40dd7
Update empty line documentation (#4239)
Reflects status quo following #4043

Fixes #4238
2024-02-25 16:36:52 -08:00
Shantanu
d1d4fc58d3
Add new release template (#4228) 2024-02-12 12:46:16 -08:00
Shantanu
6fdf8a4af2
Prepare release 24.2.0 (#4226) 2024-02-12 12:11:15 -08:00
cobalt
8af439407c
fix: Don't remove comments along with parens (#4218)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
2024-02-12 06:27:50 -08:00
dependabot[bot]
35e9776919
Bump pre-commit/action from 3.0.0 to 3.0.1 (#4225)
Bumps [pre-commit/action](https://github.com/pre-commit/action) from 3.0.0 to 3.0.1.
- [Release notes](https://github.com/pre-commit/action/releases)
- [Commits](https://github.com/pre-commit/action/compare/v3.0.0...v3.0.1)

---
updated-dependencies:
- dependency-name: pre-commit/action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-12 06:19:25 -08:00
Shantanu
23dfc5b2c3
Fix ignoring input files for symlink reasons (#4222)
This relates to #4015, #4161 and the behaviour of os.getcwd()

Black is a big user of pathlib and as such loves doing `.resolve()`,
since for a long time it was the only good way of getting an absolute
path in pathlib. However, this has two problems:

The first minor problem is performance, e.g. in #3751 I (safely) got rid
of a bunch of `.resolve()` which made Black 40% faster on cached runs.

The second more important problem is that always resolving symlinks
results in unintuitive exclusion behaviour. For instance, a gitignored
symlink should never alter formatting of your actual code. This kind of
thing was reported by users a few times.

In #3846, I improved the exclusion rule logic for symlinks in
`gen_python_files` and everything was good.

But `gen_python_files` isn't enough, there's also `get_sources`, which
handles user specified paths directly (instead of files Black
discovers). So in #4015, I made a very similar change to #3846 for
`get_sources`, and this is where some problems began.

The core issue was the line:
```
root_relative_path = path.absolute().relative_to(root).as_posix()
```
The first issue is that despite root being computed from user inputs, we
call `.resolve()` while computing it (likely unecessarily). Which means
that `path` may not actually be relative to `root`. So I started off
this PR trying to fix that, when I ran into the second issue. Which is
that `os.getcwd()` (as called by `os.path.abspath` or `Path.absolute` or
`Path.cwd`) also often resolves symlinks!
```
>>> import os
>>> os.environ.get("PWD")
'/Users/shantanu/dev/black/symlink/bug'
>>> os.getcwd()
'/Users/shantanu/dev/black/actual/bug'
```
This also meant that the breakage often would not show up when input
relative paths.

This doesn't affect `gen_python_files` / #3846 because things are always
absolute and known to be relative to `root`.

Anyway, it looks like #4161 fixed the crash by just swallowing the error
and ignoring the file. Instead, we should just try to compute the actual
relative path. I think this PR should be quite safe, but we could also
consider reverting some of the previous changes; the associated issues
weren't too popular.

At the same time, I think there's still behaviour that can be improved
and I kind of want to make larger changes, but maybe I'll save that for
if we do something like #3952

Hopefully fixes #4205, fixes #4209, actual fix for #4077
2024-02-12 00:04:09 -08:00
Shantanu
a20100395c
Simplify check for symlinks that resolve outside root (#4221)
This PR does not change any behaviour.

There have been 1-2 issues about symlinks recently. Both over and under
resolving can cause problems. This makes a case where we resolve more
explicit and prevent a resolved path from leaking out via the return.
2024-02-10 23:55:01 -08:00
Logan Hunt
dab37a6a11
Remove redundant parentheses in case statement if guards (#4214)
A follow up to #4024 but for `if` guards in `case` statements. I noticed this
when #4024 was made stable, and noticed I had some code that had extra parens
around the `if` guard.
2024-02-07 06:55:02 -08:00
Seung Wan Yoo
32230e6f5c
fix: bug where the doublestar operation had inconsistent formatting. (#4154)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-02-05 05:33:11 -08:00
Brandon J
7edb50f5a0
fix: additional newline added to docstring when the previous line length is less than the line length limit minus 1 (#4185)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-02-05 04:56:07 -08:00
dependabot[bot]
3e80de3447
Bump furo from 2023.9.10 to 2024.1.29 in /docs (#4211)
Bumps [furo](https://github.com/pradyunsg/furo) from 2023.9.10 to 2024.1.29.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2023.09.10...2024.01.29)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-05 04:47:35 -08:00
dependabot[bot]
a08b480a2f
Bump pypa/cibuildwheel from 2.16.4 to 2.16.5 (#4212) 2024-02-05 01:09:21 -08:00
cobalt
632f44bd68
docs: Refactor pycodestyle/Flake8 compatibility docs (#4194)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-02-01 22:00:41 -08:00
Jelle Zijlstra
9728b8e9b8
Move hug_parens_with_braces_and_square_brackets into the unstable style (#4198)
Primarily because of #4036 (a crash) but also because of the feedback
in #4098 and #4099.
2024-02-01 21:58:51 -08:00
Shantanu
2623269dab
Ignore pyproject.toml missing tool.black section (#4204)
Fixes #2863

This is pretty desirable in a monorepo situation where you have
configuration in the root since it will mean you don't have to
reconfigure every project.

The good news for backward compatibility is that `find_project_root`
continues to stop at any git or hg root, so in all cases repo root
coincides with a pyproject.toml missing tool.black, we'll continue to
have the project root as before and end up using default config
(i.e. we're unlikely to randomly start using the user config).

The other thing we need to be a little careful about is that changing
find_project_root logic affects what `exclude` is relative to.  Since we
only change in cases where there is no config, this only applies where
users were using `exclude` via command line arg (and had pyproject.toml
missing tool.black in a dir that was not repo root).

Finally, for the few who could be affected, the fix is to put an empty
`[tool.black]` in pyproject.toml
2024-02-01 21:50:45 -08:00
Henry Schreiner
24c9c01e91
fix: minor issue with schemastore part of script (#4195)
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
2024-02-01 09:25:38 -08:00
Jelle Zijlstra
cca3c0fd9f
Test that preview/unstable features are documented (#4187)
In #4096 I added a list of current preview/unstable features to the docs. I think
this is important for publicizing what's in our preview style. This PR adds an
automated test to ensure the list stays up to date in the future.
2024-01-30 22:22:38 -08:00
dependabot[bot]
d6e11ca399
Bump peter-evans/find-comment from 2.4.0 to 3.0.0 (#4190)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 2.4.0 to 3.0.0.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](a54c31d7fa...d5fe37641a)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-29 08:27:21 -08:00
dependabot[bot]
8912a33321
Bump peter-evans/create-or-update-comment from 3.1.0 to 4.0.0 (#4192)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 3.1.0 to 4.0.0.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](23ff15729e...71345be026)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-29 08:21:00 -08:00
Henry Schreiner
2bc5ce8ae1
feat: add schema and validate-pyproject support (#4181)
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-01-29 07:56:48 -08:00
dependabot[bot]
177e306363
Bump pypa/cibuildwheel from 2.16.2 to 2.16.4 (#4191)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.16.2 to 2.16.4.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.16.2...v2.16.4)
2024-01-28 23:07:34 -08:00
Shantanu
d919746fae
Swallow warnings when performing AST checks (#4189)
Fixes #4188
2024-01-28 07:05:56 -08:00
Jelle Zijlstra
0b4364b7e3 Add new release template 2024-01-28 05:37:12 -08:00
Jelle Zijlstra
e026c93888
Prepare release 24.1.1 (#4186) 2024-01-27 20:51:32 -08:00
Henry Schreiner
79fc1158a9
chore: ignore node_modules (produced by a pre-commit check) (#4184)
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
2024-01-27 20:24:36 -08:00
cobalt
8bf04549ff
Consistently add trailing comma on typed parameters (#4164)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-01-27 13:55:22 -08:00
Jelle Zijlstra
1607e9ab20
Fix missing space in option description (#4182) 2024-01-27 12:34:02 -08:00
Jelle Zijlstra
ed770ba4dd
Fix cache file length (#4176)
- Ensure total file length stays under 96
- Hash the path only if it's too long
- Proceed normally (with a warning) if the cache can't be read

Fixes #4172
2024-01-26 11:54:49 -08:00
Jelle Zijlstra
659c29a41c New changelog 2024-01-25 21:12:38 -08:00
Jelle Zijlstra
0e6e46b9eb
Prepare release 24.1.0 (#4170) 2024-01-25 20:35:21 -08:00
Jelle Zijlstra
4f47cac192
Add --unstable flag (#4096) 2024-01-25 17:00:47 -08:00
Daniel Krzeminski
bccec8adfb
Show warning on invalid toml configuration (#4165)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-01-25 16:41:37 -08:00
Shantanu
7d789469ed
Describe 2024 module docstring more accurately (#4168) 2024-01-25 16:15:18 -08:00
Shantanu
17f7f297ef
Simplify code in lines.py (#4167)
This has been getting a little messy. These changes neaten things up, we
don't have to keep guarding against `self.previous_line is not None`, we
make it clearer what logic has side effects, we reduce the amount of
code that tricky `before` could touch, etc
2024-01-25 13:41:45 -08:00
Shantanu
f7d552d9b7
Remove reference (#4169)
This is out-of-date and just a chore. I don't think this is useful to
contributors and Black doesn't even have a public API.
2024-01-25 13:11:26 -08:00
cobalt
a5196e6f1f
fix: Don't normalize whitespace before fmt:skip comments (#4146)
Signed-off-by: RedGuy12 <paul@reid-family.org>
2024-01-25 01:31:49 -08:00
Jelle Zijlstra
59b9d858a3
Create the 2024 stable style (#4106) 2024-01-24 17:06:14 -08:00
Daniel Krzeminski
8fe602b1fa
fix pathlib exception handling with symlinks (#4161)
Fixes #4077
2024-01-22 09:46:57 -08:00
dependabot[bot]
6f3fb78444
Bump actions/cache from 3 to 4 (#4162)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-22 09:22:56 -08:00
Shantanu
995e4ada14
Fix unnecessary nesting when wrapping long dict (#4135)
Fixes #4129
2024-01-19 17:13:26 -08:00
Kevin Paulson
7f60f3dbd7
Update using_black_with_other_tools.md to ensure flake8 configuration examples are consistant (#4157) 2024-01-19 15:54:32 -08:00
cobalt
9a331d606f
fix: Don't allow unparenthesizing walruses (#4155)
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
Signed-off-by: RedGuy12 <paul@reid-family.org>
2024-01-17 11:04:15 -08:00
Dragorn421
b7c3a9fedd
Docs: Add note on --exclude about possibly verbose regex (#4145)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-01-11 07:46:17 -08:00
Shantanu
e11eaf2f44
Make blank_line_after_nested_stub_class work for methods (#4141)
Fixes #4113

Authored by dhruvmanila
2024-01-01 20:14:57 -08:00
Shantanu
b1d17ef9a2
Fix comment handling when parenthesising conditional expressions (#4134)
Fixes #3555
2024-01-01 17:55:11 -08:00
Shantanu
4ceed0b958
Remove is_function_or_class helper footgun (#4133)
This is a no-op change.

That function was not a good way to tell if something is a function or a
class, since it basically only worked for async functions by accident
(the parent of a suite / simple_stmt of async function body is a
funcdef).
2024-01-01 17:36:49 -08:00
Shantanu
269190274b
Clean up dead code in magic trailing comma logic (#4131) 2024-01-01 17:29:21 -08:00
Shantanu
8e0a9dee1b
Remove empty lines before docstrings in async functions (#4132) 2024-01-01 16:56:39 -08:00
Shantanu
b9ad4da2e8
Revert "confine pre-commit to stages (#3940)" (#4137)
This reverts commit 7686989fc8.
2024-01-01 16:55:25 -08:00
Shantanu
fe3376141c
Allow empty lines at beginnings of more blocks (#4130)
Fixes #4043, fixes #619

These include nested functions and methods.

I think the nested function case quite clearly improves readability. I
think the method case improves consistency, adherence to PEP 8 and
resolves a point of contention.
2024-01-01 15:46:09 -08:00
pre-commit-ci[bot]
c35924663c
[pre-commit.ci] pre-commit autoupdate (#4139) 2024-01-01 15:12:18 -08:00
Jelle Zijlstra
db9c592967
Unify docstring detection (#4095)
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
2023-12-27 22:59:30 -08:00
Shantanu
bf6cabc804
Do not round cache mtimes (#4128)
Fixes #4116

This logic was introduced in #3821, I believe as a result of copying
logic inside mypy that I think isn't relevant to Black
2023-12-27 22:24:57 -08:00
cobalt
c80685f361
Treat walruses like other binary operators in subscripts (#4109)
Fixes #4078
2023-12-27 22:24:25 -08:00
Anupya Pamidimukkala
51786141cc
Fix nits, chain comparisons, unused params, hyphens (#4114) 2023-12-27 22:23:42 -08:00
Cooper Lees
1b831f214a
Add new changelog template (#4125) 2023-12-22 15:46:06 -08:00
Cooper Lees
ec91a2be3c
Prepare release 23.12.1 (#4124) 2023-12-22 15:04:32 -08:00
Bryce Willey
8fec1c3085
Adds paren to deps for hidden extra constraint (#4108)
Fix #4107
2023-12-14 00:28:28 -08:00
Jelle Zijlstra
35ce37ded7 Add new changelog template 2023-12-11 22:28:46 -08:00
Jelle Zijlstra
d9ad09a32b
Prepare release 23.12.0 (#4105) 2023-12-11 21:55:28 -08:00
Jelle Zijlstra
ebd543c0ac
Fix feature detection for parenthesized context managers (#4104) 2023-12-11 21:37:15 -08:00
Jelle Zijlstra
eb7661f8ab
Fix another case where we format dummy implementation for non-functions/classes (#4103) 2023-12-11 14:41:41 -08:00
Jelle Zijlstra
0c9899956d
Fix path in test message (#4102) 2023-12-11 14:29:33 -08:00
Jelle Zijlstra
9aea9768cb
Only use dummy implementation logic for functions and classes (#4066)
Fixes #4063
2023-12-11 13:19:02 -08:00
dependabot[bot]
67b23d7185
Bump actions/setup-python from 4 to 5 (#4101) 2023-12-11 11:32:04 -08:00
Jelle Zijlstra
ce28be2705
Add dedicated preview feature for East Asian Width (#4097) 2023-12-09 21:14:25 -08:00
Jelle Zijlstra
61b529b7d1
Allow empty lines at beginning of blocks (again) (#4060) 2023-12-09 18:29:09 -08:00
cobalt
e7e122e9ff
docs: Move fmt: off docs (#4090) 2023-12-09 17:44:15 -08:00
cobalt
432d9050c3
docs: Unify option descriptions between --help and the_basics.md (#4076) 2023-12-07 09:32:06 -08:00
cobalt
50e287cece
docs: Clarify include/exclude documentation (#4072) 2023-12-07 08:38:57 -08:00
John Litborn
e4ae213f06
test preview cases with line-length 1 unless explicitly skipped (#4087)
* Add new flag for tests, --no-preview-line-length-1, to be used for test cases known to not work in preview mode with line-length=1. Also split out the problematic cases in three cases to separate files. Removed now redundant file which explicitly tested preview annotations with line-length=1

* mode.preview -> preview_mode, mark pep_572_remove_parens as failing with ll1
2023-12-06 07:17:33 -08:00
John Litborn
50d5756e8e
fix crash in preview mode with --line-length=1 (#4086) 2023-12-05 10:19:24 -08:00
Riyazuddin Khan
3416b2c82d
Fix: --line-ranges dedents a # fmt: off in the middle of a decorator (#4084)
Fixes #4068
2023-12-04 10:10:03 -08:00
exag
66ec056e39
Fix minor typos in docstrings (#4085) 2023-12-03 21:47:30 -08:00
Alex Waygood
a0e270d0f2
Build mypycified wheels for Python 3.12 (#4070) 2023-11-24 10:05:59 -08:00
Alex Waygood
69d49c5a6f
Bump mypy to 1.7.1 (#4069) 2023-11-24 06:19:54 -08:00
Henri Holopainen
fb5e5d2be6
Prefer more equal signs before a break when splitting chained assignments (#4010)
Fixes #4007
2023-11-22 19:11:49 -08:00
Jelle Zijlstra
be336bb67f
Run lint job on Ubuntu only (#4061) 2023-11-20 22:33:16 -08:00
Yilei Yang
a8062983cd
Disable the stability check with --line-ranges for now. (#4034)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-20 20:45:39 -08:00
tungol
89e28ea66f
Permit standalone form feed characters at the module level (#4021)
Co-authored-by: Stephen Morton <git@tungol.org>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-20 20:44:33 -08:00
Cooper Lees
ec4a1525ee
[docker ci] Revert "parallel" builds in seperate actions (#4057)
- Broke tagging images together
- Saved only a few mins
  - x86_64 build is fast, time is all spent on cross compile of arm64
- Also remove evil copy pasta ... which is nice

Was worth an attempt.
2023-11-19 11:28:00 -08:00
Cooper Lees
30c6bb3651
[docker ci] Split up amd64 (x86_64) and arm64 builds (#4054)
* [docker ci] Split up amd64 (x86_64) and arm64 builds

- Lets run them seperately to cut down total time
- Will also more clearly show if either arch has specific problems
- Kept amd64 (x86_64) using qemu actions so if GitHub ever offers arm64 boxes it could stay working too

Fixes #3971

* Add CHANGES entry

---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-19 10:44:00 -08:00
Cooper Lees
f23b845a29
[ci] Move 'lint' to 3.12 (#4053)
- Add to run on MacOS + Windows too
- Do not install [d] dependecies as blackd is not actually run / checked
- Move to default GitHub action version - which is 3.12 today
2023-11-18 18:11:50 -08:00
Cooper Lees
96faa3b469
[docker] Build with 3.12 image (#4055)
Test:
```
crl-m1:black cooper$ docker build --tag black_3_12 .
...
 => [stage-1 2/2] COPY --from=builder /opt/venv /opt/venv                                                                                                                                                  0.2s
 => exporting to image                                                                                                                                                                                     0.1s
 => => exporting layers                                                                                                                                                                                    0.1s
 => => writing image sha256:bd66acc9d76d2c40d287b0684ce6601401631e0468204c4e6a81f8f1eebaf1dd                                                                                                               0.0s
 => => naming to docker.io/library/black_3_12

crl-m1:black cooper$ docker image ls | grep black_3_12
black_3_12                     latest            bd66acc9d76d   59 seconds ago   193MB
```
2023-11-18 18:09:47 -08:00
Cooper Lees
80a166f2e1
Make black[d] install + test run with 3.12 (#4035)
* Make black[d] install + test run with 3.12

- With aiohttp >= 3.9.0 we can now install all dependencies with 3.12
- Add actions to run 3.12
- Lint still needs to be 3.11

Test:
- `python3.12 -m venv /tmp/tb --upgrade-deps`
- `/tmp/tb/bin/pip install tox`
- `/tmp/tb/bin/pip install .[d]`
- `/tmp/tb/bin/tox -e py312`
```
  py312: OK (37.61=setup[3.98]+cmd[3.83,0.36,19.54,6.46,3.00,0.44] seconds)
  congratulations :) (37.63 seconds)
```

* Move to pypy-3.9

---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-18 12:09:55 -08:00
Yilei Yang
11da02da72
Handle more huggable immediately nested parens/brackets. (#4012)
Fixes #4011
2023-11-18 11:47:05 -08:00
Alex Waygood
d93a942a79
Upgrade mypy to 1.6.1 (#4049) 2023-11-18 11:42:36 -08:00
Alex Waygood
c4cd200a06
Make flake8 pass when run with Python 3.12 (#4050) 2023-11-18 11:41:46 -08:00
Alex Waygood
85b1c71a34
Block aiohttp==3.9.0 from being installed in CI on Windows/pypy (#4051) 2023-11-18 11:15:07 -08:00
cobalt
5773d5cd2b
Document target version inference (#4048) 2023-11-17 13:39:44 -08:00
Alex Waygood
1b6b0bfcac
Improve annotations for black.concurrency.cancel (#4047) 2023-11-17 07:57:00 -08:00
Jelle Zijlstra
58f31a70ef Add new release template 2023-11-07 22:10:35 -08:00
Jelle Zijlstra
2a1c67e0b2
Prepare release 23.11.0 (#4032) 2023-11-07 20:44:46 -08:00
Ran Benita
72e7a2e43e
Remove redundant condition from has_magic_trailing_comma (#4023)
The second `if` cannot be true at its execution point, because it is
already covered by the first `if`. The condition
`comma.parent.type == syms.subscriptlist` always holds if
`closing.parent.type == syms.trailer` holds, because `subscriptlist`
only appears inside `trailer` in the grammar:

```
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: (subscript|star_expr) (',' (subscript|star_expr))* [',']
```
2023-11-07 20:21:33 -08:00
Henri Holopainen
1a7d9c2f58
Preserve visible quote types for f-string debug expressions (#4005)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-07 20:19:32 -08:00
Abdenour Madani
f4c7be5445
docs: fix minor typo (#4030)
Replace "E950" with "B950"
2023-11-07 15:40:10 -08:00
Shantanu
2e4fac9d87
Apply force exclude logic before symlink resolution (#4015) 2023-11-07 11:31:44 -08:00
Henri Holopainen
66008fda5d
[563] Fix standalone comments inside complex blocks crashing Black (#4016)
Bracket depth is not an accurate indicator of standalone comment position inside more complex blocks because bracket depth can be virtual (in loops' and lambdas' parameter blocks) or from optional parens. Here we try to stop cumulating lines upon standalone comments in complex blocks, and try to make standalone comment processing more simple. The fundamental idea is, that if we have a standalone comment, it needs to go on its own line, so we always have to split.

This is not perfect, but at least a first step.
2023-11-07 11:29:24 -08:00
rdrll
50ed6221d9
Fix long case blocks not split into multiple lines (#4024)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-11-07 06:31:58 -08:00
Yilei Yang
46be1f8e54
Support formatting specified lines (#4020) 2023-11-06 18:05:25 -08:00
Shantanu
ecbd9e8cf7
Fix crash with f-string docstrings (#4019)
Python does not consider f-strings to be docstrings, so we probably
shouldn't be formatting them as such

Fixes #4018

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2023-11-06 16:58:43 -08:00
Yilei Yang
e808e61db8
Preview: Keep requiring two empty lines between module-level docstring and first function or class definition (#4028)
Fixes #4027.
2023-11-06 14:30:04 -08:00
Shantanu
9e3daa1107
Fix arm wheels on macOS (#4017) 2023-11-05 18:29:37 -08:00
Ran Benita
448324637d
Enable branch coverage (#4022)
When trying to understand the code logic, and looking at coverage
reports, branch coverage is very helpful.
2023-11-04 13:49:12 -07:00
Jelle Zijlstra
c54c213d6a
Fix crash on await (a ** b) (#3994) 2023-11-02 20:42:11 -07:00
Shantanu
e2f2bd076f
Minor refactoring in get_sources and gen_python_files (#4013) 2023-11-01 06:20:14 -07:00
Jelle Zijlstra
5758da6e3c
Fix bytes strings being treated as docstrings (#4003)
Fixes #4002
2023-10-31 17:11:28 -07:00
Henri Holopainen
e50110353a
Produce equivalent code for docstrings containing backslash followed by whitespace(s) before newline (#4008)
Fixes #3727
2023-10-31 08:27:11 -07:00
Henri Holopainen
ddfecf06c1
Hug parens also with multiline unpacking (#3992) 2023-10-30 08:35:26 -07:00
Cooper Lees
f7cbe4ae1b
Add release tool (#3974)
* Add release tool

- Add tool for release managers to use to generate commits
  - I'm trying to only use stdlib so we have no depdencies ...
- Default is to change date strings in hard coded documentation files + CHANGES.md
  - I write directly to files cause we have SCM to fix any screw ups ...
- We hackily convert calver to ints to sort (all for better ideas here)
  - If we hit a ValueError we just set to 0 for sorting - This is alhpa + beta release we can safely ignore these days
- Add new CI to only run release unittests in 3.12 only on all platforms
- Update release docs

- Checked with `mypy --strict` + ensure we are `black --preview` formatted :D

Tests:
- Run it to generate template PR
  - `python3.12 release.py --debug --add-changes-template`
- Run it to cleanup CHANGE.md + change version in specified doc files
```
crl-m1:black cooper$ python3.12 release.py -d
[2023-10-23 23:39:38,414] INFO: Current version detected to be 23.10.1 (release.py:221)
[2023-10-23 23:39:38,414] INFO: Next version will be 23.10.2 (release.py:222)
[2023-10-23 23:39:38,414] INFO: Cleaning up /Users/cooper/repos/black/CHANGES.md (release.py:127)
[2023-10-23 23:39:38,416] DEBUG: Finished Cleaning up /Users/cooper/repos/black/CHANGES.md (release.py:147)
[2023-10-23 23:39:38,416] INFO: Updating black version to 23.10.2 in /Users/cooper/repos/black/docs/integrations/source_version_control.md (release.py:173)
[2023-10-23 23:39:38,416] DEBUG: Finished updating black version to 23.10.2 in /Users/cooper/repos/black/docs/integrations/source_version_control.md (release.py:185)
[2023-10-23 23:39:38,416] INFO: Updating black version to 23.10.2 in /Users/cooper/repos/black/docs/usage_and_configuration/the_basics.md (release.py:173)
[2023-10-23 23:39:38,417] DEBUG: Finished updating black version to 23.10.2 in /Users/cooper/repos/black/docs/usage_and_configuration/the_basics.md (release.py:185)
```
- Add tests around some key logic

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix lints + add git to release CI

- Remove black + mypy as linting already runs it ...
- Ignore delete param to TemporaryDirectory as we can't set mypy to 3.12 :D

* Only run CI on linux/ubuntu for now

* Add lots of debug printing + directly run unitests (not via coverage)

* Overloading __str__ is bad on a TestCase

* Add more logging around git tag

* Print where git is in a step

* Rollback creating a fake black repo as we were not using it - I did plan to but I can't get it working on GitHub actions

* Do a deep checkout

* Add noqa for E701,E761 ... maybe we need this in our flake8 config now?

* Fix action to have correct workflow yaml to action on
- Also add fix to not double run when we push directly to psf/black

* All jelle suggestions
- Fix bug missing lines ending with --> in CHANGES.md to delete ...
- Update ci to run out of scripts dir too
- Update test_tuple_calver

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-10-29 15:34:38 -07:00
Aditya Garg
5515a5ac7a
Update README.md (#3997)
Fixed a grammatical error in README.md
2023-10-29 10:28:33 -07:00
Jelle Zijlstra
5edd99312a
Regression test for match variable inside match (#3993) 2023-10-28 11:05:53 -07:00
Shivam Singh
9a90fa2cb7
Fix typo in README.md (#3995) 2023-10-28 10:48:18 -07:00
David Culley
7686989fc8
confine pre-commit to stages (#3940)
See https://pre-commit.com/#confining-hooks-to-run-at-certain-stages

> If you are authoring a tool, it is usually a good idea to provide an appropriate `stages` property. For example a reasonable setting for a linter or code formatter would be `stages: [pre-commit, pre-merge-commit, pre-push, manual]`.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-10-27 15:43:34 -07:00
Satyam Namdev
53c4278a4c
Update CHANGES.md (#3988)
Fixed a grammatical mistake
2023-10-27 13:27:19 -07:00
Shantanu
c712d57ca9
Add trailing comma test case for hugging parens (#3991) 2023-10-27 12:17:54 -07:00
Gabriel Perren
caef19689b
Update current_style.md (#3990)
Fix small typo
2023-10-27 11:54:31 -07:00
sth
c369e446f9
Fix matching of absolute paths in --include (#3976) 2023-10-27 00:43:51 -07:00
Surav Shrestha
7bfa35cca8
docs: fix typos in change log and documentations (#3985) 2023-10-26 21:26:47 -07:00
Shantanu
de701fe6aa
Fix CI by running on Python 3.11 (#3984)
aiohttp doesn't yet support 3.12
2023-10-26 21:13:25 -07:00
Ikko Eltociear Ashimine
f7174bfc43
Fix typo in future_style.md (#3979)
parantheses -> parentheses
2023-10-26 09:43:42 -07:00
Henri Holopainen
878937bcc3
[2213] Add support for single line format skip with other comments on the same line (#3959) 2023-10-25 09:47:21 -07:00
Henri Holopainen
1d4c31aa58
[925] Improve multiline dictionary and list indentation for sole function parameter (#3964) 2023-10-25 08:35:37 -07:00
Cooper Lees
ef1048d5f8
Add Unreleased template to CHANGES.md (#3973)
Add Unreleased template to CHANGES.md - Did this via tool working on in another branch
2023-10-24 01:26:40 -05:00
Cooper Lees
744d23b348
Prepare release 23.10.1 (#3969)
* Prepare release 23.10.1

* Update docs/usage_and_configuration/the_basics.md

Add missed version string

We need to automate or remove this from docs ... It's painful.

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

---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-10-23 10:59:16 -07:00
Kiyoon Kim
8de4be5168
Fix CI failing (#3957)
* Fix CI failing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* docs: update CHANGES.md

* docs: fix changelog location to unreleased

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-23 10:37:14 -07:00
William Moreno
c0adca321d
docs: specifies the use of the .git-blame-ignore-revs file (#3961) 2023-10-23 10:21:58 -07:00
Dario Curreri
a7643fac8d
Add summary parameter to action (#3958) 2023-10-23 09:40:09 -07:00
Cooper Lees
d291c2338c
Move Docker image to hatch + compile (#3965) 2023-10-23 08:36:47 -07:00
dependabot[bot]
7f1c578b89
Bump peter-evans/create-or-update-comment from 3.0.2 to 3.1.0 (#3966)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 3.0.2 to 3.1.0.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](c6c9a1a660...23ff15729e)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-23 07:42:49 -07:00
Henri Holopainen
2db5ab0a7b
Allow empty line after block open before a comment or compound statement (#3967) 2023-10-23 07:38:36 -07:00
Aniket Patil
0a37888e79
Fix typos in CHANGES.md (#3963) 2023-10-22 14:16:43 -07:00
Henri Holopainen
882d8795c6
Fix merging implicit multiline strings that have inline comments (#3956)
* Fix test behaviour

* Add new test cases

* Skip merging strings that have inline comments

* Don't merge lines with multiline strings with inline comments

* Changelog entry

* Document implicit multiline string merging rules

* Fix PR number
2023-10-19 20:09:33 -07:00
Jelle Zijlstra
9edba85f71
Prepare release 23.10.0 (#3951) 2023-10-17 07:22:24 -07:00
Jelle Zijlstra
bb588073ab
Fix parser bug where "type" was misinterpreted as a keyword inside a match (#3950)
Fixes #3790

Slightly hacky, but I think this is correct and it should also improve performance somewhat.
2023-10-17 00:59:15 -07:00
Jelle Zijlstra
722735d20e
Fix grammar for type alias support (#3949)
Fixes #3948
2023-10-16 10:53:38 -07:00
Jelle Zijlstra
abe57e3d92
Treat raw strings like other docstrings (#3947)
Fixes #3944
2023-10-16 10:51:51 -07:00
Henri Holopainen
1648ac5180
Fix long lines with power operator(s) getting splitted before line length (#3942)
Fixes #3889
2023-10-16 07:08:21 -07:00
Charles Patel
6f84f65285
Migrate mypy config to pyproject.toml (#3936)
Co-authored-by: Charles Patel <charles.patel@apkudo.com>
2023-10-16 05:24:16 -07:00
rdrll
3bb92146f5
CI Test: Deprecating 'Healthcheck.all()' from Hypothesis in fuzz.py (#3945) 2023-10-16 05:13:53 -07:00
Jelle Zijlstra
935f303a0a
Fix test that was not being run (#3939) 2023-10-09 20:02:27 -07:00
Daniël van Noord
b7717c3f1e
Standardise newlines after module-level docstrings (#3932)
Co-authored-by: jpy-git <josephyoung.jpy@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-10-09 19:34:26 -07:00
Shantanu
7aa37ea0ad
Report all stacktraces in verbose mode (#3938)
Previously these were swallowed (unlike the ones in black/__init__.py)
2023-10-09 19:15:51 -07:00
Shantanu
5d5bf6e087
Fix cache versioning when BLACK_CACHE_DIR is set (#3937) 2023-10-09 18:44:36 -07:00
Jelle Zijlstra
a69bda3b9b
Use inline flags for test cases (#3931)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2023-10-09 18:43:47 -07:00
Shantanu
715f60c11b
Drop support for parsing Python 2 (#3933) 2023-10-09 07:02:49 -07:00
dependabot[bot]
a8f68f57fe
Bump pypa/cibuildwheel from 2.16.1 to 2.16.2 (#3934)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.16.1 to 2.16.2.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.16.1...v2.16.2)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-09 07:00:49 -07:00
Cooper Lees
738c2789cc
Set Docker to use 3.11 for now (#3927)
Until we get new aiohttp wheels we need to build with 3.11.
You can see an example of a fail here:

Workaround for #3919 - Will leave it open until we can move to 3.21
2023-10-06 11:39:20 -07:00
Cristiano Salerno
3457ec48af
Update output display to job summary (#3914)
* Update output display to job summary

* fix: handled exit-code of script

* added changelog message
2023-10-06 10:41:36 -07:00
David Lev
3a2d76c7bc
Remove $, >>> and other prompt prefixes when code copied from the… (#3884)
Adding configurations for sphinx-copybutton in conf.py
https://sphinx-copybutton.readthedocs.io/en/latest/use.html#using-regexp-prompt-identifiers
2023-10-05 18:21:56 -07:00
John Litborn
27c05e1e24
exclude tests/data/.* from mypy (#3917) 2023-10-05 18:15:35 -07:00
Jake Anto
6c88e8e46e
Update link to VS Code formatting instructions (#3921)
Update link
2023-10-05 18:14:59 -07:00
John Litborn
36078bc83f
respect magic trailing commas in return types (#3916) 2023-10-04 16:42:35 -07:00
pre-commit-ci[bot]
947bd3825e
[pre-commit.ci] pre-commit autoupdate (#3915)
updates:
- [github.com/pre-commit/mirrors-mypy: v1.5.0 → v1.5.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.5.0...v1.5.1)
- [github.com/pre-commit/mirrors-prettier: v3.0.1 → v3.0.3](https://github.com/pre-commit/mirrors-prettier/compare/v3.0.1...v3.0.3)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-03 10:19:53 -07:00
Shreya Agarwal
9e9fdce9a8
docs: use LSP for SublimeText 4 (#3913) 2023-10-02 07:35:57 -07:00
dependabot[bot]
1b08cbc634
Bump pypa/cibuildwheel from 2.16.0 to 2.16.1 (#3911) 2023-10-01 23:40:00 -07:00
Shantanu
f99ef6e190
Fix up changelog (#3910) 2023-10-01 15:41:32 -07:00
Eddie Darling
a91eb73064
Fix comments getting removed from inside parenthesized strings (#3909)
Since the id of the old leaf may be
the key to comments, the new leaf
must adopt the old comments
2023-10-01 15:35:42 -07:00
Jelle Zijlstra
e7c3368c13
Try newer clang in diff-shades job (#3904) 2023-09-28 09:10:01 -07:00
John Litborn
9b82120ddb
add support for printing the diff of AST trees when running tests (#3902)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-28 07:03:24 -07:00
dependabot[bot]
3dcacdda0d
Bump pypa/cibuildwheel from 2.15.0 to 2.16.0 (#3901)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.15.0 to 2.16.0.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.15.0...v2.16.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-25 09:32:58 -07:00
Syed Mohammad Ibrahim
5f6ea5ff20
added the py311 to target-version config (#3898) 2023-09-23 19:23:03 -07:00
John Litborn
8c5d96ffd3
fix indentation of line breaks in long type hints by adding parens (#3899)
* fix indentation of line breaks in long type hints by adding parentheses, and remove unnecessary parentheses

* add entry in CHANGES.md, make the style change only in preview mode
2023-09-22 08:38:51 -07:00
Eero Vaher
e974fc3c52
Remove outdated mentions of runtime support of Python 3.7 (#3896)
Remove mentions of runtime support of Python 3.7

Runtime support of Python 3.7 was removed in
b4dca26c7d but a few mentions of it being
supported have remained until now.
2023-09-18 10:35:07 -07:00
dependabot[bot]
7316a79318
Bump actions/checkout from 3 to 4 (#3893)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:48:27 -07:00
dependabot[bot]
f5990e8547
Bump docker/setup-qemu-action from 2 to 3 (#3890)
Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 2 to 3.
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:48:11 -07:00
dependabot[bot]
edf66baa21
Bump docker/setup-buildx-action from 2 to 3 (#3892)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2 to 3.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:48:03 -07:00
dependabot[bot]
ab92daf408
Bump docker/login-action from 2 to 3 (#3891)
Bumps [docker/login-action](https://github.com/docker/login-action) from 2 to 3.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:47:43 -07:00
dependabot[bot]
34ed4cf8fd
Bump docker/build-push-action from 4 to 5 (#3894)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 4 to 5.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:47:26 -07:00
dependabot[bot]
5a0615a7ed
Bump sphinx from 7.2.5 to 7.2.6 in /docs (#3895)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 7.2.5 to 7.2.6.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/master/CHANGES.rst)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v7.2.5...v7.2.6)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 06:47:02 -07:00
Shantanu
e9356c1ff0
Document disabling E704 (#3888)
Linking #3887
2023-09-13 00:40:41 -07:00
Shantanu
004fb79706
mypyc build improvements (#3881)
Build in separate jobs. This makes it clearer if e.g. a single Python
version is failing. It also potentially gets you more parallelism.

Build everything on push to master.

Only build Linux 3.8 and 3.11 wheels on PRs.
2023-09-11 13:36:37 -07:00
dependabot[bot]
14f60c84c8
Bump docutils from 0.19 to 0.20.1 in /docs (#3699)
Bumps [docutils](https://docutils.sourceforge.io/) from 0.19 to 0.20.1.
2023-09-11 13:20:36 -07:00
dependabot[bot]
b2f03f9132
Bump sphinx from 7.2.3 to 7.2.5 in /docs (#3882)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 7.2.3 to 7.2.5.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/master/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v7.2.3...v7.2.5)
2023-09-11 13:19:57 -07:00
Simon Alinder
e73662ca7c
Fix broken url in editors.md (#3885)
* Fix broken url in editors.md

Update a link pointing to the Arch Linux repos.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-09-11 09:47:47 -07:00
dependabot[bot]
213cb65518
Bump actions/checkout from 3 to 4 (#3883)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-11 09:34:36 -07:00
Jelle Zijlstra
e87737140f
Prepare release 23.9.1 (#3878) 2023-09-10 17:35:41 -07:00
Shantanu
62dca32dc5
mypyc builds on PRs, skip mypyc wheels for 3.12 (#3870)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-10 16:47:08 -07:00
Jelle Zijlstra
751583a1df
Pickle raw tuples in FileData cache (#3877)
Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com>
2023-09-10 16:16:24 -07:00
Jelle Zijlstra
f7917453c9
Re-export black.Mode (#3875) 2023-09-10 16:12:20 -07:00
Jelle Zijlstra
0b62b9c9a4
Ignore aiohttp DeprecationWarning for 3.12 (#3876)
Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com>
2023-09-10 15:45:13 -07:00
Hugo van Kemenade
c83ad6c077
Upgrade to Furo 2023.9.10 to fix docs build (#3873) 2023-09-10 14:36:25 -07:00
Shantanu
4eebfd1a7a
Add mypyc test marks to new tests that patch (#3871)
This is enough for me to get a clean test run on Python 3.9 with mypyc.
I have not been able to repro the pickle failures on either Linux or
macOS.
2023-09-10 07:53:27 -07:00
Richard Si
add161b367
Bump RTD Python version from 3.8 to 3.11 (#3868)
Recent ReadTheDocs builds have been failing as our documentation dependencies (notably Sphinx) require Python 3.9+.
2023-09-09 09:08:28 -07:00
Shantanu
4e93f2aa01
Add classifier for 3.12 (#3866) 2023-09-08 22:16:25 -07:00
Jelle Zijlstra
716fa08090
Upgrade mypy (#3864) 2023-09-08 22:16:15 -07:00
Jelle Zijlstra
b70b2c6196
Prepare release 23.9.0 (#3863) 2023-09-08 20:24:49 -07:00
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
Jonas Haag
74d3009ba4
Add Black PyCharm 2023.2 integration instructions (#3839) 2023-09-07 18:35:07 -07:00
KotlinIsland
8daa64a2e1
blackd: fix mishandling of single character input (#3558) 2023-09-07 00:11:50 -07:00
Shantanu
df50fee7fd
Apply ignore logic before symlink resolution (#3846)
This means, for instance, that a gitignored symlink cannot affect your
formatting. Fixes #3527, fixes #3826
2023-09-06 21:06:07 -07:00
Johnny.H
58f1bf69d2
Move coverage configurations to pyproject.toml (#3858) 2023-09-02 22:46:23 -04:00
dependabot[bot]
47676bf593
Bump furo from 2023.7.26 to 2023.8.19 in /docs + sphinx to 7.2.3 (#3848)
* Bump furo from 2023.7.26 to 2023.8.19 in /docs

Bumps [furo](https://github.com/pradyunsg/furo) from 2023.7.26 to 2023.8.19.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2023.07.26...2023.08.19)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* Move to sphinx 7.2.3 + fix intersphinx_mapping

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cooper Ry Lees <me@cooperlees.com>
2023-08-26 08:44:17 -05:00
Kjell-Magnus
d9c249c25a
Fix download badge link (#3853) 2023-08-22 12:40:10 -07:00
Shantanu
6310a405f6
Improve handling of root to get_sources (#3847)
This is a little more type safe and a little cleaner
2023-08-19 08:13:05 -07:00
Marc Mueller
066aa9210a
Remove tox pin (#3844) 2023-08-19 08:09:59 -07:00
Marc Mueller
c6a031e623
Improve caching by comparing file hashes as fallback for mtime and size (#3821)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2023-08-18 19:26:36 -07:00
Shantanu
793c2b5f9f
Pin tox to fix CI (#3843) 2023-08-18 18:32:47 -07:00
pre-commit-ci[bot]
ade371fd1c
[pre-commit.ci] pre-commit autoupdate (#3837) 2023-08-16 00:01:21 -07:00
Shantanu
7c4fe83bd8
Make pre-commit do less (#3838) 2023-08-15 06:51:26 -07:00
dependabot[bot]
66648c528a
Bump pypa/cibuildwheel from 2.14.1 to 2.15.0 (#3836) 2023-08-14 00:30:56 -07:00
Christian Proud
c36e468794
Remove ENV_PATH on Black action completion (#3759) 2023-08-08 11:12:05 -07:00
pre-commit-ci[bot]
77f19944f6
[pre-commit.ci] pre-commit autoupdate (#3833)
updates:
- [github.com/pre-commit/mirrors-prettier: v3.0.0 → v3.0.1](https://github.com/pre-commit/mirrors-prettier/compare/v3.0.0...v3.0.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-08-08 08:41:39 -07:00
Shantanu
c160e4b7ce
More concise formatting for dummy implementations (#3796) 2023-08-03 19:11:21 -07:00
Shantanu
59e8936768
Document pre-commit mirror (#3828) 2023-08-03 18:46:08 -07:00
pre-commit-ci[bot]
1b028cc9d9
[pre-commit.ci] pre-commit autoupdate (#3825) 2023-08-01 01:48:21 -07:00
dependabot[bot]
8a16b25fb1
Bump furo from 2023.5.20 to 2023.7.26 in /docs (#3824)
Bumps [furo](https://github.com/pradyunsg/furo) from 2023.5.20 to 2023.7.26.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2023.05.20...2023.07.26)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-31 08:43:32 -07:00
Aneesh Agrawal
1a972e3e11
Add Lyft to organizations using black (#3818) 2023-07-27 14:50:51 -07:00
freddiewanah
133af57207
Rewrite mostly useless assert in test_trans.py (#3810)
This PR updates an assert statement that checks the bounds of a
string-slicing operation. The updated assertion provides more accurate
and informative error handling by specifically checking the relative
values of the indices and the string length.

The original assertion was essentially checking if Python's string
slicing was behaving as expected. However, it wasn't providing any
guarantees or useful information about the bounds i and j themselves.

The updated assertion checks that the indices used for slicing are
within the bounds of the string. It will throw an AssertionError if the
indices are out of bounds or if i > j, providing a more specific and
informative error.
2023-07-27 12:51:28 -04:00
Yury V. Zaytsev
d9d0a02d89
Fix typo in target-version param wrongly used in plural (#3817) 2023-07-27 07:12:38 -07:00
Pradeep Kumar
c3235e6da7
Fix unintentionally swapped words in index.md (#3809)
Fix unintentionally swapped words in index.md

I think the intent was to say "large changes in formatting", because it doesn't make sense to say "large formatting in changes".
2023-07-23 21:56:19 -07:00
mihazagar
13bd4fffae
Fixing pre-commit using pyyaml with broken version (#3804) 2023-07-22 11:12:37 -07:00
Shantanu
e7e8d6287b
Simplify empty line tracker (#3797) 2023-07-22 07:49:51 -08:00
rdrll
0b301f8095
Improvements to contributing docs (#3753) 2023-07-18 14:11:24 -07:00
Richard Si
2f68ac850b
Fix diff-shades comment missing newlines (#3799)
Preserving newlines is done differently when writing to $GITHUB_OUTPUT
over the deprecated :set-output: command.
2023-07-18 06:51:16 -08:00
dependabot[bot]
068f6fb8fa
Bump pypa/cibuildwheel from 2.13.1 to 2.14.1 (#3795)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-16 23:59:36 -07:00
Shantanu
c1e30d97fe
Fix most blib2to3 lint (#3794) 2023-07-16 21:33:58 -07:00
Richard Si
8d80aecd50
Maintainers += Shantanu Jain (hauntsaninja) (#3792) 2023-07-16 18:16:12 -07:00
Clément Robert
92e0f5b965
Avoid importing IPython if notebook cells do not contain magics (#3782)
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2023-07-16 21:09:26 -04:00
Shantanu
0e26ada66d
Continue to avoid Click typing issue (#3791) 2023-07-16 17:35:19 -07:00
rax
6123b4ac26
Document shebang comment behaviour (#3787) 2023-07-11 12:16:43 -07:00
pre-commit-ci[bot]
37895f8e50
[pre-commit.ci] pre-commit autoupdate (#3780)
updates:
- [github.com/pycqa/flake8: 4.0.1 → 6.0.0](https://github.com/pycqa/flake8/compare/4.0.1...6.0.0)
- [github.com/pre-commit/mirrors-prettier: v2.7.1 → v3.0.0](https://github.com/pre-commit/mirrors-prettier/compare/v2.7.1...v3.0.0)
- [github.com/pre-commit/pre-commit-hooks: v4.3.0 → v4.4.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.3.0...v4.4.0)
2023-07-11 07:50:52 -07:00
Shantanu
8d2110320b
Fix lint in test_ipynb (#3781)
Unblocks #3780
2023-07-11 07:35:41 -07:00
Alex Waygood
f4490acfd7
Remove unneeded mypy dependencies (#3783) 2023-07-11 07:21:36 -07:00
Nicola Soranzo
027afda403
Remove Python 3.7 from classifiers (#3784)
Follow-up on https://github.com/psf/black/pull/3765
2023-07-11 07:21:15 -07:00
skykasko
a062d5c985
Fix typo in CITATION.cff (#3779)
Fix tiny typo in CITATION.cff
2023-07-10 19:38:01 -07:00
Jelle Zijlstra
193ee766ca
Prepare release 23.7.0 (#3776) 2023-07-10 17:09:47 -07:00
Shantanu
38723bb778
Unpin pytest-xdist (#3772) 2023-07-10 11:49:40 -07:00
Shantanu
138769aa27
Disable coverage on pypy tests (#3777)
The pypy tests are reeeeaaally slow. Maybe this will help.
2023-07-10 08:37:12 -07:00
Shantanu
ad3724b7ff
Upgrade to latest mypy (#3775) 2023-07-09 17:04:50 -07:00
Shantanu
b8e2ec728c
Fix crash on type comment with trailing space (#3773) 2023-07-09 16:28:26 -07:00
Jelle Zijlstra
257d392217
Fix removed comments in stub files (#3745) 2023-07-09 15:52:41 -07:00
Shantanu
2593af2c5d
Improve performance by skipping unnecessary normalisation (#3751)
This speeds up black by about 40% when the cache is full
2023-07-09 15:24:01 -07:00
Kenneth Schackart
f3b50e4669
Add CITATION.cff file (#3723) 2023-07-09 15:07:21 -07:00
Shantanu
0b4d7d55f7
Run pyupgrade on blib2to3 and src (#3771) 2023-07-09 15:05:01 -07:00
Shantanu
114e8357e6
Remove click patch (#3768)
Apparently this was only needed on Python 3.6. We've now dropped support
for 3.6 and 3.7. It's also not needed on new enough click.
2023-07-09 13:29:47 -07:00
Shantanu
4130c65578
Fix CI for Click typing issue (#3770)
https://github.com/pallets/click/issues/2558
2023-07-09 08:14:38 -07:00
Shantanu
b4dca26c7d
Drop support for Python 3.7 (#3765) 2023-07-05 10:08:04 -07:00
Shantanu
cf4cc29819
Better error message for invalid exclude types (#3764) 2023-07-04 22:45:57 -07:00
Zac Hatfield-Dodds
8e618f3869
Enable PYTHONWARNDEFAULTENCODING = 1 in CI (#3763) 2023-07-04 16:38:39 -07:00
rdrll
839ef35dc1
CI Test: Deprecating 'set-output' command (#3757) 2023-06-30 07:07:42 -07:00
rdrll
f01aaa63a0
Doc: Developer reference update (#3755) 2023-06-28 13:45:56 -07:00
rdrll
63481bb926
Fix a magical comment caused internal error (#3740)
`is_type_comment` now specifically deals with general type comments for a leaf.
`is_type_ignore_comment` now handles type comments contains ignore annotation for a leaf
`is_type_ignore_comment_string` used to determine if a string is an ignore type comment
2023-06-27 07:23:39 -07:00
Shantanu
31b3b6701d
Decrease cost of ipynb code path when unneeded (#3748)
IPython is a very expensive import, like, at least 300ms. I'd also
venture that it's much more common than tokenize-rt, which is like 30ms.
I work in a repo where I use black, have IPython installed and there
happen to be a couple notebooks (that we don't want formatted). I know I
can force exclude ipynb, but this change doesn't really have a cost.
2023-06-26 17:47:55 -07:00
Shantanu
e1036119f2
Check self format for the whole repo (#3750)
`black .` is changing things in gallery and scripts for me
2023-06-25 06:53:26 -07:00
Shantanu
93989e995d
Integrate verbose logging with get_sources (#3749)
Currently the verbose logging for "Sources to be formatted" is a little
suspect in that it is a completely different code path from
`get_sources`.

This can result in bugs like https://github.com/psf/black/pull/3216#issuecomment-1213557359
and generally limits the value of these logs.

This does change the "when" of this log, but the colours help separate
it from the even more verbose logs.
2023-06-24 17:27:47 -07:00
Shantanu
7be2735318
Allow specifying --workers via environment variable (#3743) 2023-06-24 16:06:12 -07:00
Stian Jensen
c732a1f13a
Build with mypyc 1.3 (#3697)
Several new versions of mypyc has been released since the last upgrade, and they include some performance improvements which could make the compiled version of Black run faster.

https://mypy-lang.org/news.html

The latest version of hatch-mypyc allows being installed next the 1.x series of mypy.
2023-06-22 21:22:28 -07:00
Renan Santos
453828d17d
Fix not honouring pyproject.toml when using stdin and calling black from parent directory (#3719)
Co-authored-by: Renan Rodrigues <renan.rodrigues@appliedbiomath.com>
2023-06-22 21:21:49 -07:00
rdrll
d1248ca9be
Doc: updating url link (#3739) 2023-06-20 07:06:03 -07:00
dependabot[bot]
e7783e9ab2
Bump myst-parser from 1.0.0 to 2.0.0 in /docs (#3738)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 1.0.0 to 2.0.0.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v1.0.0...v2.0.0)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-19 06:58:20 -07:00
Yilei "Dolee" Yang
01b8d3d409
Do not add trailing commas to return type annotations using PEP 604 unions (#3735)
Fix #3638: Do not add trailing commas to return type annotations using PEP 604 unions.
2023-06-15 17:08:26 -07:00
Alwyn Kik
35722dff62
Max line length with bugbear (#3731)
* Make phrasing for flake8 users more concise

max-line-length should be 80 with flake8-bugbear
Fixes #3716

* Re-add rationale and an explanation for

disabling E203

* Run pre-commit
2023-06-12 12:20:31 -07:00
dependabot[bot]
688f78d380
Bump peter-evans/create-or-update-comment from 3.0.1 to 3.0.2 (#3730)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 3.0.1 to 3.0.2.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](ca08ebd5dc...c6c9a1a660)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-12 10:08:45 -07:00
dependabot[bot]
c76e0b03ec
Bump pypa/cibuildwheel from 2.13.0 to 2.13.1 (#3729)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.13.0 to 2.13.1.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.13.0...v2.13.1)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-12 10:05:49 -07:00
Ville Skyttä
898915d556
Use aware datetimes to represent UTC (#3728)
Avoids a Python 3.12 deprecation warning.

Subtle difference: previously, timestamps in diff filenames had the
`+0000` separated from the timestamp by space. With this, the space is
there no more, and there is a colon, as in `+00:00`.
2023-06-10 09:54:21 -07:00
Jelle Zijlstra
3aad6e385b
Add support for PEP 695 syntax (#3703) 2023-06-01 18:37:08 -07:00
jmcb
a538ab7663
blackd: show default values for options (#3712)
* blackd: show default values for options

Reference: https://click.palletsprojects.com/en/8.1.x/api/#click.Option

* Fix spacing in CHANGES.md
2023-05-31 14:29:31 -07:00
dependabot[bot]
a4032dce64
Bump pypa/cibuildwheel from 2.12.3 to 2.13.0 (#3710)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.12.3 to 2.13.0.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.12.3...v2.13.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-29 06:33:41 -07:00
Jelle Zijlstra
c42178690e
Fix docs formatting (#3704) 2023-05-24 21:06:08 -07:00
Jelle Zijlstra
3decbd6db9
Document each configuration option in more detail (#2839) 2023-05-24 19:55:12 -07:00
Stefaan Lippens
f95b43d6fa
docs: update note on GitHub .git-blame-ignore-revs support (#3655) 2023-05-24 19:53:27 -07:00
Deepyaman Datta
c99417ffe8
Change example from %%writeline to %%writefile (#3673) 2023-05-24 19:52:59 -07:00
dependabot[bot]
cd02c2809b
Bump furo from 2023.3.27 to 2023.5.20 in /docs (#3698)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-22 11:47:58 -04:00
Jason R. Coombs
eedfc38322
Avoid EncodingWarning in blib2to3 (#3696) 2023-05-19 10:00:29 -07:00
Jonathan Berthias
2fd9d8b339
Remove blank lines before class docstring (#3692) 2023-05-18 16:57:17 -07:00
Ray Bell
db3668a381
Sort DEFAULT_EXCLUDES and add .vscode, .pytest_cache and .ruff_cache (#3691)
Co-authored-by: Ray Bell <ray.bell@dtn.com>
2023-05-16 22:47:45 -04:00
dependabot[bot]
dc188f2060
Bump peter-evans/find-comment from 2.3.0 to 2.4.0 (#3670)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 2.3.0 to 2.4.0.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](034abe94d3...a54c31d7fa)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cooper Lees <me@cooperlees.com>
2023-05-15 15:41:35 -07:00
Matthieu Simon
c97b9c55b4
[github action] display black result in job summary (#3688)
* send output to $GITHUB_STEP_SUMMARY

* update CHANGES.md

* update CHANGES.md with PR number

* implement PR feedback

* fix pre-commit issues (prettier/trailing whitespace)
2023-05-15 14:35:39 -07:00
dependabot[bot]
64887aab03
Bump peter-evans/create-or-update-comment from 2.1.1 to 3.0.1 (#3683)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 2.1.1 to 3.0.1.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](67dcc547d3...ca08ebd5dc)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-08 06:36:24 -07:00
Jelle Zijlstra
eb32729ab5
blib2to3: add a few annotations (#3675) 2023-05-03 10:26:57 -07:00
Jelle Zijlstra
a07871b9cd
Fix new mypy error in blib2to3 (#3674)
See python/mypy#15174
2023-05-03 08:43:20 -07:00
Yilei "Dolee" Yang
e712e48e06
Do not wrap implicitly concatenated strings used as func args in parens (#3640) 2023-04-28 11:10:01 -07:00
dependabot[bot]
de65741b8d
Bump pypa/cibuildwheel from 2.12.1 to 2.12.3 (#3657)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.12.1 to 2.12.3.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.12.1...v2.12.3)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-24 04:46:34 -07:00
James Braza
4b76a54815
Document black-jupyter hook (#3650)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-04-19 03:24:03 -07:00
dependabot[bot]
3da7339955
Bump sphinx-copybutton from 0.5.1 to 0.5.2 in /docs (#3651)
Bumps [sphinx-copybutton](https://github.com/executablebooks/sphinx-copybutton) from 0.5.1 to 0.5.2.
- [Release notes](https://github.com/executablebooks/sphinx-copybutton/releases)
- [Changelog](https://github.com/executablebooks/sphinx-copybutton/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/sphinx-copybutton/compare/v0.5.1...v0.5.2)

---
updated-dependencies:
- dependency-name: sphinx-copybutton
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-17 07:17:11 -07:00
Yilei "Dolee" Yang
02f81c6995
Fix two more mypyc issues with mypyc v1.2.0. (#3648) 2023-04-14 14:05:08 -07:00
Yilei "Dolee" Yang
f265ff5bcd
Explicitly annotate this with Final[str] to make it work in mypyc 1.0.0+. (#3645) 2023-04-13 17:12:05 -07:00
Harutaka Kawamura
a552f7096a
Fix an example for 'Improved parentheses management' in the (future of the) Black code style (#3635) 2023-04-03 06:56:59 -07:00
dependabot[bot]
96ee2fef3d
Bump furo from 2023.3.23 to 2023.3.27 in /docs (#3636)
Bumps [furo](https://github.com/pradyunsg/furo) from 2023.3.23 to 2023.3.27.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2023.03.23...2023.03.27)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-03 06:55:17 -07:00
Jelle Zijlstra
bf7a16254e
Fixup the changelog (#3628) 2023-03-28 17:53:23 -07:00
Jelle Zijlstra
9b2b048692
Prepare release 23.3.0 (#3625) 2023-03-28 17:46:04 -07:00
Ilia Lazarev
bf5abdb0b6
Specify Python exec path with minor version if available (#3508)
Fixes #3507
2023-03-27 21:12:24 -07:00
Jakub Kuczys
b542f589a5
Use GH action version when version argument not specified (#3543) 2023-03-27 18:40:27 -07:00
dependabot[bot]
f3b1a3b9d2
Bump furo from 2022.12.7 to 2023.3.23 in /docs (#3624)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-27 07:15:43 -04:00
Hong Minhee (洪 民憙)
ef6e079901
Let string splitters respect East_Asian_Width property (#3445)
This patch changes the preview style so that string splitters respect
Unicode East Asian Width[^1] property.  If you are not familiar to CJK
languages it is not clear immediately.  Let me elaborate with some
examples.

Traditionally, East Asian characters (including punctuation) have
taken up space twice than European letters and stops when they are
rendered in monospace typeset.  Compare the following characters:

```
abcdefg.
글、字。
```

The characters at the first line are half-width, and the second line
are full-width.  (Also note that the last character with a small
circle, the East Asian period, is also full-width.)  Therefore, if we
want to prevent those full-width characters to exceed the maximum
columns per line, we need to count their *width* rather than the number
of characters.  Again, the following characters:

```
글、字。
```

These are just 4 characters, but their total width is 8.

Suppose we want to maintain up to 4 columns per line with the following
text:

```
abcdefg.
글、字。
```

How should it be then?  We want it to look like:

```
abcd
efg.
글、
字。
```

However, Black currently turns it into like this:

```
abcd
efg.
글、字。
```

It's because Black currently counts the number of characters in the line
instead of measuring their width. So, how could we measure the width?
How can we tell if a character is full- or half-width? What if half-width
characters and full-width ones are mixed in a line? That's why Unicode
defined an attribute named `East_Asian_Width`. Unicode grouped every
single character according to their width in fixed-width typeset.

This partially addresses #1197, but only for string splitters. The other
parts need to be fixed as well in future patches.

This was implemented by copying rich's own approach to handling wide
characters: generate a table using wcwidth, check it into source
control, and use in to drive helper functions in Black's logic. This
gets us the best of both worlds: accuracy and performance (and let's us
update as per our stability policy too!).

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-03-19 19:09:57 -04:00
dependabot[bot]
5c064a986c
Bump sphinx from 5.3.0 to 6.1.3 in /docs (#3499)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-19 19:00:14 -04:00
dependabot[bot]
3a9d6f0a5f
Bump myst-parser from 0.18.1 to 1.0.0 in /docs (#3601)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Richard Si <sichard26@gmail.com>
2023-03-19 18:52:40 -04:00
Tushar Sadhwani
53c23e62df
Support files with type comment syntax errors (#3594) 2023-03-19 18:52:06 -04:00
Yilei "Dolee" Yang
dba3c2695c
Fix bug introduced in #3564. (#3615) 2023-03-19 07:43:39 -07:00
WMOkiishi
d7a28dd786
Enforce a blank line after a nested class in stubs (#3564) 2023-03-18 14:04:13 -07:00
Mitch Negus
a3e8247a41
Update documentation regarding isort compatibility (#3567) 2023-03-18 13:30:02 -07:00
Jelle Zijlstra
c9efbf9d97
Add SECURITY.md (#3612) 2023-03-18 10:41:48 -07:00
dependabot[bot]
34a93a8d49
Bump peter-evans/create-or-update-comment from 2.1.0 to 2.1.1 (#3548)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 2.1.0 to 2.1.1.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](5adcb0bb0f...67dcc547d3)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-17 21:59:33 -07:00
Yilei "Dolee" Yang
268dcb677c
Do not add an extra blank line to an import line that has fmt disabled (#3610) 2023-03-17 21:39:21 -07:00
Yilei "Dolee" Yang
fc6cea0f0e
Consistently format async statements similar to their non-async version. (#3609) 2023-03-16 13:31:27 -07:00
dependabot[bot]
71a2daaacf
Bump pypa/cibuildwheel from 2.11.4 to 2.12.1 (#3602)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.11.4 to 2.12.1.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.11.4...v2.12.1)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-15 00:30:04 -07:00
Casey Korver
6ffc5f7b01
Correct spelling mistakes (#3599) 2023-03-11 07:43:31 -08:00
Yilei "Dolee" Yang
d16a1dbd05
Consistently wrap two context managers in parens (in --preview). (#3589)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-03-09 22:01:20 -08:00
Aneesh Agrawal
4a063a9f8d
Improve multiline string handling (#1879)
Co-authored-by: Olivia Hong <ohong@lyft.com>
Co-authored-by: Olivia Hong <24500729+olivia-hong@users.noreply.github.com>
2023-03-07 11:52:19 -08:00
dependabot[bot]
25d886f52c
Bump peter-evans/find-comment from 2.2.0 to 2.3.0 (#3584)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 2.2.0 to 2.3.0.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](81e2da3af0...034abe94d3)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-27 06:38:02 -08:00
brucearctor
d9b8a6407e
Update Action example to use checkout@v3 (#3563)
Latest version of `actions/checkout` is v3 (or rather v3.3) so let's
use that in the example now.
2023-02-13 20:24:28 -05:00
Yilei "Dolee" Yang
9c8464ca7d
Fix typos in comments: assignement -> assignment (#3556) 2023-02-07 14:48:09 -08:00
dependabot[bot]
e74a05286b
Bump docker/build-push-action from 3 to 4 (#3549)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3 to 4.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-06 19:56:38 -08:00
Richard Si
e506c46f7b
Rename design label to style because it's clearer (#3547) 2023-02-04 22:51:46 -05:00
mainj12
ff53fc1b97
Actually add trailing commas to collection literals even if there are terminating comments (#3393)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <sichard26@gmail.com>
2023-02-04 19:35:43 -08:00
Yilei "Dolee" Yang
ea5293b036
Document the future style changes introduced in #3489 and #3440 (#3541) 2023-02-04 22:30:47 -05:00
Yilei "Dolee" Yang
dd0e912a6e
Fix import of blib2to3.pgen2.driver (#3546) 2023-02-03 22:00:09 -08:00
Jelle Zijlstra
b0d1fba7ac
Prepare release 23.1.0 (#3536)
Co-authored-by: Richard Si <sichard26@gmail.com>
2023-01-31 18:47:11 -08:00
Stijn de Gooijer
69ca0a4c7a
Infer target version based on project metadata (#3219)
Co-authored-by: Richard Si <sichard26@gmail.com>
2023-01-31 18:00:17 -08:00
Jelle Zijlstra
c4bd2e31ce
Draft for Black 2023 stable style (#3418) 2023-01-31 15:39:56 -08:00
Jelle Zijlstra
226cbf0226
Fix unsafe cast in linegen.py w/ await yield handling (#3533)
Fixes #3532.
2023-01-30 21:53:14 -05:00
Jelle Zijlstra
f4ebc68320
Upgrade isort (#3534)
See PyCQA/isort#2077.
2023-01-30 18:45:12 -08:00
Evan Chen
6407ebb870
Remove Python version in the_basics.md (#3528) 2023-01-28 16:12:11 -08:00
Edouard Choinière
196b1f349e
Fix black --help output for --python-cell-magics option to be reproducible (#3516) 2023-01-24 05:43:24 -08:00
Yilei "Dolee" Yang
d950f15987
Update document now that paren wrapping CMs on Python 3.9+ is implemented (#3520) 2023-01-23 21:38:30 -08:00
Yilei "Dolee" Yang
a36878eb2f
Fix an invalid quote escaping bug in f-string expressions (#3509)
Fixes #3506

We can't simply escape the quotes in a naked f-string when merging string groups, because backslashes are invalid.

The quotes in f-string expressions should be toggled (this is safe since quotes can't be reused).

This fix also means implicitly concatenated f-strings with different quotes can now be merged or quote-normalized by changing the quotes used in expressions. e.g.:

```diff
         raise sa_exc.UnboundExecutionError(
             "Could not locate a bind configured on "
-            f'{", ".join(context)} or this Session.'
+            f"{', '.join(context)} or this Session."
         )
```
2023-01-22 05:27:11 -08:00
Shivansh-007
eabff673b3
Format hex code in unicode escape sequences in string literals (#2916)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-01-22 05:21:09 -08:00
Michael Eliachevitch
1557f7d3a3
Use dashes for pycodestyle max line length config (#3513)
The option is `max-line-length` with dashes, not underscores. The config option name is given in the output of `pycodestyle -h`, which can also be checked on https://pep8.readthedocs.io/en/stable/intro.html#example-usage-and-output:
```
Configuration:
    The project options are read from the [pycodestyle] section of the
    tox.ini file or the setup.cfg file located in any parent folder of the
    path(s) being processed.  Allowed options are: exclude, filename,
    select, ignore, max-line-length, max-doc-length, hang-closing, count,
    format, quiet, show-pep8, show-source, statistics, verbose
```
2023-01-21 21:20:54 -08:00
Richard Si
c5df7b7d3c
Reenable macOS mypyc wheel build (#3511)
Hatchling implemented a workaround for the 'technically right tag but no
one understands it, including pip' issue so this should work now.
2023-01-20 23:50:00 -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
Antonio Ossa-Guerra
18fb88486d
Fix false symlink detection claims in verbose output (#3385)
When trying to format a project from the outside, the verbose output
shows says that there are symbolic links that points outside of the
project, but displays the wrong project path, meaning that these
messages are false positives.

This bug is triggered when the command is executed from outside a
project on a folder inside it, causing an inconsistency between the
path to the detected project root and the relative path to the target
contents.

The fix is to normalize the target path using the project root before
processing the sources, which removes the presence of the incorrect
messages.

---

The test attemps to emulate the behavior of the CLI as closely as
posible by patching some `pathlib.Path` methods and passing certain
reference paths to the context object and `black.get_sources`.

Before the associated fix was introduced, this test failed because
some of the captured files reported the presence of a symlink due to
an incorrectly formated path. The test also asserts that only a single
file is reported as ignored, which is part of the expected behavior.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2023-01-18 21:38:27 -05:00
Jelle Zijlstra
7e6d3fac19
Fix crash with walrus + await + with (#3473)
Fixes #3472
2023-01-17 22:25:05 -08:00
Bartosz Sokorski
24469c9bd1
Add flake8-bugbear B907 to ignore list (#3503) 2023-01-17 18:01:03 -08:00
Jelle Zijlstra
60a2e8e2c2
Fix two docstring crashes (#3451) 2023-01-16 12:26:03 -08:00
Ruslan
d4ff985853
Add IntelliJ docs on external tools and file watcher (#3365)
Revert deleted documentation on setting up Black using IntelliJ
external tool or file watcher utilities. These are still worth keeping
because some peole might not want to use a third-party plugin or
install Blackd's extra dependencies.

Co-authored-by: Richard Si <sichard26@gmail.com>
2023-01-14 13:32:00 -05:00
Yilei "Dolee" Yang
f758010340
Documentation: clarify the state of multiple context managers (#3488)
Clarify that the backslash & paren-wrapping formatting for multiple
context managers aren't yet implemented.
2023-01-14 12:51:59 -05:00
Bruno Oliveira
4bee9cca55
Remove misleading phrase in Usage and Configuration (#3492)
The CLI options were already shown in the "Command line options" in the same page.
2023-01-11 11:19:27 -08:00
Richard Si
5d0d5936db
Add email for Richard Si (#3478) 2023-01-02 06:43:48 -08:00
Richard Si
37542e6485
Fail lint CI if the PR doesn't target main (#3477)
Let's skip the check if we're running on a fork just in case someone
opens a PR against a branch on said fork as part of a PR review
upstream.
2022-12-30 22:52:35 -08:00
Jordan Ephron
4e3303fa08
Parenthesize conditional expressions (#2278)
Co-authored-by: Jordan Ephron <JEphron@users.noreply.github.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-12-29 15:13:15 -08:00
dependabot[bot]
0abe85eebb
Bump peter-evans/find-comment from 2.1.0 to 2.2.0 (#3476)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 2.1.0 to 2.2.0.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](f4499a714d...81e2da3af0)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-29 14:00:23 -08:00
dependabot[bot]
72a3408965
Bump pypa/cibuildwheel from 2.11.3 to 2.11.4 (#3475)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.11.3 to 2.11.4.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.11.3...v2.11.4)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-26 06:32:42 -08:00
Semen Zhydenko
9b91638190
Fix some typos (#3474) 2022-12-25 18:39:51 -08:00
Yilei "Dolee" Yang
3feff21eca
Significantly speedup ESP on large expressions that contain many strings (#3467) 2022-12-23 12:13:45 -08:00
Matthew Armand
3246df89d6
Add latest_prerelease Docker Hub tag for following the latest alpha release (#3465)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-12-20 19:18:15 -08:00
Yilei "Dolee" Yang
29dd257253
Fix an issue where extra empty lines are added. (#3470) 2022-12-20 17:58:02 -08:00
Matthew Armand
59f03d1b9d
Vim plugin docs improvements (#3468)
* Organize vim plugin section with headers to separate out Installation, Usage, and Troubleshooting for readability and easy linking

* Add missing plugin configuration options, with current defaults

* Add installation note for Arch Linux, now that the plugin is shipped with the python-black package (ref: https://bugs.archlinux.org/task/73024)

* Fix vim-plug specification to follow stable releases. Moving the same tag is an antipattern that doesn't re-resolve with vim-plug, see this discussion for more detail (https://github.com/junegunn/vim-plug/pull/720\#issuecomment-1105829356). Per vim-plug's maintainer's recommendation, use the 'tag' key instead with a shell wildcard. Wildcard should be '*.*.*' as that follows Black's versioning detailed here (https://black.readthedocs.io/en/latest/contributing/release_process.html\#cutting-a-release) and doesn't include current alpha releases.
2022-12-20 15:00:06 -08:00
Yilei "Dolee" Yang
73c2d5514c
Fix a crash in ESP where a standalone comment is placed before a dict's value (#3469) 2022-12-20 14:59:38 -08:00
Yilei "Dolee" Yang
a44dc3d59e
Exclude string type annotations from ESP (#3462) 2022-12-20 13:38:35 -08:00
Yilei "Dolee" Yang
1e8217fd62
Fix an f-string crash in ESP. (#3463) 2022-12-20 06:36:42 -08:00
Cooper Lees
9ce75726fc
Do not move docker latest_release tag for Pre-Releases (#3461)
* Do not move docker `latest_release` tag for Pre-Releases

- When we do a pre-release lets not move the latest_release tag
  - This tag should only move on official real releases

Fixes #3453

* Make it prettier - TIL we format our yaml
2022-12-19 18:08:13 -08:00
Jelle Zijlstra
cd9fef8bab
tomli: Don't worry about specific alpha releases (#3448)
This prevents bugs due to pypa/packaging#522.

Fixes #3447.
2022-12-17 19:02:01 -08:00
Jelle Zijlstra
23b92b48a5
Fix syntax error in match test (#3426) 2022-12-17 14:51:10 -08:00
Jelle Zijlstra
159984a735
Check stability for both preview and non-preview styles (#3423)
And fix parens-related test failures this found.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-12-17 10:31:47 -08:00
Cooper Lees
c0089ef19d
Remove separate 3.11 CI now deps support 3.11 (#3446)
* Remove separate 3.11 CI now deps support 3.11

- We can run everything now like all other stable versions of Python
- test in a 3.11 vent: `/tmp/tb/bin/tox -e py311,ci-py311`

```
  py311: OK (28.99=setup[7.90]+cmd[5.29,0.66,6.94,6.08,1.89,0.24] seconds)
  ci-py311: OK (30.33=setup[3.20]+cmd[3.66,0.31,17.43,4.60,0.90,0.23] seconds)
  congratulations :) (59.35 seconds)
```

* Add to CHANGES.md

* Add fuzz run in 3.11
2022-12-17 11:19:45 -06:00
Yilei "Dolee" Yang
78163939f1
Fix an infinite recursion error exposed by #3440 (#3444) 2022-12-16 05:02:41 -08:00
Yilei "Dolee" Yang
aafc21aa77
Prefer splitting right hand side of assignment statements. (#3368) 2022-12-15 15:58:51 -08:00
Yilei "Dolee" Yang
658c8d8d96
Improve long values in dict literals (#3440) 2022-12-15 08:25:28 -08:00
Yilei "Dolee" Yang
a2821815af
Fix a crash when a colon line is marked between # fmt: off and # fmt: on (#3439) 2022-12-14 17:56:14 -08:00
Jelle Zijlstra
7d062ecd5f
Do not put the closing quotes in a docstring on a separate line (#3430)
Fixes #3320. Followup from #3044.
2022-12-12 23:56:38 -05:00
dependabot[bot]
abd2b2556a
Bump furo from 2022.9.29 to 2022.12.7 in /docs (#3433)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.9.29 to 2022.12.7.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.09.29...2022.12.07)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-12 06:28:12 -08:00
dependabot[bot]
9bbe11dd7b
Bump pypa/cibuildwheel from 2.11.2 to 2.11.3 (#3434)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.11.2 to 2.11.3.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.11.2...v2.11.3)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-12 06:27:18 -08:00
Richard Si
80de2372e4
Bump mypy[c] from 0.971 to 0.991 (#3380) 2022-12-10 12:56:34 -08:00
mainj12
5f0dc862f5
Adding pyproject.toml configuration output to verbose logging (#3392) 2022-12-10 12:56:14 -08:00
Marco Edward Gorelli
16b98abca9
make black[jupyter] installation cross-shell (#3394) 2022-12-10 11:49:33 -08:00
Yilei "Dolee" Yang
96e62c57e3
Fix a crash in preview style with assert + parenthesized string. (#3415)
The bug is in the `get_leaves_inside_matching_brackets` on the third line below:

```python
assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
    xxxxxxxxx
).xxxxxxxxxxxxxxxxxx(), (
    "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
```

Including the invisible paren, third line is `).xxxxxxxxxxxxxxxxxx()), (`, that it has a matched pair then an unmatched closing paren afterwards. This PR ensures the returned leaves are actually matched.

Fixes #3414.
2022-12-10 07:58:45 -08:00
Isac Byeonghoon Yoo
1f7f6de4ab
Fix type annotation for gitignore pathspec (#3416) 2022-12-10 07:08:05 -08:00
Jelle Zijlstra
2ddea293a8
Prepare release 22.12.0 (#3413) 2022-12-09 07:49:43 -08:00
Jelle Zijlstra
5b1443aefd
release: skip bad macos wheels for now (#3411)
Workaround for #3312
2022-12-08 20:36:39 -08:00
dependabot[bot]
9ace064d85
Bump peter-evans/find-comment from 2.0.1 to 2.1.0 (#3404)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-08 23:28:29 -05:00
Jelle Zijlstra
19c5fe429e
Fix CI with latest flake8-bugbear (#3412) 2022-12-08 20:11:07 -08:00
dependabot[bot]
d4a85643a4
Bump sphinx-copybutton from 0.5.0 to 0.5.1 in /docs (#3390)
Bumps [sphinx-copybutton](https://github.com/executablebooks/sphinx-copybutton) from 0.5.0 to 0.5.1.
- [Release notes](https://github.com/executablebooks/sphinx-copybutton/releases)
- [Changelog](https://github.com/executablebooks/sphinx-copybutton/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/sphinx-copybutton/compare/v0.5.0...v0.5.1)

---
updated-dependencies:
- dependency-name: sphinx-copybutton
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-21 08:24:46 -08:00
sckarlin
27932494bc
Wordsmith current_style.md (#3383)
"realtime" doesn't make sense in this context.
2022-11-14 07:31:43 -08:00
Antonio Ossa-Guerra
d97b7898b3
Remove whitespaces of whitespace-only files (#3348)
Currently, empty and whitespace-only (with or without newlines) are
not modified. In some discussions (issues and pull requests) consensus
was to reformat whitespace-only files to empty or single-character
files, preserving line endings when possible. With that said, this
commit introduces the following behaviors:

* Empty files are left as is
* Whitespace-only files (no newline) reformat into empty files
* Whitespace-only files (1 or more newlines) reformat into a single
newline character

To implement these changes, we moved the initial check at
`format_file_contents` that raises `NothingChanged` if the source
(with no whitespaces) is an empty string. In the case of *.ipynb
files, `format_ipynb_string` checks a similar condition and removed
whitespaces. In the case of Python files, `format_str_once` includes a
check on the output that returns the correct newline character if
possible or an empty string otherwise.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-11-11 20:05:36 -05:00
Maximilian Cosmo Sitter
c23a5c15aa
Clarify that Black runs with --safe by default (#3378) 2022-11-10 10:14:48 -05:00
Yilei "Dolee" Yang
8091b2503d
Correctly handle trailing commas that are inside a line's leading non-nested parens (#3370)
- Fixes #1671
- Fixes #3229
2022-11-09 15:08:51 -08:00
Antonio Ossa-Guerra
ffaaf48382
Compare each .gitignore found with an appropiate relative path (#3338)
* Apply .gitignore files considering their location

When a .gitignore file contains the special rule to ignore every
subfolder content (`*/*`) and the file is located in a subfolder
relative to where the command is executed (root), the rule is
incorrectly applied and ignores every file at the same level of the
.gitignore file.

The reason for this is that the `gitignore` variable accumulates the
rules found in each .gitignore while traversing files and directories
recursively. This makes sense and, in general, works as expected. The
problem is that the gitignore rules are applied using as the relative
path from root to target directory as a reference. This is the cause
of the bug.

The implemented solution keeps track of every .gitignore file found
while traversing the targets and the absolute location of each
.gitignore file. Then, when matching files to the .gitignore rules,
compare each set of rules with the appropiate relative path to the
candidate target file.

To make this possible, we changed the single `gitignore` object with a
dictionary of similar objects, where the corresponding key is the
absolute path to the folder that contains that .gitignore file. This
required changing the signature of the `get_sources` function. Also, we
introduce a `is_ignored` function that compares a file with every set
of rules. Finally, some tests required an update to pass the gitignore
object in the new format.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Test .gitignore with `*/*` is applied correctly

The test contains three cases: 1) when the .gitignore with the special
rule to ignore every subfolder and its contents (*/*) is in the root,
2) when the file is inside a subfolder relative to root (nested), and
3) when the target folder contains the .gitignore and root is a parent
folder of the target. In all of these cases, we compare the files that
are visible by Black with a known list of paths containing the
expected values.

Before the fix introduced in the previous commit, these tests failed
when the .gitignore file was nested (second case). Now, the test is
passed for all cases.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Update CHANGES.md

Add entry about fixed bug and changes introduced: ignore files by
considering the location of each .gitignore file and the relative path
of each target

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Small refactor to improve code readability

These changes are small improvements to improve code readability:
rename a variable to a more descriptive name (from `exclude_is_None`
to `using_default_exclude`), use a better syntax to include the type
annotation for `gitignore` variable (from typing comment to
Python-style typing annotation), and replace an if-else block with a
single dictionary definition (in this case, we need to compare keys
instead of values, meaning that the change works)

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Make nested function a top-level function

The function to match a given path with every discovered .gitignore
file does not need to be a nested function and can be a top-level
function. The arguments did not change, but the naming of local
variables was improved for readability.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-11-08 07:50:04 -08:00
Antonio Ossa-Guerra
0e9d29ab73
Apply .gitignore correctly in every source entry (#3336)
When passing multiple src directories, the root gitignore was only
applied to the first processed source. The reason is that, in the
first source, exclude is `None`, but then the value gets overridden by
`re_compile_maybe_verbose(DEFAULT_EXCLUDES)`, so in the next iteration
where the source is a directory, the condition is not met and sets the
value of `gitignore` to `None`.

To fix this problem, we store a boolean indicating if `exclude` is
`None` and set the value of `exclude` to its default value if that's
the case. This makes sure that the flow enters the correct condition on
following iterations and also keeps the original value if the condition
is not met.

Also, the value of `gitignore` is initialized as `None` and overriden
if necessary. The value of `root_gitignore` is always calculated to
avoid using additional variables (at the small cost of additional
computations).

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-11-04 22:09:59 -07:00
Gerhard van Andel
2704dc796b
Update docs to include pycodestyle (#3369)
* Add pycodestyle to using_black_with_other_tools.md
2022-11-01 11:42:48 -07:00
dependabot[bot]
f67791427d
Bump pypa/cibuildwheel from 2.10.2 to 2.11.2 (#3367)
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.10.2 to 2.11.2.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.10.2...v2.11.2)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-31 06:50:42 -07:00
dependabot[bot]
3179a442af
Bump peter-evans/create-or-update-comment from 2.0.1 to 2.1.0 (#3366)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 2.0.1 to 2.1.0.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](2b2c85d0bf...5adcb0bb0f)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-31 06:49:52 -07:00
Corey Hickey
4bb6e4f64a
Vim plugin: allow using system black rather than virtualenv (#3309)
Provide a configuration parameter to the Vim plugin which will allow the
plugin to skip setting up a virtualenv. This is useful when there is a
system installation of black (e.g. from a Linux distribution) which the
user prefers to use.

Using a virtualenv remains the default.

- Fixes #3308
2022-10-27 18:55:33 -05:00
Hongbo Miao
d338de7f68
Add Archer Aviation to organizations in readme (#3361) 2022-10-27 17:22:44 -04:00
Yilei "Dolee" Yang
b73b77a9b0
Wrap concatenated strings used as function args in parens (#3307)
Fixes #3292
2022-10-26 18:03:10 -07:00
Ned Western
09d4acdcb7
Update README.md (#3284)
Minor typo
2022-10-25 19:04:31 -07:00
Jelle Zijlstra
527248b389
Exclude pytest-xdist 3.0.2 (#3356)
We're getting warnings like https://github.com/psf/black/actions/runs/3325521041/jobs/5498291478 and I'm not sure how to fix them. I'll open an issue for a long-term solution, but for now avoid 3.0.2 to unbreak CI.
2022-10-25 19:03:24 -07:00
Yilei "Dolee" Yang
4abc0399b5
Enforce empty lines before classes/functions with sticky leading comments. (#3302)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-10-25 18:03:24 -07:00
dependabot[bot]
fbc5136aa0
Bump peter-evans/create-or-update-comment from 2.0.0 to 2.0.1 (#3354)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](c9fcb64660...2b2c85d0bf)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-24 11:40:19 -07:00
dependabot[bot]
26de5f91c3
Bump peter-evans/find-comment from 2.0.0 to 2.0.1 (#3353)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](1769778a0c...b657a70ff1)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-24 09:50:14 -07:00
dependabot[bot]
f22273a72b
Bump sphinx from 5.2.3 to 5.3.0 in /docs (#3333)
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-17 21:12:41 -04:00
jlplenio
575220f460
Clarify check argument is needed for github action workflow (#3325)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-10-15 19:44:02 +01:00
nn
f16333e78b
remove unreachable code (#3328)
fixes #3321
2022-10-11 14:34:37 -07:00
Amethyst Reese
d923945513
Fix license metadata to follow PEP 621 (#3326) 2022-10-11 10:54:49 +11:00
Batuhan Taskaya
1c786ee627
Add support for named exprs inside function calls as gen-exps (#3327) 2022-10-11 10:54:09 +11:00
Hugo van Kemenade
b60b85b234
Remove redundant 3.6 code and bump mypy's python_version to 3.7 (#3313) 2022-10-06 17:37:37 -07:00
Jelle Zijlstra
27d20144a7
Prepare release 22.10.0 (#3311) 2022-10-06 15:33:51 -07:00
Antonio Ossa-Guerra
4da0851809
Add option to skip the first line of source code (#3299)
* Add option to skip the first line in source file

This commit adds a CLi option to skip the first line in the source
files, just like the Cpython command line allows [1]. By enabling the
flag, using `-x` or `--skip-source-first-line`, the first line is
removed temporarilly while the remaining contents are formatted. The
first line is added back before returning the formatted output.

[1]: https://docs.python.org/dev/using/cmdline.html#cmdoption-x

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Add tests for `--skip-source-first-line` option

When the flag is disabled (default), black formats the entire source
file, as in every line. In the other hand, if the flag is enabled, by
using `-x` or `--skip-source-first-line`, the first line is retained
while the rest of the source is formatted and then is added back.

These tests use an empty Python file that contains invalid syntax in
its first line (`invalid_header.py`, at `miscellaneous/`). First,
Black is invoked without enabling the flag which should result in an
exit code different than 0. When the flag is enabled, Black is
expected to return a successful exit code and the header is expected
to be retained (even if its not valid Python syntax).

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Support skip source first line option for blackd

The recently added option can be added as an acceptable header for
blackd. The arguments are passed in such a way that using the new
header will activate the skip source first line behaviour as expected

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Add skip source first line option to blackd docs

The new option can be passed to blackd as a header. This commit
updates the blackd docs to include the new header.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Update CHANGES.md

Include the new Black option to skip the first line of source code in
the configuration section

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Update skip first line test including valid syntax

Including valid Python syntax help us make sure that the file is still
actually valid after skipping the first line of the source file (which
contains invalid Python syntax)

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Skip first source line at `format_file_in_place`

Instead of skipping the first source line at `format_file_contents`,
do it before. This allow us to find the correct newline and encoding
on the actual source code (everything that's after the header).

This change is also applied at Blackd: take the header before passing
the source to `format_file_contents` and put the header back once we
get the formatted result.

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Test output newlines when skipping first line

When skipping the first line of source code, the reference newline must
be taken from the second line of the file instead of the first one, in
case that the file mixes more than one kind of newline character

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Test that Blackd also skips first line correctly

Simliarly to the Black tests, we first compare that Blackd fails when
the first line is invalid Python syntax and then check that the result
is the expected when tha flag is activated

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>

* Use the content encoding to decode the header

When decoding the header to put it back at the top of the contents of
the file, use the same encoding used in the content. This should be a
better "guess" that using the default value

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-10-06 15:17:32 -07:00
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
dependabot[bot]
27d7ea43eb
Bump docutils from 0.18.1 to 0.19 in /docs (#3161)
Bumps [docutils](https://docutils.sourceforge.io/) from 0.18.1 to 0.19.

---
updated-dependencies:
- dependency-name: docutils
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-10-03 09:36:44 -07:00
dependabot[bot]
1a20c4d487
Bump sphinx from 5.2.1 to 5.2.3 in /docs (#3305)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 5.2.1 to 5.2.3.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/5.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v5.2.1...v5.2.3)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-03 02:15:59 -05:00
dependabot[bot]
980997f215
Bump furo from 2022.9.15 to 2022.9.29 in /docs (#3304)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.9.15 to 2022.9.29.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.09.15...2022.09.29)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cooper Lees <cooper@fb.com>
2022-10-03 02:08:20 -05:00
dependabot[bot]
b1077aa14e
Bump myst-parser from 0.18.0 to 0.18.1 in /docs (#3303)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 0.18.0 to 0.18.1.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v0.18.0...v0.18.1)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-03 02:06:06 -05:00
Ray Bell
956bf3962e
Add .ipynb_checkpoints to DEFAULT_EXCLUDES (#3293)
Jupyter creates a checkpoint file every single time you create an .ipynb
file, and then it updates the checkpoint file every single time you
manually save your progress for the initial .ipynb. These checkpoints
are stored in a directory named `.ipynb_checkpoints`.

Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
2022-10-02 12:26:45 -04:00
Richard Si
141291a1d8
Enable build isolation under CIWB (#3297)
No idea how this is still here after the Hatchling PR, but it is no
longer useful and is breaking the build.
2022-09-28 22:56:28 -04:00
dependabot[bot]
ddb99241b5
Bump pypa/cibuildwheel from 2.10.0 to 2.10.2 (#3290)
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-patch

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-28 22:19:08 -04:00
Ray Bell
096806ee26
Mention CHANGES.md in PR template explicitly (#3295)
This makes the location more explicit which hopefully makes the PR
process smoother for other first time contributors.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-09-28 21:44:16 -04:00
Antonio Ossa-Guerra
6b42c2b8c9
Add option to format Jupyter Notebooks in GitHub Action (#3282)
To run the formatter on Jupyter Notebooks, Black must be installed
with an extra dependency (`black[jupyter]`). This commit adds an
optional argument to install Black with this dependency when using the
official GitHub Action [1]. To enable the formatter on Jupyter
Notebooks, just add `jupyter: true` as an argument. Feature requested
at [2].

[1]: https://black.readthedocs.io/en/stable/integrations/github_actions.html
[2]: https://github.com/psf/black/issues/3280

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-09-26 17:45:34 -04:00
dependabot[bot]
1f2ad77505
Bump sphinx from 5.1.1 to 5.2.1 in /docs (#3288)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 5.1.1 to 5.2.1.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/5.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v5.1.1...v5.2.1)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-26 09:48:50 -07:00
dependabot[bot]
42fdd1b91f
Bump actions/upload-artifact from 2 to 3 (#3289)
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-26 08:35:23 -04:00
Richard Si
af3de08154
Always call freeze_support() if sys.frozen is True (#3275) 2022-09-25 17:55:52 -07:00
Richard Si
2189bcaac0
Fix outdated references to 3.6 and run pyupgrade (#3286)
I also missed the accidental removal of the 3.11 classifier in the PR.
2022-09-25 17:24:18 -07:00
Ofek Lev
468ceafca5
Switch build backend to Hatchling (#3233)
This implements PEP 621, obviating the need for `setup.py`, `setup.cfg`,
and `MANIFEST.in`. The build backend Hatchling (of which I am a
maintainer in the PyPA) is now used as that is the default in the
official Python packaging tutorial. Hatchling is available on all the
major distribution channels such as Debian, Fedora, and many more.

## Python support

The earliest supported Python 3 version of Hatchling is 3.7, therefore
I've also set that as the minimum here. Python 3.6 is EOL and other
build backends like flit-core and setuptools also dropped support.
Python 3.6 accounted for 3-4% of downloads in the last month.

## Plugins 

Configuration is now completely static with the help of 3 plugins:

### Readme

hynek's hatch-fancy-pypi-readme allows for the dynamic construction of
the readme which was previously coded up in `setup.py`. Now it's simply:

```toml
[tool.hatch.metadata.hooks.fancy-pypi-readme]
content-type = "text/markdown"
fragments = [
  { path = "README.md" },
  { path = "CHANGES.md" },
]
```

### Versioning

hatch-vcs is currently just a wrapper around setuptools-scm (which
despite the legacy naming is actually now decoupled from setuptools):

```toml
[tool.hatch.version]
source = "vcs"

[tool.hatch.build.hooks.vcs]
version-file = "src/_black_version.py"
template = '''
version = "{version}"
'''
```

### mypyc

hatch-mypyc offers many benefits over the existing approach:

- No need to manually select files for inclusion
- Avoids the need for the current CI workaround for https://github.com/mypyc/mypyc/issues/946
- Intermediate artifacts (like `build/`) from setuptools and mypyc
  itself no longer clutter the project directory
- Runtime dependencies required at build time no longer need to be
  manually redeclared as this is a built-in option of Hatchling

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-09-25 17:54:33 -04:00
Stijn de Gooijer
4b4680a0a9
Make README logo link to docs (#3285)
docs: Make README logo link to docs
2022-09-25 10:28:43 +01: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
Jakub Kuczys
bfc013ab93
Support version specifiers in GH action (#3265)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-09-22 20:23:35 -07:00
Blandes22
4c99900236
Make context manager examples in future style docs consistent (#3274) 2022-09-22 20:19:31 -07:00
Richard Si
75d5c0e3fb
Build mypyc wheels for CPython 3.11 (#3276)
Bumps cibuildwheel from 2.8.1 to 2.10.0 which has 3.11 building enabled
by default. Unfortunately mypyc errors out on 3.11:

src/black/files.py:29:9: error: Name "tomllib" already defined (by an import)  [no-redef]

... so we have to also hide the fallback import of tomli on older 3.11
alphas from mypy[c].
2022-09-22 20:11:56 -07:00
dependabot[bot]
6ae8457a86
Bump furo from 2022.6.21 to 2022.9.15 in /docs (#3277)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-19 19:35:46 -04:00
Zsolt Dollenstein
d852af7167
Fix mypyc build errors on newer manylinux2014_x86_64 images (#3272)
Make sure `gcc` is installed in the build env

The mypyc build requires `gcc` to be installed even if it's being built with `clang`, otherwise `clang` fails to find `libgcc`.
2022-09-15 21:08:26 +01:00
Tom Fryers
04bce6ad2e
Improve order of paragraphs on line splitting (#3270)
These two paragraphs were tucked away at the end of the section, after
the diversion on backslashes. I nearly missed the first paragraph and
opened a nonsense issue, and I think the second belongs higher up with
it too.
2022-09-14 22:31:26 -04: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
Holger Brunn
72a25591b0
[FIX] migrate-black.py: don't fail on binary files (#3266) 2022-09-13 20:06:54 -07: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
Richard Si
062e644aae
Mitigate deprecation of aiohttp's @middleware decorator (#3259)
This is deprecated since aiohttp 4.0. If it doesn't exist just define a
no-op decorator that does nothing (after the other aiohttp imports
though!). By doing this, it's safe to ignore the DeprecationWarning
without needing to require the latest aiohttp once they remove
`@middleware`.
2022-09-05 16:27:05 -04:00
PeterGrossmann
92c93a2780
Add preview flag to Vim plugin (#3246)
This allows the configuration of the --preview flag in the Vim plugin.
2022-09-01 12:39:47 -04:00
James Salvatore
095fe0d649
docs: adds ExitStack alternative to future_style.md (#3247)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-08-31 21:25:13 -07:00
Richard Si
2018e667a6
Prepare docs for release 22.8.0 (#3248) 2022-08-31 18:39:54 -04:00
Richard Si
0019261abc
Update stable branch after publishing to PyPI (#3223)
We've decided to a) convert stable back into a branch and b) to update
it immediately as part of the release process. We may as well automate
it. And about going back to a branch ...

Git tags are not the right tool, at all[^1]. They come with the
expectation that they will never change. Things will not work as
expected if they do change, doubly so if they change regularly. Once
you pull stable from the remote and it's copied in your local
repository, no matter how many times you run git pull you'll never see
it get updated automatically. Your only recourse is to delete the tag
via `git tag -d stable` before pulling.

This gets annoying really quickly since stable is supposed to be the
solution for folks "who want to move along as Black developers deem
the newest version reliable."[^2] See this comment for how this impacts
users using our Vim plugin[^3]. It also affects us developers[^4]. If
you have stable locally, once we cut a new release and update the stable
tag, a simple `git pull` / `git fetch` will not pull down the updated
stable tag. Unless you remember to delete stable before pulling, stable
will become stale and useless.

You can argue this is a good thing ("people should explicitly opt into
updating stable"), but IMO it does not match user expectations nor
developer expectations[^5]. Especially since not all our integrations
that use stable are bound by this security measure, for example our
GitHub Action (since it does a clean fetch of the repository every time
it's used). I believe consistency would be good here.

Finally, ever since we switched to a tag, we've been facing issues with
ReadTheDocs not picking up updates to stable unless we force a rebuild.
The initial rebuild on the stable update just pulls the commit the tag
previously pointed to. I'm not sure if switching back to a branch will
fix this, but I'd wager it will.

[^1]: https://git-scm.com/docs/git-tag#_on_re_tagging

[^2]: https://black.readthedocs.io/en/stable/contributing/release_process.html#moving-the-stable-tag

[^3]: https://github.com/psf/black/issues/2503#issuecomment-1196357379

[^4]: In fairness, most folks working on Black probably don't use the
      `stable` ref anyway, especially us maintainers who'd know what is
      the latest version by heart, but it'd still be nice to make it
      usable for local dev though.

[^5]: Also what benefit does a `stable` ref have over explicit version
      tags like `22.6.0`? If you're going to opt into some odd pin
      mechanism, might as well use explicit version tags for clarity
      and consistency.
2022-08-31 17:56:47 -04:00
Richard Si
7757078ecd
Improve & update release process to reflect recent changes (#3242)
- Formalise release cadence guidelines
- Overhaul release steps to be easier to follow and more thorough
- Reorder changelog template to something more sensible
- Update release automation docs to reflect recent improvements (notably
  the addition of in-repo mypyc wheel builds)

Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-08-31 14:46:48 -07: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
c0cc19b5b3 Delay worker count determination
os.cpu_count() can return None (sounds like a super arcane edge case
though) so the type annotation for the `workers` parameter of
`black.main` is wrong. This *could* technically cause a runtime
TypeError since it'd trip one of mypyc's runtime type checks so we
might as well fix it.

Reading the documentation (and cross-checking with the source code),
you are actually allowed to pass None as `max_workers` to
`concurrent.futures.ProcessPoolExecutor`. If it is None, the pool
initializer will simply call os.cpu_count() [^1] (defaulting to 1 if it
returns None [^2]). It'll even round down the worker count to a level
that's safe for Windows.

... so theoretically we don't even need to call os.cpu_count()
ourselves, but our Windows limit is 60 (unlike the stdlib's 61) and I'd
prefer not accidentally reintroducing a crash on machines with many,
many CPU cores.

[^1]: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor
[^2]: a372a7d653/Lib/concurrent/futures/process.py (L600)
2022-08-26 21:11:00 -04:00
Richard Si
afed2c0190 Load .gitignore and exclude regex at time of use
Loading .gitignore and compiling the exclude regex can take more than
15ms. We shouldn't and don't need to pay this cost if we're simply
formatting files given on the command line directly.

I would've loved to lazily import pathspec, but the patch won't be clean
until the file collection and discovery logic is refactored first.

Co-authored-by: Fabio Zadrozny <fabiofz@gmail.com>
2022-08-26 21:11: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
Ionite
a5fde8ab9b
Remove hacky subprocess call in action.yml (#3226)
Updates action.yml to use the alternative $GITHUB_ACTION_PATH variable
instead of the original ${{ github.action_path }} which caused issues
with bash on the Windows runners. This removes the need for a Python
subprocess to call the main.py script.
2022-08-26 15:45:31 -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
Alexander Huynh
6e0ad52e7a
Update email (#3235)
This file gets scraped a lot, so create a distinct email for potential
spam.
2022-08-20 10:45:20 -07:00
Shantanu
4ebf14d17e
Strip trailing commas in subscripts with -C (#3209)
Fixes #2296, #3204
2022-08-13 06:41:34 -07:00
Richard Si
e7b967132f
Port & upstream mypyc wheel build workflow (#3197) 2022-08-12 20:33:17 -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
680cbe3a4f
Use --no-implicit-optional for type checking (#3220)
This makes type checking PEP 484 compliant (as of 2018).
mypy will change its defaults soon.

See:
https://github.com/python/mypy/issues/9091
https://github.com/python/mypy/pull/13401
2022-08-12 19:28:47 -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
Nicolò Intrieri
f066e3fcae
makes install available for all users in docker image (#3202)
* makes install available for all users in docker image

moves the installation path from /root/.local to a
virtualenv. this way we still get the lightweight
multistage build without excluding non-root users.

* adds changelog entry for docker-image fix

A changelog entry has been added under the Integration
subheader

* changes dockerfile to use the venv activate script

we are now using the inbuilt venv activate script, as well
as explicitly mentioning the binary location in the entrypoint
cmd.

Co-authored-by: Nicolò <nicolo.intrieri@spinforward.it>
Co-authored-by: Cooper Lees <me@cooperlees.com>
2022-08-02 09:01:15 -07:00
dependabot[bot]
b776bf92ad
Bump sphinx from 5.1.0 to 5.1.1 in /docs (#3201)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 5.1.0 to 5.1.1.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/5.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v5.1.0...v5.1.1)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-01 13:51:46 -04:00
Richard Si
ca0dbb8fa6
Move fuzz.py to scripts/ (#3199) 2022-07-31 07:34:29 -07:00
Richard Si
eaa048925e
Add sanity check to executable CD + more (#3190)
Building executables without any testing is quite sketchy, let's at
least verify they won't crash on startup and format Black's own
codebase.

Also replaced "binaries" with "executables" since it's clearer and
won't be confused with mypyc.

Finally, I added colorama so all Windows users can get colour.
2022-07-29 20:38:39 -07:00
Richard Si
d85cf00ee8
Remove blib2to3 grammar cache logging (#3193)
As error logs are emitted often (they happen when Black's cache
directory is created after blib2to3 tries to write its cache) and cause
issues to be filed by users who think Black isn't working correctly.

These errors are expected for now and aren't a cause for concern so
let's remove them to stop worrying users (and new issues from being
opened). We can improve the blib2to3 caching mechanism to write its
cache at the end of a successful command line invocation later.
2022-07-29 20:28:43 -07:00
Théophile Bastian
4f1772e2ae
Vim plugin: prefix messages with "Black: " (#3194)
As mentioned in GH-3185, when using Black as a Vim plugin, especially
automatically on save, the plugin's messages can be confusing, as
nothing indicates that they come from Black.
2022-07-28 19:49:00 -04:00
Richard Si
ef8deb6d4a
Consolidate test CI and add concurrency limits (#3189) 2022-07-28 16:55:36 -04:00
Richard Si
411ed778d5
Bump pre-commit hooks (#3191) 2022-07-27 22:04:14 -04:00
Richard Si
44d5da00b5 Reformat codebase with isort 2022-07-27 17:19:28 -04:00
Richard Si
e0a780a505 Add isort to linting toolchain
Co-authored-by: Shivansh-007 <shivansh-007@outlook.com>
2022-07-27 17:19:28 -04:00
dependabot[bot]
e9e756da7a
Bump sphinx from 5.0.2 to 5.1.0 in /docs (#3183)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 5.0.2 to 5.1.0.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/5.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v5.0.2...v5.1.0)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-26 20:51:32 -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
Thomas Grainger
33f0d9e79a
Add pypy-3.8 to test matrix (#3174) 2022-07-16 21:55:46 -04:00
Thomas Grainger
df5a87d93b
configure strict pytest and filterwarnings=['error', ... (#3173)
* configure strict pytest

* ignore current warnings
2022-07-16 13:18:55 +01:00
onescriptkid
b0eed7c6bd
Fix typo in config docs for --extend-exclude (#3170)
The old regex in the example was invalid and caused an error on startup.
2022-07-14 19:51:18 -04: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
Cooper Lees
9aa33f467b
Move to explicitly creating a new loop (#3164)
* Move to explicitly creating a new loop

- >= 3.10 add a warning that `get_event_loop` will not automatically create a loop
- Move to explicit API

Test:
- `python3.11 -m venv --upgrade-deps /tmp/tb`
  - `/tmp/tb/bin/pip install -e .`
  - Install deps and no blackd as aiohttp + yarl can't build still with 3.11
  - https://github.com/aio-libs/aiohttp/issues/6600
- `export PYTHONWARNINGS=error`
```
cooper@l33t:~/repos/black$ /tmp/tb/bin/black .
All done!  🍰 
44 files left unchanged.
```

Fixes #3110

* Add to CHANGES.md

* Fix a cooper typo yet again

* Set default asyncio loop to our explicitly created one + unset on exit

* Update CHANGES.md

Fix my silly typo.

Co-authored-by: Thomas Grainger <tagrain@gmail.com>

Co-authored-by: Cooper Ry Lees <me@wcooperlees.com>
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2022-07-14 15:24:34 -07:00
Nimrod
8900e3ac8a
Add warning to not run blackd publicly in docs (#3167)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-07-14 15:22:29 -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
Maciej Olko
05b63c4bcc
Recommend using BlackConnect in IntelliJ IDEs (#3150)
* Recommend using BlackConnect in IntelliJ IDEs

* IntelliJ IDEs integration docs: improve formatting

* Add changelog for recommending BlackConnect

* IntelliJ IDEs integration docs: improve formatting

* Apply suggestions from code review

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

* Fix indentation

* Apply italic to Black name

Consequently with other places in the document

* Move CHANGELOG entry to Unreleased section

* IntelliJ IDEs integration docs: bring back a point with formatting a file

* IntelliJ IDEs integration docs: fix extra whitespace and linebreak

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-07-11 09:27:51 -07:00
Jelle Zijlstra
7af77d1cf1
Stability policy: permit exceptional changes for unformatted code (#3155) 2022-07-06 13:33:07 -04:00
Jakub Kuczys
b859a377c0
Use RTD's new build process and config (#3149)
See the deprecation notice:
https://docs.readthedocs.io/en/stable/config-file/v2.html#python-version
2022-07-03 16:47:18 -04:00
Dimitri Merejkowsky
6debce63bc
Fix typo in CHANGES.md (#3142) 2022-06-28 10:44:55 +03:00
Richard Si
f6c139c521
Prepare docs for release 22.6.0 (#3139) 2022-06-27 20:33:35 -04:00
Felix Hildén
eb5d175c9c
Update preview style docs to include recent changes (#3136)
Covers GH-2926, GH-2990, GH-2991, and GH-3035.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-06-27 16:24:34 -04:00
dependabot[bot]
d848209d38
Bump furo from 2022.6.4.1 to 2022.6.21 in /docs (#3138)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.6.4.1 to 2022.6.21.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.06.04.1...2022.06.21)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-27 09:54:49 -04:00
Yilei "Dolee" Yang
fa6caa6ca8
Only call get_future_imports when needed (#3135) 2022-06-23 12:41:05 -07:00
dependabot[bot]
6463fb874f
Bump sphinx from 5.0.1 to 5.0.2 in /docs (#3128)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 5.0.1 to 5.0.2.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/5.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v5.0.1...v5.0.2)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-20 10:22:24 -04:00
Nate Prewitt
e3c9b0430e
Replace link to Requests documentation (#3125) 2022-06-17 12:37:33 -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
Hugo van Kemenade
799adb5323
Bump actions/setup-python from 3 to 4 (#3121)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 3 to 4.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-13 07:02:39 -07:00
Marco Edward Gorelli
162ecd1d2c
Use is_number_token instead of assertion (#3069) 2022-06-11 12:04:09 -04:00
Richard Si
8c8675c62a
Update documentation dependencies (#3118)
Furo, myst-parser, and Sphinx (had to pin docutils due to sphinx breakage)
2022-06-11 11:44:01 -04: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
dependabot[bot]
6d32ab02c5
Bump pre-commit/action from 2.0.3 to 3.0.0 (#3108)
Bumps [pre-commit/action](https://github.com/pre-commit/action) from 2.0.3 to 3.0.0.
- [Release notes](https://github.com/pre-commit/action/releases)
- [Commits](https://github.com/pre-commit/action/compare/v2.0.3...v3.0.0)

---
updated-dependencies:
- dependency-name: pre-commit/action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-10 20:29:32 -04:00
Vivek Vashist
f51e53726b
Fix minor typo (#3096) 2022-06-03 15:59:26 -07:00
Holger Brunn
436e12f290
Add script to ease migration to black (#3038)
* Add script to ease migration to black

* Update CHANGES.md

Co-authored-by: Cooper Lees <me@cooperlees.com>
2022-06-01 11:20:02 -07:00
Batuhan Taskaya
1e557184b0
Implement support for PEP 646 (#3071) 2022-05-26 09:45:22 -07:00
Yusuke Nishioka
9fe788d870
Add more examples to exclude files in addition to the defaults (#3070)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-05-26 07:44:26 -07:00
laundmo
fdb01f8622
Document new Microsoft Black Formatter extension for VSCode (#3063)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-05-21 16:18:06 -04:00
Sagi Shadur
2893c42176
Remove hard coded test cases (#3062) 2022-05-18 12:11:37 -07:00
dependabot[bot]
7f033136ac
Bump docker/setup-buildx-action from 1 to 2 (#3058)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 1 to 2.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-09 22:22:01 -04:00
dependabot[bot]
4af87d8a43
Bump docker/login-action from 1 to 2 (#3059)
Bumps [docker/login-action](https://github.com/docker/login-action) from 1 to 2.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-09 22:13:12 -04:00
dependabot[bot]
ba21a85699
Bump docker/build-push-action from 2 to 3 (#3057)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 2 to 3.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-09 22:11:29 -04:00
dependabot[bot]
5d5b7316db
Bump docker/setup-qemu-action from 1 to 2 (#3056)
Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 1 to 2.
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-09 22:08:56 -04: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
Felix Hildén
62c2b167bc
Docs: clarify fmt:on/off requirements (#2985) (#3048) 2022-05-07 17:58:10 -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
Naveen
c940f75d5b
chore: Set permissions for GitHub actions (#3043)
Restrict the GitHub token permissions only to the required ones; this way, even if the attackers will succeed in compromising your workflow, they won’t be able to do much.

- Included permissions for the action. https://github.com/ossf/scorecard/blob/main/docs/checks.md#token-permissions

https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions

https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs

[Keeping your GitHub Actions and workflows secure Part 1: Preventing pwn requests](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/)

Signed-off-by: naveen <172697+naveensrinivasan@users.noreply.github.com>
2022-05-03 07:08:33 -06:00
dependabot[bot]
9d5edd3020
Bump myst-parser from 0.16.1 to 0.17.2 in /docs (#3019)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 0.16.1 to 0.17.2.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v0.16.1...v0.17.2)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-02 11:12:23 -06:00
Cooper Lees
fb8dfdeec5
Stop pinning lark-parser (#3041)
- Latest version works more

Test: `tox -e fuzz`
2022-04-28 10:27:16 -06:00
Vadim Nikolaev
c6800e0c65
Fix strtobool function (#3025)
* Fix strtobool function for vim plugin
* Update CHANGES.md

Co-authored-by: Cooper Lees <me@cooperlees.com>
2022-04-28 09:17:23 -06:00
JiriKr
8ed3e3d07e
Updated Black Docker Hub link in docs (#3023)
Fixes #3022
2022-04-21 12:55:56 -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
Jelle Zijlstra
96bd428524
Quote black[jupyter] and black[d] in installation docs (#3006)
We just got someone on Discord who was confused because the command as
written caused their shell to try to do command expansion.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-04-11 19:25:46 -04:00
dependabot[bot]
911b59fb4f
Bump furo from 2022.3.4 to 2022.4.7 in /docs (#3003)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.3.4 to 2022.4.7.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.03.04...2022.04.07)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-11 19:24:00 -04:00
Sam Ezeh
40053b522e
Quote "black[jupyter]" in README.md (#3007) 2022-04-11 15:10:46 -07:00
dependabot[bot]
abdc31cd4f
Bump actions/upload-artifact from 2 to 3 (#3004)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 2 to 3.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-11 17:26:28 -04:00
Richard Si
497a72560d
Explain our use of mypyc in the FAQ (#3002)
I realized we don't have a FAQ entry about this, let's change that so
compiled: yes/no doesn't surprise as many people :)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-04-10 19:45:34 -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
f6188ce6dc
Output python version and implementation as part of --version flag (#2997)
Example:

black, 22.1.1.dev56+g421383d.d20220405 (compiled: no)
Python (CPython) 3.9.12

Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
2022-04-06 14:04:12 -04:00
Hugo van Kemenade
9b307405fb
Top PyPI Packages: Use 30-days data, 365 is no longer available (#2995) 2022-04-06 15:48:50 +03:00
Jan-Hendrik Müller
421383d560
Update FAQ: Mention formatting of custom jupyter cell magic (#2982)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-04-04 18:24:16 -07: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
Joe Young
4d0a4b15a9
Fix broken link in README.md (#2989)
Broken when we converted some more RST docs to MyST
2022-04-02 19:18:13 -04:00
Jelle Zijlstra
1af29fbfa5
try-except tomllib import (#2987)
See #2965 

I left the version check in place because mypy doesn't generally like try-excepted imports.
2022-04-02 08:29:32 -07:00
dependabot[bot]
5436810921
Bump peter-evans/create-or-update-comment from 1.4.5 to 2 (#2961)
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 1.4.5 to 2.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](a35cf36e53...c9fcb64660)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-02 11:23:08 -04:00
dependabot[bot]
3451502daa
Bump peter-evans/find-comment from 1.3.0 to 2 (#2960)
Bumps [peter-evans/find-comment](https://github.com/peter-evans/find-comment) from 1.3.0 to 2.
- [Release notes](https://github.com/peter-evans/find-comment/releases)
- [Commits](d2dae40ed1...1769778a0c)

---
updated-dependencies:
- dependency-name: peter-evans/find-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-02 11:22:52 -04:00
Jelle Zijlstra
def048356b
Remove click pin in diff-shades workflow (#2979)
Click 8.1.1 was released with a fix for pallets/click#2227.
2022-03-30 14:33:16 -07:00
Jelle Zijlstra
a66016cb94
Add # type: ignore for click._unicodefun import (#2981) 2022-03-30 14:01:03 -07:00
Gunung P. Wibisono
3dea6e3635
Convert index.rst and license.rst to markdown (#2852)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-03-30 13:43:46 -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
dependabot[bot]
2d62a09e83
Bump actions/cache from 2.1.7 to 3 (GH-2962)
Bumps [actions/cache](https://github.com/actions/cache) from 2.1.7 to 3.
- [Release notes](https://github.com/actions/cache/releases)
- [Commits](https://github.com/actions/cache/compare/v2.1.7...v3)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-28 21:42:53 -04:00
Jelle Zijlstra
ae2c0758c9
Prepare release 22.3.0 (#2968) 2022-03-28 12:08:29 -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
dependabot[bot]
ac7402cbf6
Bump sphinx from 4.4.0 to 4.5.0 in /docs (GH-2959)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 4.4.0 to 4.5.0.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/4.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v4.4.0...v4.5.0)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-28 13:21:13 -04:00
Richard Si
f239d227c0
Enforce no formatting changes for PRs via CI (GH-2951)
Now PRs will run two diff-shades jobs, "preview-changes" which formats
all projects with preview=True, and "assert-no-changes" which formats
all projects with preview=False. The latter also fails if any changes
were made.

Pushes to main will only run "preview-changes"

Also the workflow_dispatch feature was dropped since it was
complicating everything for little gain.
2022-03-26 17:22:38 -04: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
14d84ba2e9
Resolve new flake8-bugbear errors (B020) (GH-2950)
Fixes a couple places where we were using the same variable name as we
are iterating over.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-03-24 11:14:21 -04: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
Richard Si
062b54931d
Github now supports .git-blame-ignore-revs (GH-2948)
It's in beta.

https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view
2022-03-23 13:31:13 -04:00
Jelle Zijlstra
5379d4f3f4
stub style: remove some possible future changes (#2940)
Fixes #2938.

All of these suggested future changes are out of scope for an autoformatter and should be handled by a linter instead.
2022-03-21 15:20:41 -07:00
Marco Edward Gorelli
f87df0e3c8
dont skip formatting #%% (#2919)
Fixes #2588
2022-03-21 14:51:07 -07:00
Joseph Young
fa7f01592b
Update pylint config docs (#2931) 2022-03-16 10:00:30 -07:00
Shivansh-007
086ae68076
Remove power hugging formatting from preview (#2928)
It is falsely placed in preview features and always formats the power operators, it was added in #2789 but there is no check for formatting added along with it.
2022-03-15 20:13:56 -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
Richard Si
9ce3c806e4
Bump mypy, flake8, and pre-commit-hooks in pre-commit (GH-2922) 2022-03-14 19:41:46 -04:00
Shantanu
71e71e5f52
Use tomllib on Python 3.11 (#2903) 2022-03-08 08:47:51 -08:00
yoerg
24ffc54a53
Fix handling of Windows junctions in normalize_path_maybe_ignore (#2904)
Fixes #2569
2022-03-08 07:28:13 -08:00
dependabot[bot]
fd6e92aa46
Bump actions/setup-python from 2 to 3 (#2908)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 2 to 3.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Cooper Lees <me@cooperlees.com>
2022-03-07 12:33:25 -08:00
dependabot[bot]
dab1be38e6
Bump actions/checkout from 2 to 3 (#2909)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-07 08:44:01 -08:00
Batuhan Taskaya
6f4976a7ac
Allow for's target expression to be starred (#2879)
Fixes #2878
2022-03-04 17:37:16 -08:00
dependabot[bot]
eb213151ce
Bump furo from 2022.2.14.1 to 2022.3.4 in /docs (#2906)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.2.14.1 to 2022.3.4.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.02.14.1...2022.03.04)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-04 16:48:53 -08:00
oncomouse
7af3abd383
Move test for g:load_black to improve plugin performance (GH-2896)
If a vim/neovim user wishes to suppress loading the vim plugin by
setting g:load_black in their VIMRC (for me, Arch linux automatically
adds the plugin to Neovim's RTP, even though I'm not using it), the
current location of the test comes after a call to has('python3'). This
adds, in my tests, between 35 and 45 ms to Vim load time (which I know
isn't a lot but it's also unnecessary). Moving the call to
`exists('g:load_black')` to before the call to `has('python3')` removes
this unnecessary test and speeds up loading.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-03-04 19:15:39 -05:00
Tomáš Jelínek
67eaf24665
replace md5 with sha256 (#2905)
MD5 is unavailable on systems with active FIPS mode. That makes black
crash when run on such systems.
2022-03-03 09:29:48 -08:00
Shantanu
147526451a
README: fix "Pragmatism" link target (#2901)
Fixes #2897
2022-02-28 20:13:34 -08:00
Jelle Zijlstra
9b161072c1
fix new formatting issue (#2895)
Race between #2889 and another PR.
2022-02-23 19:41:42 -08:00
Jelle Zijlstra
6cfb51871b
separate CHANGELOG section for preview style (#2890) 2022-02-23 18:32:00 -08:00
Jelle Zijlstra
2918ea3b07
Format ourselves in preview mode (#2889) 2022-02-23 18:20:59 -08:00
dependabot[bot]
7e2b2d4784
Bump furo from 2022.1.2 to 2022.2.14.1 in /docs (GH-2892)
Bumps [furo](https://github.com/pradyunsg/furo) from 2022.1.2 to 2022.2.14.1.
- [Release notes](https://github.com/pradyunsg/furo/releases)
- [Changelog](https://github.com/pradyunsg/furo/blob/main/docs/changelog.md)
- [Commits](https://github.com/pradyunsg/furo/compare/2022.01.02...2022.02.14.1)

---
updated-dependencies:
- dependency-name: furo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-23 12:00:06 -05:00
Shivansh-007
c26c7728e8
Add special config verbose log case when black is using user-level config (#2861) 2022-02-20 17:59:36 -08:00
D. Ben Knoble
8089aaad6b
correct Vim integration code (#2853)
- use `Black` directly: the commands an autocommand runs are Ex commands, so no
  execute or colon is necessary.
- use an `augroup` (best practice) to prevent duplicate autocommands from
  hindering performance.
2022-02-20 17:37:07 -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
Laurent Lyaudet
07a2e6f678
Fix typo in file_collection_and_discovery.md (GH-2860)
"you your" -> "your"

Co-authored-by: Felix Hildén <felix.hilden@gmail.com>
2022-02-10 20:32:55 -05:00
Xuan (Sean) Hu
862c6f2c0c
Order the disabled error codes for pylint (GH-2870)
Just make them alphabetical.
2022-02-10 20:31:28 -05:00
Joachim Jablon
b4a6bb08fa
Avoid crashing when the user has no homedir (#2814) 2022-02-08 12:13:58 -08:00
Paolo Melchiorre
9b317178d6
Add Django in 'used by' section in Readme (#2875)
* Add Django in 'used by' section in Readme

* Fix Readme issue
2022-02-08 11:38:39 -08:00
dependabot[bot]
01001d5cff
Bump sphinx-copybutton from 0.4.0 to 0.5.0 in /docs (#2871)
Bumps [sphinx-copybutton](https://github.com/executablebooks/sphinx-copybutton) from 0.4.0 to 0.5.0.
- [Release notes](https://github.com/executablebooks/sphinx-copybutton/releases)
- [Changelog](https://github.com/executablebooks/sphinx-copybutton/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/sphinx-copybutton/compare/v0.4.0...v0.5.0)

---
updated-dependencies:
- dependency-name: sphinx-copybutton
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-07 07:31:58 -08:00
Felix Hildén
31fe97e7ce
Create indentation FAQ entry (#2855)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-02-02 08:59:42 +02:00
Peter Mescalchin
111880efc7
Update description for GitHub Action options: argument (GH-2858)
It was missing --diff as one of the default arguments passed.
2022-02-01 22:17:45 -05:00
Richard Si
fb9fe6b565
Isolate command line tests from user-level config (#2851) 2022-01-31 21:29:01 -08:00
S. Co1
f3f3acc444
Surface links to Stability Policy (GH-2848) 2022-01-31 19:06:52 -05:00
Jelle Zijlstra
afc0fb05cb
release process: formalize the changelog template (#2837)
I did this manually for the last few releases and I think it's going to be
helpful in the future too. Unfortunately this adds a little more work during
the release (sorry @cooperlees).

This change will also improve the merge conflict situation a bit, because
changes to different sections won't merge conflict.

For the last release, the sections were in a kind of random order. In the
template I put highlights and "Style" first because they're most important
to users, and alphabetized the rest.
2022-01-30 14:04:06 -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
Jelle Zijlstra
f61299a62a
Exclude __pypackages__ by default (GH-2836)
PDM uses this as part of not-accepted-yet PEP 582.
2022-01-30 15:01:56 -05:00
Jelle Zijlstra
bbe1bdf1ed
Adjust --preview documentation (#2833) 2022-01-30 21:53:45 +02:00
Richard Si
d038a24ca2
Prepare docs for release 22.1.0 (GH-2826) 2022-01-29 14:30:25 -05:00
Jelle Zijlstra
dea2f94ebd
Fix changelog entries in the wrong release (#2825) 2022-01-29 09:32:52 -08:00
Jelle Zijlstra
c5f8e8bd59
Fix changelog entries in the wrong release (#2825) 2022-01-29 09:32:26 -08:00
Jelle Zijlstra
0d768e58f4
Remove test suite from setup.py (#2824)
We no longer use it
2022-01-29 08:00:59 -08:00
Richard Si
8acb8548c3
Update classifiers to reflect stable (#2823) 2022-01-29 07:37:51 -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
Shantanu
95e77cb559
Fix arithmetic stability issue (#2817)
It turns out "simple_stmt" isn't that simple: it can contain multiple
statements separated by semicolons. Invisible parenthesis logic for
arithmetic expressions only looked at the first child of simple_stmt.
This causes instability in the presence of semicolons, since the next
run through the statement following the semicolon will be the first
child of another simple_stmt.

I believe this along with #2572 fix the known stability issues.
2022-01-28 16:57:05 -08:00
Felix Hildén
df0aeeeee0
Formalise style preference description (#2818)
Closes #1256: I reworded our style docs to be more explicit about the style we're aiming for and how it is changed (or isn't).
2022-01-28 16:49:43 -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
Felix Hildén
e1506769a4
Elaborate on Python support policy (#2819) 2022-01-28 10:58:17 -08:00
Jelle Zijlstra
5f01b872e0
reorganize release notes for 22.1.0 (#2790)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-01-28 06:25:24 -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
b517dfb396
black-primer: stop running it (#2809)
At the moment, it's just a source of spurious CI failures and busywork
updating the configuration file.

Unlike diff-shades, it is run across many different platforms and
Python versions, but that doesn't seem essential. We already run unit
tests across platforms and versions.

I chose to leave the code around for now in case somebody is using it,
but CI will no longer run it.
2022-01-26 17:18:43 -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
Nikita Sobolev
3905173cb3
Use magic_trailing_comma and preview for FileMode in fuzz (#2802)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-01-23 12:34:29 -08:00
Cooper Lees
d2c938eb02
Remove Beta mentions in README + Docs (#2801)
- State we're now stable and that we'll uphold our formatting changes as per policy
- Link to The Black Style doc.

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-01-23 12:34:01 -08:00
Richard Si
6e3677f3f0
Allow blackd to be run as a package (#2800) 2022-01-23 08:49:11 -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
Shantanu
b3b341b44f
Mention "skip news" label in CHANGELOG action (#2797)
Co-authored-by: hauntsaninja <>
2022-01-22 07:30:18 -08:00
Shantanu
811de5f36b
Refactor logic for stub empty lines (#2796)
This PR is intended to have no change to semantics.

This is in preparation for #2784 which will likely introduce more logic
that depends on `current_line.depth`.

Inlining the subtraction gets rid of offsetting and makes it much easier
to see what the result will be.
2022-01-22 07:29:38 -08:00
Richard Si
fb1d1b2fc8
Mark Felix and Batuhan as maintainers (#2794)
Y'all deserve it :)
2022-01-22 14:08:27 +03: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
Richard Si
d24bc4364c
Switch to Furo (#2793)
- Add Furo dependency to docs/requirements.txt
- Drop a fair bit of theme configuration
- Fix the toctree declarations in index.rst
- Move stuff around as Furo isn't 100% compatible with Alabaster

Furo was chosen as it provides excellent mobile support, user
controllable light/dark theming, and is overall easier to read
2022-01-21 15:00:13 -08:00
Rob Hammond
95c03b9638
add wind technology software projects using black (#2792) 2022-01-21 10:23:26 -08:00
Shivansh-007
e0c572833a
Set click lower bound to 8.0.0 (#2791)
Closes #2774
2022-01-21 08:54:57 -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
emfdavid
e66e0f8ff0
Hint at likely cause of ast parsing failure in error message (#2786)
Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-01-20 15:48:49 -08:00
Felix Hildén
6e97c5f47c
Deprecate ESP and move the functionality under --preview (#2789) 2022-01-20 15:42:07 -08:00
Richard Si
9bd4134f31
Fix and speedup diff-shades integration (#2773) 2022-01-19 19:05:58 -08:00
Felix Hildén
8c22d232b5
Create --preview CLI flag (#2752) 2022-01-19 17:34:52 -08:00
Jelle Zijlstra
98db4abc21
Fix typo in diff_shades.yml workflow (#2778) 2022-01-17 07:52:29 -08:00
dependabot[bot]
1d2ed2bb42
Bump sphinx from 4.3.2 to 4.4.0 in /docs (#2776)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 4.3.2 to 4.4.0.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/4.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v4.3.2...v4.4.0)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-17 06:50:27 -08:00
Batuhan Taskaya
33e3bb1e4e
[trivial] Use proper test cases on unittest (#2775) 2022-01-15 14:19:37 -08:00
Marco Edward Gorelli
5fe6d48fcd
Dont require typing-extensions in 3.10 (GH-2772)
3.10 ships with TypeGuard which is the newest feature we need.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-01-14 23:24:55 -05:00
Richard Si
565f9c92b7
CI: add diff-shades integration (#2725)
Hopefully this makes it much easier to gauge the impacts of future
changes!
2022-01-13 18:50:02 -08:00
VanSHOE
5543d1b55a
Added decent coloring (#2712) 2022-01-13 18:31:08 -08:00
Batuhan Taskaya
7a29568115
Don't make redundant copies of the DFA (#2763) 2022-01-13 18:01:44 -08:00
Felix Hildén
799f76f537
Normalise string prefix order (#2297)
Closes #2171
2022-01-13 09:59:43 -08:00
Jelle Zijlstra
f298032ddb
don't expect changes on poetry (#2769)
They just made themselves ESP-compliant in ecb030e1f0
2022-01-13 09:33:56 -08:00
Jeffrey Lazar
8954e58ccf
Change installation url to comply with git security change (#2765)
Co-authored-by: Jeffrey Lazar <jlazar@MacBook-Pro-2.local>
2022-01-11 14:37:07 -08:00
cbows
4efb795129
Change git url for pip installation in README (#2761)
* Change git url for pip installation in README

Unauthenticated git protocol was disabled recently by Github and should not be used anymore.

https://github.blog/2021-09-01-improving-git-protocol-security-github/#no-more-unauthenticated-git

* Update CHANGES.md
2022-01-11 09:31:07 -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
Josh Owen
ea4c772746
Action: Support running in a docker container (#2748)
see: https://github.com/actions/runner/issues/716
2022-01-07 18:50:50 +02:00
Richard Si
05e1fbf27d
Stubs: preserve blank line between attributes and methods (#2736) 2022-01-07 18:38:03 +02:00
Felix Hildén
668bace2ab
Improve CLI reference wording (#2753) 2022-01-07 18:19:03 +02:00
Gunung Pambudi Wibisono
8a84bebcfc
Documentation: include Wing IDE 8 integrations (GH-2733)
Wing IDE 8 now supports autoformatting w/ Black natively 🎉

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-01-01 22:33:20 -05:00
Richard Si
4f5268af4f
Primer: exclude crashing sqlalchemy file for now (GH-2735)
Until we can properly look into and fix it.
-> https://github.com/psf/black/issues/2734
2021-12-30 19:59:53 -05:00
Jelle Zijlstra
b8df7e4b10
Drop upper version bounds on dependencies (GH-2718)
They mostly cause unnecessary trouble.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-30 16:17:11 -05: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
Marco Edward Gorelli
ced2d65679
remove all type: ignores in src/black (GH-2720)
Excet
;t
2021-12-24 21:25:03 -05:00
Felix Hildén
f0a99f6402
Update contributing wording (#2719)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-21 10:43:10 -08:00
Batuhan Taskaya
3fafd806b3
Support multiple top-level as-expressions on case statements (#2716) 2021-12-21 10:16:55 -08:00
Łukasz Langa
c758126a27
Remove usage of Pipenv, rely on good ol' pip and virtualenv in docs (#2717) 2021-12-21 08:24:20 -08:00
Marco Edward Gorelli
7c94ed61a5
Define is_name_token (and friends) to resolve some type: ignores (GH-2714)
Gets rid of a few # type: ignores by using TypeGuard.
2021-12-21 11:20:55 -05:00
Taneli Hukkinen
389e9c23a9
Disable universal newlines when reading TOML (#2408) 2021-12-21 08:03:07 -08:00
dependabot[bot]
c5b458ef4b
Bump myst-parser from 0.16.0 to 0.16.1 in /docs (#2710)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 0.16.0 to 0.16.1.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v0.16.0...v0.16.1)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-20 07:42:03 -08:00
dependabot[bot]
6ef3e466db
Bump sphinx from 4.3.1 to 4.3.2 in /docs (#2709)
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 4.3.1 to 4.3.2.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/4.x/CHANGES)
- [Commits](https://github.com/sphinx-doc/sphinx/compare/v4.3.1...v4.3.2)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-20 07:24:53 -08:00
Batuhan Taskaya
b97ec62368
Imply 3.8+ when annotated assigments used with unparenthesized tuples (#2708) 2021-12-17 13:43:14 -08:00
Mike Taves
61fe8418cc
Use 'python -m build' to build wheel and source distributions (#2701) 2021-12-15 19:35:01 -08:00
Batuhan Taskaya
dc90d4951f
Unpacking on flow constructs (return/yield) now implies 3.8+ (#2700) 2021-12-15 16:17:33 -08:00
dependabot[bot]
f10ce0c942
Bump pre-commit/action from 2.0.2 to 2.0.3 (GH-2695)
Bumps [pre-commit/action](https://github.com/pre-commit/action) from 2.0.2 to 2.0.3.
- [Release notes](https://github.com/pre-commit/action/releases)
- [Commits](https://github.com/pre-commit/action/compare/v2.0.2...v2.0.3)

---
updated-dependencies:
- dependency-name: pre-commit/action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-15 18:55:26 -05:00
dependabot[bot]
e9f520c16a
Bump myst-parser from 0.15.2 to 0.16.0 in /docs (GH-2696)
Bumps [myst-parser](https://github.com/executablebooks/MyST-Parser) from 0.15.2 to 0.16.0.
- [Release notes](https://github.com/executablebooks/MyST-Parser/releases)
- [Changelog](https://github.com/executablebooks/MyST-Parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/MyST-Parser/compare/v0.15.2...v0.16.0)

---
updated-dependencies:
- dependency-name: myst-parser
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-15 18:26:01 -05:00
Richard Si
3501cefb09
Include underlying error when AST safety check parsing fails (#2693) 2021-12-14 18:21:28 -08:00
aru
93701d249e
use valid package-ecosystem key (#2694) 2021-12-14 18:21:15 -08:00
Richard Si
72fbacd996
chore: dump docs deps and pre-commit hooks (#2676) 2021-12-14 17:25:47 -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
e7ddf524b0
Show details when a regex fails to compile (GH-2678) 2021-12-07 22:13:05 -05:00
Jelle Zijlstra
085efac037
no longer expect changes on pyanalyze (#2674)
https://github.com/quora/pyanalyze/pull/316
2021-12-05 15:47:53 -08:00
Richard Si
f1d4e742c9
Prepare for release 21.12b0 (GH-2673)
Let's do this!
2021-12-05 16:39:34 -05:00
Batuhan Taskaya
28ab82aab0
perf: drop the initial stack copy (#2670)
Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-12-05 13:03:48 -08:00
Richard Si
d9eee31ec8
blib2to3 can raise TokenError and IndentationError too (#2671) 2021-12-05 08:53:58 -08:00
Jelle Zijlstra
9424e795bf
Reorganize changelog (#2669)
I believe it would be useful to split up the long list of changes a bit more.

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

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

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

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

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

    if condition:

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

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

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

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-12-01 18:05:59 -05:00
Jelle Zijlstra
8485191448
slightly better example link (#2617)
Since we also need to update two places in the docs
2021-12-01 13:47:33 -08:00
Shantanu
f1813e31b6
Fix determination of f-string expression spans (#2654)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-12-01 09:52:24 -08:00
Jelle Zijlstra
0f7cf9187f
fix error message for match (#2649)
Fixes #2648.

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

My goal is to remove the `regex` dependency to reduce the risk of breakage due to dependencies and make life easier for users on platforms without wheels.
2021-11-30 18:01:36 -08:00
Batuhan Taskaya
b336b390d0
Fix line generation for match match: / case case: (GH-2661) 2021-11-30 15:56:38 -05:00
Jelle Zijlstra
ebd3e391da
add FAQ entry about undetected syntax errors (#2645)
This came up in #2644.
2021-11-30 12:34:45 -08:00
Jameel Al-Aziz
e151686c6f
Remove hidden import from PyInstaller build (#2657)
The recent 2021.4 release of pyinstaller-hooks-contrib now contains a
built-in hook for platformdirs. Manually specifying the hidden import
arg should no longer be needed.
2021-11-30 08:20:27 -08: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
72a84d4099
add missing f-string (#2650) 2021-11-26 18:53:16 -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
Wael Nasreddine
db2715441a
README: Add KeepTruckin to the list of orgs (GH-2638)
At KT, we used Black to format all Python code in our Mono-repo.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-11-25 20:09:47 -05: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
Ash
40759445c9
Change cfg to ini for text highlighting (#2632) 2021-11-21 07:02:08 -08:00
Matthew D. Scholefield
05954c0950
Fix process pool fallback on Python 3.10 (GH-2631)
In Python 3.10 the exception generated by creating a process pool on
a Python build that doesn't support this is now `NotImplementedError`

Commit history before merge:

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

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-11-20 14:25:30 -05:00
Richard Si
9a73bb86db
Fix mypyc compat issue w/ AST safety check (GH-2628)
I can't wait for when we drop Python 2 support FWIW :)
2021-11-18 22:20:44 -05:00
Jelle Zijlstra
19f6aa8208
prepare release 2021.11b1 (#2622) 2021-11-17 19:51:49 -08:00
Rowan Seymour
ecf8c74481
Bump regex dependency to 2021.4.4 to fix import of Pattern class (#2621)
Fixes #2620
2021-11-17 19:46:28 -08:00
Jelle Zijlstra
d0b04d9f21
prepare release 21.11b0 (#2616) 2021-11-16 18:30:19 -08:00
Jelle Zijlstra
7dacdbe6dc
fix vim plugin (#2615) 2021-11-16 18:22:32 -08:00
Richard Si
0d1b957d40
Fix 3.10's supported features (#2614) 2021-11-15 21:07:25 -08:00
Richard Si
117891878e
Implementing mypyc support pt. 2 (#2431) 2021-11-15 20:24:16 -08:00
Jelle Zijlstra
1d7260050d
vim: Parse skip_magic_trailing_comma from pyproject.toml (#2613)
Co-authored-by: Kyle Kovacs <kkovacs@diconfiberoptics.com>
2021-11-15 19:03:47 -08:00
pszlazak
1d7163957a
Docker image usage description (#2412)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-11-15 18:47:21 -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
Michal Siska
78317a4cfb
Removed distutils import from autoload/black.vim (#2607) (#2610) 2021-11-15 08:51:56 -08:00
Hugo van Kemenade
3cb010ec8e
Declare support for Python 3.10 (#2562) 2021-11-14 06:37:06 -08:00
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
5e191c29d4
Bump deps in Pipfile.lock (GH-2605)
Mostly because the hashes for typed-ast were valid for 1.4.2 when the
version is pinned to 1.4.3 ... pipenv is pleasant to use /s
2021-11-12 20:41:46 -05:00
Kian Meng Ang
53cabe7265
Fix typos (#2603) 2021-11-11 19:02:43 -08:00
Richard Si
0753d99519
Improve Python 2 only syntax detection (GH-2592)
* Improve Python 2 only syntax detection

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

Also add support for the following cases:

    print "hello, world!"

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

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

    try:
        pass
    except Exception, err:
        pass

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

    `wow_these_really_did_exist`

    10L

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

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

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-11-11 20:28:48 -05:00
Richard Si
f297c4644e
primer: Hypothesis now requires Python>=3.8 (GH-2602)
looks like their project dev tooling uses some newer syntax or something
2021-11-11 17:52:13 -05:00
LordOfPolls
f80f49767c
Add a missing space in Python 2 deprecation (GH-2590)
`DEPRECATION: Python 2 support will be removed in the first stable releaseexpected in January 2022` - > `DEPRECATION: Python 2 support will be removed in the first stable release expected in January 2022`
2021-11-06 12:04:27 -04:00
Cooper Lees
64c8be01f0
Update CHANGES.md for 21.10b0 release (#2583)
* Update CHANGES.md for 21.10b0 release

* Update version in docs/usage_and_configuration/the_basics.md

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

- Use BlackRunner and .stdout in command line test

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

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

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

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

* Add in that the pin is only for docker
2021-10-31 13:41:12 -04:00
Richard Si
9afffacaa0
Address mypy errors on 3.10 w/ asyncio loop parameter (#2580) 2021-10-30 15:35:55 -07:00
Felix Hildén
fac498bf31
Update bug template (#2538) 2021-10-30 15:01:40 -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
Roma
6b38b52187
Add Tesla to organizations list (#2577) 2021-10-30 11:45:09 -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
Marco Edward Gorelli
26970742b7
Refactor Jupyter magic handling (#2545) 2021-10-27 07:36:10 -07:00
Nipunn Koorapati
62ed5389fc
Remove some unneeded exceptions from mypy.ini (#2557) 2021-10-21 20:59:48 -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
Jelle Zijlstra
c75abed63e
Define a stability policy (#2529)
Fixes #2394. Eventually fixes #517.

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

Co-authored-by: Pradyun Gedam <pradyunsg@gmail.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2021-10-21 17:02:38 +02:00
Marco Edward Gorelli
847d468b82
bump sphinx so it works on Python3.10 (#2546) 2021-10-19 10:52:10 -07:00
Zac Hatfield-Dodds
2f3fa1f6d0
Fix feature detection for positional-only arguments in lambdas (#2532) 2021-10-11 21:45:58 -07:00
Mathieu Kniewallner
3b2a7d196b
chore(ci): use official Python 3.10 (#2521)
Python 3.10 (final) was released yesterday and is now available on GHA!
2021-10-05 17:22:56 -04:00
Richard Si
872bb9474e
Bump typed-ast minimum to 1.4.3 for 3.10 compat (#2519) 2021-10-04 17:36:57 -07:00
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
Fergus Mitchell
0fd353f163
Add --workers CLI parameter (fixes #2513) (#2514)
Fixes #2513
2021-09-29 09:50:44 -07:00
shaoran
09915f4bd2
Allow to pass the FileMode options in the vim plugin (#1319) 2021-09-28 17:31:29 -07:00
Richard Si
31a9d8a184
Fix python_version markers in Pipfile.lock (#2511)
This took way too much effort but in the end I was able to achieve a
(mostly) functional Pipfile.lock ranging from 3.6 to 3.9 🎉
2021-09-28 18:41:35 -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
1af5331089
Bump required aiohttp version to 3.7.4 (#2509)
Commit history before merge:

* Bump required aiohttp version to 3.7.4

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

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

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

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-09-25 12:58:44 +01:00
Deepyaman Datta
7b15393658
Add Kedro to project list and QuantumBlack to orgs (#2502) 2021-09-23 22:20:48 -04:00
Clément Robert
37861b4ce2
DOC: cleanup pre-commit instructions following #2430 (#2481) 2021-09-19 10:15:39 +01:00
Marco Edward Gorelli
0540591e25
add check for version in the-basics example (#2459) 2021-09-18 20:24:09 -07:00
Zsolt Dollenstein
22747a6937
fix all b904s (#2501) 2021-09-18 22:18:06 +01:00
Jelle Zijlstra
911470a610
Update CHANGES.md for 21.9b0 release (#2494) 2021-09-13 19:23:11 -07:00
Sorin Sbarnea
41e6700640
Fix missing toml extra w/ setuptools-scm (GH-2475)
Project packaging is using TOML due to pyproject.toml but fails to
mention it, causing installation failures with newer setuptools-scm 6.3.0.

Commit history before merge:

* Fix missing toml extra

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

* Bump setuptools[-scm] to avoid toml extra

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

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

* Actually for safety reasons, just use the extra

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-09-06 17:10:39 -04:00
Marco Edward Gorelli
8b0c7bcfda
Remove blackcellmagic reference (#2477)
This package seems to be unmaintained (last commit is from > 2 years ago), and `black` now runs on Jupyter Notebooks directly
2021-09-05 07:52:16 -07:00
Jameel Al-Aziz
72de89f54e
Add hidden import to PyInstaller build (GH-2466)
Add new platformdirs dependencies as hidden imports when creating
PyInstaller-based binaries.

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

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

Commit history before merge:

* Add hidden import to PyInstaller build

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

* Only include the platformdirs for the relevant os
2021-09-01 18:05:11 -04:00
pszlazak
77d11bb4b4
Change docker workflow for latest_release tag (#2468) 2021-08-31 11:26:31 -07:00
aru
79575f3376
fix: run pypi / docker upload from published draft releases (#2461)
Draft releases don't trigger the workflows (that's good!) but since they only 

Commit history before merge:

* fix: run pypi upload from published draft releases
* Fix broken task list markup in PR template
* change docker workflow to build on release publish

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-08-30 13:26:21 -04:00
Richard Si
a8b4665e7d
Exclude broken typing-extensions version + fix import (#2460)
re. import, the ipynb code was assuming that typing-extensions would
always be available, but that's not the case! There's an environment
marker on the requirement meaning it won't get installed on 3.10 or
higher. The test suite didn't catch this issue since aiohttp pulls in
typing-extensions unconditionally.
2021-08-29 17:04:49 -04:00
Richard Si
16275d24e3
Prepare CHANGES.md for release 21.8b0 (#2458)
Hopefully my first release doesn't end up in flames 🔥

Commit history before merge:

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

Commit history before merge:

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

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

Co-authored-by: FiNs <24248249+FabianNiehaus@users.noreply.github.com>
2021-08-28 15:37:53 -04:00
Marco Edward Gorelli
7a093f0303
add test which covers stdin filename ipynb (#2454) 2021-08-28 08:27:55 -07:00
Marco Edward Gorelli
fcfead919b
set mypy_path in mypy.ini (#2455) 2021-08-28 06:55:34 -07:00
Marco Edward Gorelli
8b06805334
Document jupyter hook (#2416)
This also introduces a script so we can reference the latest version in
the example pre-commit configuration in the docs without forgetting to
update it when doing a release!

Commit history before merge:

* document jupyter hook
* note minimum version
* add check for pre-commit version
* use git tag
* curl api during ci
* parse version from changes file
* fixup script
* rename variables
* Tweak the docs & magical script
* fix couple of typos
* pin additional dependencies in hook
* Add types-PyYAML to lockfile

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-08-27 16:21:08 -04:00
Richard Si
366a0806eb
blib2to3: support unparenthesized wulruses in more places (#2447)
Implementation stolen from PR davidhalter/parso#162. Thanks parso!

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

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

The root problem was that the type annotation was treated as if it was
a parameter & import list (is_body=True to linegen::bracket_split_build_line)
where a trailing comma is usually fine. Now there's another check in the
aforementioned function to make sure the body it's operating on isn't
a return annotation before truly adding a trailing comma.
2021-08-25 18:32:27 -07:00
Richard Si
d249f2d838
MNT: add pull request template (#2443)
So we don't have to request changes on these basic requirements as
often - hopefully :)
2021-08-25 21:25:44 -04: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
erykoff
0969ca4a46
Change sys.exit to raise ImportError (#2440)
The fix for #1688 in #1761 breaks help("modules") introspection and also leads
to unhappy results when inadvertently importing blackd from Python. Basically
the sys.exit(-1) causes the whole Python REPL to exit -- not great to suffice.

Commit history before merge:

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

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-08-24 16:59:24 -04:00
Richard Si
b97a4ac449
Add test requirements to Pipfile[.lock] & bump deps (#2436)
While this development environment / requirements situation is a mess,
let's at least make it consistent. We're effectively supporting two
modes of development in this project, 1) tox based dev commands
(e.g. `tox -e fuzz`) that are dead simple to use, and 2) manual dev
commands (e.g. `pytest -n auto`) that give more control and are usually
faster.

Right now the Pipfile.lock based development environment is incomplete
missing the test requirements specified in ./test_requirements.txt.
This is annoying since manual test commands (e.g. `pytest -k fmtonoff`)
fail. Let's fix this by making Pipfile.lock basically a
"everything you need" requirements file (fuzzing not included since
running it locally is not something common).

Oh and let's bump some documentation deps (and bring some requirements
across .pre-commit-config.yaml, Pipfile, and docs/requirement.txt in
alignment again). Don't worry, I tested these changes so they should
be fine (hopefully!).
2021-08-22 20:20:06 -07:00
Richard Si
8c04847aa2
Improve f-string expression detection regex so ... (#2437)
we don't accidentally add backslashes to them when normalizing quotes
because that's invalid syntax!

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

    {a}{b}{c}

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

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

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

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

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

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

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

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

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

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

* Add changelog entry
2021-08-18 12:24:14 -04:00
Marco Edward Gorelli
b92ec34843
Add jupyter deps to Pipfile.lock (#2419) 2021-08-15 22:54:42 -04:00
Tom Fryers
e465acf6f8
Update language server links (#2425)
python-language-server is no longer maintained.
2021-08-12 18:45:33 -04:00
aru
355a6b34b3
fix: remove unneccessary escape character (#2423) 2021-08-11 21:50:46 -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
Taneli Hukkinen
e76adbecb8
Fix type dependencies of mypy invocation (#2411)
Commit history before merge:

* Fix type dependencies of mypy invocation
* Consistent version upper bound
2021-08-06 14:53:24 -04:00
Hugo van Kemenade
8ea641eed5
Test on Python 3.10-dev (#2406) 2021-07-28 07:29:11 -07:00
Richard Si
4760b6e71e
Fix issue templates + add docs template (#2399)
The template weren't applying the default labels ever since I renamed
the labels.

There has been enough issues about documentation opened recently so it's
probably worth a template for it.
2021-07-27 20:38:04 -04:00
Richard Si
982e7fd9de
Add ESP to sqlalchemy for black-primer (#2400)
The crash has been fixed for a little while now. Tentatively assuming
that this will lead to changes.
2021-07-24 17:04:01 -07:00
Jelle Zijlstra
6665677495
Clarify contributing docs (#2398)
"as configurable as gofmt" means little to people who haven't used gofmt.
2021-07-24 15:59:53 -07:00
David Szotten
6559bdbd9d
isort docs have changed urls (#2390) 2021-07-22 07:04:53 -07: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
Bernát Gábor
4dd100bff2
Use platformdirs over appdirs (#2375)
Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
Signed-off-by: Bernát Gábor <gaborjbernat@gmail.com>
2021-07-16 13:45:47 -04:00
Cooper Lees
e3000ace2f
Update CHANGES.md for 21.7b0 release (#2376)
* Update CHANGES.md for 21.7b0 release

* move some changes to the right section

* another one

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2021-07-16 07:42:47 -07:00
pszlazak
4622e4cb82
Create Docker tag 'latest_release' (#2374)
Docker images created during release process will have extra tag 'latest_release'.

This closes #2373.
2021-07-16 07:26:29 -07:00
Richard Si
756177a617
Don't include profiling/ to cut down sdist by ~2x (#2362)
They seem to be used as test cases for a specific region of formatting
that was slow. Now performance testing is probably something end users
won't be needing to do, so this is an easy way of reducing the sdist
size sigificantly.
2021-07-15 17:21:53 -07:00
Felix Hildén
91773b8909
Improve AST safety parsing error message (#2304)
Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2021-07-13 10:24:55 -07:00
Richard Si
2946d3b03d
Switch toml TOML library for tomli (#2301)
toml unfortunately has a lack of maintainership issue right now. It's
evident by the fact toml only supports TOML v0.5.0. TOML v1.0.0 has
been recently released and right now Black crashes hard on its usage.

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

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

Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Co-authored-by: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com>
2021-07-12 16:01:38 -04:00
Łukasz Langa
c64fb8cbb1
Add LocalStack and Twisted to projects using Black 2021-07-12 11:56:03 +02:00
Marco Edward Gorelli
548d699161
Second run of tox -e py results in a test error for test marked with no_python2 (#2369)
Fixes #2367
2021-07-11 13:03:36 -07: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
Richard Si
ae56983a5f
Avoid src being marked as optional in help (#2356) 2021-07-08 18:46:32 -07:00
Marco Edward Gorelli
14072be245
fix typo (#2358) 2021-07-04 14:23:00 -04:00
simaki
017aafea99
Accept empty stdin (close #2337) (#2346)
Commit history before merge:

* Accept empty stdin (close #2337)
* Update tests/test_black.py
* Add changelog
* Assert Black reformats an empty string to an empty string (#2337) (#2346)
* fix
2021-06-23 15:11:23 -04:00
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
SADIK KUZU
3980b4b176
Update pre-commit config (#2331)
via `pre-commit autoupdate`

```
Updating https://gitlab.com/pycqa/flake8
... updating 3.9.0 -> 3.9.2.
Updating https://github.com/pre-commit/mirrors-mypy
... updating v0.812 -> v0.902.
Updating https://github.com/pre-commit/mirrors-prettier
... updating v2.2.1 -> v2.3.1.
```

Signed-off-by: SADIK KUZU <sadikkuzu@hotmail.com>

* Add necessary typeshed packages to requirements

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2021-06-21 18:28:25 -07:00
Art Chaidarun
8d8b3d1805
Add Duolingo to list of users (#2341) 2021-06-17 09:32:03 -07:00
Felix Hildén
742ddd1561
Chat on Discord instead of Freenode (#2336)
Now that we've moved, let's direct our users to Discord in the
documentation and readme.
2021-06-15 10:37:59 -04:00
Felix Hildén
bd7f49df3e
Docs: no space is inserted to empty docstrings (#2249) (#2333) 2021-06-13 12:27:57 -07: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
Bartosz Telenczuk
52384bf0a3
Vim plugin fix string normalization option (#1869)
This commit fixes parsing of the skip-string-normalization option in vim
plugin. Originally, the plugin read the string-normalization option,
which does not exist in help (--help) and it's not respected by black
on command line.

Commit history before merge:

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

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

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

=== Problem #1 ===

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

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

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

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

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

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

=== Problem #2 ===

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

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

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

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

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

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

---

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #2310
2021-06-10 21:06:50 -07:00
Ryan McPartlan
05b54b8432
Fix incorrect document referance (#2326) 2021-06-10 17:45:43 -07:00
409 changed files with 28533 additions and 8349 deletions

View File

@ -1,9 +0,0 @@
[report]
omit =
src/blib2to3/*
tests/data/*
*/site-packages/*
.tox/*
[run]
relative_files = True

View File

@ -1,7 +1,8 @@
[flake8] [flake8]
ignore = E203, E266, E501, W503 # B905 should be enabled when we drop support for 3.9
ignore = E203, E266, E501, E701, E704, W503, B905, B907
# line length is intentionally set to 80 here because black uses Bugbear # line length is intentionally set to 80 here because black uses Bugbear
# See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-length for more details # See https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#bugbear for more details
max-line-length = 80 max-line-length = 80
max-complexity = 18 max-complexity = 18
select = B,C,E,F,W,T4,B9 select = B,C,E,F,W,T4,B9

3
.git_archival.txt Normal file
View File

@ -0,0 +1,3 @@
node: $Format:%H$
node-date: $Format:%cI$
describe-name: $Format:%(describe:tags=true,match=[0-9]*)$

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
.git_archival.txt export-subst
*.py diff=python

View File

@ -1,47 +1,66 @@
--- ---
name: Bug report name: Bug report
about: Create a report to help us improve about: Create a report to help us improve Black's quality
title: "" title: ""
labels: bug labels: "T: bug"
assignees: "" assignees: ""
--- ---
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
1. Update Black's version if a newer release exists: `pip install -U black`
2. Use the online formatter at <https://black.vercel.app/?version=main>, which will use
the latest main branch. Note that the online formatter currently runs on
an older version of Python and may not support newer syntax, such as the
extended f-string syntax added in Python 3.12.
3. Or run _Black_ on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run `pip install -e .[d]`;
- run `pip install -r test_requirements.txt`
- make sure it's sane by running `python -m pytest`; and
- run `black` like you did last time.
-->
**Describe the bug** **Describe the bug**
<!-- A clear and concise description of what the bug is. --> <!-- A clear and concise description of what the bug is. -->
**To Reproduce** **To Reproduce**
<!-- Steps to reproduce the behavior: <!--
Minimal steps to reproduce the behavior with source code and Black's configuration.
-->
For example: For example, take this code:
1. Take this file '...'
1. Run _Black_ on it with these arguments '...' ```python
1. See error --> this = "code"
```
And run it with these arguments:
```sh
$ black file.py --target-version py39
```
The resulting error is:
> cannot format file.py: INTERNAL ERROR: ...
**Expected behavior** **Expected behavior**
<!-- A clear and concise description of what you expected to happen. --> <!-- A clear and concise description of what you expected to happen. -->
**Environment (please complete the following information):** **Environment**
- Version: <!-- e.g. [main] --> <!-- Please complete the following information: -->
- Black's version: <!-- e.g. [main] -->
- OS and Python version: <!-- e.g. [Linux/Python 3.7.4rc1] --> - OS and Python version: <!-- e.g. [Linux/Python 3.7.4rc1] -->
**Does this bug also happen on main?**
<!-- To answer this, you have two options:
1. Use the online formatter at <https://black.vercel.app/?version=main>, which will use
the latest main branch.
1. Or run _Black_ on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run `pip install -e .[d,python2]`;
- run `pip install -r test_requirements.txt`
- make sure it's sane by running `python -m pytest`; and
- run `black` like you did last time. -->
**Additional context** **Additional context**
<!-- Add any other context about the problem here. --> <!-- Add any other context about the problem here. -->

12
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,12 @@
# See also: https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository#configuring-the-template-chooser
# This is the default and blank issues are useful so let's keep 'em.
blank_issues_enabled: true
contact_links:
- name: Chat on Python Discord
url: https://discord.gg/RtVdv86PrH
about: |
User support, questions, and other lightweight requests can be
handled via the #black-formatter text channel we have on Python
Discord.

27
.github/ISSUE_TEMPLATE/docs-issue.md vendored Normal file
View File

@ -0,0 +1,27 @@
---
name: Documentation
about: Report a problem with or suggest something for the documentation
title: ""
labels: "T: documentation"
assignees: ""
---
**Is this related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is.
e.g. I'm always frustrated when [...] / I wished that [...] -->
**Describe the solution you'd like**
<!-- A clear and concise description of what you want to
happen or see changed. -->
**Describe alternatives you've considered**
<!-- A clear and concise description of any
alternative solutions or features you've considered. -->
**Additional context**
<!-- Add any other context or screenshots about the issue
here. -->

View File

@ -2,7 +2,7 @@
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: "" title: ""
labels: enhancement labels: "T: enhancement"
assignees: "" assignees: ""
--- ---

View File

@ -1,8 +1,8 @@
--- ---
name: Style issue name: Code style issue
about: Help us improve the Black style about: Help us improve the Black code style
title: "" title: ""
labels: design labels: "T: style"
assignees: "" assignees: ""
--- ---

36
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,36 @@
<!-- Hello! Thanks for submitting a PR. To help make things go a bit more
smoothly we would appreciate that you go through this template. -->
### Description
<!-- Good things to put here include: reasoning for the change (please link
any relevant issues!), any noteworthy (or hacky) choices to be aware of,
or what the problem resolved here looked like ... we won't mind a ranty
story :) -->
### Checklist - did you ...
<!-- If any of the following items aren't relevant for your contribution
please still tick them so we know you've gone through the checklist.
All user-facing changes should get an entry. Otherwise, signal to us
this should get the magical label to silence the CHANGELOG entry check.
Tests are required for bugfixes and new features. Documentation changes
are necessary for formatting and most enhancement changes. -->
- [ ] Add an entry in `CHANGES.md` if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
<!-- Just as a reminder, everyone in all psf/black spaces including PRs
must follow the PSF Code of Conduct (link below).
Finally, once again thanks for your time and effort. If you have any
feedback in regards to your experience contributing here, please
let us know!
Helpful links:
PSF COC: https://www.python.org/psf/conduct/
Contributing docs: https://black.readthedocs.io/en/latest/contributing/index.html
Chat on Python Discord: https://discord.gg/RtVdv86PrH -->

16
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,16 @@
# https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "github-actions"
# Workflow files in .github/workflows will be checked
directory: "/"
schedule:
interval: "weekly"
labels: ["skip news", "C: dependencies"]
- package-ecosystem: "pip"
directory: "docs/"
schedule:
interval: "weekly"
labels: ["skip news", "C: dependencies", "T: documentation"]

View File

@ -4,6 +4,9 @@ on:
pull_request: pull_request:
types: [opened, synchronize, labeled, unlabeled, reopened] types: [opened, synchronize, labeled, unlabeled, reopened]
permissions:
contents: read
jobs: jobs:
build: build:
name: Changelog Entry Check name: Changelog Entry Check
@ -11,11 +14,11 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Grep CHANGES.md for PR number - name: Grep CHANGES.md for PR number
if: contains(github.event.pull_request.labels.*.name, 'skip news') != true if: contains(github.event.pull_request.labels.*.name, 'skip news') != true
run: | run: |
grep -Pz "\((\n\s*)?#${{ github.event.pull_request.number }}(\n\s*)?\)" CHANGES.md || \ grep -Pz "\((\n\s*)?#${{ github.event.pull_request.number }}(\n\s*)?\)" CHANGES.md || \
(echo "Please add '(#${{ github.event.pull_request.number }})' change line to CHANGES.md" && \ (echo "Please add '(#${{ github.event.pull_request.number }})' change line to CHANGES.md (or if appropriate, ask a maintainer to add the 'skip news' label)" && \
exit 1) exit 1)

155
.github/workflows/diff_shades.yml vendored Normal file
View File

@ -0,0 +1,155 @@
name: diff-shades
on:
push:
branches: [main]
paths: ["src/**", "pyproject.toml", ".github/workflows/*"]
pull_request:
paths: ["src/**", "pyproject.toml", ".github/workflows/*"]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
configure:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-config.outputs.matrix }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install diff-shades and support dependencies
run: |
python -m pip install 'click>=8.1.7' packaging urllib3
python -m pip install https://github.com/ichard26/diff-shades/archive/stable.zip
- name: Calculate run configuration & metadata
id: set-config
env:
GITHUB_TOKEN: ${{ github.token }}
run: >
python scripts/diff_shades_gha_helper.py config ${{ github.event_name }}
${{ matrix.mode }}
analysis:
name: analysis / ${{ matrix.mode }}
needs: configure
runs-on: ubuntu-latest
env:
HATCH_BUILD_HOOKS_ENABLE: "1"
# Clang is less picky with the C code it's given than gcc (and may
# generate faster binaries too).
CC: clang-18
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.configure.outputs.matrix) }}
steps:
- name: Checkout this repository (full clone)
uses: actions/checkout@v4
with:
# The baseline revision could be rather old so a full clone is ideal.
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install diff-shades and support dependencies
run: |
python -m pip install https://github.com/ichard26/diff-shades/archive/stable.zip
python -m pip install 'click>=8.1.7' packaging urllib3
# After checking out old revisions, this might not exist so we'll use a copy.
cat scripts/diff_shades_gha_helper.py > helper.py
git config user.name "diff-shades-gha"
git config user.email "diff-shades-gha@example.com"
- name: Attempt to use cached baseline analysis
id: baseline-cache
uses: actions/cache@v4
with:
path: ${{ matrix.baseline-analysis }}
key: ${{ matrix.baseline-cache-key }}
- name: Build and install baseline revision
if: steps.baseline-cache.outputs.cache-hit != 'true'
env:
GITHUB_TOKEN: ${{ github.token }}
run: >
${{ matrix.baseline-setup-cmd }}
&& python -m pip install .
- name: Analyze baseline revision
if: steps.baseline-cache.outputs.cache-hit != 'true'
run: >
diff-shades analyze -v --work-dir projects-cache/
${{ matrix.baseline-analysis }} ${{ matrix.force-flag }}
- name: Build and install target revision
env:
GITHUB_TOKEN: ${{ github.token }}
run: >
${{ matrix.target-setup-cmd }}
&& python -m pip install .
- name: Analyze target revision
run: >
diff-shades analyze -v --work-dir projects-cache/
${{ matrix.target-analysis }} --repeat-projects-from
${{ matrix.baseline-analysis }} ${{ matrix.force-flag }}
- name: Generate HTML diff report
run: >
diff-shades --dump-html diff.html compare --diff
${{ matrix.baseline-analysis }} ${{ matrix.target-analysis }}
- name: Upload diff report
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.mode }}-diff.html
path: diff.html
- name: Upload baseline analysis
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.baseline-analysis }}
path: ${{ matrix.baseline-analysis }}
- name: Upload target analysis
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.target-analysis }}
path: ${{ matrix.target-analysis }}
- name: Generate summary file (PR only)
if: github.event_name == 'pull_request' && matrix.mode == 'preview-changes'
run: >
python helper.py comment-body ${{ matrix.baseline-analysis }}
${{ matrix.target-analysis }} ${{ matrix.baseline-sha }}
${{ matrix.target-sha }} ${{ github.event.pull_request.number }}
- name: Upload summary file (PR only)
if: github.event_name == 'pull_request' && matrix.mode == 'preview-changes'
uses: actions/upload-artifact@v4
with:
name: .pr-comment.json
path: .pr-comment.json
- name: Verify zero changes (PR only)
if: matrix.mode == 'assert-no-changes'
run: >
diff-shades compare --check ${{ matrix.baseline-analysis }} ${{ matrix.target-analysis }}
|| (echo "Please verify you didn't change the stable code style unintentionally!" && exit 1)
- name: Check for failed files for target revision
# Even if the previous step failed, we should still check for failed files.
if: always()
run: >
diff-shades show-failed --check --show-log ${{ matrix.target-analysis }}

View File

@ -0,0 +1,49 @@
name: diff-shades-comment
on:
workflow_run:
workflows: [diff-shades]
types: [completed]
permissions:
pull-requests: write
jobs:
comment:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "*"
- name: Install support dependencies
run: |
python -m pip install pip --upgrade
python -m pip install click packaging urllib3
- name: Get details from initial workflow run
id: metadata
env:
GITHUB_TOKEN: ${{ github.token }}
run: >
python scripts/diff_shades_gha_helper.py comment-details
${{github.event.workflow_run.id }}
- name: Try to find pre-existing PR comment
if: steps.metadata.outputs.needs-comment == 'true'
id: find-comment
uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e
with:
issue-number: ${{ steps.metadata.outputs.pr-number }}
comment-author: "github-actions[bot]"
body-includes: "diff-shades"
- name: Create or update PR comment
if: steps.metadata.outputs.needs-comment == 'true'
uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043
with:
comment-id: ${{ steps.find-comment.outputs.comment-id }}
issue-number: ${{ steps.metadata.outputs.pr-number }}
body: ${{ steps.metadata.outputs.comment-body }}
edit-mode: replace

View File

@ -1,7 +1,10 @@
name: Documentation Build name: Documentation
on: [push, pull_request] on: [push, pull_request]
permissions:
contents: read
jobs: jobs:
build: build:
# We want to run on external PRs, but not on our own internal PRs as they'll be run # We want to run on external PRs, but not on our own internal PRs as they'll be run
@ -18,16 +21,20 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up latest Python - name: Set up latest Python
uses: actions/setup-python@v2 uses: actions/setup-python@v5
with:
python-version: "3.13"
allow-prereleases: true
- name: Install dependencies - name: Install dependencies
run: | run: |
python -m pip install --upgrade pip setuptools wheel python -m pip install uv
python -m pip install -e ".[d]" python -m uv venv
python -m pip install -r "docs/requirements.txt" python -m uv pip install -e ".[d]"
python -m uv pip install -r "docs/requirements.txt"
- name: Build documentation - name: Build documentation
run: sphinx-build -a -b html -W --keep-going docs/ docs/_build run: sphinx-build -a -b html -W --keep-going docs/ docs/_build

View File

@ -5,7 +5,10 @@ on:
branches: branches:
- "main" - "main"
release: release:
types: created types: [published]
permissions:
contents: read
jobs: jobs:
docker: docker:
@ -13,16 +16,16 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v4
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v1 uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1 uses: docker/setup-buildx-action@v3
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v1 uses: docker/login-action@v3
with: with:
username: ${{ secrets.DOCKERHUB_USERNAME }} username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }} password: ${{ secrets.DOCKERHUB_TOKEN }}
@ -33,12 +36,34 @@ jobs:
latest_non_release)" >> $GITHUB_ENV latest_non_release)" >> $GITHUB_ENV
- name: Build and push - name: Build and push
uses: docker/build-push-action@v2 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
push: true push: true
tags: pyfound/black:latest,pyfound/black:${{ env.GIT_TAG }} tags: pyfound/black:latest,pyfound/black:${{ env.GIT_TAG }}
- name: Build and push latest_release tag
if:
${{ github.event_name == 'release' && github.event.action == 'published' &&
!github.event.release.prerelease }}
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: pyfound/black:latest_release
- name: Build and push latest_prerelease tag
if:
${{ github.event_name == 'release' && github.event.action == 'published' &&
github.event.release.prerelease }}
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: pyfound/black:latest_prerelease
- name: Image digest - name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }} run: echo ${{ steps.docker_build.outputs.digest }}

View File

@ -2,6 +2,13 @@ name: Fuzz
on: [push, pull_request] on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: true
permissions:
contents: read
jobs: jobs:
build: build:
# We want to run on external PRs, but not on our own internal PRs as they'll be run # We want to run on external PRs, but not on our own internal PRs as they'll be run
@ -15,15 +22,16 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
python-version: [3.6, 3.7, 3.8, 3.9] python-version: ["3.9", "3.10", "3.11", "3.12.4", "3.13"]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2 uses: actions/setup-python@v5
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
allow-prereleases: true
- name: Install dependencies - name: Install dependencies
run: | run: |

View File

@ -1,4 +1,4 @@
name: Lint name: Lint + format ourselves
on: [push, pull_request] on: [push, pull_request]
@ -14,15 +14,35 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up Python - name: Assert PR target is main
uses: actions/setup-python@v2 if: github.event_name == 'pull_request' && github.repository == 'psf/black'
run: |
if [ "$GITHUB_BASE_REF" != "main" ]; then
echo "::error::PR targeting '$GITHUB_BASE_REF', please refile targeting 'main'." && exit 1
fi
- name: Set up latest Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
allow-prereleases: true
- name: Install dependencies - name: Install dependencies
run: | run: |
python -m pip install --upgrade pip python -m pip install --upgrade pip
python -m pip install -e '.[d]' python -m pip install -e '.'
python -m pip install tox
- name: Lint - name: Run pre-commit hooks
uses: pre-commit/action@v2.0.2 uses: pre-commit/action@v3.0.1
- name: Format ourselves
run: |
tox -e run_self
- name: Regenerate schema
run: |
tox -e generate_schema
git diff --exit-code

View File

@ -1,47 +0,0 @@
name: Primer
on:
push:
paths-ignore:
- "docs/**"
- "*.md"
pull_request:
paths-ignore:
- "docs/**"
- "*.md"
jobs:
build:
# We want to run on external PRs, but not on our own internal PRs as they'll be run
# by the push to the branch. Without this if check, checks are duplicated since
# internal PRs match both the push and pull_request events.
if:
github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=
github.repository
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install -e ".[d]"
- name: Primer run
env:
pythonioencoding: utf-8
run: |
black-primer

View File

@ -1,31 +1,130 @@
name: pypi_upload name: Build and publish
on: on:
release: release:
types: created types: [published]
pull_request:
push:
branches:
- main
permissions:
contents: read
jobs: jobs:
build: main:
name: PyPI Upload name: sdist + pure wheel
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.event_name == 'release'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up Python - name: Set up latest Python
uses: actions/setup-python@v2 uses: actions/setup-python@v5
with:
python-version: "3.13"
allow-prereleases: true
- name: Install latest pip, setuptools, twine + wheel - name: Install latest pip, build, twine
run: | run: |
python -m pip install --upgrade pip setuptools twine wheel python -m pip install --upgrade --disable-pip-version-check pip
python -m pip install --upgrade build twine
- name: Build wheels - name: Build wheel and source distributions
run: | run: python -m build
python setup.py bdist_wheel
python setup.py sdist
- name: Upload to PyPI via Twine - if: github.event_name == 'release'
name: Upload to PyPI via Twine
env: env:
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
run: twine upload --verbose -u '__token__' dist/*
generate_wheels_matrix:
name: generate wheels matrix
runs-on: ubuntu-latest
outputs:
include: ${{ steps.set-matrix.outputs.include }}
steps:
- uses: actions/checkout@v4
# Keep cibuildwheel version in sync with below
- name: Install cibuildwheel and pypyp
run: | run: |
twine upload --verbose -u '__token__' dist/* pipx install cibuildwheel==2.22.0
pipx install pypyp==1.3.0
- name: generate matrix
if: github.event_name != 'pull_request'
run: |
{
cibuildwheel --print-build-identifiers --platform linux \
| pyp 'json.dumps({"only": x, "os": "ubuntu-latest"})' \
&& cibuildwheel --print-build-identifiers --platform macos \
| pyp 'json.dumps({"only": x, "os": "macos-latest"})' \
&& cibuildwheel --print-build-identifiers --platform windows \
| pyp 'json.dumps({"only": x, "os": "windows-latest"})'
} | pyp 'json.dumps(list(map(json.loads, lines)))' > /tmp/matrix
env:
CIBW_ARCHS_LINUX: x86_64
CIBW_ARCHS_MACOS: x86_64 arm64
CIBW_ARCHS_WINDOWS: AMD64
- name: generate matrix (PR)
if: github.event_name == 'pull_request'
run: |
{
cibuildwheel --print-build-identifiers --platform linux \
| pyp 'json.dumps({"only": x, "os": "ubuntu-latest"})'
} | pyp 'json.dumps(list(map(json.loads, lines)))' > /tmp/matrix
env:
CIBW_BUILD: "cp39-* cp313-*"
CIBW_ARCHS_LINUX: x86_64
- id: set-matrix
run: echo "include=$(cat /tmp/matrix)" | tee -a $GITHUB_OUTPUT
mypyc:
name: mypyc wheels ${{ matrix.only }}
needs: generate_wheels_matrix
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.generate_wheels_matrix.outputs.include) }}
steps:
- uses: actions/checkout@v4
# Keep cibuildwheel version in sync with above
- uses: pypa/cibuildwheel@v2.23.3
with:
only: ${{ matrix.only }}
- name: Upload wheels as workflow artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.only }}-mypyc-wheels
path: ./wheelhouse/*.whl
- if: github.event_name == 'release'
name: Upload wheels to PyPI via Twine
env:
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
run: pipx run twine upload --verbose -u '__token__' wheelhouse/*.whl
update-stable-branch:
name: Update stable branch
needs: [main, mypyc]
runs-on: ubuntu-latest
if: github.event_name == 'release'
permissions:
contents: write
steps:
- name: Checkout stable branch
uses: actions/checkout@v4
with:
ref: stable
fetch-depth: 0
- if: github.event_name == 'release'
name: Update stable branch to release tag & push
run: |
git reset --hard ${{ github.event.release.tag_name }}
git push

56
.github/workflows/release_tests.yml vendored Normal file
View File

@ -0,0 +1,56 @@
name: Release tool CI
on:
push:
paths:
- .github/workflows/release_tests.yml
- release.py
- release_tests.py
pull_request:
paths:
- .github/workflows/release_tests.yml
- release.py
- release_tests.py
jobs:
build:
# We want to run on external PRs, but not on our own internal PRs as they'll be run
# by the push to the branch. Without this if check, checks are duplicated since
# internal PRs match both the push and pull_request events.
if:
github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=
github.repository
name: Running python ${{ matrix.python-version }} on ${{matrix.os}}
runs-on: ${{ matrix.os }}
strategy:
matrix:
python-version: ["3.13"]
os: [macOS-latest, ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v4
with:
# Give us all history, branches and tags
fetch-depth: 0
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
allow-prereleases: true
- name: Print Python Version
run: python --version --version && which python
- name: Print Git Version
run: git --version && which git
- name: Update pip, setuptools + wheels
run: |
python -m pip install --upgrade pip setuptools wheel
- name: Run unit tests via coverage + print report
run: |
python -m pip install coverage
coverage run scripts/release_tests.py
coverage report --show-missing

View File

@ -11,8 +11,15 @@ on:
- "docs/**" - "docs/**"
- "*.md" - "*.md"
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs: jobs:
build: main:
# We want to run on external PRs, but not on our own internal PRs as they'll be run # We want to run on external PRs, but not on our own internal PRs as they'll be run
# by the push to the branch. Without this if check, checks are duplicated since # by the push to the branch. Without this if check, checks are duplicated since
# internal PRs match both the push and pull_request events. # internal PRs match both the push and pull_request events.
@ -24,35 +31,39 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
python-version: [3.6, 3.7, 3.8, 3.9] python-version: ["3.9", "3.10", "3.11", "3.12.4", "3.13", "pypy-3.9"]
os: [ubuntu-latest, macOS-latest, windows-latest] os: [ubuntu-latest, macOS-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2 uses: actions/setup-python@v5
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
allow-prereleases: true
- name: Install dependencies - name: Install tox
run: | run: |
python -m pip install --upgrade pip python -m pip install --upgrade pip
python -m pip install --upgrade tox python -m pip install --upgrade tox
- name: Unit tests - name: Unit tests
run: | if: "!startsWith(matrix.python-version, 'pypy')"
tox -e ci-py -- -v --color=yes run:
tox -e ci-py$(echo ${{ matrix.python-version }} | tr -d '.') -- -v --color=yes
- name: Publish coverage to Coveralls - name: Unit tests (pypy)
# If pushed / is a pull request against main repo AND if: "startsWith(matrix.python-version, 'pypy')"
run: tox -e ci-pypy3 -- -v --color=yes
- name: Upload coverage to Coveralls
# Upload coverage if we are on the main repository and
# we're running on Linux (this action only supports Linux) # we're running on Linux (this action only supports Linux)
if: if:
((github.event_name == 'push' && github.repository == 'psf/black') || github.repository == 'psf/black' && matrix.os == 'ubuntu-latest' &&
github.event.pull_request.base.repo.full_name == 'psf/black') && matrix.os == !startsWith(matrix.python-version, 'pypy')
'ubuntu-latest' uses: AndreMiras/coveralls-python-action@ac868b9540fad490f7ca82b8ca00480fd751ed19
uses: AndreMiras/coveralls-python-action@v20201129
with: with:
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
parallel: true parallel: true
@ -60,17 +71,40 @@ jobs:
debug: true debug: true
coveralls-finish: coveralls-finish:
needs: build needs: main
# If pushed / is a pull request against main repo if: github.repository == 'psf/black'
if:
(github.event_name == 'push' && github.repository == 'psf/black') ||
github.event.pull_request.base.repo.full_name == 'psf/black'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Coveralls finished - name: Send finished signal to Coveralls
uses: AndreMiras/coveralls-python-action@v20201129 uses: AndreMiras/coveralls-python-action@ac868b9540fad490f7ca82b8ca00480fd751ed19
with: with:
parallel-finished: true parallel-finished: true
debug: true debug: true
uvloop:
if:
github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=
github.repository
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macOS-latest]
steps:
- uses: actions/checkout@v4
- name: Set up latest Python
uses: actions/setup-python@v5
with:
python-version: "3.12.4"
- name: Install black with uvloop
run: |
python -m pip install pip --upgrade --disable-pip-version-check
python -m pip install -e ".[uvloop]"
- name: Format ourselves
run: python -m black --check src/ tests/

View File

@ -1,22 +1,25 @@
name: Upload self-contained binaries name: Publish executables
on: on:
release: release:
types: [published] types: [published]
permissions:
contents: write # actions/upload-release-asset needs this.
jobs: jobs:
build: build:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-2019, ubuntu-20.04, macos-latest] os: [windows-2019, ubuntu-22.04, macos-latest]
include: include:
- os: windows-2019 - os: windows-2019
pathsep: ";" pathsep: ";"
asset_name: black_windows.exe asset_name: black_windows.exe
executable_mime: "application/vnd.microsoft.portable-executable" executable_mime: "application/vnd.microsoft.portable-executable"
- os: ubuntu-20.04 - os: ubuntu-22.04
pathsep: ":" pathsep: ":"
asset_name: black_linux asset_name: black_linux
executable_mime: "application/x-executable" executable_mime: "application/x-executable"
@ -26,22 +29,28 @@ jobs:
executable_mime: "application/x-mach-binary" executable_mime: "application/x-mach-binary"
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Set up latest Python - name: Set up latest Python
uses: actions/setup-python@v2 uses: actions/setup-python@v5
with: with:
python-version: "*" python-version: "3.12.4"
- name: Install dependencies - name: Install Black and PyInstaller
run: | run: |
python -m pip install --upgrade pip wheel setuptools python -m pip install --upgrade pip wheel
python -m pip install . python -m pip install .[colorama]
python -m pip install pyinstaller python -m pip install pyinstaller
- name: Build binary - name: Build executable with PyInstaller
run: >
python -m PyInstaller -F --name ${{ matrix.asset_name }} --add-data
'src/blib2to3${{ matrix.pathsep }}blib2to3' src/black/__main__.py
- name: Quickly test executable
run: | run: |
python -m PyInstaller -F --name ${{ matrix.asset_name }} --add-data 'src/blib2to3${{ matrix.pathsep }}blib2to3' src/black/__main__.py ./dist/${{ matrix.asset_name }} --version
./dist/${{ matrix.asset_name }} src --verbose
- name: Upload binary as release asset - name: Upload binary as release asset
uses: actions/upload-release-asset@v1 uses: actions/upload-release-asset@v1

View File

@ -1,45 +0,0 @@
name: test uvloop
on:
push:
paths-ignore:
- "docs/**"
- "*.md"
pull_request:
paths-ignore:
- "docs/**"
- "*.md"
jobs:
build:
# We want to run on external PRs, but not on our own internal PRs as they'll be run
# by the push to the branch. Without this if check, checks are duplicated since
# internal PRs match both the push and pull_request events.
if:
github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=
github.repository
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macOS-latest]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
- name: Install latest pip
run: |
python -m pip install --upgrade pip
- name: Test uvloop Extra Install
run: |
python -m pip install -e ".[uvloop]"
- name: Primer uvloop run
run: |
black-primer

12
.gitignore vendored
View File

@ -4,17 +4,25 @@
_build _build
.DS_Store .DS_Store
.vscode .vscode
.python-version
docs/_static/pypi.svg docs/_static/pypi.svg
.tox .tox
__pycache__ __pycache__
# Packaging artifacts
black.egg-info black.egg-info
black.dist-info
build/ build/
dist/ dist/
pip-wheel-metadata/ pip-wheel-metadata/
.eggs
src/_black_version.py src/_black_version.py
.idea .idea
.eggs
.dmypy.json .dmypy.json
*.swp *.swp
.hypothesis/ .hypothesis/
venv/ venv/
.ipynb_checkpoints/
node_modules/

View File

@ -1,30 +1,83 @@
# Note: don't use this config for your own repositories. Instead, see # Note: don't use this config for your own repositories. Instead, see
# "Version control integration" in README.md. # "Version control integration" in docs/integrations/source_version_control.md
exclude: ^(src/blib2to3/|profiling/|tests/data/) exclude: ^(profiling/|tests/data/)
repos: repos:
- repo: local - repo: local
hooks: hooks:
- id: black - id: check-pre-commit-rev-in-example
name: black name: Check pre-commit rev in example
language: system language: python
entry: black entry: python -m scripts.check_pre_commit_rev_in_example
minimum_pre_commit_version: 2.9.2 files: '(CHANGES\.md|source_version_control\.md)$'
require_serial: true additional_dependencies:
types_or: [python, pyi] &version_check_dependencies [
commonmark==0.9.1,
pyyaml==6.0.1,
beautifulsoup4==4.9.3,
]
- repo: https://gitlab.com/pycqa/flake8 - id: check-version-in-the-basics-example
rev: 3.9.0 name: Check black version in the basics example
language: python
entry: python -m scripts.check_version_in_basics_example
files: '(CHANGES\.md|the_basics\.md)$'
additional_dependencies: *version_check_dependencies
- repo: https://github.com/pycqa/isort
rev: 6.0.1
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 7.2.0
hooks: hooks:
- id: flake8 - id: flake8
additional_dependencies: [flake8-bugbear] additional_dependencies:
- flake8-bugbear==24.2.6
- flake8-comprehensions
- flake8-simplify
exclude: ^src/blib2to3/
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.812 rev: v1.15.0
hooks: hooks:
- id: mypy - id: mypy
exclude: ^docs/conf.py exclude: ^(docs/conf.py|scripts/generate_schema.py)$
args: []
additional_dependencies: &mypy_deps
- types-PyYAML
- types-atheris
- tomli >= 0.2.6, < 2.0.0
- click >= 8.2.0
# Click is intentionally out-of-sync with pyproject.toml
# v8.2 has breaking changes. We work around them at runtime, but we need the newer stubs.
- packaging >= 22.0
- platformdirs >= 2.1.0
- pytokens >= 0.1.10
- pytest
- hypothesis
- aiohttp >= 3.7.4
- types-commonmark
- urllib3
- hypothesmith
- id: mypy
name: mypy (Python 3.10)
files: scripts/generate_schema.py
args: ["--python-version=3.10"]
additional_dependencies: *mypy_deps
- repo: https://github.com/pre-commit/mirrors-prettier - repo: https://github.com/rbubley/mirrors-prettier
rev: v2.2.1 rev: v3.5.3
hooks: hooks:
- id: prettier - id: prettier
types_or: [markdown, yaml, json]
exclude: \.github/workflows/diff_shades\.yml
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
ci:
autoupdate_schedule: quarterly

View File

@ -1,9 +1,20 @@
# Note that we recommend using https://github.com/psf/black-pre-commit-mirror instead
# This will work about 2x as fast as using the hooks in this repository
- id: black - id: black
name: black name: black
description: "Black: The uncompromising Python code formatter" description: "Black: The uncompromising Python code formatter"
entry: black entry: black
language: python language: python
language_version: python3
minimum_pre_commit_version: 2.9.2 minimum_pre_commit_version: 2.9.2
require_serial: true require_serial: true
types_or: [python, pyi] types_or: [python, pyi]
- id: black-jupyter
name: black-jupyter
description:
"Black: The uncompromising Python code formatter (with Jupyter Notebook support)"
entry: black
language: python
minimum_pre_commit_version: 2.9.2
require_serial: true
types_or: [python, pyi, jupyter]
additional_dependencies: [".[jupyter]"]

View File

@ -3,8 +3,12 @@ version: 2
formats: formats:
- htmlzip - htmlzip
build:
os: ubuntu-22.04
tools:
python: "3.11"
python: python:
version: 3.8
install: install:
- requirements: docs/requirements.txt - requirements: docs/requirements.txt
@ -12,3 +16,6 @@ python:
path: . path: .
extra_requirements: extra_requirements:
- d - d
sphinx:
configuration: docs/conf.py

View File

@ -2,27 +2,36 @@
Glued together by [Łukasz Langa](mailto:lukasz@langa.pl). Glued together by [Łukasz Langa](mailto:lukasz@langa.pl).
Maintained with [Carol Willing](mailto:carolcode@willingconsulting.com), Maintained with:
[Carl Meyer](mailto:carl@oddbird.net),
[Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com), - [Carol Willing](mailto:carolcode@willingconsulting.com)
[Mika Naylor](mailto:mail@autophagy.io), - [Carl Meyer](mailto:carl@oddbird.net)
[Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), - [Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com)
[Cooper Lees](mailto:me@cooperlees.com), and Richard Si. - [Mika Naylor](mailto:mail@autophagy.io)
- [Zsolt Dollenstein](mailto:zsol.zsol@gmail.com)
- [Cooper Lees](mailto:me@cooperlees.com)
- [Richard Si](mailto:sichard26@gmail.com)
- [Felix Hildén](mailto:felix.hilden@gmail.com)
- [Batuhan Taskaya](mailto:batuhan@python.org)
- [Shantanu Jain](mailto:hauntsaninja@gmail.com)
Multiple contributions by: Multiple contributions by:
- [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com) - [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com)
- [Adam Johnson](mailto:me@adamj.eu) - [Adam Johnson](mailto:me@adamj.eu)
- [Adam Williamson](mailto:adamw@happyassassin.net) - [Adam Williamson](mailto:adamw@happyassassin.net)
- [Alexander Huynh](mailto:github@grande.coffee) - [Alexander Huynh](mailto:ahrex-gh-psf-black@e.sc)
- [Alexandr Artemyev](mailto:mogost@gmail.com)
- [Alex Vandiver](mailto:github@chmrr.net) - [Alex Vandiver](mailto:github@chmrr.net)
- [Allan Simon](mailto:allan.simon@supinfo.com) - [Allan Simon](mailto:allan.simon@supinfo.com)
- Anders-Petter Ljungquist - Anders-Petter Ljungquist
- [Amethyst Reese](mailto:amy@n7.gg)
- [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com) - [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com)
- [Andrew Zhou](mailto:andrewfzhou@gmail.com) - [Andrew Zhou](mailto:andrewfzhou@gmail.com)
- [Andrey](mailto:dyuuus@yandex.ru) - [Andrey](mailto:dyuuus@yandex.ru)
- [Andy Freeland](mailto:andy@andyfreeland.net) - [Andy Freeland](mailto:andy@andyfreeland.net)
- [Anthony Sottile](mailto:asottile@umich.edu) - [Anthony Sottile](mailto:asottile@umich.edu)
- [Antonio Ossa Guerra](mailto:aaossa+black@uc.cl)
- [Arjaan Buijk](mailto:arjaan.buijk@gmail.com) - [Arjaan Buijk](mailto:arjaan.buijk@gmail.com)
- [Arnav Borbornah](mailto:arnavborborah11@gmail.com) - [Arnav Borbornah](mailto:arnavborborah11@gmail.com)
- [Artem Malyshev](mailto:proofit404@gmail.com) - [Artem Malyshev](mailto:proofit404@gmail.com)
@ -73,6 +82,7 @@ Multiple contributions by:
- [Hugo Barrera](mailto::hugo@barrera.io) - [Hugo Barrera](mailto::hugo@barrera.io)
- Hugo van Kemenade - Hugo van Kemenade
- [Hynek Schlawack](mailto:hs@ox.cx) - [Hynek Schlawack](mailto:hs@ox.cx)
- [Ionite](mailto:dev@ionite.io)
- [Ivan Katanić](mailto:ivan.katanic@gmail.com) - [Ivan Katanić](mailto:ivan.katanic@gmail.com)
- [Jakub Kadlubiec](mailto:jakub.kadlubiec@skyscanner.net) - [Jakub Kadlubiec](mailto:jakub.kadlubiec@skyscanner.net)
- [Jakub Warczarek](mailto:jakub.warczarek@gmail.com) - [Jakub Warczarek](mailto:jakub.warczarek@gmail.com)
@ -143,6 +153,7 @@ Multiple contributions by:
- [Rishikesh Jha](mailto:rishijha424@gmail.com) - [Rishikesh Jha](mailto:rishijha424@gmail.com)
- [Rupert Bedford](mailto:rupert@rupertb.com) - [Rupert Bedford](mailto:rupert@rupertb.com)
- Russell Davis - Russell Davis
- [Sagi Shadur](mailto:saroad2@gmail.com)
- [Rémi Verschelde](mailto:rverschelde@gmail.com) - [Rémi Verschelde](mailto:rverschelde@gmail.com)
- [Sami Salonen](mailto:sakki@iki.fi) - [Sami Salonen](mailto:sakki@iki.fi)
- [Samuel Cormier-Iijima](mailto:samuel@cormier-iijima.com) - [Samuel Cormier-Iijima](mailto:samuel@cormier-iijima.com)
@ -170,6 +181,7 @@ Multiple contributions by:
- [Tony Narlock](mailto:tony@git-pull.com) - [Tony Narlock](mailto:tony@git-pull.com)
- [Tsuyoshi Hombashi](mailto:tsuyoshi.hombashi@gmail.com) - [Tsuyoshi Hombashi](mailto:tsuyoshi.hombashi@gmail.com)
- [Tushar Chandra](mailto:tusharchandra2018@u.northwestern.edu) - [Tushar Chandra](mailto:tusharchandra2018@u.northwestern.edu)
- [Tushar Sadhwani](mailto:tushar.sadhwani000@gmail.com)
- [Tzu-ping Chung](mailto:uranusjr@gmail.com) - [Tzu-ping Chung](mailto:uranusjr@gmail.com)
- [Utsav Shah](mailto:ukshah2@illinois.edu) - [Utsav Shah](mailto:ukshah2@illinois.edu)
- utsav-dbx - utsav-dbx

1324
CHANGES.md

File diff suppressed because it is too large Load Diff

22
CITATION.cff Normal file
View File

@ -0,0 +1,22 @@
cff-version: 1.2.0
title: "Black: The uncompromising Python code formatter"
message: >-
If you use this software, please cite it using the metadata from this file.
type: software
authors:
- family-names: Langa
given-names: Łukasz
- name: "contributors to Black"
repository-code: "https://github.com/psf/black"
url: "https://black.readthedocs.io/en/stable/"
abstract: >-
Black is the uncompromising Python code formatter. By using it, you agree to cede
control over minutiae of hand-formatting. In return, Black gives you speed,
determinism, and freedom from pycodestyle nagging about formatting. You will save time
and mental energy for more important matters.
Blackened code looks the same regardless of the project you're reading. Formatting
becomes transparent after a while and you can focus on the content instead.
Black makes code review faster by producing the smallest diffs possible.
license: MIT

View File

@ -1,10 +1,13 @@
# Contributing to _Black_ # Contributing to _Black_
Welcome! Happy to see you willing to make the project better. Have you read the entire Welcome future contributor! We're happy to see you willing to make the project better.
[user documentation](https://black.readthedocs.io/en/latest/) yet?
Our [contributing documentation](https://black.readthedocs.org/en/latest/contributing/) If you aren't familiar with _Black_, or are looking for documentation on something
contains details on all you need to know about contributing to _Black_, the basics to specific, the [user documentation](https://black.readthedocs.io/en/latest/) is the best
the internals of _Black_. place to look.
We look forward to your contributions! For getting started on contributing, please read the
[contributing documentation](https://black.readthedocs.org/en/latest/contributing/) for
all you need to know.
Thank you, and we look forward to your contributions!

View File

@ -1,14 +1,22 @@
FROM python:3-slim FROM python:3.12-slim AS builder
RUN mkdir /src RUN mkdir /src
COPY . /src/ COPY . /src/
RUN pip install --no-cache-dir --upgrade pip setuptools wheel \ ENV VIRTUAL_ENV=/opt/venv
&& apt update && apt install -y git \ ENV HATCH_BUILD_HOOKS_ENABLE=1
&& cd /src \ # Install build tools to compile black + dependencies
&& pip install --no-cache-dir .[colorama,d] \ RUN apt update && apt install -y build-essential git python3-dev
&& rm -rf /src \ RUN python -m venv $VIRTUAL_ENV
&& apt remove -y git \ RUN python -m pip install --no-cache-dir hatch hatch-fancy-pypi-readme hatch-vcs
&& apt autoremove -y \ RUN . /opt/venv/bin/activate && pip install --no-cache-dir --upgrade pip setuptools \
&& rm -rf /var/lib/apt/lists/* && cd /src && hatch build -t wheel \
&& pip install --no-cache-dir dist/*-cp* \
&& pip install black[colorama,d,uvloop]
CMD ["black"] FROM python:3.12-slim
# copy only Python packages to limit the image size
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
CMD ["/opt/venv/bin/black"]

36
Pipfile
View File

@ -1,36 +0,0 @@
[[source]]
name = "pypi"
url = "https://pypi.python.org/simple"
verify_ssl = true
[dev-packages]
Sphinx = ">=3.1.2"
coverage = "*"
docutils = "==0.15" # not a direct dependency, see https://github.com/pypa/pipenv/issues/3865
flake8 = "*"
flake8-bugbear = "*"
mypy = ">=0.812"
pre-commit = "*"
readme_renderer = "*"
MyST-Parser = ">=0.13.7"
sphinxcontrib-programoutput = ">=0.17"
sphinx-copybutton = ">=0.3.0"
setuptools = ">=39.2.0"
setuptools-scm = "*"
twine = ">=1.11.0"
wheel = ">=0.31.1"
black = {editable = true, extras = ["d"], path = "."}
[packages]
aiohttp = ">=3.6.0"
aiohttp-cors = ">=0.4.0"
appdirs = "*"
click = ">=7.1.2"
mypy_extensions = ">=0.4.3"
pathspec = ">=0.8.1"
regex = ">=2020.1.8"
toml = ">=0.10.1"
typed-ast = "==1.4.2"
typing_extensions = {"python_version <" = "3.8","version >=" = "3.7.4"}
black = {editable = true,extras = ["d"],path = "."}
dataclasses = {"python_version <" = "3.7","version >" = "0.6"}

1262
Pipfile.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,14 @@
![Black Logo](https://raw.githubusercontent.com/psf/black/main/docs/_static/logo2-readme.png) [![Black Logo](https://raw.githubusercontent.com/psf/black/main/docs/_static/logo2-readme.png)](https://black.readthedocs.io/en/stable/)
<h2 align="center">The Uncompromising Code Formatter</h2> <h2 align="center">The Uncompromising Code Formatter</h2>
<p align="center"> <p align="center">
<a href="https://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Test/badge.svg"></a> <a href="https://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Test/badge.svg"></a>
<a href="https://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Primer/badge.svg"></a>
<a href="https://black.readthedocs.io/en/stable/?badge=stable"><img alt="Documentation Status" src="https://readthedocs.org/projects/black/badge/?version=stable"></a> <a href="https://black.readthedocs.io/en/stable/?badge=stable"><img alt="Documentation Status" src="https://readthedocs.org/projects/black/badge/?version=stable"></a>
<a href="https://coveralls.io/github/psf/black?branch=main"><img alt="Coverage Status" src="https://coveralls.io/repos/github/psf/black/badge.svg?branch=main"></a> <a href="https://coveralls.io/github/psf/black?branch=main"><img alt="Coverage Status" src="https://coveralls.io/repos/github/psf/black/badge.svg?branch=main"></a>
<a href="https://github.com/psf/black/blob/main/LICENSE"><img alt="License: MIT" src="https://black.readthedocs.io/en/stable/_static/license.svg"></a> <a href="https://github.com/psf/black/blob/main/LICENSE"><img alt="License: MIT" src="https://black.readthedocs.io/en/stable/_static/license.svg"></a>
<a href="https://pypi.org/project/black/"><img alt="PyPI" src="https://img.shields.io/pypi/v/black"></a> <a href="https://pypi.org/project/black/"><img alt="PyPI" src="https://img.shields.io/pypi/v/black"></a>
<a href="https://pepy.tech/project/black"><img alt="Downloads" src="https://pepy.tech/badge/black"></a> <a href="https://pepy.tech/project/black"><img alt="Downloads" src="https://static.pepy.tech/badge/black"></a>
<a href="https://anaconda.org/conda-forge/black/"><img alt="conda-forge" src="https://img.shields.io/conda/dn/conda-forge/black.svg?label=conda-forge"></a> <a href="https://anaconda.org/conda-forge/black/"><img alt="conda-forge" src="https://img.shields.io/conda/dn/conda-forge/black.svg?label=conda-forge"></a>
<a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a> <a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
</p> </p>
@ -39,13 +38,12 @@ Try it out now using the [Black Playground](https://black.vercel.app). Watch the
### Installation ### Installation
_Black_ can be installed by running `pip install black`. It requires Python 3.6.2+ to _Black_ can be installed by running `pip install black`. It requires Python 3.9+ to run.
run. If you want to format Python 2 code as well, install with If you want to format Jupyter Notebooks, install with `pip install "black[jupyter]"`.
`pip install black[python2]`.
If you can't wait for the latest _hotness_ and want to install from GitHub, use: If you can't wait for the latest _hotness_ and want to install from GitHub, use:
`pip install git+git://github.com/psf/black` `pip install git+https://github.com/psf/black`
### Usage ### Usage
@ -65,16 +63,13 @@ Further information can be found in our docs:
- [Usage and Configuration](https://black.readthedocs.io/en/stable/usage_and_configuration/index.html) - [Usage and Configuration](https://black.readthedocs.io/en/stable/usage_and_configuration/index.html)
### NOTE: This is a beta product
_Black_ is already [successfully used](https://github.com/psf/black#used-by) by many _Black_ is already [successfully used](https://github.com/psf/black#used-by) by many
projects, small and big. Black has a comprehensive test suite, with efficient parallel projects, small and big. _Black_ has a comprehensive test suite, with efficient parallel
tests, and our own auto formatting and parallel Continuous Integration runner. However, tests, and our own auto formatting and parallel Continuous Integration runner. Now that
_Black_ is still beta. Things will probably be wonky for a while. This is made explicit we have become stable, you should not expect large formatting changes in the future.
by the "Beta" trove classifier, as well as by the "b" in the version number. What this Stylistic changes will mostly be responses to bug reports and support for new Python
means for you is that **until the formatter becomes stable, you should expect some syntax. For more information please refer to
formatting to change in the future**. That being said, no drastic stylistic changes are [The Black Code Style](https://black.readthedocs.io/en/stable/the_black_code_style/index.html).
planned, mostly responses to bug reports.
Also, as a safety measure which slows down processing, _Black_ will check that the Also, as a safety measure which slows down processing, _Black_ will check that the
reformatted code still produces a valid AST that is effectively equivalent to the reformatted code still produces a valid AST that is effectively equivalent to the
@ -86,14 +81,20 @@ section for details). If you're feeling confident, use `--fast`.
_Black_ is a PEP 8 compliant opinionated formatter. _Black_ reformats entire files in _Black_ is a PEP 8 compliant opinionated formatter. _Black_ reformats entire files in
place. Style configuration options are deliberately limited and rarely added. It doesn't place. Style configuration options are deliberately limited and rarely added. It doesn't
take previous formatting into account (see [Pragmatism](#pragmatism) for exceptions). take previous formatting into account (see
[Pragmatism](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#pragmatism)
for exceptions).
Our documentation covers the current _Black_ code style, but planned changes to it are Our documentation covers the current _Black_ code style, but planned changes to it are
also documented. They're both worth taking a look: also documented. They're both worth taking a look at:
- [The _Black_ Code Style: Current style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html) - [The _Black_ Code Style: Current style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html)
- [The _Black_ Code Style: Future style](https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html) - [The _Black_ Code Style: Future style](https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html)
Changes to the _Black_ code style are bound by the Stability Policy:
- [The _Black_ Code Style: Stability Policy](https://black.readthedocs.io/en/stable/the_black_code_style/index.html#stability-policy)
Please refer to this document before submitting an issue. What seems like a bug might be Please refer to this document before submitting an issue. What seems like a bug might be
intended behaviour. intended behaviour.
@ -131,11 +132,13 @@ code in compliance with many other _Black_ formatted projects.
## Used by ## Used by
The following notable open-source projects trust _Black_ with enforcing a consistent The following notable open-source projects trust _Black_ with enforcing a consistent
code style: pytest, tox, Pyramid, Django Channels, Hypothesis, attrs, SQLAlchemy, code style: pytest, tox, Pyramid, Django, Django Channels, Hypothesis, attrs,
Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow, SQLAlchemy, Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv),
every Datadog Agent Integration, Home Assistant, Zulip. pandas, Pillow, Twisted, LocalStack, every Datadog Agent Integration, Home Assistant,
Zulip, Kedro, OpenOA, FLORIS, ORBIT, WOMBAT, and many more.
The following organizations use _Black_: Facebook, Dropbox, Mozilla, Quora. The following organizations use _Black_: Dropbox, KeepTruckin, Lyft, Mozilla, Quora,
Duolingo, QuantumBlack, Tesla, Archer Aviation.
Are we missing anyone? Let us know. Are we missing anyone? Let us know.
@ -162,8 +165,8 @@ Twisted and CPython:
> At least the name is good. > At least the name is good.
**Kenneth Reitz**, creator of [`requests`](http://python-requests.org/) and **Kenneth Reitz**, creator of [`requests`](https://requests.readthedocs.io/en/latest/)
[`pipenv`](https://readthedocs.org/projects/pipenv/): and [`pipenv`](https://readthedocs.org/projects/pipenv/):
> This vastly improves the formatting of our code. Thanks a ton! > This vastly improves the formatting of our code. Thanks a ton!
@ -200,7 +203,7 @@ You can also take a look at the rest of the contributing docs or talk with the
developers: developers:
- [Contributing documentation](https://black.readthedocs.io/en/latest/contributing/index.html) - [Contributing documentation](https://black.readthedocs.io/en/latest/contributing/index.html)
- [IRC channel on Freenode](https://webchat.freenode.net/?channels=%23blackformatter) - [Chat on Discord](https://discord.gg/RtVdv86PrH)
## Change log ## Change log

11
SECURITY.md Normal file
View File

@ -0,0 +1,11 @@
# Security Policy
## Supported Versions
Only the latest non-prerelease version is supported.
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the
fix and disclosure.

View File

@ -5,13 +5,18 @@ inputs:
options: options:
description: description:
"Options passed to Black. Use `black --help` to see available options. Default: "Options passed to Black. Use `black --help` to see available options. Default:
'--check'" '--check --diff'"
required: false required: false
default: "--check --diff" default: "--check --diff"
src: src:
description: "Source to run Black. Default: '.'" description: "Source to run Black. Default: '.'"
required: false required: false
default: "." default: "."
jupyter:
description:
"Set this option to true to include Jupyter Notebook files. Default: false"
required: false
default: false
black_args: black_args:
description: "[DEPRECATED] Black input arguments." description: "[DEPRECATED] Black input arguments."
required: false required: false
@ -22,38 +27,53 @@ inputs:
description: 'Python Version specifier (PEP440) - e.g. "21.5b1"' description: 'Python Version specifier (PEP440) - e.g. "21.5b1"'
required: false required: false
default: "" default: ""
use_pyproject:
description: Read Black version specifier from pyproject.toml if `true`.
required: false
default: "false"
summary:
description: "Whether to add the output to the workflow summary"
required: false
default: true
branding: branding:
color: "black" color: "black"
icon: "check-circle" icon: "check-circle"
runs: runs:
using: composite using: composite
steps: steps:
- run: | - name: black
# Exists since using github.action_path + path to main script doesn't work because bash run: |
# interprets the backslashes in github.action_path (which are used when the runner OS # Even when black fails, do not close the shell
# is Windows) destroying the path to the target file. set +e
#
# Also semicolons are necessary because I can't get the newlines to work
entrypoint="import sys;
import subprocess;
from pathlib import Path;
MAIN_SCRIPT = Path(r'${{ github.action_path }}') / 'action' / 'main.py';
proc = subprocess.run([sys.executable, str(MAIN_SCRIPT)]);
sys.exit(proc.returncode)
"
if [ "$RUNNER_OS" == "Windows" ]; then if [ "$RUNNER_OS" == "Windows" ]; then
echo $entrypoint | python runner="python"
else else
echo $entrypoint | python3 runner="python3"
fi fi
out=$(${runner} $GITHUB_ACTION_PATH/action/main.py)
exit_code=$?
# Display the raw output in the step
echo "${out}"
if [ "${{ inputs.summary }}" == "true" ]; then
# Display the Markdown output in the job summary
echo "\`\`\`python" >> $GITHUB_STEP_SUMMARY
echo "${out}" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
fi
# Exit with the exit-code returned by Black
exit ${exit_code}
env: env:
# TODO: Remove once https://github.com/actions/runner/issues/665 is fixed. # TODO: Remove once https://github.com/actions/runner/issues/665 is fixed.
INPUT_OPTIONS: ${{ inputs.options }} INPUT_OPTIONS: ${{ inputs.options }}
INPUT_SRC: ${{ inputs.src }} INPUT_SRC: ${{ inputs.src }}
INPUT_JUPYTER: ${{ inputs.jupyter }}
INPUT_BLACK_ARGS: ${{ inputs.black_args }} INPUT_BLACK_ARGS: ${{ inputs.black_args }}
INPUT_VERSION: ${{ inputs.version }} INPUT_VERSION: ${{ inputs.version }}
INPUT_USE_PYPROJECT: ${{ inputs.use_pyproject }}
pythonioencoding: utf-8 pythonioencoding: utf-8
shell: bash shell: bash

View File

@ -1,39 +1,182 @@
import os import os
import re
import shlex import shlex
import shutil
import sys import sys
from pathlib import Path from pathlib import Path
from subprocess import run, PIPE, STDOUT from subprocess import PIPE, STDOUT, run
from typing import Union
ACTION_PATH = Path(os.environ["GITHUB_ACTION_PATH"]) ACTION_PATH = Path(os.environ["GITHUB_ACTION_PATH"])
ENV_PATH = ACTION_PATH / ".black-env" ENV_PATH = ACTION_PATH / ".black-env"
ENV_BIN = ENV_PATH / ("Scripts" if sys.platform == "win32" else "bin") ENV_BIN = ENV_PATH / ("Scripts" if sys.platform == "win32" else "bin")
OPTIONS = os.getenv("INPUT_OPTIONS", default="") OPTIONS = os.getenv("INPUT_OPTIONS", default="")
SRC = os.getenv("INPUT_SRC", default="") SRC = os.getenv("INPUT_SRC", default="")
JUPYTER = os.getenv("INPUT_JUPYTER") == "true"
BLACK_ARGS = os.getenv("INPUT_BLACK_ARGS", default="") BLACK_ARGS = os.getenv("INPUT_BLACK_ARGS", default="")
VERSION = os.getenv("INPUT_VERSION", default="") VERSION = os.getenv("INPUT_VERSION", default="")
USE_PYPROJECT = os.getenv("INPUT_USE_PYPROJECT") == "true"
BLACK_VERSION_RE = re.compile(r"^black([^A-Z0-9._-]+.*)$", re.IGNORECASE)
EXTRAS_RE = re.compile(r"\[.*\]")
EXPORT_SUBST_FAIL_RE = re.compile(r"\$Format:.*\$")
def determine_version_specifier() -> str:
"""Determine the version of Black to install.
The version can be specified either via the `with.version` input or via the
pyproject.toml file if `with.use_pyproject` is set to `true`.
"""
if USE_PYPROJECT and VERSION:
print(
"::error::'with.version' and 'with.use_pyproject' inputs are "
"mutually exclusive.",
file=sys.stderr,
flush=True,
)
sys.exit(1)
if USE_PYPROJECT:
return read_version_specifier_from_pyproject()
elif VERSION and VERSION[0] in "0123456789":
return f"=={VERSION}"
else:
return VERSION
def read_version_specifier_from_pyproject() -> str:
if sys.version_info < (3, 11):
print(
"::error::'with.use_pyproject' input requires Python 3.11 or later.",
file=sys.stderr,
flush=True,
)
sys.exit(1)
import tomllib # type: ignore[import-not-found,unreachable]
try:
with Path("pyproject.toml").open("rb") as fp:
pyproject = tomllib.load(fp)
except FileNotFoundError:
print(
"::error::'with.use_pyproject' input requires a pyproject.toml file.",
file=sys.stderr,
flush=True,
)
sys.exit(1)
version = pyproject.get("tool", {}).get("black", {}).get("required-version")
if version is not None:
return f"=={version}"
arrays = [
*pyproject.get("dependency-groups", {}).values(),
pyproject.get("project", {}).get("dependencies"),
*pyproject.get("project", {}).get("optional-dependencies", {}).values(),
]
for array in arrays:
version = find_black_version_in_array(array)
if version is not None:
break
if version is None:
print(
"::error::'black' dependency missing from pyproject.toml.",
file=sys.stderr,
flush=True,
)
sys.exit(1)
return version
def find_black_version_in_array(array: object) -> Union[str, None]:
if not isinstance(array, list):
return None
try:
for item in array:
# Rudimentary PEP 508 parsing.
item = item.split(";")[0]
item = EXTRAS_RE.sub("", item).strip()
if item == "black":
print(
"::error::Version specifier missing for 'black' dependency in "
"pyproject.toml.",
file=sys.stderr,
flush=True,
)
sys.exit(1)
elif m := BLACK_VERSION_RE.match(item):
return m.group(1).strip()
except TypeError:
pass
return None
run([sys.executable, "-m", "venv", str(ENV_PATH)], check=True) run([sys.executable, "-m", "venv", str(ENV_PATH)], check=True)
req = "black[colorama,python2]" version_specifier = determine_version_specifier()
if VERSION: if JUPYTER:
req += f"=={VERSION}" extra_deps = "[colorama,jupyter]"
else:
extra_deps = "[colorama]"
if version_specifier:
req = f"black{extra_deps}{version_specifier}"
else:
describe_name = ""
with open(ACTION_PATH / ".git_archival.txt", encoding="utf-8") as fp:
for line in fp:
if line.startswith("describe-name: "):
describe_name = line[len("describe-name: ") :].rstrip()
break
if not describe_name:
print("::error::Failed to detect action version.", file=sys.stderr, flush=True)
sys.exit(1)
# expected format is one of:
# - 23.1.0
# - 23.1.0-51-g448bba7
# - $Format:%(describe:tags=true,match=*[0-9]*)$ (if export-subst fails)
if (
describe_name.count("-") < 2
and EXPORT_SUBST_FAIL_RE.match(describe_name) is None
):
# the action's commit matches a tag exactly, install exact version from PyPI
req = f"black{extra_deps}=={describe_name}"
else:
# the action's commit does not match any tag, install from the local git repo
req = f".{extra_deps}"
print(f"Installing {req}...", flush=True)
pip_proc = run( pip_proc = run(
[str(ENV_BIN / "python"), "-m", "pip", "install", req], [str(ENV_BIN / "python"), "-m", "pip", "install", req],
stdout=PIPE, stdout=PIPE,
stderr=STDOUT, stderr=STDOUT,
encoding="utf-8", encoding="utf-8",
cwd=ACTION_PATH,
) )
if pip_proc.returncode: if pip_proc.returncode:
print(pip_proc.stdout) print(pip_proc.stdout)
print("::error::Failed to install Black.", flush=True) print("::error::Failed to install Black.", file=sys.stderr, flush=True)
sys.exit(pip_proc.returncode) sys.exit(pip_proc.returncode)
base_cmd = [str(ENV_BIN / "black")] base_cmd = [str(ENV_BIN / "black")]
if BLACK_ARGS: if BLACK_ARGS:
# TODO: remove after a while since this is deprecated in favour of SRC + OPTIONS. # TODO: remove after a while since this is deprecated in favour of SRC + OPTIONS.
proc = run([*base_cmd, *shlex.split(BLACK_ARGS)]) proc = run(
[*base_cmd, *shlex.split(BLACK_ARGS)],
stdout=PIPE,
stderr=STDOUT,
encoding="utf-8",
)
else: else:
proc = run([*base_cmd, *shlex.split(OPTIONS), *shlex.split(SRC)]) proc = run(
[*base_cmd, *shlex.split(OPTIONS), *shlex.split(SRC)],
stdout=PIPE,
stderr=STDOUT,
encoding="utf-8",
)
shutil.rmtree(ENV_PATH, ignore_errors=True)
print(proc.stdout)
sys.exit(proc.returncode) sys.exit(proc.returncode)

View File

@ -3,8 +3,13 @@ import collections
import os import os
import sys import sys
import vim import vim
from distutils.util import strtobool
def strtobool(text):
if text.lower() in ['y', 'yes', 't', 'true', 'on', '1']:
return True
if text.lower() in ['n', 'no', 'f', 'false', 'off', '0']:
return False
raise ValueError(f"{text} is not convertible to boolean")
class Flag(collections.namedtuple("FlagBase", "name, cast")): class Flag(collections.namedtuple("FlagBase", "name, cast")):
@property @property
@ -22,12 +27,14 @@ class Flag(collections.namedtuple("FlagBase", "name, cast")):
FLAGS = [ FLAGS = [
Flag(name="line_length", cast=int), Flag(name="line_length", cast=int),
Flag(name="fast", cast=strtobool), Flag(name="fast", cast=strtobool),
Flag(name="string_normalization", cast=strtobool), Flag(name="skip_string_normalization", cast=strtobool),
Flag(name="quiet", cast=strtobool), Flag(name="quiet", cast=strtobool),
Flag(name="skip_magic_trailing_comma", cast=strtobool),
Flag(name="preview", cast=strtobool),
] ]
def _get_python_binary(exec_prefix): def _get_python_binary(exec_prefix, pyver):
try: try:
default = vim.eval("g:pymode_python").strip() default = vim.eval("g:pymode_python").strip()
except vim.error: except vim.error:
@ -36,7 +43,15 @@ def _get_python_binary(exec_prefix):
return default return default
if sys.platform[:3] == "win": if sys.platform[:3] == "win":
return exec_prefix / 'python.exe' return exec_prefix / 'python.exe'
return exec_prefix / 'bin' / 'python3' bin_path = exec_prefix / "bin"
exec_path = (bin_path / f"python{pyver[0]}.{pyver[1]}").resolve()
if exec_path.exists():
return exec_path
# It is possible that some environments may only have python3
exec_path = (bin_path / f"python3").resolve()
if exec_path.exists():
return exec_path
raise ValueError("python executable not found")
def _get_pip(venv_path): def _get_pip(venv_path):
if sys.platform[:3] == "win": if sys.platform[:3] == "win":
@ -49,9 +64,19 @@ def _get_virtualenv_site_packages(venv_path, pyver):
return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages' return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages'
def _initialize_black_env(upgrade=False): def _initialize_black_env(upgrade=False):
if vim.eval("g:black_use_virtualenv ? 'true' : 'false'") == "false":
if upgrade:
print("Upgrade disabled due to g:black_use_virtualenv being disabled.")
print("Either use your system package manager (or pip) to upgrade black separately,")
print("or modify your vimrc to have 'let g:black_use_virtualenv = 1'.")
return False
else:
# Nothing needed to be done.
return True
pyver = sys.version_info[:3] pyver = sys.version_info[:3]
if pyver < (3, 6, 2): if pyver < (3, 9):
print("Sorry, Black requires Python 3.6.2+ to run.") print("Sorry, Black requires Python 3.9+ to run.")
return False return False
from pathlib import Path from pathlib import Path
@ -65,7 +90,7 @@ def _initialize_black_env(upgrade=False):
_executable = sys.executable _executable = sys.executable
_base_executable = getattr(sys, "_base_executable", _executable) _base_executable = getattr(sys, "_base_executable", _executable)
try: try:
executable = str(_get_python_binary(Path(sys.exec_prefix))) executable = str(_get_python_binary(Path(sys.exec_prefix), pyver))
sys.executable = executable sys.executable = executable
sys._base_executable = executable sys._base_executable = executable
print(f'Creating a virtualenv in {virtualenv_path}...') print(f'Creating a virtualenv in {virtualenv_path}...')
@ -98,13 +123,49 @@ if _initialize_black_env():
import black import black
import time import time
def Black(): def get_target_version(tv):
if isinstance(tv, black.TargetVersion):
return tv
ret = None
try:
ret = black.TargetVersion[tv.upper()]
except KeyError:
print(f"WARNING: Target version {tv!r} not recognized by Black, using default target")
return ret
def Black(**kwargs):
"""
kwargs allows you to override ``target_versions`` argument of
``black.FileMode``.
``target_version`` needs to be cleaned because ``black.FileMode``
expects the ``target_versions`` argument to be a set of TargetVersion enums.
Allow kwargs["target_version"] to be a string to allow
to type it more quickly.
Using also target_version instead of target_versions to remain
consistent to Black's documentation of the structure of pyproject.toml.
"""
start = time.time() start = time.time()
configs = get_configs() configs = get_configs()
black_kwargs = {}
if "target_version" in kwargs:
target_version = kwargs["target_version"]
if not isinstance(target_version, (list, set)):
target_version = [target_version]
target_version = set(filter(lambda x: x, map(lambda tv: get_target_version(tv), target_version)))
black_kwargs["target_versions"] = target_version
mode = black.FileMode( mode = black.FileMode(
line_length=configs["line_length"], line_length=configs["line_length"],
string_normalization=configs["string_normalization"], string_normalization=not configs["skip_string_normalization"],
is_pyi=vim.current.buffer.name.endswith('.pyi'), is_pyi=vim.current.buffer.name.endswith('.pyi'),
magic_trailing_comma=not configs["skip_magic_trailing_comma"],
preview=configs["preview"],
**black_kwargs,
) )
quiet = configs["quiet"] quiet = configs["quiet"]
@ -117,9 +178,9 @@ def Black():
) )
except black.NothingChanged: except black.NothingChanged:
if not quiet: if not quiet:
print(f'Already well formatted, good job. (took {time.time() - start:.4f}s)') print(f'Black: already well formatted, good job. (took {time.time() - start:.4f}s)')
except Exception as exc: except Exception as exc:
print(exc) print(f'Black: {exc}')
else: else:
current_buffer = vim.current.window.buffer current_buffer = vim.current.window.buffer
cursors = [] cursors = []
@ -136,17 +197,18 @@ def Black():
except vim.error: except vim.error:
window.cursor = (len(window.buffer), 0) window.cursor = (len(window.buffer), 0)
if not quiet: if not quiet:
print(f'Reformatted in {time.time() - start:.4f}s.') print(f'Black: reformatted in {time.time() - start:.4f}s.')
def get_configs(): def get_configs():
path_pyproject_toml = black.find_pyproject_toml(vim.eval("fnamemodify(getcwd(), ':t')")) filename = vim.eval("@%")
path_pyproject_toml = black.find_pyproject_toml((filename,))
if path_pyproject_toml: if path_pyproject_toml:
toml_config = black.parse_pyproject_toml(path_pyproject_toml) toml_config = black.parse_pyproject_toml(path_pyproject_toml)
else: else:
toml_config = {} toml_config = {}
return { return {
flag.var_name: flag.cast(toml_config.get(flag.name, vim.eval(flag.vim_rc_name))) flag.var_name: toml_config.get(flag.name, flag.cast(vim.eval(flag.vim_rc_name)))
for flag in FLAGS for flag in FLAGS
} }
@ -159,8 +221,17 @@ def BlackVersion():
EndPython3 EndPython3
function black#Black() function black#Black(...)
:py3 Black() let kwargs = {}
for arg in a:000
let arg_list = split(arg, '=')
let kwargs[arg_list[0]] = arg_list[1]
endfor
python3 << EOF
import vim
kwargs = vim.eval("kwargs")
EOF
:py3 Black(**kwargs)
endfunction endfunction
function black#BlackUpgrade() function black#BlackUpgrade()

View File

@ -17,4 +17,4 @@ help:
# Catch-all target: route all unknown targets to Sphinx using the new # Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile %: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@ -1,44 +0,0 @@
/* Make the sidebar scrollable. Fixes https://github.com/psf/black/issues/990 */
div.sphinxsidebar {
max-height: calc(100% - 18px);
overflow-y: auto;
}
/* Hide scrollbar for Chrome, Safari and Opera */
div.sphinxsidebar::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE 6, 7 and 8 */
@media \0screen\, screen\9 {
div.sphinxsidebar {
-ms-overflow-style: none;
}
}
/* Hide scrollbar for IE 9 and 10 */
/* backslash-9 removes ie11+ & old Safari 4 */
@media screen and (min-width: 0\0) {
div.sphinxsidebar {
-ms-overflow-style: none\9;
}
}
/* Hide scrollbar for IE 11 and up */
_:-ms-fullscreen,
:root div.sphinxsidebar {
-ms-overflow-style: none;
}
/* Hide scrollbar for Edge */
@supports (-ms-ime-align: auto) {
div.sphinxsidebar {
-ms-overflow-style: none;
}
}
/* Nicer style for local document toc */
.contents.topic {
background: none;
border: none;
}

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="78" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="78" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555" d="M0 0h47v20H0z"/><path fill="#7900CA" d="M47 0h31v20H47z"/><path fill="url(#b)" d="M0 0h78v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"><text x="245" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">license</text><text x="245" y="140" transform="scale(.1)" textLength="370">license</text><text x="615" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">MIT</text><text x="615" y="140" transform="scale(.1)" textLength="210">MIT</text></g> </svg> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="78" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="78" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555" d="M0 0h47v20H0z"/><path fill="#7900CA" d="M47 0h31v20H47z"/><path fill="url(#b)" d="M0 0h78v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"><text x="245" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">license</text><text x="245" y="140" transform="scale(.1)" textLength="370">license</text><text x="615" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">MIT</text><text x="615" y="140" transform="scale(.1)" textLength="210">MIT</text></g> </svg>

Before

Width:  |  Height:  |  Size: 949 B

After

Width:  |  Height:  |  Size: 950 B

View File

@ -1,3 +1,3 @@
[flake8] [flake8]
max-line-length = 88 max-line-length = 88
extend-ignore = E203 extend-ignore = E203,E701

View File

@ -1,3 +1,3 @@
[flake8] [flake8]
max-line-length = 88 max-line-length = 88
extend-ignore = E203 extend-ignore = E203,E701

View File

@ -1,3 +1,3 @@
[flake8] [flake8]
max-line-length = 88 max-line-length = 88
extend-ignore = E203 extend-ignore = E203,E701

View File

@ -0,0 +1,3 @@
[pycodestyle]
max-line-length = 88
ignore = E203,E701

View File

@ -0,0 +1,3 @@
[pycodestyle]
max-line-length = 88
ignore = E203,E701

View File

@ -0,0 +1,3 @@
[pycodestyle]
max-line-length = 88
ignore = E203,E701

View File

@ -1,5 +1,2 @@
[MESSAGES CONTROL]
disable = C0330, C0326
[format] [format]
max-line-length = 88 max-line-length = 88

View File

@ -1,5 +1,2 @@
[tool.pylint.messages_control]
disable = "C0330, C0326"
[tool.pylint.format] [tool.pylint.format]
max-line-length = "88" max-line-length = "88"

View File

@ -1,5 +1,2 @@
[pylint] [pylint]
max-line-length = 88 max-line-length = 88
[pylint.messages_control]
disable = C0330, C0326

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# #
# Configuration file for the Sphinx documentation builder. # Configuration file for the Sphinx documentation builder.
# #
@ -14,10 +13,12 @@
# #
import os import os
import re
import string import string
from importlib.metadata import version
from pathlib import Path from pathlib import Path
from pkg_resources import get_distribution from sphinx.application import Sphinx
CURRENT_DIR = Path(__file__).parent CURRENT_DIR = Path(__file__).parent
@ -25,12 +26,33 @@
def make_pypi_svg(version: str) -> None: def make_pypi_svg(version: str) -> None:
template: Path = CURRENT_DIR / "_static" / "pypi_template.svg" template: Path = CURRENT_DIR / "_static" / "pypi_template.svg"
target: Path = CURRENT_DIR / "_static" / "pypi.svg" target: Path = CURRENT_DIR / "_static" / "pypi.svg"
with open(str(template), "r", encoding="utf8") as f: with open(str(template), encoding="utf8") as f:
svg: str = string.Template(f.read()).substitute(version=version) svg: str = string.Template(f.read()).substitute(version=version)
with open(str(target), "w", encoding="utf8") as f: with open(str(target), "w", encoding="utf8") as f:
f.write(svg) f.write(svg)
def replace_pr_numbers_with_links(content: str) -> str:
"""Replaces all PR numbers with the corresponding GitHub link."""
return re.sub(r"#(\d+)", r"[#\1](https://github.com/psf/black/pull/\1)", content)
def handle_include_read(
app: Sphinx,
relative_path: Path,
parent_docname: str,
content: list[str],
) -> None:
"""Handler for the include-read sphinx event."""
if parent_docname == "change_log":
content[0] = replace_pr_numbers_with_links(content[0])
def setup(app: Sphinx) -> None:
"""Sets up a minimal sphinx extension."""
app.connect("include-read", handle_include_read)
# Necessary so Click doesn't hit an encode error when called by # Necessary so Click doesn't hit an encode error when called by
# sphinxcontrib-programoutput on Windows. # sphinxcontrib-programoutput on Windows.
os.putenv("pythonioencoding", "utf-8") os.putenv("pythonioencoding", "utf-8")
@ -43,7 +65,7 @@ def make_pypi_svg(version: str) -> None:
# Autopopulate version # Autopopulate version
# The version, including alpha/beta/rc tags, but not commit hash and datestamps # The version, including alpha/beta/rc tags, but not commit hash and datestamps
release = get_distribution("black").version.split("+")[0] release = version("black").split("+")[0]
# The short X.Y version. # The short X.Y version.
version = release version = release
for sp in "abcfr": for sp in "abcfr":
@ -55,7 +77,7 @@ def make_pypi_svg(version: str) -> None:
# -- General configuration --------------------------------------------------- # -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "3.0" needs_sphinx = "4.4"
# Add any Sphinx extension module names here, as strings. They can be # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@ -87,7 +109,7 @@ def make_pypi_svg(version: str) -> None:
# #
# This is also used if you do content translation via gettext catalogs. # This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases. # Usually you set "language" from the command line for these cases.
language = None language = "en"
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
@ -105,39 +127,22 @@ def make_pypi_svg(version: str) -> None:
# Prettier support formatting some MyST syntax but not all, so let's disable the # Prettier support formatting some MyST syntax but not all, so let's disable the
# unsupported yet still enabled by default ones. # unsupported yet still enabled by default ones.
myst_disable_syntax = [ myst_disable_syntax = [
"colon_fence",
"myst_block_break", "myst_block_break",
"myst_line_comment", "myst_line_comment",
"math_block", "math_block",
] ]
# Optional MyST Syntaxes
myst_enable_extensions = []
# -- Options for HTML output ------------------------------------------------- # -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
# #
html_theme = "alabaster" html_theme = "furo"
html_logo = "_static/logo2-readme.png"
html_sidebars = {
"**": [
"about.html",
"navigation.html",
"relations.html",
"searchbox.html",
]
}
html_theme_options = {
"show_related": False,
"description": "“Any color you like.”",
"github_button": True,
"github_user": "psf",
"github_repo": "black",
"github_type": "star",
"show_powered_by": True,
"fixed_sidebar": True,
"logo": "logo2.png",
}
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
@ -166,15 +171,13 @@ def make_pypi_svg(version: str) -> None:
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [(
( master_doc,
master_doc, "black.tex",
"black.tex", "Documentation for Black",
"Documentation for Black", "Łukasz Langa and contributors to Black",
"Łukasz Langa and contributors to Black", "manual",
"manual", )]
)
]
# -- Options for manual page output ------------------------------------------ # -- Options for manual page output ------------------------------------------
@ -189,17 +192,15 @@ def make_pypi_svg(version: str) -> None:
# Grouping the document tree into Texinfo files. List of tuples # Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [(
( master_doc,
master_doc, "Black",
"Black", "Documentation for Black",
"Documentation for Black", author,
author, "Black",
"Black", "The uncompromising Python code formatter",
"The uncompromising Python code formatter", "Miscellaneous",
"Miscellaneous", )]
)
]
# -- Options for Epub output ------------------------------------------------- # -- Options for Epub output -------------------------------------------------
@ -227,7 +228,14 @@ def make_pypi_svg(version: str) -> None:
autodoc_member_order = "bysource" autodoc_member_order = "bysource"
# -- sphinx-copybutton configuration ----------------------------------------
copybutton_prompt_text = (
r">>> |\.\.\. |> |\$ |\# | In \[\d*\]: | {2,5}\.\.\.: | {5,8}: "
)
copybutton_prompt_is_regexp = True
copybutton_remove_prompts = True
# -- Options for intersphinx extension --------------------------------------- # -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"https://docs.python.org/3/": None} intersphinx_mapping = {"<name>": ("https://docs.python.org/3/", None)}

View File

@ -7,36 +7,52 @@ It's recommended you evaluate the quantifiable changes your _Black_ formatting
modification causes before submitting a PR. Think about if the change seems disruptive modification causes before submitting a PR. Think about if the change seems disruptive
enough to cause frustration to projects that are already "black formatted". enough to cause frustration to projects that are already "black formatted".
## black-primer ## diff-shades
`black-primer` is a tool built for CI (and humans) to have _Black_ `--check` a number of diff-shades is a tool that runs _Black_ across a list of open-source projects recording
Git accessible projects in parallel. (configured in `primer.json`) _(A PR will be the results. The main highlight feature of diff-shades is being able to compare two
accepted to add Mercurial support.)_ revisions of _Black_. This is incredibly useful as it allows us to see what exact
changes will occur, say merging a certain PR.
### Run flow For more information, please see the [diff-shades documentation][diff-shades].
- Ensure we have a `black` + `git` in PATH ### CI integration
- Load projects from `primer.json`
- Run projects in parallel with `--worker` workers (defaults to CPU count / 2)
- Checkout projects
- Run black and record result
- Clean up repository checkout _(can optionally be disabled via `--keep`)_
- Display results summary to screen
- Default to cleaning up `--work-dir` (which defaults to tempfile schemantics)
- Return
- 0 for successful run
- \< 0 for environment / internal error
- \> 0 for each project with an error
### Speed up runs 🏎 diff-shades is also the tool behind the "diff-shades results comparing ..." /
"diff-shades reports zero changes ..." comments on PRs. The project has a GitHub Actions
workflow that analyzes and compares two revisions of _Black_ according to these rules:
If you're running locally yourself to test black on lots of code try: | | Baseline revision | Target revision |
| --------------------- | ----------------------- | ---------------------------- |
| On PRs | latest commit on `main` | PR commit with `main` merged |
| On pushes (main only) | latest PyPI version | the pushed commit |
- Using `-k` / `--keep` + `-w` / `--work-dir` so you don't have to re-checkout the repo For pushes to main, there's only one analysis job named `preview-changes` where the
each run preview style is used for all projects.
### CLI arguments For PRs they get one more analysis job: `assert-no-changes`. It's similar to
`preview-changes` but runs with the stable code style. It will fail if changes were
made. This makes sure code won't be reformatted again and again within the same year in
accordance to Black's stability policy.
```{program-output} black-primer --help Additionally for PRs, a PR comment will be posted embedding a summary of the preview
changes and links to further information. If there's a pre-existing diff-shades comment,
it'll be updated instead the next time the workflow is triggered on the same PR.
```{note}
The `preview-changes` job will only fail intentionally if while analyzing a file failed to
format. Otherwise a failure indicates a bug in the workflow.
``` ```
The workflow uploads several artifacts upon completion:
- The raw analyses (.json)
- HTML diffs (.html)
- `.pr-comment.json` (if triggered by a PR)
The last one is downloaded by the `diff-shades-comment` workflow and shouldn't be
downloaded locally. The HTML diffs come in handy for push-based where there's no PR to
post a comment. And the analyses exist just in case you want to do further analysis
using the collected data locally.
[diff-shades]: https://github.com/ichard26/diff-shades#readme

View File

@ -0,0 +1,45 @@
# Contributing
```{toctree}
---
hidden:
---
the_basics
gauging_changes
issue_triage
release_process
```
Welcome! Happy to see you willing to make the project better. Have you read the entire
[user documentation](https://black.readthedocs.io/en/latest/) yet?
```{rubric} Bird's eye view
```
In terms of inspiration, _Black_ is about as configurable as _gofmt_ (which is to say,
not very). This is deliberate. _Black_ aims to provide a consistent style and take away
opportunities for arguing about style.
Bug reports and fixes are always welcome! Please follow the
[issue templates on GitHub](https://github.com/psf/black/issues/new/choose) for best
results.
Before you suggest a new feature or configuration knob, ask yourself why you want it. If
it enables better integration with some workflow, fixes an inconsistency, speeds things
up, and so on - go for it! On the other hand, if your answer is "because I don't like a
particular formatting" then you're not ready to embrace _Black_ yet. Such changes are
unlikely to get accepted. You can still try but prepare to be disappointed.
```{rubric} Contents
```
This section covers the following topics:
- {doc}`the_basics`
- {doc}`gauging_changes`
- {doc}`release_process`
For an overview on contributing to the _Black_, please checkout {doc}`the_basics`.

View File

@ -1,42 +0,0 @@
Contributing
============
.. toctree::
:hidden:
the_basics
gauging_changes
issue_triage
release_process
reference/reference_summary
Welcome! Happy to see you willing to make the project better. Have you read the entire
`user documentation <https://black.readthedocs.io/en/latest/>`_ yet?
.. rubric:: Bird's eye view
In terms of inspiration, *Black* is about as configurable as *gofmt*. This is
deliberate.
Bug reports and fixes are always welcome! Please follow the
`issue template on GitHub <https://github.com/psf/black/issues/new>`_ for best results.
Before you suggest a new feature or configuration knob, ask yourself why you want it. If
it enables better integration with some workflow, fixes an inconsistency, speeds things
up, and so on - go for it! On the other hand, if your answer is "because I don't like a
particular formatting" then you're not ready to embrace *Black* yet. Such changes are
unlikely to get accepted. You can still try but prepare to be disappointed.
.. rubric:: Contents
This section covers the following topics:
- :doc:`the_basics`
- :doc:`gauging_changes`
- :doc:`release_process`
- :doc:`reference/reference_summary`
For an overview on contributing to the *Black*, please checkout :doc:`the_basics`.
If you need a reference of the functions, classes, etc. available to you while
developing *Black*, there's the :doc:`reference/reference_summary` docs.

View File

@ -1,6 +1,6 @@
# Issue triage # Issue triage
Currently, _Black_ uses the issue tracker for bugs, feature requests, proposed design Currently, _Black_ uses the issue tracker for bugs, feature requests, proposed style
modifications, and general user support. Each of these issues have to be triaged so they modifications, and general user support. Each of these issues have to be triaged so they
can be eventually be resolved somehow. This document outlines the triaging process and can be eventually be resolved somehow. This document outlines the triaging process and
also the current guidelines and recommendations. also the current guidelines and recommendations.
@ -42,7 +42,7 @@ The lifecycle of a bug report or user support issue typically goes something lik
1. _the issue is waiting for triage_ 1. _the issue is waiting for triage_
2. **identified** - has been marked with a type label and other relevant labels, more 2. **identified** - has been marked with a type label and other relevant labels, more
details or a functional reproduction may be still needed (and therefore should be details or a functional reproduction may be still needed (and therefore should be
marked with `S: needs repro` or `S: awaiting reponse`) marked with `S: needs repro` or `S: awaiting response`)
3. **confirmed** - the issue can reproduced and necessary details have been provided 3. **confirmed** - the issue can reproduced and necessary details have been provided
4. **discussion** - initial triage has been done and now the general details on how the 4. **discussion** - initial triage has been done and now the general details on how the
issue should be best resolved are being hashed out issue should be best resolved are being hashed out
@ -53,13 +53,13 @@ The lifecycle of a bug report or user support issue typically goes something lik
- the issue has been fixed - the issue has been fixed
- duplicate of another pre-existing issue or is invalid - duplicate of another pre-existing issue or is invalid
For enhancement, documentation, and design issues, the lifecycle looks very similar but For enhancement, documentation, and style issues, the lifecycle looks very similar but
the details are different: the details are different:
1. _the issue is waiting for triage_ 1. _the issue is waiting for triage_
2. **identified** - has been marked with a type label and other relevant labels 2. **identified** - has been marked with a type label and other relevant labels
3. **discussion** - the merits of the suggested changes are currently being discussed, a 3. **discussion** - the merits of the suggested changes are currently being discussed, a
PR would be acceptable but would be at sigificant risk of being rejected PR would be acceptable but would be at significant risk of being rejected
4. **accepted & awaiting PR** - it's been determined the suggested changes are OK and a 4. **accepted & awaiting PR** - it's been determined the suggested changes are OK and a
PR would be welcomed (`S: accepted`) PR would be welcomed (`S: accepted`)
5. **closed**: - the issue has been resolved, reasons include: 5. **closed**: - the issue has been resolved, reasons include:

View File

@ -1,76 +0,0 @@
*Black* classes
===============
*Contents are subject to change.*
.. currentmodule:: black
:class:`BracketTracker`
-----------------------
.. autoclass:: black.brackets.BracketTracker
:members:
:class:`EmptyLineTracker`
-------------------------
.. autoclass:: black.EmptyLineTracker
:members:
:class:`Line`
-------------
.. autoclass:: black.Line
:members:
:special-members: __str__, __bool__
:class:`LineGenerator`
----------------------
.. autoclass:: black.LineGenerator
:show-inheritance:
:members:
:class:`ProtoComment`
---------------------
.. autoclass:: black.comments.ProtoComment
:members:
:class:`Report`
---------------
.. autoclass:: black.Report
:members:
:special-members: __str__
:class:`Visitor`
----------------
.. autoclass:: black.nodes.Visitor
:show-inheritance:
:members:
Enums
=====
:class:`Changed`
----------------
.. autoclass:: black.Changed
:show-inheritance:
:members:
:class:`Mode`
-----------------
.. autoclass:: black.Mode
:show-inheritance:
:members:
:class:`WriteBack`
------------------
.. autoclass:: black.WriteBack
:show-inheritance:
:members:

View File

@ -1,12 +0,0 @@
*Black* exceptions
==================
*Contents are subject to change.*
.. currentmodule:: black
.. autoexception:: black.linegen.CannotSplit
.. autoexception:: black.NothingChanged
.. autoexception:: black.InvalidInput

View File

@ -1,178 +0,0 @@
*Black* functions
=================
*Contents are subject to change.*
.. currentmodule:: black
Assertions and checks
---------------------
.. autofunction:: black.assert_equivalent
.. autofunction:: black.assert_stable
.. autofunction:: black.lines.can_be_split
.. autofunction:: black.lines.can_omit_invisible_parens
.. autofunction:: black.nodes.is_empty_tuple
.. autofunction:: black.nodes.is_import
.. autofunction:: black.lines.is_line_short_enough
.. autofunction:: black.nodes.is_multiline_string
.. autofunction:: black.nodes.is_one_tuple
.. autofunction:: black.brackets.is_split_after_delimiter
.. autofunction:: black.brackets.is_split_before_delimiter
.. autofunction:: black.nodes.is_stub_body
.. autofunction:: black.nodes.is_stub_suite
.. autofunction:: black.nodes.is_vararg
.. autofunction:: black.nodes.is_yield
Formatting
----------
.. autofunction:: black.format_file_contents
.. autofunction:: black.format_file_in_place
.. autofunction:: black.format_stdin_to_stdout
.. autofunction:: black.format_str
.. autofunction:: black.reformat_one
.. autofunction:: black.schedule_formatting
File operations
---------------
.. autofunction:: black.dump_to_file
.. autofunction:: black.find_project_root
.. autofunction:: black.gen_python_files
.. autofunction:: black.read_pyproject_toml
Parsing
-------
.. autofunction:: black.decode_bytes
.. autofunction:: black.parsing.lib2to3_parse
.. autofunction:: black.parsing.lib2to3_unparse
Split functions
---------------
.. autofunction:: black.linegen.bracket_split_build_line
.. autofunction:: black.linegen.bracket_split_succeeded_or_raise
.. autofunction:: black.linegen.delimiter_split
.. autofunction:: black.linegen.left_hand_split
.. autofunction:: black.linegen.right_hand_split
.. autofunction:: black.linegen.standalone_comment_split
.. autofunction:: black.linegen.transform_line
Caching
-------
.. autofunction:: black.cache.filter_cached
.. autofunction:: black.cache.get_cache_file
.. autofunction:: black.cache.get_cache_info
.. autofunction:: black.cache.read_cache
.. autofunction:: black.cache.write_cache
Utilities
---------
.. py:function:: black.debug.DebugVisitor.show(code: str) -> None
Pretty-print the lib2to3 AST of a given string of `code`.
.. autofunction:: black.concurrency.cancel
.. autofunction:: black.nodes.child_towards
.. autofunction:: black.nodes.container_of
.. autofunction:: black.comments.convert_one_fmt_off_pair
.. autofunction:: black.diff
.. autofunction:: black.linegen.dont_increase_indentation
.. autofunction:: black.numerics.format_float_or_int_string
.. autofunction:: black.nodes.ensure_visible
.. autofunction:: black.lines.enumerate_reversed
.. autofunction:: black.comments.generate_comments
.. autofunction:: black.comments.generate_ignored_nodes
.. autofunction:: black.comments.is_fmt_on
.. autofunction:: black.comments.contains_fmt_on_at_column
.. autofunction:: black.nodes.first_leaf_column
.. autofunction:: black.linegen.generate_trailers_to_omit
.. autofunction:: black.get_future_imports
.. autofunction:: black.comments.list_comments
.. autofunction:: black.comments.make_comment
.. autofunction:: black.linegen.maybe_make_parens_invisible_in_atom
.. autofunction:: black.brackets.max_delimiter_priority_in_atom
.. autofunction:: black.normalize_fmt_off
.. autofunction:: black.numerics.normalize_numeric_literal
.. autofunction:: black.linegen.normalize_prefix
.. autofunction:: black.strings.normalize_string_prefix
.. autofunction:: black.strings.normalize_string_quotes
.. autofunction:: black.linegen.normalize_invisible_parens
.. autofunction:: black.patch_click
.. autofunction:: black.nodes.preceding_leaf
.. autofunction:: black.re_compile_maybe_verbose
.. autofunction:: black.linegen.should_split_line
.. autofunction:: black.shutdown
.. autofunction:: black.strings.sub_twice
.. autofunction:: black.nodes.whitespace

View File

@ -1,16 +0,0 @@
Developer reference
===================
.. note::
The documentation here is quite outdated and has been neglected. Many objects worthy
of inclusion aren't documented. Contributions are appreciated!
*Contents are subject to change.*
.. toctree::
:maxdepth: 2
reference_classes
reference_functions
reference_exceptions

View File

@ -1,89 +1,174 @@
# Release process # Release process
_Black_ has had a lot of work automating its release process. This document sets out to _Black_ has had a lot of work done into standardizing and automating its release
explain what everything does and how to release _Black_ using said automation. process. This document sets out to explain how everything works and how to release
_Black_ using said automation.
## Cutting a Release ## Release cadence
To cut a release, you must be a _Black_ maintainer with `GitHub Release` creation **We aim to release whatever is on `main` every 1-2 months.** This ensures merged
access. Using this access, the release process is: improvements and bugfixes are shipped to users reasonably quickly, while not massively
fracturing the user-base with too many versions. This also keeps the workload on
maintainers consistent and predictable.
1. Cut a new PR editing `CHANGES.md` to version the latest changes If there's not much new on `main` to justify a release, it's acceptable to skip a
1. Example PR: https://github.com/psf/black/pull/2192 month's release. Ideally January releases should not be skipped because as per our
2. Example title: `Update CHANGES.md for XX.X release` [stability policy](labels/stability-policy), the first release in a new calendar year
2. Once the release PR is merged ensure all CI passes may make changes to the _stable_ style. While the policy applies to the first release
1. If not, ensure there is an Issue open for the cause of failing CI (generally we'd (instead of only January releases), confining changes to the stable style to January
want this fixed before cutting a release) will keep things predictable (and nicer) for users.
3. Open `CHANGES.md` and copy the _raw markdown_ of the latest changes to use in the
description of the GitHub Release.
4. Go and [cut a release](https://github.com/psf/black/releases) using the GitHub UI so
that all workflows noted below are triggered.
1. The release version and tag should be the [CalVer](https://calver.org) version
_Black_ used for the current release e.g. `21.6` / `21.5b1`
2. _Black_ uses [setuptools scm](https://pypi.org/project/setuptools-scm/) to pull
the current version for the package builds and release.
5. Once the release is cut, you're basically done. It's a good practice to go and watch
to make sure all the [GitHub Actions](https://github.com/psf/black/actions) pass,
although you should receive an email to your registered GitHub email address should
one fail.
1. You should see all the release workflows and lint/unittests workflows running on
the new tag in the Actions UI
If anything fails, please go read the respective action's log output and configuration Unless there is a serious regression or bug that requires immediate patching, **there
file to reverse engineer your way to a fix/soluton. should not be more than one release per month**. While version numbers are cheap,
releases require a maintainer to both commit to do the actual cutting of a release, but
also to be able to deal with the potential fallout post-release. Releasing more
frequently than monthly nets rapidly diminishing returns.
## Cutting a release
**You must have `write` permissions for the _Black_ repository to cut a release.**
The 10,000 foot view of the release process is that you prepare a release PR and then
publish a [GitHub Release]. This triggers [release automation](#release-workflows) that
builds all release artifacts and publishes them to the various platforms we publish to.
We now have a `scripts/release.py` script to help with cutting the release PRs.
- `python3 scripts/release.py --help` is your friend.
- `release.py` has only been tested in Python 3.12 (so get with the times :D)
To cut a release:
1. Determine the release's version number
- **_Black_ follows the [CalVer] versioning standard using the `YY.M.N` format**
- So unless there already has been a release during this month, `N` should be `0`
- Example: the first release in January, 2022 → `22.1.0`
- `release.py` will calculate this and log to stderr for you copy paste pleasure
1. File a PR editing `CHANGES.md` and the docs to version the latest changes
- Run `python3 scripts/release.py [--debug]` to generate most changes
- Sub headings in the template, if they have no bullet points need manual removal
_PR welcome to improve :D_
1. If `release.py` fail manually edit; otherwise, yay, skip this step!
1. Replace the `## Unreleased` header with the version number
1. Remove any empty sections for the current release
1. (_optional_) Read through and copy-edit the changelog (eg. by moving entries,
fixing typos, or rephrasing entries)
1. Double-check that no changelog entries since the last release were put in the
wrong section (e.g., run `git diff <last release> CHANGES.md`)
1. Update references to the latest version in
{doc}`/integrations/source_version_control` and
{doc}`/usage_and_configuration/the_basics`
- Example PR: [GH-3139]
1. Once the release PR is merged, wait until all CI passes
- If CI does not pass, **stop** and investigate the failure(s) as generally we'd want
to fix failing CI before cutting a release
1. [Draft a new GitHub Release][new-release]
1. Click `Choose a tag` and type in the version number, then select the
`Create new tag: YY.M.N on publish` option that appears
1. Verify that the new tag targets the `main` branch
1. You can leave the release title blank, GitHub will default to the tag name
1. Copy and paste the _raw changelog Markdown_ for the current release into the
description box
1. Publish the GitHub Release, triggering [release automation](#release-workflows) that
will handle the rest
1. Once CI is done add + commit (git push - No review) a new empty template for the next
release to CHANGES.md _(Template is able to be copy pasted from release.py should we
fail)_
1. `python3 scripts/release.py --add-changes-template|-a [--debug]`
1. Should that fail, please return to copy + paste
1. At this point, you're basically done. It's good practice to go and [watch and verify
that all the release workflows pass][black-actions], although you will receive a
GitHub notification should something fail.
- If something fails, don't panic. Please go read the respective workflow's logs and
configuration file to reverse-engineer your way to a fix/solution.
Congratulations! You've successfully cut a new release of _Black_. Go and stand up and
take a break, you deserve it.
```{important}
Once the release artifacts reach PyPI, you may see new issues being filed indicating
regressions. While regressions are not great, they don't automatically mean a hotfix
release is warranted. Unless the regressions are serious and impact many users, a hotfix
release is probably unnecessary.
In the end, use your best judgement and ask other maintainers for their thoughts.
```
## Release workflows ## Release workflows
All _Blacks_'s automation workflows use GitHub Actions. All workflows are therefore All of _Black_'s release automation uses [GitHub Actions]. All workflows are therefore
configured using `.yml` files in the `.github/workflows` directory of the _Black_ configured using YAML files in the `.github/workflows` directory of the _Black_
repository. repository.
They are triggered by the publication of a [GitHub Release].
Below are descriptions of our release workflows. Below are descriptions of our release workflows.
### Docker ### Publish to PyPI
This workflow uses the QEMU powered `buildx` feature of docker to upload a `arm64` and This is our main workflow. It builds an [sdist] and [wheels] to upload to PyPI where the
`amd64`/`x86_64` build of the official _Black_ docker image™. vast majority of users will download Black from. It's divided into three job groups:
- Currently this workflow uses an API Token associated with @cooperlees account #### sdist + pure wheel
### pypi_upload This single job builds the sdist and pure Python wheel (i.e., a wheel that only contains
Python code) using [build] and then uploads them to PyPI using [twine]. These artifacts
are general-purpose and can be used on basically any platform supported by Python.
This workflow builds a Python #### mypyc wheels (…)
[sdist](https://docs.python.org/3/distutils/sourcedist.html) and
[wheel](https://pythonwheels.com) using the latest
[setuptools](https://pypi.org/project/setuptools/) and
[wheel](https://pypi.org/project/wheel/) modules.
It will then use [twine](https://pypi.org/project/twine/) to upload both release formats We use [mypyc] to compile _Black_ into a CPython C extension for significantly improved
to PyPI for general downloading of the _Black_ Python package. This is where performance. Wheels built with mypyc are platform and Python version specific.
[pip](https://pypi.org/project/pip/) looks by default. [Supported platforms are documented in the FAQ](labels/mypyc-support).
- Currently this workflow uses an API token associated with @ambv's PyPI account These matrix jobs use [cibuildwheel] which handles the complicated task of building C
extensions for many environments for us. Since building these wheels is slow, there are
multiple mypyc wheels jobs (hence the term "matrix") that build for a specific platform
(as noted in the job name in parentheses).
### Upload self-contained binaries Like the previous job group, the built wheels are uploaded to PyPI using [twine].
This workflow builds self-contained binaries for multiple platforms. This allows people #### Update stable branch
to download the executable for their platform and run _Black_ without a
[Python Runtime](https://wiki.python.org/moin/PythonImplementations) installed.
The created binaries are attached/stored on the associated So this job doesn't _really_ belong here, but updating the `stable` branch after the
[GitHub Release](https://github.com/psf/black/releases) for download over _IPv4 only_ other PyPI jobs pass (they must pass for this job to start) makes the most sense. This
(GitHub still does not have IPv6 access 😢). saves us from remembering to update the branch sometime after cutting the release.
## Moving the `stable` tag - _Currently this workflow uses an API token associated with @ambv's PyPI account_
_Black_ provides a stable tag for people who want to move along as _Black_ developers ### Publish executables
deem the newest version reliable. Here the _Black_ developers will move once the release
has been problem free for at least ~24 hours from release. Given the large _Black_
userbase we hear about bad bugs quickly. We do strive to continually improve our CI too.
### Tag moving process This workflow builds native executables for multiple platforms using [PyInstaller]. This
allows people to download the executable for their platform and run _Black_ without a
[Python runtime](https://wiki.python.org/moin/PythonImplementations) installed.
#### stable The created binaries are stored on the associated GitHub Release for download over _IPv4
only_ (GitHub still does not have IPv6 access 😢).
From a rebased `main` checkout: ### docker
1. `git tag -f stable VERSION_TAG` This workflow uses the QEMU powered `buildx` feature of Docker to upload an `arm64` and
1. e.g. `git tag -f stable 21.5b1` `amd64`/`x86_64` build of the official _Black_ Docker image™.
1. `git push --tags -f`
- _Currently this workflow uses an API Token associated with @cooperlees account_
```{note}
This also runs on each push to `main`.
```
[black-actions]: https://github.com/psf/black/actions
[build]: https://pypa-build.readthedocs.io/
[calver]: https://calver.org
[cibuildwheel]: https://cibuildwheel.readthedocs.io/
[gh-3139]: https://github.com/psf/black/pull/3139
[github actions]: https://github.com/features/actions
[github release]: https://github.com/psf/black/releases
[new-release]: https://github.com/psf/black/releases/new
[mypyc]: https://mypyc.readthedocs.io/
[mypyc-platform-support]:
/faq.html#what-is-compiled-yes-no-all-about-in-the-version-output
[pyinstaller]: https://www.pyinstaller.org/
[sdist]:
https://packaging.python.org/en/latest/glossary/#term-Source-Distribution-or-sdist
[twine]: https://github.com/features/actions
[wheels]: https://packaging.python.org/en/latest/glossary/#term-Wheel

View File

@ -4,26 +4,27 @@ An overview on contributing to the _Black_ project.
## Technicalities ## Technicalities
Development on the latest version of Python is preferred. As of this writing it's 3.9. Development on the latest version of Python is preferred. You can use any operating
You can use any operating system. system.
Install all development dependencies using: First clone the _Black_ repository:
```console ```console
$ pipenv install --dev $ git clone https://github.com/psf/black.git
$ pipenv shell $ cd black
$ pre-commit install
``` ```
If you haven't used `pipenv` before but are comfortable with virtualenvs, just run Then install development dependencies inside a virtual environment of your choice, for
`pip install pipenv` in the virtualenv you're already using and invoke the command above example:
from the cloned _Black_ repo. It will do the correct thing.
Non pipenv install works too:
```console ```console
$ pip install -r test_requirements.txt $ python3 -m venv .venv
$ pip install -e .[d] $ source .venv/bin/activate # activation for linux and mac
$ .venv\Scripts\activate # activation for windows
(.venv)$ pip install -r test_requirements.txt
(.venv)$ pip install -e ".[d]"
(.venv)$ pre-commit install
``` ```
Before submitting pull requests, run lints and tests with the following commands from Before submitting pull requests, run lints and tests with the following commands from
@ -31,69 +32,125 @@ the root of the black repo:
```console ```console
# Linting # Linting
$ pre-commit run -a (.venv)$ pre-commit run -a
# Unit tests # Unit tests
$ tox -e py (.venv)$ tox -e py
# Optional Fuzz testing # Optional Fuzz testing
$ tox -e fuzz (.venv)$ tox -e fuzz
# Optional CI run to test your changes on many popular python projects # Format Black itself
$ black-primer [-k -w /tmp/black_test_repos] (.venv)$ tox -e run_self
``` ```
### Development
Further examples of invoking the tests
```console
# Run all of the above mentioned, in parallel
(.venv)$ tox --parallel=auto
# Run tests on a specific python version
(.venv)$ tox -e py39
# Run an individual test
(.venv)$ pytest -k <test name>
# Pass arguments to pytest
(.venv)$ tox -e py -- --no-cov
# Print full tree diff, see documentation below
(.venv)$ tox -e py -- --print-full-tree
# Disable diff printing, see documentation below
(.venv)$ tox -e py -- --print-tree-diff=False
```
### Testing
All aspects of the _Black_ style should be tested. Normally, tests should be created as
files in the `tests/data/cases` directory. These files consist of up to three parts:
- A line that starts with `# flags: ` followed by a set of command-line options. For
example, if the line is `# flags: --preview --skip-magic-trailing-comma`, the test
case will be run with preview mode on and the magic trailing comma off. The options
accepted are mostly a subset of those of _Black_ itself, except for the
`--minimum-version=` flag, which should be used when testing a grammar feature that
works only in newer versions of Python. This flag ensures that we don't try to
validate the AST on older versions and tests that we autodetect the Python version
correctly when the feature is used. For the exact flags accepted, see the function
`get_flags_parser` in `tests/util.py`. If this line is omitted, the default options
are used.
- A block of Python code used as input for the formatter.
- The line `# output`, followed by the output of _Black_ when run on the previous block.
If this is omitted, the test asserts that _Black_ will leave the input code unchanged.
_Black_ has two pytest command-line options affecting test files in `tests/data/` that
are split into an input part, and an output part, separated by a line with`# output`.
These can be passed to `pytest` through `tox`, or directly into pytest if not using
`tox`.
#### `--print-full-tree`
Upon a failing test, print the full concrete syntax tree (CST) as it is after processing
the input ("actual"), and the tree that's yielded after parsing the output ("expected").
Note that a test can fail with different output with the same CST. This used to be the
default, but now defaults to `False`.
#### `--print-tree-diff`
Upon a failing test, print the diff of the trees as described above. This is the
default. To turn it off pass `--print-tree-diff=False`.
### News / Changelog Requirement ### News / Changelog Requirement
`Black` has CI that will check for an entry corresponding to your PR in `CHANGES.md`. If `Black` has CI that will check for an entry corresponding to your PR in `CHANGES.md`. If
you feel this PR does not require a changelog entry please state that in a comment and a you feel this PR does not require a changelog entry please state that in a comment and a
maintainer can add a `skip news` label to make the CI pass. Otherwise, please ensure you maintainer can add a `skip news` label to make the CI pass. Otherwise, please ensure you
have a line in the following format: have a line in the following format added below the appropriate header:
```md ```md
- `Black` is now more awesome (#X) - `Black` is now more awesome (#X)
``` ```
<!---
The Next PR Number link uses HTML because of a bug in MyST-Parser that double-escapes the ampersand, causing the query parameters to not be processed.
MyST-Parser issue: https://github.com/executablebooks/MyST-Parser/issues/760
MyST-Parser stalled fix PR: https://github.com/executablebooks/MyST-Parser/pull/929
-->
Note that X should be your PR number, not issue number! To workout X, please use Note that X should be your PR number, not issue number! To workout X, please use
[Next PR Number](https://ichard26.github.io/next-pr-number/?owner=psf&name=black). This <a href="https://ichard26.github.io/next-pr-number/?owner=psf&name=black">Next PR
is not perfect but saves a lot of release overhead as now the releaser does not need to Number</a>. This is not perfect but saves a lot of release overhead as now the releaser
go back and workout what to add to the `CHANGES.md` for each release. does not need to go back and workout what to add to the `CHANGES.md` for each release.
### Style Changes ### Style Changes
If a change would affect the advertised code style, please modify the documentation (The If a change would affect the advertised code style, please modify the documentation (The
_Black_ code style) to reflect that change. Patches that fix unintended bugs in _Black_ code style) to reflect that change. Patches that fix unintended bugs in
formatting don't need to be mentioned separately though. formatting don't need to be mentioned separately though. If the change is implemented
with the `--preview` flag, please include the change in the future style document
instead and write the changelog entry under the dedicated "Preview style" heading.
### Docs Testing ### Docs Testing
If you make changes to docs, you can test they still build locally too. If you make changes to docs, you can test they still build locally too.
```console ```console
$ pip install -r docs/requirements.txt (.venv)$ pip install -r docs/requirements.txt
$ pip install [-e] .[d] (.venv)$ pip install -e ".[d]"
$ sphinx-build -a -b html -W docs/ docs/_build/ (.venv)$ sphinx-build -a -b html -W docs/ docs/_build/
``` ```
## black-primer
`black-primer` is used by CI to pull down well-known _Black_ formatted projects and see
if we get source code changes. It will error on formatting changes or errors. Please run
before pushing your PR to see if you get the actions you would expect from _Black_ with
your PR. You may need to change
[primer.json](https://github.com/psf/black/blob/main/src/black_primer/primer.json)
configuration for it to pass.
For more `black-primer` information visit the
[documentation](./gauging_changes.md#black-primer).
## Hygiene ## Hygiene
If you're fixing a bug, add a test. Run it first to confirm it fails, then fix the bug, If you're fixing a bug, add a test. Run it first to confirm it fails, then fix the bug,
run it again to confirm it's really fixed. and run the test again to confirm it's really fixed.
If adding a new feature, add a test. In fact, always add a test. But wait, before adding If adding a new feature, add a test. In fact, always add a test. If adding a large
any large feature, first open an issue for us to discuss the idea first. feature, please first open an issue to discuss it beforehand.
## Finally ## Finally

View File

@ -5,20 +5,32 @@ The most common questions and issues users face are aggregated to this FAQ.
```{contents} ```{contents}
:local: :local:
:backlinks: none :backlinks: none
:class: this-will-duplicate-information-and-it-is-still-useful-here
``` ```
## Why spaces? I prefer tabs
PEP 8 recommends spaces over tabs, and they are used by most of the Python community.
_Black_ provides no options to configure the indentation style, and requests for such
options will not be considered.
However, we recognise that using tabs is an accessibility issue as well. While the
option will never be added to _Black_, visually impaired developers may find conversion
tools such as `expand/unexpand` (for Linux) useful when contributing to Python projects.
A workflow might consist of e.g. setting up appropriate pre-commit and post-merge git
hooks, and scripting `unexpand` to run after applying _Black_.
## Does Black have an API? ## Does Black have an API?
Not yet. _Black_ is fundamentally a command line tool. Many Not yet. _Black_ is fundamentally a command line tool. Many
[integrations](integrations/index.rst) are provided, but a Python interface is not one [integrations](/integrations/index.md) are provided, but a Python interface is not one
of them. A simple API is being [planned](https://github.com/psf/black/issues/779) of them. A simple API is being [planned](https://github.com/psf/black/issues/779)
though. though.
## Is Black safe to use? ## Is Black safe to use?
Yes, for the most part. _Black_ is strictly about formatting, nothing else. But because Yes. _Black_ is strictly about formatting, nothing else. Black strives to ensure that
_Black_ is still in [beta](index.rst), some edges are still a bit rough. To combat after formatting the AST is
issues, the equivalence of code after formatting is
[checked](the_black_code_style/current_style.md#ast-before-and-after-formatting) with [checked](the_black_code_style/current_style.md#ast-before-and-after-formatting) with
limited special cases where the code is allowed to differ. If issues are found, an error limited special cases where the code is allowed to differ. If issues are found, an error
is raised and the file is left untouched. Magical comments that influence linters and is raised and the file is left untouched. Magical comments that influence linters and
@ -26,10 +38,13 @@ other tools, such as `# noqa`, may be moved by _Black_. See below for more detai
## How stable is Black's style? ## How stable is Black's style?
Quite stable. _Black_ aims to enforce one style and one style only, with some room for Stable. _Black_ aims to enforce one style and one style only, with some room for
pragmatism. However, _Black_ is still in beta so style changes are both planned and pragmatism. See [The Black Code Style](the_black_code_style/index.md) for more details.
still proposed on the issue tracker. See
[The Black Code Style](the_black_code_style/index.rst) for more details. Starting in 2022, the formatting output is stable for the releases made in the same year
(other than unintentional bugs). At the beginning of every year, the first release will
make changes to the stable style. It is possible to opt in to the latest formatting
styles using the `--preview` flag.
## Why is my file not formatted? ## Why is my file not formatted?
@ -37,20 +52,51 @@ Most likely because it is ignored in `.gitignore` or excluded with configuration
[file collection and discovery](usage_and_configuration/file_collection_and_discovery.md) [file collection and discovery](usage_and_configuration/file_collection_and_discovery.md)
for details. for details.
## Why are Flake8's E203 and W503 violated? ## Why is my Jupyter Notebook cell not formatted?
Because they go against PEP 8. E203 falsely triggers on list _Black_ is timid about formatting Jupyter Notebooks. Cells containing any of the
[slices](the_black_code_style/current_style.md#slices), and adhering to W503 hinders following will not be formatted:
readability because operators are misaligned. Disable W503 and enable the
disabled-by-default counterpart W504. E203 should be disabled while changes are still
[discussed](https://github.com/PyCQA/pycodestyle/issues/373).
## Does Black support Python 2? - automagics (e.g. `pip install black`)
- non-Python cell magics (e.g. `%%writefile`). These can be added with the flag
`--python-cell-magics`, e.g. `black --python-cell-magics writefile hello.ipynb`.
- multiline magics, e.g.:
For formatting, yes! [Install](getting_started.md#installation) with the `python2` extra ```python
to format Python 2 files too! There are no current plans to drop support, but most %timeit f(1, \
likely it is bound to happen. Sometime. Eventually. In terms of running _Black_ though, 2, \
Python 3.6 or newer is required. 3)
```
- code which `IPython`'s `TransformerManager` would transform magics into, e.g.:
```python
get_ipython().system('ls')
```
- invalid syntax, as it can't be safely distinguished from automagics in the absence of
a running `IPython` kernel.
## Why does Flake8 report warnings?
Some of Flake8's rules conflict with Black's style. We recommend disabling these rules.
See [Using _Black_ with other tools](labels/why-pycodestyle-warnings).
## Which Python versions does Black support?
_Black_ generally supports all Python versions supported by CPython (see
[the Python devguide](https://devguide.python.org/versions/) for current information).
We promise to support at least all Python versions that have not reached their end of
life. This is the case for both running _Black_ and formatting code.
Support for formatting Python 2 code was removed in version 22.0. While we've made no
plans to stop supporting older Python 3 minor versions immediately, their support might
also be removed some time in the future without a deprecation period.
`await`/`async` as soft keywords/indentifiers are no longer supported as of 25.2.0.
Runtime support for 3.6 was removed in version 22.10.0, for 3.7 in version 23.7.0, and
for 3.8 in version 24.10.0.
## Why does my linter or typechecker complain after I format my code? ## Why does my linter or typechecker complain after I format my code?
@ -59,3 +105,35 @@ influence their behavior. While Black does its best to recognize such comments a
them in the right place, this detection is not and cannot be perfect. Therefore, you'll them in the right place, this detection is not and cannot be perfect. Therefore, you'll
sometimes have to manually move these comments to the right place after you format your sometimes have to manually move these comments to the right place after you format your
codebase with _Black_. codebase with _Black_.
## Can I run Black with PyPy?
Yes, there is support for PyPy 3.8 and higher.
## Why does Black not detect syntax errors in my code?
_Black_ is an autoformatter, not a Python linter or interpreter. Detecting all syntax
errors is not a goal. It can format all code accepted by CPython (if you find an example
where that doesn't hold, please report a bug!), but it may also format some code that
CPython doesn't accept.
(labels/mypyc-support)=
## What is `compiled: yes/no` all about in the version output?
While _Black_ is indeed a pure Python project, we use [mypyc] to compile _Black_ into a
C Python extension, usually doubling performance. These compiled wheels are available
for 64-bit versions of Windows, Linux (via the manylinux standard), and macOS across all
supported CPython versions.
Platforms including musl-based and/or ARM Linux distributions, and ARM Windows are
currently **not** supported. These platforms will fall back to the slower pure Python
wheel available on PyPI.
If you are experiencing exceptionally weird issues or even segfaults, you can try
passing `--no-binary black` to your pip install invocation. This flag excludes all
wheels (including the pure Python wheel), so this command will use the [sdist].
[mypyc]: https://mypyc.readthedocs.io/en/latest/
[sdist]:
https://packaging.python.org/en/latest/glossary/#term-Source-Distribution-or-sdist

View File

@ -16,13 +16,14 @@ Also, you can try out _Black_ online for minimal fuss on the
## Installation ## Installation
_Black_ can be installed by running `pip install black`. It requires Python 3.6.2+ to _Black_ can be installed by running `pip install black`. It requires Python 3.9+ to run.
run, but can format Python 2 code too. Python 2 support needs the `typed_ast` If you want to format Jupyter Notebooks, install with `pip install "black[jupyter]"`.
dependency, which be installed with `pip install black[python2]`.
If you use pipx, you can install Black with `pipx install black`.
If you can't wait for the latest _hotness_ and want to install from GitHub, use: If you can't wait for the latest _hotness_ and want to install from GitHub, use:
`pip install git+git://github.com/psf/black` `pip install git+https://github.com/psf/black`
## Basic usage ## Basic usage

16
docs/guides/index.md Normal file
View File

@ -0,0 +1,16 @@
# Guides
```{toctree}
---
hidden:
---
introducing_black_to_your_project
using_black_with_other_tools
```
Wondering how to do something specific? You've found the right place! Listed below are
topic specific guides available:
- {doc}`introducing_black_to_your_project`
- {doc}`using_black_with_other_tools`

View File

@ -1,14 +0,0 @@
Guides
======
.. toctree::
:hidden:
introducing_black_to_your_project
using_black_with_other_tools
Wondering how to do something specific? You've found the right place! Listed below
are topic specific guides available:
- :doc:`introducing_black_to_your_project`
- :doc:`using_black_with_other_tools`

View File

@ -18,7 +18,8 @@ previous revision that modified those lines.
So when migrating your project's code style to _Black_, reformat everything and commit So when migrating your project's code style to _Black_, reformat everything and commit
the changes (preferably in one massive commit). Then put the full 40 characters commit the changes (preferably in one massive commit). Then put the full 40 characters commit
identifier(s) into a file. identifier(s) into a file usually called `.git-blame-ignore-revs` at the root of your
project directory.
```text ```text
# Migrate code style to Black # Migrate code style to Black
@ -43,8 +44,9 @@ call to `git blame`.
$ git config blame.ignoreRevsFile .git-blame-ignore-revs $ git config blame.ignoreRevsFile .git-blame-ignore-revs
``` ```
**The one caveat is that GitHub and GitLab do not yet support ignoring revisions using **The one caveat is that some online Git-repositories like GitLab do not yet support
their native UI of blame.** So blame information will be cluttered with a reformatting ignoring revisions using their native blame UI.** So blame information will be cluttered
commit on those platforms. (If you'd like this feature, there's an open issue for with a reformatting commit on those platforms. (If you'd like this feature, there's an
[GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub open issue for [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423)).
know!) [GitHub supports `.git-blame-ignore-revs`](https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view)
by default in blame views however.

View File

@ -24,10 +24,10 @@ to conflicting changes.
#### Profile #### Profile
Since version 5.0.0, isort supports Since version 5.0.0, isort supports
[profiles](https://pycqa.github.io/isort/docs/configuration/profiles/) to allow easy [profiles](https://pycqa.github.io/isort/docs/configuration/profiles.html) to allow easy
interoperability with common code styles. You can set the black profile in any of the interoperability with common code styles. You can set the black profile in any of the
[config files](https://pycqa.github.io/isort/docs/configuration/config_files/) supported [config files](https://pycqa.github.io/isort/docs/configuration/config_files.html)
by isort. Below, an example for `pyproject.toml`: supported by isort. Below, an example for `pyproject.toml`:
```toml ```toml
[tool.isort] [tool.isort]
@ -51,9 +51,9 @@ line_length = 88
#### Why those options above? #### Why those options above?
_Black_ wraps imports that surpass `line-length` by moving identifiers into their own _Black_ wraps imports that surpass `line-length` by moving identifiers onto separate
indented line. If that still doesn't fit the bill, it will put all of them in separate lines and by adding a trailing comma after each. A more detailed explanation of this
lines and put a trailing comma. A more detailed explanation of this behaviour can be behaviour can be
[found here](../the_black_code_style/current_style.md#how-black-wraps-lines). [found here](../the_black_code_style/current_style.md#how-black-wraps-lines).
isort's default mode of wrapping imports that extend past the `line_length` limit is isort's default mode of wrapping imports that extend past the `line_length` limit is
@ -97,7 +97,7 @@ does not break older versions so you can keep it if you are running previous ver
<details> <details>
<summary>.isort.cfg</summary> <summary>.isort.cfg</summary>
```cfg ```ini
[settings] [settings]
profile = black profile = black
``` ```
@ -107,7 +107,7 @@ profile = black
<details> <details>
<summary>setup.cfg</summary> <summary>setup.cfg</summary>
```cfg ```ini
[isort] [isort]
profile = black profile = black
``` ```
@ -134,10 +134,10 @@ profile = black
</details> </details>
### Flake8 ### pycodestyle
[Flake8](https://pypi.org/p/flake8/) is a code linter. It warns you of syntax errors, [pycodestyle](https://pycodestyle.pycqa.org/) is a code linter. It warns you of syntax
possible bugs, stylistic errors, etc. For the most part, Flake8 follows errors, possible bugs, stylistic errors, etc. For the most part, pycodestyle follows
[PEP 8](https://www.python.org/dev/peps/pep-0008/) when warning about stylistic errors. [PEP 8](https://www.python.org/dev/peps/pep-0008/) when warning about stylistic errors.
There are a few deviations that cause incompatibilities with _Black_. There are a few deviations that cause incompatibilities with _Black_.
@ -145,96 +145,129 @@ There are a few deviations that cause incompatibilities with _Black_.
``` ```
max-line-length = 88 max-line-length = 88
extend-ignore = E203 ignore = E203,E701
``` ```
(labels/why-pycodestyle-warnings)=
#### Why those options above? #### Why those options above?
##### `max-line-length`
As with isort, pycodestyle should be configured to allow lines up to the length limit of
`88`, _Black_'s default.
##### `E203`
In some cases, as determined by PEP 8, _Black_ will enforce an equal amount of In some cases, as determined by PEP 8, _Black_ will enforce an equal amount of
whitespace around slice operators. Due to this, Flake8 will raise whitespace around slice operators. Due to this, pycodestyle will raise
`E203 whitespace before ':'` warnings. Since this warning is not PEP 8 compliant, Flake8 `E203 whitespace before ':'` warnings. Since this warning is not PEP 8 compliant, it
should be configured to ignore it via `extend-ignore = E203`. should be disabled.
##### `E701` / `E704`
_Black_ will collapse implementations of classes and functions consisting solely of `..`
to a single line. This matches how such examples are formatted in PEP 8. It remains true
that in all other cases Black will prevent multiple statements on the same line, in
accordance with PEP 8 generally discouraging this.
However, `pycodestyle` does not mirror this logic and may raise
`E701 multiple statements on one line (colon)` in this situation. Its
disabled-by-default `E704 multiple statements on one line (def)` rule may also raise
warnings and should not be enabled.
##### `W503`
When breaking a line, _Black_ will break it before a binary operator. This is compliant When breaking a line, _Black_ will break it before a binary operator. This is compliant
with PEP 8 as of with PEP 8 as of
[April 2016](https://github.com/python/peps/commit/c59c4376ad233a62ca4b3a6060c81368bd21e85b#diff-64ec08cc46db7540f18f2af46037f599). [April 2016](https://github.com/python/peps/commit/c59c4376ad233a62ca4b3a6060c81368bd21e85b#diff-64ec08cc46db7540f18f2af46037f599).
There's a disabled-by-default warning in Flake8 which goes against this PEP 8 There's a disabled-by-default warning in Flake8 which goes against this PEP 8
recommendation called `W503 line break before binary operator`. It should not be enabled recommendation called `W503 line break before binary operator`. It should not be enabled
in your configuration. in your configuration. You can use its counterpart
`W504 line break after binary operator` instead.
Also, as like with isort, flake8 should be configured to allow lines up to the length
limit of `88`, _Black_'s default. This explains `max-line-length = 88`.
#### Formats #### Formats
<details> <details>
<summary>.flake8</summary> <summary>setup.cfg, .pycodestyle, tox.ini</summary>
```ini ```ini
[flake8] [pycodestyle]
max-line-length = 88 max-line-length = 88
extend-ignore = E203 ignore = E203,E701
``` ```
</details> </details>
<details> ### Flake8
<summary>setup.cfg</summary>
```cfg [Flake8](https://pypi.org/p/flake8/) is a wrapper around multiple linters, including
pycodestyle. As such, it has many of the same issues.
#### Bugbear
It's recommended to use [the Bugbear plugin](https://github.com/PyCQA/flake8-bugbear)
and enable
[its B950 check](https://github.com/PyCQA/flake8-bugbear#opinionated-warnings#:~:text=you%20expect%20it.-,B950,-%3A%20Line%20too%20long)
instead of using Flake8's E501, because it aligns with
[Black's 10% rule](labels/line-length).
Install Bugbear and use the following config:
```
[flake8] [flake8]
max-line-length = 88 max-line-length = 80
extend-ignore = E203 extend-select = B950
extend-ignore = E203,E501,E701
``` ```
</details> #### Minimal Configuration
In cases where you can't or don't want to install Bugbear, you can use this minimally
compatible config:
```
[flake8]
max-line-length = 88
extend-ignore = E203,E701
```
#### Why those options above?
See [the pycodestyle section](labels/why-pycodestyle-warnings) above.
#### Formats
<details> <details>
<summary>tox.ini</summary> <summary>.flake8, setup.cfg, tox.ini</summary>
```ini ```ini
[flake8] [flake8]
max-line-length = 88 max-line-length = 88
extend-ignore = E203 extend-ignore = E203,E701
``` ```
</details> </details>
### Pylint ### Pylint
[Pylint](https://pypi.org/p/pylint/) is also a code linter like Flake8. It has the same [Pylint](https://pypi.org/p/pylint/) is also a code linter like Flake8. It has many of
checks as flake8 and more. In particular, it has more formatting checks regarding style the same checks as Flake8 and more. It particularly has more formatting checks regarding
conventions like variable naming. With so many checks, Pylint is bound to have some style conventions like variable naming.
mixed feelings about _Black_'s formatting style.
#### Configuration #### Configuration
``` ```
disable = C0330, C0326
max-line-length = 88 max-line-length = 88
``` ```
#### Why those options above? #### Why those options above?
When _Black_ is folding very long expressions, the closing brackets will Pylint should be configured to only complain about lines that surpass `88` characters
[be dedented](../the_black_code_style/current_style.md#how-black-wraps-lines). via `max-line-length = 88`.
```py3 If using `pylint<2.6.0`, also disable `C0326` and `C0330` as these are incompatible with
ImportantClass.important_method( _Black_ formatting and have since been removed.
exc, limit, lookup_lines, capture_locals, callback
)
```
Although this style is PEP 8 compliant, Pylint will raise
`C0330: Wrong hanging indentation before block (add 4 spaces)` warnings. Since _Black_
isn't configurable on this style, Pylint should be told to ignore these warnings via
`disable = C0330`.
Also, since _Black_ deals with whitespace around operators and brackets, Pylint's
warning `C0326: Bad whitespace` should be disabled using `disable = C0326`.
And as usual, Pylint should be configured to only complain about lines that surpass `88`
characters via `max-line-length = 88`.
#### Formats #### Formats
@ -242,9 +275,6 @@ characters via `max-line-length = 88`.
<summary>pylintrc</summary> <summary>pylintrc</summary>
```ini ```ini
[MESSAGES CONTROL]
disable = C0330, C0326
[format] [format]
max-line-length = 88 max-line-length = 88
``` ```
@ -257,9 +287,6 @@ max-line-length = 88
```cfg ```cfg
[pylint] [pylint]
max-line-length = 88 max-line-length = 88
[pylint.messages_control]
disable = C0330, C0326
``` ```
</details> </details>
@ -268,9 +295,6 @@ disable = C0330, C0326
<summary>pyproject.toml</summary> <summary>pyproject.toml</summary>
```toml ```toml
[tool.pylint.messages_control]
disable = "C0330, C0326"
[tool.pylint.format] [tool.pylint.format]
max-line-length = "88" max-line-length = "88"
``` ```

139
docs/index.md Normal file
View File

@ -0,0 +1,139 @@
<!--
black documentation master file, created by
sphinx-quickstart on Fri Mar 23 10:53:30 2018.
-->
# The uncompromising code formatter
> “Any color you like.”
By using _Black_, you agree to cede control over minutiae of hand-formatting. In return,
_Black_ gives you speed, determinism, and freedom from `pycodestyle` nagging about
formatting. You will save time and mental energy for more important matters.
_Black_ makes code review faster by producing the smallest diffs possible. Blackened
code looks the same regardless of the project you're reading. Formatting becomes
transparent after a while and you can focus on the content instead.
Try it out now using the [Black Playground](https://black.vercel.app).
```{admonition} Note - Black is now stable!
*Black* is [successfully used](https://github.com/psf/black#used-by) by
many projects, small and big. *Black* has a comprehensive test suite, with efficient
parallel tests, our own auto formatting and parallel Continuous Integration runner.
Now that we have become stable, you should not expect large changes to formatting in
the future. Stylistic changes will mostly be responses to bug reports and support for new Python
syntax.
Also, as a safety measure which slows down processing, *Black* will check that the
reformatted code still produces a valid AST that is effectively equivalent to the
original (see the
[Pragmatism](./the_black_code_style/current_style.md#pragmatism)
section for details). If you're feeling confident, use `--fast`.
```
```{note}
{doc}`Black is licensed under the MIT license <license>`.
```
## Testimonials
**Mike Bayer**, author of [SQLAlchemy](https://www.sqlalchemy.org/):
> _I can't think of any single tool in my entire programming career that has given me a
> bigger productivity increase by its introduction. I can now do refactorings in about
> 1% of the keystrokes that it would have taken me previously when we had no way for
> code to format itself._
**Dusty Phillips**,
[writer](https://smile.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=dusty+phillips):
> _Black is opinionated so you don't have to be._
**Hynek Schlawack**, creator of [attrs](https://www.attrs.org/), core developer of
Twisted and CPython:
> _An auto-formatter that doesn't suck is all I want for Xmas!_
**Carl Meyer**, [Django](https://www.djangoproject.com/) core developer:
> _At least the name is good._
**Kenneth Reitz**, creator of [requests](http://python-requests.org/) and
[pipenv](https://docs.pipenv.org/):
> _This vastly improves the formatting of our code. Thanks a ton!_
## Show your style
Use the badge in your project's README.md:
```md
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
```
Using the badge in README.rst:
```rst
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
```
Looks like this:
```{image} https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
```
## Contents
```{toctree}
---
maxdepth: 3
includehidden:
---
the_black_code_style/index
```
```{toctree}
---
maxdepth: 3
includehidden:
caption: User Guide
---
getting_started
usage_and_configuration/index
integrations/index
guides/index
faq
```
```{toctree}
---
maxdepth: 2
includehidden:
caption: Development
---
contributing/index
change_log
authors
```
```{toctree}
---
hidden:
caption: Project Links
---
GitHub <https://github.com/psf/black>
PyPI <https://pypi.org/project/black>
Chat <https://discord.gg/RtVdv86PrH>
```
# Indices and tables
- {ref}`genindex`
- {ref}`search`

View File

@ -1,128 +0,0 @@
.. black documentation master file, created by
sphinx-quickstart on Fri Mar 23 10:53:30 2018.
The uncompromising code formatter
=================================
By using *Black*, you agree to cede control over minutiae of
hand-formatting. In return, *Black* gives you speed, determinism, and
freedom from `pycodestyle` nagging about formatting. You will save time
and mental energy for more important matters.
*Black* makes code review faster by producing the smallest diffs
possible. Blackened code looks the same regardless of the project
you're reading. Formatting becomes transparent after a while and you
can focus on the content instead.
Try it out now using the `Black Playground <https://black.vercel.app>`_.
.. admonition:: Note - this is a beta product
*Black* is already `successfully used <https://github.com/psf/black#used-by>`_ by
many projects, small and big. *Black* has a comprehensive test suite, with efficient
parallel tests, our own auto formatting and parallel Continuous Integration runner.
However, *Black* is still beta. Things will probably be wonky for a while. This is
made explicit by the "Beta" trove classifier, as well as by the "b" in the version
number. What this means for you is that **until the formatter becomes stable, you
should expect some formatting to change in the future**. That being said, no drastic
stylistic changes are planned, mostly responses to bug reports.
Also, as a safety measure which slows down processing, *Black* will check that the
reformatted code still produces a valid AST that is effectively equivalent to the
original (see the
`Pragmatism <./the_black_code_style/current_style.html#pragmatism>`_
section for details). If you're feeling confident, use ``--fast``.
.. note::
:doc:`Black is licensed under the MIT license <license>`.
Testimonials
------------
**Mike Bayer**, author of `SQLAlchemy <https://www.sqlalchemy.org/>`_:
*I can't think of any single tool in my entire programming career that has given me a
bigger productivity increase by its introduction. I can now do refactorings in about
1% of the keystrokes that it would have taken me previously when we had no way for
code to format itself.*
**Dusty Phillips**, `writer <https://smile.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=dusty+phillips>`_:
*Black is opinionated so you don't have to be.*
**Hynek Schlawack**, creator of `attrs <https://www.attrs.org/>`_, core
developer of Twisted and CPython:
*An auto-formatter that doesn't suck is all I want for Xmas!*
**Carl Meyer**, `Django <https://www.djangoproject.com/>`_ core developer:
*At least the name is good.*
**Kenneth Reitz**, creator of `requests <http://python-requests.org/>`_
and `pipenv <https://docs.pipenv.org/>`_:
*This vastly improves the formatting of our code. Thanks a ton!*
Show your style
---------------
Use the badge in your project's README.md:
.. code-block:: md
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
Using the badge in README.rst:
.. code-block:: rst
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
Looks like this:
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
Contents
--------
.. toctree::
:maxdepth: 3
:includehidden:
the_black_code_style/index
.. toctree::
:maxdepth: 3
:includehidden:
getting_started
usage_and_configuration/index
integrations/index
guides/index
faq
.. toctree::
:maxdepth: 3
:includehidden:
contributing/index
change_log
authors
.. toctree::
:hidden:
GitHub ↪ <https://github.com/psf/black>
PyPI ↪ <https://pypi.org/project/black>
IRC ↪ <https://webchat.freenode.net/?channels=%23blackformatter>
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`

View File

@ -10,6 +10,67 @@ Options include the following:
## PyCharm/IntelliJ IDEA ## PyCharm/IntelliJ IDEA
There are several different ways you can use _Black_ from PyCharm:
1. Using the built-in _Black_ integration (PyCharm 2023.2 and later). This option is the
simplest to set up.
1. As local server using the BlackConnect plugin. This option formats the fastest. It
spins up {doc}`Black's HTTP server </usage_and_configuration/black_as_a_server>`, to
avoid the startup cost on subsequent formats.
1. As external tool.
1. As file watcher.
### Built-in _Black_ integration
1. Install `black`.
```console
$ pip install black
```
1. Go to `Preferences or Settings -> Tools -> Black` and configure _Black_ to your
liking.
### As local server
1. Install _Black_ with the `d` extra.
```console
$ pip install 'black[d]'
```
1. Install
[BlackConnect IntelliJ IDEs plugin](https://plugins.jetbrains.com/plugin/14321-blackconnect).
1. Open plugin configuration in PyCharm/IntelliJ IDEA
On macOS:
`PyCharm -> Preferences -> Tools -> BlackConnect`
On Windows / Linux / BSD:
`File -> Settings -> Tools -> BlackConnect`
1. In `Local Instance (shared between projects)` section:
1. Check `Start local blackd instance when plugin loads`.
1. Press the `Detect` button near `Path` input. The plugin should detect the `blackd`
executable.
1. In `Trigger Settings` section check `Trigger on code reformat` to enable code
reformatting with _Black_.
1. Format the currently opened file by selecting `Code -> Reformat Code` or using a
shortcut.
1. Optionally, to run _Black_ on every file save:
- In `Trigger Settings` section of plugin configuration check
`Trigger when saving changed files`.
### As external tool
1. Install `black`. 1. Install `black`.
```console ```console
@ -57,29 +118,7 @@ Options include the following:
- Alternatively, you can set a keyboard shortcut by navigating to - Alternatively, you can set a keyboard shortcut by navigating to
`Preferences or Settings -> Keymap -> External Tools -> External Tools - Black`. `Preferences or Settings -> Keymap -> External Tools -> External Tools - Black`.
1. Optionally, run _Black_ on every file save: ### As file watcher
1. Make sure you have the
[File Watchers](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin
installed.
1. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a
new watcher:
- Name: Black
- File type: Python
- Scope: Project Files
- Program: \<install_location_from_step_2>
- Arguments: `$FilePath$`
- Output paths to refresh: `$FilePath$`
- Working directory: `$ProjectFileDir$`
- In Advanced Options
- Uncheck "Auto-save edited files to trigger the watcher"
- Uncheck "Trigger the watcher on external changes"
## Wing IDE
Wing supports black via the OS Commands tool, as explained in the Wing documentation on
[pep8 formatting](https://wingware.com/doc/edit/pep8). The detailed procedure is:
1. Install `black`. 1. Install `black`.
@ -87,27 +126,89 @@ Wing supports black via the OS Commands tool, as explained in the Wing documenta
$ pip install black $ pip install black
``` ```
1. Make sure it runs from the command line, e.g. 1. Locate your `black` installation folder.
On macOS / Linux / BSD:
```console ```console
$ black --help $ which black
/usr/local/bin/black # possible location
``` ```
1. In Wing IDE, activate the **OS Commands** panel and define the command **black** to On Windows:
execute black on the currently selected file:
- Use the Tools -> OS Commands menu selection ```console
- click on **+** in **OS Commands** -> New: Command line.. $ where black
- Title: black %LocalAppData%\Programs\Python\Python36-32\Scripts\black.exe # possible location
- Command Line: black %s ```
- I/O Encoding: Use Default
- Key Binding: F1
- [x] Raise OS Commands when executed
- [x] Auto-save files before execution
- [x] Line mode
1. Select a file in the editor and press **F1** , or whatever key binding you selected Note that if you are using a virtual environment detected by PyCharm, this is an
in step 3, to reformat the file. unneeded step. In this case the path to `black` is `$PyInterpreterDirectory$/black`.
1. Make sure you have the
[File Watchers](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin
installed.
1. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a new
watcher:
- Name: Black
- File type: Python
- Scope: Project Files
- Program: \<install_location_from_step_2>
- Arguments: `$FilePath$`
- Output paths to refresh: `$FilePath$`
- Working directory: `$ProjectFileDir$`
- In Advanced Options
- Uncheck "Auto-save edited files to trigger the watcher"
- Uncheck "Trigger the watcher on external changes"
## Wing IDE
Wing IDE supports `black` via **Preference Settings** for system wide settings and
**Project Properties** for per-project or workspace specific settings, as explained in
the Wing documentation on
[Auto-Reformatting](https://wingware.com/doc/edit/auto-reformatting). The detailed
procedure is:
### Prerequistes
- Wing IDE version 8.0+
- Install `black`.
```console
$ pip install black
```
- Make sure it runs from the command line, e.g.
```console
$ black --help
```
### Preference Settings
If you want Wing IDE to always reformat with `black` for every project, follow these
steps:
1. In menubar navigate to `Edit -> Preferences -> Editor -> Reformatting`.
1. Set **Auto-Reformat** from `disable` (default) to `Line after edit` or
`Whole files before save`.
1. Set **Reformatter** from `PEP8` (default) to `Black`.
### Project Properties
If you want to just reformat for a specific project and not intervene with Wing IDE
global setting, follow these steps:
1. In menubar navigate to `Project -> Project Properties -> Options`.
1. Set **Auto-Reformat** from `Use Preferences setting` (default) to `Line after edit`
or `Whole files before save`.
1. Set **Reformatter** from `Use Preferences setting` (default) to `Black`.
## Vim ## Vim
@ -116,23 +217,61 @@ Wing supports black via the OS Commands tool, as explained in the Wing documenta
Commands and shortcuts: Commands and shortcuts:
- `:Black` to format the entire file (ranges not supported); - `:Black` to format the entire file (ranges not supported);
- you can optionally pass `target_version=<version>` with the same values as in the
command line.
- `:BlackUpgrade` to upgrade _Black_ inside the virtualenv; - `:BlackUpgrade` to upgrade _Black_ inside the virtualenv;
- `:BlackVersion` to get the current version of _Black_ inside the virtualenv. - `:BlackVersion` to get the current version of _Black_ in use.
Configuration: Configuration:
- `g:black_fast` (defaults to `0`) - `g:black_fast` (defaults to `0`)
- `g:black_linelength` (defaults to `88`) - `g:black_linelength` (defaults to `88`)
- `g:black_skip_string_normalization` (defaults to `0`) - `g:black_skip_string_normalization` (defaults to `0`)
- `g:black_skip_magic_trailing_comma` (defaults to `0`)
- `g:black_virtualenv` (defaults to `~/.vim/black` or `~/.local/share/nvim/black`) - `g:black_virtualenv` (defaults to `~/.vim/black` or `~/.local/share/nvim/black`)
- `g:black_use_virtualenv` (defaults to `1`)
- `g:black_target_version` (defaults to `""`)
- `g:black_quiet` (defaults to `0`) - `g:black_quiet` (defaults to `0`)
- `g:black_preview` (defaults to `0`)
#### Installation
This plugin **requires Vim 7.0+ built with Python 3.9+ support**. It needs Python 3.9 to
be able to run _Black_ inside the Vim process which is much faster than calling an
external command.
##### `vim-plug`
To install with [vim-plug](https://github.com/junegunn/vim-plug): To install with [vim-plug](https://github.com/junegunn/vim-plug):
_Black_'s `stable` branch tracks official version updates, and can be used to simply
follow the most recent stable version.
``` ```
Plug 'psf/black', { 'branch': 'stable' } Plug 'psf/black', { 'branch': 'stable' }
``` ```
Another option which is a bit more explicit and offers more control is to use
`vim-plug`'s `tag` option with a shell wildcard. This will resolve to the latest tag
which matches the given pattern.
The following matches all stable versions (see the
[Release Process](../contributing/release_process.md) section for documentation of
version scheme used by Black):
```
Plug 'psf/black', { 'tag': '*.*.*' }
```
and the following demonstrates pinning to a specific year's stable style (2022 in this
case):
```
Plug 'psf/black', { 'tag': '22.*.*' }
```
##### Vundle
or with [Vundle](https://github.com/VundleVim/Vundle.vim): or with [Vundle](https://github.com/VundleVim/Vundle.vim):
``` ```
@ -146,6 +285,14 @@ $ cd ~/.vim/bundle/black
$ git checkout origin/stable -b stable $ git checkout origin/stable -b stable
``` ```
##### Arch Linux
On Arch Linux, the plugin is shipped with the
[`python-black`](https://archlinux.org/packages/extra/any/python-black/) package, so you
can start using it in Vim after install with no additional setup.
##### Vim 8 Native Plugin Management
or you can copy the plugin files from or you can copy the plugin files from
[plugin/black.vim](https://github.com/psf/black/blob/stable/plugin/black.vim) and [plugin/black.vim](https://github.com/psf/black/blob/stable/plugin/black.vim) and
[autoload/black.vim](https://github.com/psf/black/blob/stable/autoload/black.vim). [autoload/black.vim](https://github.com/psf/black/blob/stable/autoload/black.vim).
@ -160,9 +307,7 @@ curl https://raw.githubusercontent.com/psf/black/stable/autoload/black.vim -o ~/
Let me know if this requires any changes to work with Vim 8's builtin `packadd`, or Let me know if this requires any changes to work with Vim 8's builtin `packadd`, or
Pathogen, and so on. Pathogen, and so on.
This plugin **requires Vim 7.0+ built with Python 3.6+ support**. It needs Python 3.6 to #### Usage
be able to run _Black_ inside the Vim process which is much faster than calling an
external command.
On first run, the plugin creates its own virtualenv using the right Python version and On first run, the plugin creates its own virtualenv using the right Python version and
automatically installs _Black_. You can upgrade it later by calling `:BlackUpgrade` and automatically installs _Black_. You can upgrade it later by calling `:BlackUpgrade` and
@ -172,10 +317,25 @@ If you need to do anything special to make your virtualenv work and install _Bla
example you want to run a version from main), create a virtualenv manually and point example you want to run a version from main), create a virtualenv manually and point
`g:black_virtualenv` to it. The plugin will use it. `g:black_virtualenv` to it. The plugin will use it.
To run _Black_ on save, add the following line to `.vimrc` or `init.vim`: If you would prefer to use the system installation of _Black_ rather than a virtualenv,
then add this to your vimrc:
``` ```
autocmd BufWritePre *.py execute ':Black' let g:black_use_virtualenv = 0
```
Note that the `:BlackUpgrade` command is only usable and useful with a virtualenv, so
when the virtualenv is not in use, `:BlackUpgrade` is disabled. If you need to upgrade
the system installation of _Black_, then use your system package manager or pip--
whatever tool you used to install _Black_ originally.
To run _Black_ on save, add the following lines to `.vimrc` or `init.vim`:
```
augroup black_on_save
autocmd!
autocmd BufWritePre *.py Black
augroup end
``` ```
To run _Black_ on a key press (e.g. F9 below), add this: To run _Black_ on a key press (e.g. F9 below), add this:
@ -184,60 +344,6 @@ To run _Black_ on a key press (e.g. F9 below), add this:
nnoremap <F9> :Black<CR> nnoremap <F9> :Black<CR>
``` ```
**How to get Vim with Python 3.6?** On Ubuntu 17.10 Vim comes with Python 3.6 by
default. On macOS with Homebrew run: `brew install vim`. When building Vim from source,
use: `./configure --enable-python3interp=yes`. There's many guides online how to do
this.
**I get an import error when using _Black_ from a virtual environment**: If you get an
error message like this:
```text
Traceback (most recent call last):
File "<string>", line 63, in <module>
File "/home/gui/.vim/black/lib/python3.7/site-packages/black.py", line 45, in <module>
from typed_ast import ast3, ast27
File "/home/gui/.vim/black/lib/python3.7/site-packages/typed_ast/ast3.py", line 40, in <module>
from typed_ast import _ast3
ImportError: /home/gui/.vim/black/lib/python3.7/site-packages/typed_ast/_ast3.cpython-37m-x86_64-linux-gnu.so: undefined symbool: PyExc_KeyboardInterrupt
```
Then you need to install `typed_ast` and `regex` directly from the source code. The
error happens because `pip` will download [Python wheels](https://pythonwheels.com/) if
they are available. Python wheels are a new standard of distributing Python packages and
packages that have Cython and extensions written in C are already compiled, so the
installation is much more faster. The problem here is that somehow the Python
environment inside Vim does not match with those already compiled C extensions and these
kind of errors are the result. Luckily there is an easy fix: installing the packages
from the source code.
The two packages that cause the problem are:
- [regex](https://pypi.org/project/regex/)
- [typed-ast](https://pypi.org/project/typed-ast/)
Now remove those two packages:
```console
$ pip uninstall regex typed-ast -y
```
And now you can install them with:
```console
$ pip install --no-binary :all: regex typed-ast
```
The C extensions will be compiled and now Vim's Python environment will match. Note that
you need to have the GCC compiler and the Python development files installed (on
Ubuntu/Debian do `sudo apt-get install build-essential python3-dev`).
If you later want to update _Black_, you should do it like this:
```console
$ pip install -U black --no-binary regex,typed-ast
```
### With ALE ### With ALE
1. Install [`ale`](https://github.com/dense-analysis/ale) 1. Install [`ale`](https://github.com/dense-analysis/ale)
@ -283,24 +389,27 @@ close and reopen your File, _Black_ will be done with its job.
## Visual Studio Code ## Visual Studio Code
Use the - Use the
[Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
([instructions](https://code.visualstudio.com/docs/python/editing#_formatting)). ([instructions](https://code.visualstudio.com/docs/python/formatting)).
## SublimeText 3 - Alternatively the pre-release
[Black Formatter](https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter)
extension can be used which runs a [Language Server Protocol](https://langserver.org/)
server for Black. Formatting is much more responsive using this extension, **but the
minimum supported version of Black is 22.3.0**.
Use [sublack plugin](https://github.com/jgirardet/sublack). ## SublimeText
## Jupyter Notebook Magic For SublimeText 3, use [sublack plugin](https://github.com/jgirardet/sublack). For
higher versions, it is recommended to use [LSP](#python-lsp-server) as documented below.
Use [blackcellmagic](https://github.com/csurfer/blackcellmagic). ## Python LSP Server
## Python Language Server
If your editor supports the [Language Server Protocol](https://langserver.org/) (Atom, If your editor supports the [Language Server Protocol](https://langserver.org/) (Atom,
Sublime Text, Visual Studio Code and many more), you can use the Sublime Text, Visual Studio Code and many more), you can use the
[Python Language Server](https://github.com/palantir/python-language-server) with the [Python LSP Server](https://github.com/python-lsp/python-lsp-server) with the
[pyls-black](https://github.com/rupert/pyls-black) plugin. [python-lsp-black](https://github.com/python-lsp/python-lsp-black) plugin.
## Atom/Nuclide ## Atom/Nuclide
@ -323,4 +432,4 @@ hook global WinSetOption filetype=python %{
## Thonny ## Thonny
Use [Thonny-black-code-format](https://github.com/Franccisco/thonny-black-code-format). Use [Thonny-black-formatter](https://pypi.org/project/thonny-black-formatter/).

View File

@ -3,13 +3,13 @@
You can use _Black_ within a GitHub Actions workflow without setting your own Python You can use _Black_ within a GitHub Actions workflow without setting your own Python
environment. Great for enforcing that your code matches the _Black_ code style. environment. Great for enforcing that your code matches the _Black_ code style.
## Compatiblity ## Compatibility
This action is known to support all GitHub-hosted runner OSes. In addition, only This action is known to support all GitHub-hosted runner OSes. In addition, only
published versions of _Black_ are supported (i.e. whatever is available on PyPI). published versions of _Black_ are supported (i.e. whatever is available on PyPI).
Finally, this action installs _Black_ with both the `colorama` and `python2` extras so Finally, this action installs _Black_ with the `colorama` extra so the `--color` flag
the `--color` flag and formatting Python 2 code are supported. should work fine.
## Usage ## Usage
@ -24,7 +24,7 @@ jobs:
lint: lint:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- uses: psf/black@stable - uses: psf/black@stable
``` ```
@ -32,12 +32,24 @@ We recommend the use of the `@stable` tag, but per version tags also exist if yo
that. Note that the action's version you select is independent of the version of _Black_ that. Note that the action's version you select is independent of the version of _Black_
the action will use. the action will use.
The version of _Black_ the action will use can be configured via `version`. The action The version of _Black_ the action will use can be configured via `version` or read from
defaults to the latest release available on PyPI. Only versions available from PyPI are the `pyproject.toml` file. `version` can be any
supported, so no commit SHAs or branch names. [valid version specifier](https://packaging.python.org/en/latest/glossary/#term-Version-Specifier)
or just the version number if you want an exact version. To read the version from the
`pyproject.toml` file instead, set `use_pyproject` to `true`. This will first look into
the `tool.black.required-version` field, then the `dependency-groups` table, then the
`project.dependencies` array and finally the `project.optional-dependencies` table. The
action defaults to the latest release available on PyPI. Only versions available from
PyPI are supported, so no commit SHAs or branch names.
If you want to include Jupyter Notebooks, _Black_ must be installed with the `jupyter`
extra. Installing the extra and including Jupyter Notebook files can be configured via
`jupyter` (default is `false`).
You can also configure the arguments passed to _Black_ via `options` (defaults to You can also configure the arguments passed to _Black_ via `options` (defaults to
`'--check --diff'`) and `src` (default is `'.'`) `'--check --diff'`) and `src` (default is `'.'`). Please note that the
[`--check` flag](labels/exit-code) is required so that the workflow fails if _Black_
finds files that need to be formatted.
Here's an example configuration: Here's an example configuration:
@ -46,5 +58,33 @@ Here's an example configuration:
with: with:
options: "--check --verbose" options: "--check --verbose"
src: "./src" src: "./src"
jupyter: true
version: "21.5b1" version: "21.5b1"
``` ```
If you want to match versions covered by Black's
[stability policy](labels/stability-policy), you can use the compatible release operator
(`~=`):
```yaml
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "./src"
version: "~= 22.0"
```
If you want to read the version from `pyproject.toml`, set `use_pyproject` to `true`.
Note that this requires Python >= 3.11, so using the setup-python action may be
required, for example:
```yaml
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "./src"
use_pyproject: true
```

View File

@ -0,0 +1,31 @@
# Integrations
```{toctree}
---
hidden:
---
editors
github_actions
source_version_control
```
_Black_ can be integrated into many environments, providing a better and smoother
experience. Documentation for integrating _Black_ with a tool can be found for the
following areas:
- {doc}`Editor / IDE <./editors>`
- {doc}`GitHub Actions <./github_actions>`
- {doc}`Source version control <./source_version_control>`
Editors and tools not listed will require external contributions.
Patches welcome! ✨ 🍰 ✨
Any tool can pipe code through _Black_ using its stdio mode (just
[use `-` as the file name](https://www.tldp.org/LDP/abs/html/special-chars.html#DASHREF2)).
The formatted code will be returned on stdout (unless `--check` was passed). _Black_
will still emit messages on stderr but that shouldn't affect your use case.
This can be used for example with PyCharm's or IntelliJ's
[File Watchers](https://www.jetbrains.com/help/pycharm/file-watchers.html).

View File

@ -1,28 +0,0 @@
Integrations
============
.. toctree::
:hidden:
editors
github_actions
source_version_control
*Black* can be integrated into many environments, providing a better and smoother experience. Documentation for integrating *Black* with a tool can be found for the
following areas:
- :doc:`Editor / IDE <./editors>`
- :doc:`GitHub Actions <./github_actions>`
- :doc:`Source version control <./source_version_control>`
Editors and tools not listed will require external contributions.
Patches welcome! ✨ 🍰 ✨
Any tool can pipe code through *Black* using its stdio mode (just
`use \`-\` as the file name <https://www.tldp.org/LDP/abs/html/special-chars.html#DASHREF2>`_).
The formatted code will be returned on stdout (unless ``--check`` was passed). *Black*
will still emit messages on stderr but that shouldn't affect your use case.
This can be used for example with PyCharm's or IntelliJ's
`File Watchers <https://www.jetbrains.com/help/pycharm/file-watchers.html>`_.

View File

@ -6,9 +6,48 @@ Use [pre-commit](https://pre-commit.com/). Once you
```yaml ```yaml
repos: repos:
- repo: https://github.com/psf/black # Using this mirror lets us use mypyc-compiled black, which is about 2x faster
rev: stable # Replace by any tag/version: https://github.com/psf/black/tags - repo: https://github.com/psf/black-pre-commit-mirror
rev: 25.1.0
hooks: hooks:
- id: black - id: black
language_version: python3 # Should be a command that runs python3.6+ # It is recommended to specify the latest version of Python
# supported by your project here, or alternatively use
# pre-commit's default_language_version, see
# https://pre-commit.com/#top_level-default_language_version
language_version: python3.11
``` ```
Feel free to switch out the `rev` value to a different version of Black.
Note if you'd like to use a specific commit in `rev`, you'll need to swap the repo
specified from the mirror to https://github.com/psf/black. We discourage the use of
branches or other mutable refs since the hook [won't auto update as you may
expect][pre-commit-mutable-rev].
## Jupyter Notebooks
There is an alternate hook `black-jupyter` that expands the targets of `black` to
include Jupyter Notebooks. To use this hook, simply replace the hook's `id: black` with
`id: black-jupyter` in the `.pre-commit-config.yaml`:
```yaml
repos:
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 25.1.0
hooks:
- id: black-jupyter
# It is recommended to specify the latest version of Python
# supported by your project here, or alternatively use
# pre-commit's default_language_version, see
# https://pre-commit.com/#top_level-default_language_version
language_version: python3.11
```
```{note}
The `black-jupyter` hook became available in version 21.8b0.
```
[pre-commit-mutable-rev]:
https://pre-commit.com/#using-the-latest-version-for-a-repository

9
docs/license.md Normal file
View File

@ -0,0 +1,9 @@
---
orphan: true
---
# License
```{include} ../LICENSE
```

View File

@ -1,6 +0,0 @@
:orphan:
License
=======
.. include:: ../LICENSE

View File

@ -1,6 +1,9 @@
# Used by ReadTheDocs; pinned requirements for stability. # Used by ReadTheDocs; pinned requirements for stability.
MyST-Parser==0.14.0 myst-parser==4.0.1
Sphinx==3.5.4 Sphinx==8.2.3
sphinxcontrib-programoutput==0.17 # Older versions break Sphinx even though they're declared to be supported.
sphinx_copybutton==0.3.1 docutils==0.21.2
sphinxcontrib-programoutput==0.18
sphinx_copybutton==0.5.2
furo==2024.8.6

View File

@ -2,20 +2,21 @@
## Code style ## Code style
_Black_ reformats entire files in place. Style configuration options are deliberately _Black_ aims for consistency, generality, readability and reducing git diffs. Similar
limited and rarely added. It doesn't take previous formatting into account, except for language constructs are formatted with similar rules. Style configuration options are
the magic trailing comma and preserving newlines. It doesn't reformat blocks that start deliberately limited and rarely added. Previous formatting is taken into account as
with `# fmt: off` and end with `# fmt: on`, or lines that ends with `# fmt: skip`. little as possible, with rare exceptions like the magic trailing comma. The coding style
`# fmt: on/off` have to be on the same level of indentation. It also recognizes used by _Black_ can be viewed as a strict subset of PEP 8.
[YAPF](https://github.com/google/yapf)'s block comments to the same effect, as a
courtesy for straddling code. This document describes the current formatting style. If you're interested in trying out
where the style is heading, see [future style](./future_style.md) and try running
`black --preview`.
### How _Black_ wraps lines ### How _Black_ wraps lines
_Black_ ignores previous formatting and applies uniform horizontal and vertical _Black_ ignores previous formatting and applies uniform horizontal and vertical
whitespace to your code. The rules for horizontal whitespace can be summarized as: do whitespace to your code. The rules for horizontal whitespace can be summarized as: do
whatever makes `pycodestyle` happy. The coding style used by _Black_ can be viewed as a whatever makes `pycodestyle` happy.
strict subset of PEP 8.
As for vertical whitespace, _Black_ tries to render one full expression or simple As for vertical whitespace, _Black_ tries to render one full expression or simple
statement per line. If this fits the allotted line length, great. statement per line. If this fits the allotted line length, great.
@ -77,6 +78,19 @@ def very_important_function(
... ...
``` ```
If a data structure literal (tuple, list, set, dict) or a line of "from" imports cannot
fit in the allotted length, it's always split into one element per line. This minimizes
diffs as well as enables readers of code to find which commit introduced a particular
entry. This also makes _Black_ compatible with
[isort](../guides/using_black_with_other_tools.md#isort) with the ready-made `black`
profile or manual configuration.
You might have noticed that closing brackets are always dedented and that a trailing
comma is always added. Such formatting produces smaller diffs; when you add or remove an
element, it's always just one line. Also, having the closing bracket dedented provides a
clear delimiter between two distinct sections of the code that otherwise share the same
indentation level (like the arguments list and the docstring in the example above).
(labels/why-no-backslashes)= (labels/why-no-backslashes)=
_Black_ prefers parentheses over backslashes, and will remove backslashes if found. _Black_ prefers parentheses over backslashes, and will remove backslashes if found.
@ -119,18 +133,7 @@ If you're reaching for backslashes, that's a clear signal that you can do better
slightly refactor your code. I hope some of the examples above show you that there are slightly refactor your code. I hope some of the examples above show you that there are
many ways in which you can do it. many ways in which you can do it.
You might have noticed that closing brackets are always dedented and that a trailing (labels/line-length)=
comma is always added. Such formatting produces smaller diffs; when you add or remove an
element, it's always just one line. Also, having the closing bracket dedented provides a
clear delimiter between two distinct sections of the code that otherwise share the same
indentation level (like the arguments list and the docstring in the example above).
If a data structure literal (tuple, list, set, dict) or a line of "from" imports cannot
fit in the allotted length, it's always split into one element per line. This minimizes
diffs as well as enables readers of code to find which commit introduced a particular
entry. This also makes _Black_ compatible with
[isort](../guides/using_black_with_other_tools.md#isort) with the ready-made `black`
profile or manual configuration.
### Line length ### Line length
@ -140,7 +143,7 @@ significantly shorter files than sticking with 80 (the most popular), or even 79
by the standard library). In general, by the standard library). In general,
[90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260). [90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260).
If you're paid by the line of code you write, you can pass `--line-length` with a lower If you're paid by the lines of code you write, you can pass `--line-length` with a lower
number. _Black_ will try to respect that. However, sometimes it won't be able to without number. _Black_ will try to respect that. However, sometimes it won't be able to without
breaking other rules. In those rare cases, auto-formatted code will exceed your allotted breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
limit. limit.
@ -150,33 +153,10 @@ harder to work with line lengths exceeding 100 characters. It also adversely aff
side-by-side diff review on typical screen resolutions. Long lines also make it harder side-by-side diff review on typical screen resolutions. Long lines also make it harder
to present code neatly in documentation or talk slides. to present code neatly in documentation or talk slides.
If you're using Flake8, you can bump `max-line-length` to 88 and mostly forget about it. #### Flake8 and other linters
However, it's better if you use [Bugbear](https://github.com/PyCQA/flake8-bugbear)'s
B950 warning instead of E501, and bump the max line length to 88 (or the `--line-length`
you used for black), which will align more with black's _"try to respect
`--line-length`, but don't become crazy if you can't"_. You'd do it like this:
```ini See [Using _Black_ with other tools](../guides/using_black_with_other_tools.md) about
[flake8] linter compatibility.
max-line-length = 88
...
select = C,E,F,W,B,B950
extend-ignore = E203, E501
```
Explanation of why E203 is disabled can be found further in this documentation. And if
you're curious about the reasoning behind B950,
[Bugbear's documentation](https://github.com/PyCQA/flake8-bugbear#opinionated-warnings)
explains it. The tl;dr is "it's like highway speed limits, we won't bother you if you
overdo it by a few km/h".
**If you're looking for a minimal, black-compatible flake8 configuration:**
```ini
[flake8]
max-line-length = 88
extend-ignore = E203
```
### Empty lines ### Empty lines
@ -188,6 +168,35 @@ lines on module level left by the original editors, except when they're within
parenthesized expressions. Since such expressions are always reformatted to fit minimal parenthesized expressions. Since such expressions are always reformatted to fit minimal
space, this whitespace is lost. space, this whitespace is lost.
```python
# in:
def function(
some_argument: int,
other_argument: int = 5,
) -> EmptyLineInParenWillBeDeleted:
print("One empty line above me will be kept!")
def this_is_okay_too():
print("No empty line here")
# out:
def function(
some_argument: int,
other_argument: int = 5,
) -> EmptyLineInParenWillBeDeleted:
print("One empty line above me will be kept!")
def this_is_okay_too():
print("No empty line here")
```
It will also insert proper spacing before and after function definitions. It's one line It will also insert proper spacing before and after function definitions. It's one line
before and after inner functions and two lines before and after module-level functions before and after inner functions and two lines before and after module-level functions
and classes. _Black_ will not put empty lines between function/class definitions and and classes. _Black_ will not put empty lines between function/class definitions and
@ -204,11 +213,12 @@ required due to an inner function starting immediately after.
_Black_ does not format comment contents, but it enforces two spaces between code and a _Black_ does not format comment contents, but it enforces two spaces between code and a
comment on the same line, and a space before the comment text begins. Some types of comment on the same line, and a space before the comment text begins. Some types of
comments that require specific spacing rules are respected: doc comments (`#: comment`), comments that require specific spacing rules are respected: shebangs (`#! comment`), doc
section comments with long runs of hashes, and Spyder cells. Non-breaking spaces after comments (`#: comment`), section comments with long runs of hashes, and Spyder cells.
hashes are also preserved. Comments may sometimes be moved because of formatting Non-breaking spaces after hashes are also preserved. Comments may sometimes be moved
changes, which can break tools that assign special meaning to them. See because of formatting changes, which can break tools that assign special meaning to
[AST before and after formatting](#ast-before-and-after-formatting) for more discussion. them. See [AST before and after formatting](#ast-before-and-after-formatting) for more
discussion.
### Trailing commas ### Trailing commas
@ -227,16 +237,23 @@ A pre-existing trailing comma informs _Black_ to always explode contents of the
bracket pair into one item per line. Read more about this in the bracket pair into one item per line. Read more about this in the
[Pragmatism](#pragmatism) section below. [Pragmatism](#pragmatism) section below.
(labels/strings)=
### Strings ### Strings
_Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It _Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It
will replace the latter with the former as long as it does not result in more backslash will replace the latter with the former as long as it does not result in more backslash
escapes than before. escapes than before.
_Black_ also standardizes string prefixes, making them always lowercase. On top of that, _Black_ also standardizes string prefixes. Prefix characters are made lowercase with the
if your code is already Python 3.6+ only or it's using the `unicode_literals` future exception of [capital "R" prefixes](#rstrings-and-rstrings), unicode literal markers
import, _Black_ will remove `u` from the string prefix as it is meaningless in those (`u`) are removed because they are meaningless in Python 3, and in the case of multiple
scenarios. characters "r" is put first as in spoken language: "raw f-string".
Another area where Python allows multiple ways to format a string is escape sequences.
For example, `"\uabcd"` and `"\uABCD"` evaluate to the same string. _Black_ normalizes
such escape sequences to lowercase, but uses uppercase for `\N` named character escapes,
such as `"\N{MEETEI MAYEK LETTER HUK}"`.
The main reason to standardize on a single form of quotes is aesthetics. Having one kind The main reason to standardize on a single form of quotes is aesthetics. Having one kind
of quotes everywhere reduces reader distraction. It will also enable a future version of of quotes everywhere reduces reader distraction. It will also enable a future version of
@ -260,29 +277,18 @@ If you are adopting _Black_ in a large project with pre-existing string conventi
you can pass `--skip-string-normalization` on the command line. This is meant as an you can pass `--skip-string-normalization` on the command line. This is meant as an
adoption helper, avoid using this for new projects. adoption helper, avoid using this for new projects.
(labels/experimental-string)=
As an experimental option (can be enabled by `--experimental-string-processing`),
_Black_ splits long strings (using parentheses where appropriate) and merges short ones.
When split, parts of f-strings that don't need formatting are converted to plain
strings. User-made splits are respected when they do not exceed the line length limit.
Line continuation backslashes are converted into parenthesized strings. Unnecessary
parentheses are stripped. Because the functionality is experimental, feedback and issue
reports are highly encouraged!
_Black_ also processes docstrings. Firstly the indentation of docstrings is corrected _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected
for both quotations and the text within, although relative indentation in the text is for both quotations and the text within, although relative indentation in the text is
preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the
end of the docstring are removed. All leading tabs are converted to spaces, but tabs end of the docstring are removed. All leading tabs are converted to spaces, but tabs
inside text are preserved. Whitespace leading and trailing one-line docstrings is inside text are preserved. Whitespace leading and trailing one-line docstrings is
removed. The quotations of an empty docstring are separated with one space. removed.
### Numeric literals ### Numeric literals
_Black_ standardizes most numeric literals to use lowercase letters for the syntactic _Black_ standardizes most numeric literals to use lowercase letters for the syntactic
parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and
`1e10` instead of `1E10`. Python 2 long literals are styled as `2L` instead of `2l` to `1e10` instead of `1E10`.
avoid confusion between `l` and `1`.
### Line breaks & binary operators ### Line breaks & binary operators
@ -291,6 +297,26 @@ multiple lines. This is so that _Black_ is compliant with the recent changes in
[PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator) [PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
style guide, which emphasizes that this approach improves readability. style guide, which emphasizes that this approach improves readability.
Almost all operators will be surrounded by single spaces, the only exceptions are unary
operators (`+`, `-`, and `~`), and power operators when both operands are simple. For
powers, 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.
```python
# For example, these won't be surrounded by whitespace
a = x**y
b = config.base**5.2
c = config.base**runtime.config.exponent
d = 2**5
e = 2**~5
# ... but these will be surrounded by whitespace
f = 2 ** get_exponent()
g = get_x() ** get_y()
h = config['base'] ** 2
```
### Slices ### Slices
PEP 8 PEP 8
@ -383,16 +409,22 @@ recommended code style for those files is more terse than PEP 8:
_Black_ enforces the above rules. There are additional guidelines for formatting `.pyi` _Black_ enforces the above rules. There are additional guidelines for formatting `.pyi`
file that are not enforced yet but might be in a future version of the formatter: file that are not enforced yet but might be in a future version of the formatter:
- all function bodies should be empty (contain `...` instead of the body);
- do not use docstrings;
- prefer `...` over `pass`; - prefer `...` over `pass`;
- for arguments with a default, use `...` instead of the actual default;
- avoid using string literals in type annotations, stub files support forward references - avoid using string literals in type annotations, stub files support forward references
natively (like Python 3.7 code with `from __future__ import annotations`); natively (like Python 3.7 code with `from __future__ import annotations`);
- use variable annotations instead of type comments, even for stubs that target older - use variable annotations instead of type comments, even for stubs that target older
versions of Python; versions of Python.
- for arguments that default to `None`, use `Optional[]` explicitly;
- use `float` instead of `Union[int, float]`. ### Line endings
_Black_ will normalize line endings (`\n` or `\r\n`) based on the first line ending of
the file.
### Form feed characters
_Black_ will retain form feed characters on otherwise empty lines at the module level.
Only one form feed is retained for a group of consecutive empty lines. Where there are
two empty lines in a row, the form feed is placed on the second line.
## Pragmatism ## Pragmatism
@ -402,6 +434,8 @@ there were not many users anyway. Not many edge cases were reported. As a mature
_Black_ does make some exceptions to rules it otherwise holds. This section documents _Black_ does make some exceptions to rules it otherwise holds. This section documents
what those exceptions are and why this is the case. what those exceptions are and why this is the case.
(labels/magic-trailing-comma)=
### The magic trailing comma ### The magic trailing comma
_Black_ in general does not take existing formatting into account. _Black_ in general does not take existing formatting into account.
@ -438,17 +472,19 @@ default by (among others) GitHub and Visual Studio Code, differentiates between
r-strings and R-strings. The former are syntax highlighted as regular expressions while r-strings and R-strings. The former are syntax highlighted as regular expressions while
the latter are treated as true raw strings with no special semantics. the latter are treated as true raw strings with no special semantics.
(labels/ast-changes)=
### AST before and after formatting ### AST before and after formatting
When run with `--safe`, _Black_ checks that the code before and after is semantically When run with `--safe` (the default), _Black_ checks that the code before and after is
equivalent. This check is done by comparing the AST of the source with the AST of the semantically equivalent. This check is done by comparing the AST of the source with the
target. There are three limited cases in which the AST does differ: AST of the target. There are three limited cases in which the AST does differ:
1. _Black_ cleans up leading and trailing whitespace of docstrings, re-indenting them if 1. _Black_ cleans up leading and trailing whitespace of docstrings, re-indenting them if
needed. It's been one of the most popular user-reported features for the formatter to needed. It's been one of the most popular user-reported features for the formatter to
fix whitespace issues with docstrings. While the result is technically an AST fix whitespace issues with docstrings. While the result is technically an AST
difference, due to the various possibilities of forming docstrings, all realtime use difference, due to the various possibilities of forming docstrings, all real-world
of docstrings that we're aware of sanitizes indentation and leading/trailing uses of docstrings that we're aware of sanitize indentation and leading/trailing
whitespace anyway. whitespace anyway.
1. _Black_ manages optional parentheses for some statements. In the case of the `del` 1. _Black_ manages optional parentheses for some statements. In the case of the `del`

View File

@ -1,42 +1,269 @@
# The (future of the) Black code style # The (future of the) Black code style
```{warning} ## Preview style
Changes to this document often aren't tied and don't relate to releases of
_Black_. It's recommended that you read the latest version available. (labels/preview-style)=
Experimental, potentially disruptive style changes are gathered under the `--preview`
CLI flag. At the end of each year, these changes may be adopted into the default style,
as described in [The Black Code Style](index.md). Because the functionality is
experimental, feedback and issue reports are highly encouraged!
In the past, the preview style included some features with known bugs, so that we were
unable to move these features to the stable style. Therefore, such features are now
moved to the `--unstable` style. All features in the `--preview` style are expected to
make it to next year's stable style; features in the `--unstable` style will be
stabilized only if issues with them are fixed. If bugs are discovered in a `--preview`
feature, it is demoted to the `--unstable` style. To avoid thrash when a feature is
demoted from the `--preview` to the `--unstable` style, users can use the
`--enable-unstable-feature` flag to enable specific unstable features.
(labels/preview-features)=
Currently, the following features are included in the preview style:
- `always_one_newline_after_import`: Always force one blank line after import
statements, except when the line after the import is a comment or an import statement
- `wrap_long_dict_values_in_parens`: Add parentheses around long values in dictionaries
([see below](labels/wrap-long-dict-values))
- `fix_fmt_skip_in_one_liners`: Fix `# fmt: skip` behaviour on one-liner declarations,
such as `def foo(): return "mock" # fmt: skip`, where previously the declaration
would have been incorrectly collapsed.
(labels/unstable-features)=
The unstable style additionally includes the following features:
- `string_processing`: split long string literals and related changes
([see below](labels/string-processing))
- `multiline_string_handling`: more compact formatting of expressions involving
multiline strings ([see below](labels/multiline-string-handling))
- `hug_parens_with_braces_and_square_brackets`: more compact formatting of nested
brackets ([see below](labels/hug-parens))
(labels/wrap-long-dict-values)=
### Improved parentheses management in dicts
For dict literals with long values, they are now wrapped in parentheses. Unnecessary
parentheses are now removed. For example:
```python
my_dict = {
"a key in my dict": a_very_long_variable
* and_a_very_long_function_call()
/ 100000.0,
"another key": (short_value),
}
``` ```
## Using backslashes for with statements will be changed to:
[Backslashes are bad and should be never be used](labels/why-no-backslashes) however ```python
there is one exception: `with` statements using multiple context managers. Before Python my_dict = {
3.9 Python's grammar does not allow organizing parentheses around the series of context "a key in my dict": (
managers. a_very_long_variable * and_a_very_long_function_call() / 100000.0
),
We don't want formatting like: "another key": short_value,
}
```py3
with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4:
... # nothing to split on - line too long
``` ```
So _Black_ will eventually format it like this: (labels/hug-parens)=
```py3 ### Improved multiline dictionary and list indentation for sole function parameter
with \
make_context_manager(1) as cm1, \ For better readability and less verticality, _Black_ now pairs parentheses ("(", ")")
make_context_manager(2) as cm2, \ with braces ("{", "}") and square brackets ("[", "]") on the same line. For example:
make_context_manager(3) as cm3, \
make_context_manager(4) as cm4 \ ```python
: foo(
... # backslashes and an ugly stranded colon [
1,
2,
3,
]
)
nested_array = [
[
1,
2,
3,
]
]
``` ```
Although when the target version is Python 3.9 or higher, _Black_ will use parentheses will be changed to:
instead since they're allowed in Python 3.9 and higher.
## Improved string processing ```python
foo([
1,
2,
3,
])
Currently, _Black_ does not split long strings to fit the line length limit. Currently, nested_array = [[
there is [an experimental option](labels/experimental-string) to enable splitting 1,
strings. We plan to enable this option by default once it is fully stable. This is 2,
tracked in [this issue](https://github.com/psf/black/issues/2188). 3,
]]
```
This also applies to list and dictionary unpacking:
```python
foo(
*[
a_long_function_name(a_long_variable_name)
for a_long_variable_name in some_generator
]
)
```
will become:
```python
foo(*[
a_long_function_name(a_long_variable_name)
for a_long_variable_name in some_generator
])
```
You can use a magic trailing comma to avoid this compacting behavior; by default,
_Black_ will not reformat the following code:
```python
foo(
[
1,
2,
3,
],
)
```
(labels/string-processing)=
### Improved string processing
_Black_ will split long string literals and merge short ones. Parentheses are used where
appropriate. When split, parts of f-strings that don't need formatting are converted to
plain strings. f-strings will not be merged if they contain internal quotes and it would
change their quotation mark style. User-made splits are respected when they do not
exceed the line length limit. Line continuation backslashes are converted into
parenthesized strings. Unnecessary parentheses are stripped. The stability and status of
this feature istracked in [this issue](https://github.com/psf/black/issues/2188).
(labels/multiline-string-handling)=
### Improved multiline string handling
_Black_ is smarter when formatting multiline strings, especially in function arguments,
to avoid introducing extra line breaks. Previously, it would always consider multiline
strings as not fitting on a single line. With this new feature, _Black_ looks at the
context around the multiline string to decide if it should be inlined or split to a
separate line. For example, when a multiline string is passed to a function, _Black_
will only split the multiline string if a line is too long or if multiple arguments are
being passed.
For example, _Black_ will reformat
```python
textwrap.dedent(
"""\
This is a
multiline string
"""
)
```
to:
```python
textwrap.dedent("""\
This is a
multiline string
""")
```
And:
```python
MULTILINE = """
foobar
""".replace(
"\n", ""
)
```
to:
```python
MULTILINE = """
foobar
""".replace("\n", "")
```
Implicit multiline strings are special, because they can have inline comments. Strings
without comments are merged, for example
```python
s = (
"An "
"implicit "
"multiline "
"string"
)
```
becomes
```python
s = "An implicit multiline string"
```
A comment on any line of the string (or between two string lines) will block the
merging, so
```python
s = (
"An " # Important comment concerning just this line
"implicit "
"multiline "
"string"
)
```
and
```python
s = (
"An "
"implicit "
# Comment in between
"multiline "
"string"
)
```
will not be merged. Having the comment after or before the string lines (but still
inside the parens) will merge the string. For example
```python
s = ( # Top comment
"An "
"implicit "
"multiline "
"string"
# Bottom comment
)
```
becomes
```python
s = ( # Top comment
"An implicit multiline string"
# Bottom comment
)
```

View File

@ -0,0 +1,54 @@
# The Black Code Style
```{toctree}
---
hidden:
---
Current style <current_style>
Future style <future_style>
```
_Black_ is a PEP 8 compliant opinionated formatter with its own style.
While keeping the style unchanged throughout releases has always been a goal, the
_Black_ code style isn't set in stone. It evolves to accommodate for new features in the
Python language and, occasionally, in response to user feedback. Large-scale style
preferences presented in {doc}`current_style` are very unlikely to change, but minor
style aspects and details might change according to the stability policy presented
below. Ongoing style considerations are tracked on GitHub with the
[style](https://github.com/psf/black/labels/T%3A%20style) issue label.
(labels/stability-policy)=
## Stability Policy
The following policy applies for the _Black_ code style, in non pre-release versions of
_Black_:
- If code has been formatted with _Black_, it will remain unchanged when formatted with
the same options using any other release in the same calendar year.
This means projects can safely use `black ~= 22.0` without worrying about formatting
changes disrupting their project in 2022. We may still fix bugs where _Black_ crashes
on some code, and make other improvements that do not affect formatting.
In rare cases, we may make changes affecting code that has not been previously
formatted with _Black_. For example, we have had bugs where we accidentally removed
some comments. Such bugs can be fixed without breaking the stability policy.
- The first release in a new calendar year _may_ contain formatting changes, although
these will be minimised as much as possible. This is to allow for improved formatting
enabled by newer Python language syntax as well as due to improvements in the
formatting logic.
- The `--preview` and `--unstable` flags are exempt from this policy. There are no
guarantees around the stability of the output with these flags passed into _Black_.
They are intended for allowing experimentation with proposed changes to the _Black_
code style. The `--preview` style at the end of a year should closely match the stable
style for the next year, but we may always make changes.
Documentation for both the current and future styles can be found:
- {doc}`current_style`
- {doc}`future_style`

View File

@ -1,19 +0,0 @@
The Black Code Style
====================
.. toctree::
:hidden:
Current style <current_style>
Future style <future_style>
*Black* is a PEP 8 compliant opinionated formatter with its own style.
It should be noted that while keeping the style unchanged throughout releases is a
goal, the *Black* code style isn't set in stone. Sometimes it's modified in response to
user feedback or even changes to the Python language!
Documentation for both the current and future styles can be found:
- :doc:`current_style`
- :doc:`future_style`

View File

@ -4,10 +4,15 @@
protocol. The main benefit of using it is to avoid the cost of starting up a new _Black_ protocol. The main benefit of using it is to avoid the cost of starting up a new _Black_
process every time you want to blacken a file. process every time you want to blacken a file.
```{warning}
`blackd` should not be run as a publicly accessible server as there are no security
precautions in place to prevent abuse. **It is intended for local use only**.
```
## Usage ## Usage
`blackd` is not packaged alongside _Black_ by default because it has additional `blackd` is not packaged alongside _Black_ by default because it has additional
dependencies. You will need to execute `pip install black[d]` to install it. dependencies. You will need to execute `pip install 'black[d]'` to install it.
You can start the server on the default port, binding only to the local interface by You can start the server on the default port, binding only to the local interface by
running `blackd`. You will see a single line mentioning the server's version, and the running `blackd`. You will see a single line mentioning the server's version, and the
@ -45,12 +50,24 @@ is rejected with `HTTP 501` (Not Implemented).
The headers controlling how source code is formatted are: The headers controlling how source code is formatted are:
- `X-Line-Length`: corresponds to the `--line-length` command line flag. - `X-Line-Length`: corresponds to the `--line-length` command line flag.
- `X-Skip-Source-First-Line`: corresponds to the `--skip-source-first-line` command line
flag. If present and its value is not an empty string, the first line of the source
code will be ignored.
- `X-Skip-String-Normalization`: corresponds to the `--skip-string-normalization` - `X-Skip-String-Normalization`: corresponds to the `--skip-string-normalization`
command line flag. If present and its value is not the empty string, no string command line flag. If present and its value is not the empty string, no string
normalization will be performed. normalization will be performed.
- `X-Skip-Magic-Trailing-Comma`: corresponds to the `--skip-magic-trailing-comma` - `X-Skip-Magic-Trailing-Comma`: corresponds to the `--skip-magic-trailing-comma`
command line flag. If present and its value is not the empty string, trailing commas command line flag. If present and its value is not an empty string, trailing commas
will not be used as a reason to split lines. will not be used as a reason to split lines.
- `X-Preview`: corresponds to the `--preview` command line flag. If present and its
value is not an empty string, experimental and potentially disruptive style changes
will be used.
- `X-Unstable`: corresponds to the `--unstable` command line flag. If present and its
value is not an empty string, experimental style changes that are known to be buggy
will be used.
- `X-Enable-Unstable-Feature`: corresponds to the `--enable-unstable-feature` flag. The
contents of the flag must be a comma-separated list of unstable features to be
enabled. Example: `X-Enable-Unstable-Feature: feature1, feature2`.
- `X-Fast-Or-Safe`: if set to `fast`, `blackd` will act as _Black_ does when passed the - `X-Fast-Or-Safe`: if set to `fast`, `blackd` will act as _Black_ does when passed the
`--fast` command line flag. `--fast` command line flag.
- `X-Python-Variant`: if set to `pyi`, `blackd` will act as _Black_ does when passed the - `X-Python-Variant`: if set to `pyi`, `blackd` will act as _Black_ does when passed the

View File

@ -0,0 +1,53 @@
# Black Docker image
Official _Black_ Docker images are available on
[Docker Hub](https://hub.docker.com/r/pyfound/black).
_Black_ images with the following tags are available:
- release numbers, e.g. `21.5b2`, `21.6b0`, `21.7b0` etc.\
Recommended for users who want to use a particular version of _Black_.
- `latest_release` - tag created when a new version of _Black_ is released.\
Recommended for users who want to use released versions of _Black_. It maps to
[the latest release](https://github.com/psf/black/releases/latest) of _Black_.
- `latest_prerelease` - tag created when a new alpha (prerelease) version of _Black_ is
released.\
Recommended for users who want to preview or test alpha versions of _Black_. Note
that the most recent release may be newer than any prerelease, because no prereleases
are created before most releases.
- `latest` - tag used for the newest image of _Black_.\
Recommended for users who always want to use the latest version of _Black_, even
before it is released.
There is one more tag used for _Black_ Docker images - `latest_non_release`. It is
created for all unreleased
[commits on the `main` branch](https://github.com/psf/black/commits/main). This tag is
not meant to be used by external users.
From version 23.11.0 the Docker image installs a compiled black into the image.
## Usage
A permanent container doesn't have to be created to use _Black_ as a Docker image. It's
enough to run _Black_ commands for the chosen image denoted as `:tag`. In the below
examples, the `latest_release` tag is used. If `:tag` is omitted, the `latest` tag will
be used.
More about _Black_ usage can be found in
[Usage and Configuration: The basics](./the_basics.md).
### Check Black version
```console
$ docker run --rm pyfound/black:latest_release black --version
```
### Check code
```console
$ docker run --rm --volume $(pwd):/src --workdir /src pyfound/black:latest_release black --check .
```
_Remark_: besides [regular _Black_ exit codes](./the_basics.md) returned by `--check`
option, [Docker exit codes](https://docs.docker.com/engine/reference/run/#exit-status)
should also be considered.

View File

@ -22,10 +22,12 @@ run. The file is non-portable. The standard location on common operating systems
`file-mode` is an int flag that determines whether the file was formatted as 3.6+ only, `file-mode` is an int flag that determines whether the file was formatted as 3.6+ only,
as .pyi, and whether string normalization was omitted. as .pyi, and whether string normalization was omitted.
To override the location of these files on macOS or Linux, set the environment variable To override the location of these files on all systems, set the environment variable
`BLACK_CACHE_DIR` to the preferred location. Alternatively on macOS and Linux, set
`XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache `XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache
in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will in the directory you're running _Black_ from, set `BLACK_CACHE_DIR=.cache/black`.
then write the above files to `.cache/black/<version>/`. _Black_ will then write the above files to `.cache/black`. Note that `BLACK_CACHE_DIR`
will take precedence over `XDG_CACHE_HOME` if both are set.
## .gitignore ## .gitignore

View File

@ -0,0 +1,28 @@
# Usage and Configuration
```{toctree}
---
hidden:
---
the_basics
file_collection_and_discovery
black_as_a_server
black_docker_image
```
Sometimes, running _Black_ with its defaults and passing filepaths to it just won't cut
it. Passing each file using paths will become burdensome, and maybe you would like
_Black_ to not touch your files and just output diffs. And yes, you _can_ tweak certain
parts of _Black_'s style, but please know that configurability in this area is
purposefully limited.
Using many of these more advanced features of _Black_ will require some configuration.
Configuration that will either live on the command line or in a TOML configuration file.
This section covers features of _Black_ and configuring _Black_ in detail:
- {doc}`The basics <./the_basics>`
- {doc}`File collection and discovery <file_collection_and_discovery>`
- {doc}`Black as a server (blackd) <./black_as_a_server>`
- {doc}`Black Docker image <./black_docker_image>`

View File

@ -1,24 +0,0 @@
Usage and Configuration
=======================
.. toctree::
:hidden:
the_basics
file_collection_and_discovery
black_as_a_server
Sometimes, running *Black* with its defaults and passing filepaths to it just won't cut
it. Passing each file using paths will become burdensome, and maybe you would like
*Black* to not touch your files and just output diffs. And yes, you *can* tweak certain
parts of *Black*'s style, but please know that configurability in this area is
purposefully limited.
Using many of these more advanced features of *Black* will require some configuration.
Configuration that will either live on the command line or in a TOML configuration file.
This section covers features of *Black* and configuring *Black* in detail:
- :doc:`The basics <./the_basics>`
- :doc:`File collection and discovery <file_collection_and_discovery>`
- :doc:`Black as a server (blackd) <./black_as_a_server>`

View File

@ -4,15 +4,16 @@ Foundational knowledge on using and configuring Black.
_Black_ is a well-behaved Unix-style command-line tool: _Black_ is a well-behaved Unix-style command-line tool:
- it does nothing if no sources are passed to it; - it does nothing if it finds no sources to format;
- it will read from standard input and write to standard output if `-` is used as the - it will read from standard input and write to standard output if `-` is used as the
filename; filename;
- it only outputs messages to users on standard error; - it only outputs messages to users on standard error;
- exits with code 0 unless an internal error occurred (or `--check` was used). - exits with code 0 unless an internal error occurred or a CLI option prompted it.
## Usage ## Usage
To get started right away with sensible defaults: _Black_ will reformat entire files in place. To get started right away with sensible
defaults:
```sh ```sh
black {source_file_or_directory} black {source_file_or_directory}
@ -24,66 +25,167 @@ You can run _Black_ as a package if running it as a script doesn't work:
python -m black {source_file_or_directory} python -m black {source_file_or_directory}
``` ```
### Ignoring sections
Black will not reformat lines that contain `# fmt: skip` or blocks that start with
`# fmt: off` and end with `# fmt: on`. `# fmt: skip` can be mixed with other
pragmas/comments either with multiple comments (e.g. `# fmt: skip # pylint # noqa`) or
as a semicolon separated list (e.g. `# fmt: skip; pylint; noqa`). `# fmt: on/off` must
be on the same level of indentation and in the same block, meaning no unindents beyond
the initial indentation level between them. Black also recognizes
[YAPF](https://github.com/google/yapf)'s block comments to the same effect, as a
courtesy for straddling code.
### Command line options ### Command line options
_Black_ has quite a few knobs these days, although _Black_ is opinionated so style The CLI options of _Black_ can be displayed by running `black --help`. All options are
configuration options are deliberately limited and rarely added. You can list them by also covered in more detail below.
running `black --help`.
<details> While _Black_ has quite a few knobs these days, it is still opinionated so style options
are deliberately limited and rarely added.
<summary>Help output</summary> Note that all command-line options listed above can also be configured using a
`pyproject.toml` file (more on that below).
```{program-output} black --help #### `-h`, `--help`
``` Show available command-line options and exit.
</details> #### `-c`, `--code`
### Code input alternatives Format the code passed in as a string.
#### Standard Input
_Black_ supports formatting code via stdin, with the result being printed to stdout.
Just let _Black_ know with `-` as the path.
```console
$ echo "print ( 'hello, world' )" | black -
print("hello, world")
reformatted -
All done! ✨ 🍰 ✨
1 file reformatted.
```
**Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
option on some editors that rely on using stdin.
#### As a string
You can also pass code as a string using the `-c` / `--code` option.
```console ```console
$ black --code "print ( 'hello, world' )" $ black --code "print ( 'hello, world' )"
print("hello, world") print("hello, world")
``` ```
### Writeback and reporting #### `-l`, `--line-length`
By default _Black_ reformats the files given and/or found in place. Sometimes you need How many characters per line to allow. The default is 88.
_Black_ to just tell you what it _would_ do without actually rewriting the Python files.
There's two variations to this mode that are independently enabled by their respective See also [the style documentation](labels/line-length).
flags. Both variations can be enabled at once.
#### Exit code #### `-t`, `--target-version`
Passing `--check` will make _Black_ exit with: Python versions that should be supported by Black's output. You can run `black --help`
and look for the `--target-version` option to see the full list of supported versions.
You should include all versions that your code supports. If you support Python 3.11
through 3.13, you should write:
```console
$ black -t py311 -t py312 -t py313
```
In a [configuration file](#configuration-via-a-file), you can write:
```toml
target-version = ["py311", "py312", "py313"]
```
By default, Black will infer target versions from the project metadata in
`pyproject.toml`, specifically the `[project.requires-python]` field. If this does not
yield conclusive results, Black will use per-file auto-detection.
_Black_ uses this option to decide what grammar to use to parse your code. In addition,
it may use it to decide what style to use. For example, support for a trailing comma
after `*args` in a function call was added in Python 3.5, so _Black_ will add this comma
only if the target versions are all Python 3.5 or higher:
```console
$ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
f(
a,
*args,
)
$ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
f(
a,
*args
)
$ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
f(
a,
*args
)
```
#### `--pyi`
Format all input files like typing stubs regardless of file extension. This is useful
when piping source on standard input.
#### `--ipynb`
Format all input files like Jupyter Notebooks regardless of file extension. This is
useful when piping source on standard input.
#### `--python-cell-magics`
When processing Jupyter Notebooks, add the given magic to the list of known python-
magics. Useful for formatting cells with custom python magics.
#### `-x, --skip-source-first-line`
Skip the first line of the source code.
#### `-S, --skip-string-normalization`
By default, _Black_ uses double quotes for all strings and normalizes string prefixes,
as described in [the style documentation](labels/strings). If this option is given,
strings are left unchanged instead.
#### `-C, --skip-magic-trailing-comma`
By default, _Black_ uses existing trailing commas as an indication that short lines
should be left separate, as described in
[the style documentation](labels/magic-trailing-comma). If this option is given, the
magic trailing comma is ignored.
#### `--preview`
Enable potentially disruptive style changes that we expect to add to Black's main
functionality in the next major release. Use this if you want a taste of what next
year's style will look like.
Read more about [our preview style](labels/preview-style).
There is no guarantee on the code style produced by this flag across releases.
#### `--unstable`
Enable all style changes in `--preview`, plus additional changes that we would like to
make eventually, but that have known issues that need to be fixed before they can move
back to the `--preview` style. Use this if you want to experiment with these changes and
help fix issues with them.
There is no guarantee on the code style produced by this flag across releases.
#### `--enable-unstable-feature`
Enable specific features from the `--unstable` style. See
[the preview style documentation](labels/unstable-features) for the list of supported
features. This flag can only be used when `--preview` is enabled. Users are encouraged
to use this flag if they use `--preview` style and a feature that affects their code is
moved from the `--preview` to the `--unstable` style, but they want to avoid the thrash
from undoing this change.
There are no guarantees on the behavior of these features, or even their existence,
across releases.
(labels/exit-code)=
#### `--check`
Don't write the files back, just return the status. _Black_ will exit with:
- code 0 if nothing would change; - code 0 if nothing would change;
- code 1 if some files would be reformatted; or - code 1 if some files would be reformatted; or
- code 123 if there was an internal error - code 123 if there was an internal error
If used in combination with `--quiet` then only the exit code will be returned, unless
there was an internal error.
```console ```console
$ black test.py --check $ black test.py --check
All done! ✨ 🍰 ✨ All done! ✨ 🍰 ✨
@ -106,17 +208,17 @@ $ echo $?
123 123
``` ```
#### Diffs #### `--diff`
Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_ Don't write the files back, just output a diff to indicate what changes _Black_ would've
would've made. They are printed to stdout so capturing them is simple. made. They are printed to stdout so capturing them is simple.
If you'd like colored diffs, you can enable them with the `--color`. If you'd like colored diffs, you can enable them with `--color`.
```console ```console
$ black test.py --diff $ black test.py --diff
--- test.py 2021-03-08 22:23:40.848954 +0000 --- test.py 2021-03-08 22:23:40.848954+00:00
+++ test.py 2021-03-08 22:23:47.126319 +0000 +++ test.py 2021-03-08 22:23:47.126319+00:00
@@ -1 +1 @@ @@ -1 +1 @@
-print ( 'hello, world' ) -print ( 'hello, world' )
+print("hello, world") +print("hello, world")
@ -125,6 +227,198 @@ All done! ✨ 🍰 ✨
1 file would be reformatted. 1 file would be reformatted.
``` ```
#### `--color` / `--no-color`
Show (or do not show) colored diff. Only applies when `--diff` is given.
#### `--line-ranges`
When specified, _Black_ will try its best to only format these lines.
This option can be specified multiple times, and a union of the lines will be formatted.
Each range must be specified as two integers connected by a `-`: `<START>-<END>`. The
`<START>` and `<END>` integer indices are 1-based and inclusive on both ends.
_Black_ may still format lines outside of the ranges for multi-line statements.
Formatting more than one file or any ipynb files with this option is not supported. This
option cannot be specified in the `pyproject.toml` config.
Example: `black --line-ranges=1-10 --line-ranges=21-30 test.py` will format lines from
`1` to `10` and `21` to `30`.
This option is mainly for editor integrations, such as "Format Selection".
```{note}
Due to [#4052](https://github.com/psf/black/issues/4052), `--line-ranges` might format
extra lines outside of the ranges when ther are unformatted lines with the exact
content. It also disables _Black_'s formatting stability check in `--safe` mode.
```
#### `--fast` / `--safe`
By default, _Black_ performs [an AST safety check](labels/ast-changes) after formatting
your code. The `--fast` flag turns off this check and the `--safe` flag explicitly
enables it.
#### `--required-version`
Require a specific version of _Black_ to be running. This is useful for ensuring that
all contributors to your project are using the same version, because different versions
of _Black_ may format code a little differently. This option can be set in a
configuration file for consistent results across environments.
```console
$ black --version
black, 25.1.0 (compiled: yes)
$ black --required-version 25.1.0 -c "format = 'this'"
format = "this"
$ black --required-version 31.5b2 -c "still = 'beta?!'"
Oh no! 💥 💔 💥 The required version does not match the running version!
```
You can also pass just the major version:
```console
$ black --required-version 22 -c "format = 'this'"
format = "this"
$ black --required-version 31 -c "still = 'beta?!'"
Oh no! 💥 💔 💥 The required version does not match the running version!
```
Because of our [stability policy](../the_black_code_style/index.md), this will guarantee
stable formatting, but still allow you to take advantage of improvements that do not
affect formatting.
#### `--exclude`
A regular expression that matches files and directories that should be excluded on
recursive searches. An empty value means no paths are excluded. Use forward slashes for
directories on all platforms (Windows, too). By default, Black also ignores all paths
listed in `.gitignore`. Changing this value will override all default exclusions.
If the regular expression contains newlines, it is treated as a
[verbose regular expression](https://docs.python.org/3/library/re.html#re.VERBOSE). This
is typically useful when setting these options in a `pyproject.toml` configuration file;
see [Configuration format](#configuration-format) for more information.
#### `--extend-exclude`
Like `--exclude`, but adds additional files and directories on top of the default values
instead of overriding them.
#### `--force-exclude`
Like `--exclude`, but files and directories matching this regex will be excluded even
when they are passed explicitly as arguments. This is useful when invoking Black
programmatically on changed files, such as in a pre-commit hook or editor plugin.
#### `--stdin-filename`
The name of the file when passing it through stdin. Useful to make sure Black will
respect the `--force-exclude` option on some editors that rely on using stdin.
#### `--include`
A regular expression that matches files and directories that should be included on
recursive searches. An empty value means all files are included regardless of the name.
Use forward slashes for directories on all platforms (Windows, too). Overrides all
exclusions, including from `.gitignore` and command line options.
#### `-W`, `--workers`
When _Black_ formats multiple files, it may use a process pool to speed up formatting.
This option controls the number of parallel workers. This can also be specified via the
`BLACK_NUM_WORKERS` environment variable. Defaults to the number of CPUs in the system.
#### `-q`, `--quiet`
Stop emitting all non-critical output. Error messages will still be emitted (which can
silenced by `2>/dev/null`).
```console
$ black src/ -q
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
```
#### `-v`, `--verbose`
Emit messages about files that were not changed or were ignored due to exclusion
patterns. If _Black_ is using a configuration file, a message detailing which one it is
using will be emitted.
```console
$ black src/ -v
Using configuration from /tmp/pyproject.toml.
src/blib2to3 ignored: matches the --extend-exclude regular expression
src/_black_version.py wasn't modified on disk since last run.
src/black/__main__.py wasn't modified on disk since last run.
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
reformatted src/black_primer/lib.py
reformatted src/blackd/__init__.py
reformatted src/black/__init__.py
Oh no! 💥 💔 💥
3 files reformatted, 2 files left unchanged, 1 file failed to reformat
```
#### `--version`
You can check the version of _Black_ you have installed using the `--version` flag.
```console
$ black --version
black, 25.1.0
```
#### `--config`
Read configuration options from a configuration file. See
[below](#configuration-via-a-file) for more details on the configuration file.
### Environment variable options
_Black_ supports the following configuration via environment variables.
#### `BLACK_CACHE_DIR`
The directory where _Black_ should store its cache.
#### `BLACK_NUM_WORKERS`
The number of parallel workers _Black_ should use. The command line option `-W` /
`--workers` takes precedence over this environment variable.
### Code input alternatives
_Black_ supports formatting code via stdin, with the result being printed to stdout.
Just let _Black_ know with `-` as the path.
```console
$ echo "print ( 'hello, world' )" | black -
print("hello, world")
reformatted -
All done! ✨ 🍰 ✨
1 file reformatted.
```
**Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
option on some editors that rely on using stdin.
You can also pass code as a string using the `--code` option.
### Writeback and reporting
By default _Black_ reformats the files given and/or found in place. Sometimes you need
_Black_ to just tell you what it _would_ do without actually rewriting the Python files.
There's two variations to this mode that are independently enabled by their respective
flags:
- `--check` (exit with code 1 if any file would be reformatted)
- `--diff` (print a diff instead of reformatting files)
Both variations can be enabled at once.
### Output verbosity ### Output verbosity
_Black_ in general tries to produce the right amount of output, balancing between _Black_ in general tries to produce the right amount of output, balancing between
@ -141,53 +435,7 @@ Oh no! 💥 💔 💥
3 files reformatted, 2 files left unchanged, 1 file failed to reformat. 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
``` ```
Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that The `--quiet` and `--verbose` flags control output verbosity.
were not changed or were ignored due to exclusion patterns. If _Black_ is using a
configuration file, a blue message detailing which one it is using will be emitted.
```console
$ black src/ -v
Using configuration from /tmp/pyproject.toml.
src/blib2to3 ignored: matches the --extend-exclude regular expression
src/_black_version.py wasn't modified on disk since last run.
src/black/__main__.py wasn't modified on disk since last run.
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
reformatted src/black_primer/lib.py
reformatted src/blackd/__init__.py
reformatted src/black/__init__.py
Oh no! 💥 💔 💥
3 files reformatted, 2 files left unchanged, 1 file failed to reformat
```
Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critial output.
Error messages will still be emitted (which can silenced by `2>/dev/null`).
```console
$ black src/ -q
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
```
### Versions
You can check the version of _Black_ you have installed using the `--version` flag.
```console
$ black --version
black, version 21.5b0
```
An option to require a specific version to be running is also provided.
```console
$ black --required-version 21.5b2 -c "format = 'this'"
format = "this"
$ black --required-version 31.5b2 -c "still = 'beta?!'"
Oh no! 💥 💔 💥 The required version does not match the running version!
```
This is useful for example when running _Black_ in multiple environments that haven't
necessarily installed the correct version. This option can be set in a configuration
file for consistent results across environments.
## Configuration via a file ## Configuration via a file
@ -204,16 +452,18 @@ code in compliance with many other _Black_ formatted projects.
[PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
configuration file to store build system requirements for Python projects. With the help configuration file to store build system requirements for Python projects. With the help
of tools like [Poetry](https://python-poetry.org/) or of tools like [Poetry](https://python-poetry.org/),
[Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the need for [Flit](https://flit.readthedocs.io/en/latest/), or
`setup.py` and `setup.cfg` files. [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
`setup.cfg` files.
### Where _Black_ looks for the file ### Where _Black_ looks for the file
By default _Black_ looks for `pyproject.toml` starting from the common base directory of By default _Black_ looks for `pyproject.toml` containing a `[tool.black]` section
all files and directories passed on the command line. If it's not there, it looks in starting from the common base directory of all files and directories passed on the
parent directories. It stops looking when it finds the file, or a `.git` directory, or a command line. If it's not there, it looks in parent directories. It stops looking when
`.hg` directory, or the root of the file system, whichever comes first. it finds the file, or a `.git` directory, or a `.hg` directory, or the root of the file
system, whichever comes first.
If you're formatting standard input, _Black_ will look for configuration starting from If you're formatting standard input, _Black_ will look for configuration starting from
the current working directory. the current working directory.
@ -228,15 +478,15 @@ operating system, this configuration file should be stored as:
`XDG_CONFIG_HOME` environment variable is not set) `XDG_CONFIG_HOME` environment variable is not set)
Note that these are paths to the TOML file itself (meaning that they shouldn't be named Note that these are paths to the TOML file itself (meaning that they shouldn't be named
as `pyproject.toml`), not directories where you store the configuration. Here, `~` as `pyproject.toml`), not directories where you store the configuration (i.e.,
refers to the path to your home directory. On Windows, this will be something like `black`/`.black` is the file to create and add your configuration options to, in the
`C:\\Users\UserName`. `~/.config/` directory). Here, `~` refers to the path to your home directory. On
Windows, this will be something like `C:\\Users\UserName`.
You can also explicitly specify the path to a particular file that you want with You can also explicitly specify the path to a particular file that you want with
`--config`. In this situation _Black_ will not look for any other file. `--config`. In this situation _Black_ will not look for any other file.
If you're running with `--verbose`, you will see a blue message if a file was found and If you're running with `--verbose`, you will see a message if a file was found and used.
used.
Please note `blackd` will not use `pyproject.toml` configuration. Please note `blackd` will not use `pyproject.toml` configuration.
@ -259,10 +509,14 @@ expressions by Black. Use `[ ]` to denote a significant space character.
line-length = 88 line-length = 88
target-version = ['py37'] target-version = ['py37']
include = '\.pyi?$' include = '\.pyi?$'
# 'extend-exclude' excludes files or directories in addition to the defaults
extend-exclude = ''' extend-exclude = '''
# A regex preceded with ^/ will apply only to files and directories # A regex preceded with ^/ will apply only to files and directories
# in the root of the project. # in the root of the project.
^/foo.py # exclude a file named foo.py in the root of the project (in addition to the defaults) (
^/foo.py # exclude a file named foo.py in the root of the project
| .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
)
''' '''
``` ```
@ -280,9 +534,6 @@ file hierarchy.
## Next steps ## Next steps
You've probably noted that not all of the options you can pass to _Black_ have been
covered. Don't worry, the rest will be covered in a later section.
A good next step would be configuring auto-discovery so `black .` is all you need A good next step would be configuring auto-discovery so `black .` is all you need
instead of laborously listing every file or directory. You can get started by heading instead of laborously listing every file or directory. You can get started by heading
over to [File collection and discovery](./file_collection_and_discovery.md). over to [File collection and discovery](./file_collection_and_discovery.md).

View File

@ -7,29 +7,20 @@
import venv import venv
import zipfile import zipfile
from argparse import ArgumentParser, Namespace from argparse import ArgumentParser, Namespace
from collections.abc import Generator
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache, partial from functools import lru_cache, partial
from pathlib import Path from pathlib import Path
from typing import ( # type: ignore # typing can't see Literal from typing import NamedTuple, Optional, Union, cast
Generator,
List,
Literal,
NamedTuple,
Optional,
Tuple,
Union,
cast,
)
from urllib.request import urlopen, urlretrieve from urllib.request import urlopen, urlretrieve
PYPI_INSTANCE = "https://pypi.org/pypi" PYPI_INSTANCE = "https://pypi.org/pypi"
PYPI_TOP_PACKAGES = ( PYPI_TOP_PACKAGES = (
"https://hugovk.github.io/top-pypi-packages/top-pypi-packages-{days}-days.json" "https://hugovk.github.io/top-pypi-packages/top-pypi-packages.min.json"
) )
INTERNAL_BLACK_REPO = f"{tempfile.gettempdir()}/__black" INTERNAL_BLACK_REPO = f"{tempfile.gettempdir()}/__black"
ArchiveKind = Union[tarfile.TarFile, zipfile.ZipFile] ArchiveKind = Union[tarfile.TarFile, zipfile.ZipFile]
Days = Union[Literal[30], Literal[365]]
subprocess.run = partial(subprocess.run, check=True) # type: ignore subprocess.run = partial(subprocess.run, check=True) # type: ignore
# https://github.com/python/mypy/issues/1484 # https://github.com/python/mypy/issues/1484
@ -64,8 +55,8 @@ def get_pypi_download_url(package: str, version: Optional[str]) -> str:
return cast(str, source["url"]) return cast(str, source["url"])
def get_top_packages(days: Days) -> List[str]: def get_top_packages() -> list[str]:
with urlopen(PYPI_TOP_PACKAGES.format(days=days)) as page: with urlopen(PYPI_TOP_PACKAGES) as page:
result = json.load(page) result = json.load(page)
return [package["project"] for package in result["rows"]] return [package["project"] for package in result["rows"]]
@ -128,13 +119,12 @@ def get_package(
def download_and_extract_top_packages( def download_and_extract_top_packages(
directory: Path, directory: Path,
days: Days = 365,
workers: int = 8, workers: int = 8,
limit: slice = DEFAULT_SLICE, limit: slice = DEFAULT_SLICE,
) -> Generator[Path, None, None]: ) -> Generator[Path, None, None]:
with ThreadPoolExecutor(max_workers=workers) as executor: with ThreadPoolExecutor(max_workers=workers) as executor:
bound_downloader = partial(get_package, version=None, directory=directory) bound_downloader = partial(get_package, version=None, directory=directory)
for package in executor.map(bound_downloader, get_top_packages(days)[limit]): for package in executor.map(bound_downloader, get_top_packages()[limit]):
if package is not None: if package is not None:
yield package yield package
@ -161,7 +151,7 @@ def git_switch_branch(
subprocess.run(args, cwd=repo) subprocess.run(args, cwd=repo)
def init_repos(options: Namespace) -> Tuple[Path, ...]: def init_repos(options: Namespace) -> tuple[Path, ...]:
options.output.mkdir(exist_ok=True) options.output.mkdir(exist_ok=True)
if options.top_packages: if options.top_packages:
@ -217,7 +207,7 @@ def format_repo_with_version(
git_switch_branch(black_version.version, repo=black_repo) git_switch_branch(black_version.version, repo=black_repo)
git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch) git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch)
format_cmd: List[Union[Path, str]] = [ format_cmd: list[Union[Path, str]] = [
black_runner(black_version.version, black_repo), black_runner(black_version.version, black_repo),
(black_repo / "black.py").resolve(), (black_repo / "black.py").resolve(),
".", ".",
@ -233,7 +223,7 @@ def format_repo_with_version(
return current_branch return current_branch
def format_repos(repos: Tuple[Path, ...], options: Namespace) -> None: def format_repos(repos: tuple[Path, ...], options: Namespace) -> None:
black_versions = tuple( black_versions = tuple(
BlackVersion(*version.split(":")) for version in options.versions BlackVersion(*version.split(":")) for version in options.versions
) )
@ -254,11 +244,9 @@ def format_repos(repos: Tuple[Path, ...], options: Namespace) -> None:
def main() -> None: def main() -> None:
parser = ArgumentParser( parser = ArgumentParser(description="""Black Gallery is a script that
description="""Black Gallery is a script that
automates the process of applying different Black versions to a selected automates the process of applying different Black versions to a selected
PyPI package and seeing the results between versions.""" PyPI package and seeing the results between versions.""")
)
group = parser.add_mutually_exclusive_group(required=True) group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-p", "--pypi-package", help="PyPI package to download.") group.add_argument("-p", "--pypi-package", help="PyPI package to download.")

View File

@ -1,39 +0,0 @@
[mypy]
# Specify the target platform details in config, so your developers are
# free to run mypy on Windows, Linux, or macOS and get consistent
# results.
python_version=3.6
platform=linux
show_column_numbers=True
# show error messages from unrelated files
follow_imports=normal
# suppress errors about unsatisfied imports
ignore_missing_imports=True
# be strict
disallow_untyped_calls=True
warn_return_any=True
strict_optional=True
warn_no_return=True
warn_redundant_casts=True
warn_unused_ignores=True
# Until we're not supporting 3.6 primer needs this
disallow_any_generics=False
# The following are off by default. Flip them on if you feel
# adventurous.
disallow_untyped_defs=True
check_untyped_defs=True
# No incremental mode
cache_dir=/dev/null
[mypy-aiohttp.*]
follow_imports=skip
[mypy-black]
# The following is because of `patch_click()`. Remove when
# we drop Python 3.6 support.
warn_unused_ignores=False

View File

@ -15,9 +15,13 @@
" 1.2: " 1.2:
" - use autoload script " - use autoload script
if exists("g:load_black")
finish
endif
if v:version < 700 || !has('python3') if v:version < 700 || !has('python3')
func! __BLACK_MISSING() func! __BLACK_MISSING()
echo "The black.vim plugin requires vim7.0+ with Python 3.6 support." echo "The black.vim plugin requires vim7.0+ with Python 3.9 support."
endfunc endfunc
command! Black :call __BLACK_MISSING() command! Black :call __BLACK_MISSING()
command! BlackUpgrade :call __BLACK_MISSING() command! BlackUpgrade :call __BLACK_MISSING()
@ -25,10 +29,6 @@ if v:version < 700 || !has('python3')
finish finish
endif endif
if exists("g:load_black")
finish
endif
let g:load_black = "py1.0" let g:load_black = "py1.0"
if !exists("g:black_virtualenv") if !exists("g:black_virtualenv")
if has("nvim") if has("nvim")
@ -43,18 +43,43 @@ endif
if !exists("g:black_linelength") if !exists("g:black_linelength")
let g:black_linelength = 88 let g:black_linelength = 88
endif endif
if !exists("g:black_string_normalization") if !exists("g:black_skip_string_normalization")
if exists("g:black_skip_string_normalization") if exists("g:black_string_normalization")
let g:black_string_normalization = !g:black_skip_string_normalization let g:black_skip_string_normalization = !g:black_string_normalization
else else
let g:black_string_normalization = 1 let g:black_skip_string_normalization = 0
endif
endif
if !exists("g:black_skip_magic_trailing_comma")
if exists("g:black_magic_trailing_comma")
let g:black_skip_magic_trailing_comma = !g:black_magic_trailing_comma
else
let g:black_skip_magic_trailing_comma = 0
endif endif
endif endif
if !exists("g:black_quiet") if !exists("g:black_quiet")
let g:black_quiet = 0 let g:black_quiet = 0
endif endif
if !exists("g:black_target_version")
let g:black_target_version = ""
endif
if !exists("g:black_use_virtualenv")
let g:black_use_virtualenv = 1
endif
if !exists("g:black_preview")
let g:black_preview = 0
endif
function BlackComplete(ArgLead, CmdLine, CursorPos)
return [
\ 'target_version=py39',
\ 'target_version=py310',
\ 'target_version=py311',
\ 'target_version=py312',
\ 'target_version=py313',
\ ]
endfunction
command! Black :call black#Black() command! -nargs=* -complete=customlist,BlackComplete Black :call black#Black(<f-args>)
command! BlackUpgrade :call black#BlackUpgrade() command! BlackUpgrade :call black#BlackUpgrade()
command! BlackVersion :call black#BlackVersion() command! BlackVersion :call black#BlackVersion()

View File

@ -7,28 +7,238 @@
[tool.black] [tool.black]
line-length = 88 line-length = 88
target-version = ['py36', 'py37', 'py38'] target-version = ['py39']
include = '\.pyi?$' include = '\.pyi?$'
extend-exclude = ''' extend-exclude = '''
/( /(
# The following are specific to Black, you probably don't want those. # The following are specific to Black, you probably don't want those.
| blib2to3 tests/data/
| tests/data | profiling/
| profiling | scripts/generate_schema.py # Uses match syntax
)/ )
''' '''
# We use the unstable style for formatting Black itself. If you
# want bug-free formatting, you should keep this off. If you want
# stable formatting across releases, you should also keep `preview = true`
# (which is implied by this flag) off.
unstable = true
# Build system information and other project-specific configuration below.
# Build system information below.
# NOTE: You don't need this in your own Black configuration. # NOTE: You don't need this in your own Black configuration.
[build-system] [build-system]
requires = ["setuptools>=41.0", "setuptools-scm", "wheel"] requires = ["hatchling>=1.20.0", "hatch-vcs", "hatch-fancy-pypi-readme"]
build-backend = "setuptools.build_meta" build-backend = "hatchling.build"
[project]
name = "black"
description = "The uncompromising code formatter."
license = "MIT"
requires-python = ">=3.9"
authors = [
{ name = "Łukasz Langa", email = "lukasz@langa.pl" },
]
keywords = [
"automation",
"autopep8",
"formatter",
"gofmt",
"pyfmt",
"rustfmt",
"yapf",
]
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Quality Assurance",
]
dependencies = [
"click>=8.0.0",
"mypy_extensions>=0.4.3",
"packaging>=22.0",
"pathspec>=0.9.0",
"platformdirs>=2",
"pytokens>=0.1.10",
"tomli>=1.1.0; python_version < '3.11'",
"typing_extensions>=4.0.1; python_version < '3.11'",
]
dynamic = ["readme", "version"]
[project.optional-dependencies]
colorama = ["colorama>=0.4.3"]
uvloop = ["uvloop>=0.15.2"]
d = ["aiohttp>=3.10"]
jupyter = [
"ipython>=7.8.0",
"tokenize-rt>=3.2.0",
]
[project.scripts]
black = "black:patched_main"
blackd = "blackd:patched_main [d]"
[project.entry-points."validate_pyproject.tool_schema"]
black = "black.schema:get_schema"
[project.urls]
Documentation = "https://black.readthedocs.io/"
Changelog = "https://github.com/psf/black/blob/main/CHANGES.md"
Repository = "https://github.com/psf/black"
Issues = "https://github.com/psf/black/issues"
[tool.hatch.metadata.hooks.fancy-pypi-readme]
content-type = "text/markdown"
fragments = [
{ path = "README.md" },
{ path = "CHANGES.md" },
]
[tool.hatch.version]
source = "vcs"
[tool.hatch.build.hooks.vcs]
version-file = "src/_black_version.py"
template = '''
version = "{version}"
'''
[tool.hatch.build.targets.sdist]
exclude = ["/profiling"]
[tool.hatch.build.targets.wheel]
only-include = ["src"]
sources = ["src"]
# Note that we change the behaviour of this flag below
macos-max-compat = true
[tool.hatch.build.targets.wheel.hooks.mypyc]
enable-by-default = false
dependencies = [
"hatch-mypyc>=0.16.0",
"mypy>=1.12",
"click>=8.1.7",
]
require-runtime-dependencies = true
exclude = [
# There's no good reason for blackd to be compiled.
"/src/blackd",
# Not performance sensitive, so save bytes + compilation time:
"/src/blib2to3/__init__.py",
"/src/blib2to3/pgen2/__init__.py",
"/src/black/output.py",
"/src/black/concurrency.py",
"/src/black/files.py",
"/src/black/report.py",
# Breaks the test suite when compiled (and is also useless):
"/src/black/debug.py",
# Compiled modules can't be run directly and that's a problem here:
"/src/black/__main__.py",
]
mypy-args = ["--ignore-missing-imports"]
options = { debug_level = "0" }
[tool.cibuildwheel]
build-verbosity = 1
# So these are the environments we target:
# - Python: CPython 3.9+ only
# - Architecture (64-bit only): amd64 / x86_64, universal2, and arm64
# - OS: Linux (no musl), Windows, and macOS
build = "cp3*"
skip = ["*-manylinux_i686", "*-musllinux_*", "*-win32", "pp*"]
# This is the bare minimum needed to run the test suite. Pulling in the full
# test_requirements.txt would download a bunch of other packages not necessary
# here and would slow down the testing step a fair bit.
test-requires = ["pytest>=6.1.1"]
test-command = 'pytest {project} -k "not incompatible_with_mypyc"'
test-extras = ["d"," jupyter"]
# Skip trying to test arm64 builds on Intel Macs. (so cross-compilation doesn't
# straight up crash)
test-skip = ["*-macosx_arm64", "*-macosx_universal2:arm64"]
[tool.cibuildwheel.environment]
HATCH_BUILD_HOOKS_ENABLE = "1"
MYPYC_OPT_LEVEL = "3"
MYPYC_DEBUG_LEVEL = "0"
[tool.cibuildwheel.linux]
manylinux-x86_64-image = "manylinux_2_28"
before-build = [
"yum install -y clang gcc",
]
[tool.cibuildwheel.linux.environment]
HATCH_BUILD_HOOKS_ENABLE = "1"
MYPYC_OPT_LEVEL = "3"
MYPYC_DEBUG_LEVEL = "0"
# Black needs Clang to compile successfully on Linux.
CC = "clang"
[tool.isort]
atomic = true
profile = "black"
line_length = 88
skip_gitignore = true
skip_glob = ["tests/data", "profiling"]
known_first_party = ["black", "blib2to3", "blackd", "_black_version"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
# Option below requires `tests/optional.py` # Option below requires `tests/optional.py`
addopts = "--strict-config --strict-markers"
optional-tests = [ optional-tests = [
"no_python2: run when `python2` extra NOT installed",
"no_blackd: run when `d` extra NOT installed", "no_blackd: run when `d` extra NOT installed",
] "no_jupyter: run when `jupyter` extra NOT installed",
]
markers = [
"incompatible_with_mypyc: run when testing mypyc compiled black"
]
xfail_strict = true
filterwarnings = ["error"]
[tool.coverage.report]
omit = [
"src/blib2to3/*",
"tests/data/*",
"*/site-packages/*",
".tox/*"
]
[tool.coverage.run]
relative_files = true
branch = true
[tool.mypy]
# Specify the target platform details in config, so your developers are
# free to run mypy on Windows, Linux, or macOS and get consistent
# results.
python_version = "3.9"
mypy_path = "src"
strict = true
strict_bytes = true
local_partial_types = true
# Unreachable blocks have been an issue when compiling mypyc, let's try to avoid 'em in the first place.
warn_unreachable = true
implicit_reexport = true
show_error_codes = true
show_column_numbers = true
[[tool.mypy.overrides]]
module = ["pathspec.*", "IPython.*", "colorama.*", "tokenize_rt.*", "uvloop.*", "_black_version.*"]
ignore_missing_imports = true
# CI only checks src/, but in case users are running LSP or similar we explicitly ignore
# errors in test data files.
[[tool.mypy.overrides]]
module = ["tests.data.*"]
ignore_errors = true

0
scripts/__init__.py Normal file
View File

View File

@ -0,0 +1,54 @@
"""
Check that the rev value in the example pre-commit configuration matches
the latest version of Black. This saves us from forgetting to update that
during the release process.
Why can't we just use `rev: stable` and call it a day? Well pre-commit
won't auto update the hook as you may expect (and for good reasons, some
technical and some pragmatic). Encouraging bad practice is also just
not ideal. xref: https://github.com/psf/black/issues/420
"""
import os
import sys
import commonmark
import yaml
from bs4 import BeautifulSoup # type: ignore[import-untyped]
def main(changes: str, source_version_control: str) -> None:
changes_html = commonmark.commonmark(changes)
changes_soup = BeautifulSoup(changes_html, "html.parser")
headers = changes_soup.find_all("h2")
latest_tag, *_ = [
header.string for header in headers if header.string != "Unreleased"
]
source_version_control_html = commonmark.commonmark(source_version_control)
source_version_control_soup = BeautifulSoup(
source_version_control_html, "html.parser"
)
pre_commit_repos = yaml.safe_load(
source_version_control_soup.find(class_="language-yaml").string
)["repos"]
for repo in pre_commit_repos:
pre_commit_rev = repo["rev"]
if not pre_commit_rev == latest_tag:
print(
"Please set the rev in ``source_version_control.md`` to be the latest "
f"one.\nExpected {latest_tag}, got {pre_commit_rev}.\n"
)
sys.exit(1)
if __name__ == "__main__":
with open("CHANGES.md", encoding="utf-8") as fd:
changes = fd.read()
with open(
os.path.join("docs", "integrations", "source_version_control.md"),
encoding="utf-8",
) as fd:
source_version_control = fd.read()
main(changes, source_version_control)

View File

@ -0,0 +1,48 @@
"""
Check that the rev value in the example from ``the_basics.md`` matches
the latest version of Black. This saves us from forgetting to update that
during the release process.
"""
import os
import sys
import commonmark
from bs4 import BeautifulSoup # type: ignore[import-untyped]
def main(changes: str, the_basics: str) -> None:
changes_html = commonmark.commonmark(changes)
changes_soup = BeautifulSoup(changes_html, "html.parser")
headers = changes_soup.find_all("h2")
tags = [header.string for header in headers if header.string != "Unreleased"]
latest_tag = tags[0]
the_basics_html = commonmark.commonmark(the_basics)
the_basics_soup = BeautifulSoup(the_basics_html, "html.parser")
version_examples = [
code_block.string
for code_block in the_basics_soup.find_all(class_="language-console")
if "$ black --version" in code_block.string
]
for tag in tags:
for version_example in version_examples:
if tag in version_example and tag != latest_tag:
print(
"Please set the version in the ``black --version`` "
"examples from ``the_basics.md`` to be the latest one.\n"
f"Expected {latest_tag}, got {tag}.\n"
)
sys.exit(1)
if __name__ == "__main__":
with open("CHANGES.md", encoding="utf-8") as fd:
changes = fd.read()
with open(
os.path.join("docs", "usage_and_configuration", "the_basics.md"),
encoding="utf-8",
) as fd:
the_basics = fd.read()
main(changes, the_basics)

View File

@ -0,0 +1,231 @@
"""Helper script for psf/black's diff-shades Github Actions integration.
diff-shades is a tool for analyzing what happens when you run Black on
OSS code capturing it for comparisons or other usage. It's used here to
help measure the impact of a change *before* landing it (in particular
posting a comment on completion for PRs).
This script exists as a more maintainable alternative to using inline
Javascript in the workflow YAML files. The revision configuration and
resolving, caching, and PR comment logic is contained here.
For more information, please see the developer docs:
https://black.readthedocs.io/en/latest/contributing/gauging_changes.html#diff-shades
"""
import json
import os
import platform
import pprint
import subprocess
import sys
import zipfile
from base64 import b64encode
from io import BytesIO
from pathlib import Path
from typing import Any, Final, Literal
import click
import urllib3
from packaging.version import Version
COMMENT_FILE: Final = ".pr-comment.json"
DIFF_STEP_NAME: Final = "Generate HTML diff report"
DOCS_URL: Final = (
"https://black.readthedocs.io/en/latest/"
"contributing/gauging_changes.html#diff-shades"
)
USER_AGENT: Final = f"psf/black diff-shades workflow via urllib3/{urllib3.__version__}"
SHA_LENGTH: Final = 10
GH_API_TOKEN: Final = os.getenv("GITHUB_TOKEN")
REPO: Final = os.getenv("GITHUB_REPOSITORY", default="psf/black")
http = urllib3.PoolManager()
def set_output(name: str, value: str) -> None:
if len(value) < 200:
print(f"[INFO]: setting '{name}' to '{value}'")
else:
print(f"[INFO]: setting '{name}' to [{len(value)} chars]")
if "GITHUB_OUTPUT" in os.environ:
if "\n" in value:
# https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
delimiter = b64encode(os.urandom(16)).decode()
value = f"{delimiter}\n{value}\n{delimiter}"
command = f"{name}<<{value}"
else:
command = f"{name}={value}"
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
print(command, file=f)
def http_get(url: str, *, is_json: bool = True, **kwargs: Any) -> Any:
headers = kwargs.get("headers") or {}
headers["User-Agent"] = USER_AGENT
if "github" in url:
if GH_API_TOKEN:
headers["Authorization"] = f"token {GH_API_TOKEN}"
headers["Accept"] = "application/vnd.github.v3+json"
kwargs["headers"] = headers
r = http.request("GET", url, **kwargs)
if is_json:
data = json.loads(r.data.decode("utf-8"))
else:
data = r.data
print(f"[INFO]: issued GET request for {r.geturl()}")
if not (200 <= r.status < 300):
pprint.pprint(dict(r.info()))
pprint.pprint(data)
raise RuntimeError(f"unexpected status code: {r.status}")
return data
def get_main_revision() -> str:
data = http_get(
f"https://api.github.com/repos/{REPO}/commits",
fields={"per_page": "1", "sha": "main"},
)
assert isinstance(data[0]["sha"], str)
return data[0]["sha"]
def get_pr_revision(pr: int) -> str:
data = http_get(f"https://api.github.com/repos/{REPO}/pulls/{pr}")
assert isinstance(data["head"]["sha"], str)
return data["head"]["sha"]
def get_pypi_version() -> Version:
data = http_get("https://pypi.org/pypi/black/json")
versions = [Version(v) for v in data["releases"]]
sorted_versions = sorted(versions, reverse=True)
return sorted_versions[0]
@click.group()
def main() -> None:
pass
@main.command("config", help="Acquire run configuration and metadata.")
@click.argument("event", type=click.Choice(["push", "pull_request"]))
def config(event: Literal["push", "pull_request"]) -> None:
import diff_shades # type: ignore[import-not-found]
if event == "push":
jobs = [{"mode": "preview-changes", "force-flag": "--force-preview-style"}]
# Push on main, let's use PyPI Black as the baseline.
baseline_name = str(get_pypi_version())
baseline_cmd = f"git checkout {baseline_name}"
target_rev = os.getenv("GITHUB_SHA")
assert target_rev is not None
target_name = "main-" + target_rev[:SHA_LENGTH]
target_cmd = f"git checkout {target_rev}"
elif event == "pull_request":
jobs = [
{"mode": "preview-changes", "force-flag": "--force-preview-style"},
{"mode": "assert-no-changes", "force-flag": "--force-stable-style"},
]
# PR, let's use main as the baseline.
baseline_rev = get_main_revision()
baseline_name = "main-" + baseline_rev[:SHA_LENGTH]
baseline_cmd = f"git checkout {baseline_rev}"
pr_ref = os.getenv("GITHUB_REF")
assert pr_ref is not None
pr_num = int(pr_ref[10:-6])
pr_rev = get_pr_revision(pr_num)
target_name = f"pr-{pr_num}-{pr_rev[:SHA_LENGTH]}"
target_cmd = f"gh pr checkout {pr_num} && git merge origin/main"
env = f"{platform.system()}-{platform.python_version()}-{diff_shades.__version__}"
for entry in jobs:
entry["baseline-analysis"] = f"{entry['mode']}-{baseline_name}.json"
entry["baseline-setup-cmd"] = baseline_cmd
entry["target-analysis"] = f"{entry['mode']}-{target_name}.json"
entry["target-setup-cmd"] = target_cmd
entry["baseline-cache-key"] = f"{env}-{baseline_name}-{entry['mode']}"
if event == "pull_request":
# These are only needed for the PR comment.
entry["baseline-sha"] = baseline_rev
entry["target-sha"] = pr_rev
set_output("matrix", json.dumps(jobs, indent=None))
pprint.pprint(jobs)
@main.command("comment-body", help="Generate the body for a summary PR comment.")
@click.argument("baseline", type=click.Path(exists=True, path_type=Path))
@click.argument("target", type=click.Path(exists=True, path_type=Path))
@click.argument("baseline-sha")
@click.argument("target-sha")
@click.argument("pr-num", type=int)
def comment_body(
baseline: Path, target: Path, baseline_sha: str, target_sha: str, pr_num: int
) -> None:
# fmt: off
cmd = [
sys.executable, "-m", "diff_shades", "--no-color",
"compare", str(baseline), str(target), "--quiet", "--check"
]
# fmt: on
proc = subprocess.run(cmd, stdout=subprocess.PIPE, encoding="utf-8")
if not proc.returncode:
body = (
f"**diff-shades** reports zero changes comparing this PR ({target_sha}) to"
f" main ({baseline_sha}).\n\n---\n\n"
)
else:
body = (
f"**diff-shades** results comparing this PR ({target_sha}) to main"
f" ({baseline_sha}). The full diff is [available in the logs]"
f'($job-diff-url) under the "{DIFF_STEP_NAME}" step.'
)
body += "\n```text\n" + proc.stdout.strip() + "\n```\n"
body += (
f"[**What is this?**]({DOCS_URL}) | [Workflow run]($workflow-run-url) |"
" [diff-shades documentation](https://github.com/ichard26/diff-shades#readme)"
)
print(f"[INFO]: writing comment details to {COMMENT_FILE}")
with open(COMMENT_FILE, "w", encoding="utf-8") as f:
json.dump({"body": body, "pr-number": pr_num}, f)
@main.command("comment-details", help="Get PR comment resources from a workflow run.")
@click.argument("run-id")
def comment_details(run_id: str) -> None:
data = http_get(f"https://api.github.com/repos/{REPO}/actions/runs/{run_id}")
if data["event"] != "pull_request" or data["conclusion"] == "cancelled":
set_output("needs-comment", "false")
return
set_output("needs-comment", "true")
jobs = http_get(data["jobs_url"])["jobs"]
job = next(j for j in jobs if j["name"] == "analysis / preview-changes")
diff_step = next(s for s in job["steps"] if s["name"] == DIFF_STEP_NAME)
diff_url = job["html_url"] + f"#step:{diff_step['number']}:1"
artifacts = http_get(data["artifacts_url"])["artifacts"]
comment_artifact = next(a for a in artifacts if a["name"] == COMMENT_FILE)
comment_url = comment_artifact["archive_download_url"]
comment_zip = BytesIO(http_get(comment_url, is_json=False))
with zipfile.ZipFile(comment_zip) as zfile:
with zfile.open(COMMENT_FILE) as rf:
comment_data = json.loads(rf.read().decode("utf-8"))
set_output("pr-number", str(comment_data["pr-number"]))
body = comment_data["body"]
# It's more convenient to fill in these fields after the first workflow is done
# since this command can access the workflows API (doing it in the main workflow
# while it's still in progress seems impossible).
body = body.replace("$workflow-run-url", data["html_url"])
body = body.replace("$job-diff-url", diff_url)
set_output("comment-body", body)
if __name__ == "__main__":
main()

View File

@ -5,13 +5,11 @@
a coverage-guided fuzzer I'm working on. a coverage-guided fuzzer I'm working on.
""" """
import re
import hypothesmith import hypothesmith
from hypothesis import HealthCheck, given, settings, strategies as st from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
import black import black
from blib2to3.pgen2.tokenize import TokenError
# This test uses the Hypothesis and Hypothesmith libraries to generate random # This test uses the Hypothesis and Hypothesmith libraries to generate random
@ -20,7 +18,7 @@
max_examples=1000, # roughly 1k tests/minute, or half that under coverage max_examples=1000, # roughly 1k tests/minute, or half that under coverage
derandomize=True, # deterministic mode to avoid CI flakiness derandomize=True, # deterministic mode to avoid CI flakiness
deadline=None, # ignore Hypothesis' health checks; we already know that deadline=None, # ignore Hypothesis' health checks; we already know that
suppress_health_check=HealthCheck.all(), # this is slow and filter-heavy. suppress_health_check=list(HealthCheck), # this is slow and filter-heavy.
) )
@given( @given(
# Note that while Hypothesmith might generate code unlike that written by # Note that while Hypothesmith might generate code unlike that written by
@ -32,7 +30,9 @@
black.FileMode, black.FileMode,
line_length=st.just(88) | st.integers(0, 200), line_length=st.just(88) | st.integers(0, 200),
string_normalization=st.booleans(), string_normalization=st.booleans(),
preview=st.booleans(),
is_pyi=st.booleans(), is_pyi=st.booleans(),
magic_trailing_comma=st.booleans(),
), ),
) )
def test_idempotent_any_syntatically_valid_python( def test_idempotent_any_syntatically_valid_python(
@ -42,23 +42,7 @@ def test_idempotent_any_syntatically_valid_python(
compile(src_contents, "<string>", "exec") # else the bug is in hypothesmith compile(src_contents, "<string>", "exec") # else the bug is in hypothesmith
# Then format the code... # Then format the code...
try: dst_contents = black.format_str(src_contents, mode=mode)
dst_contents = black.format_str(src_contents, mode=mode)
except black.InvalidInput:
# This is a bug - if it's valid Python code, as above, Black should be
# able to cope with it. See issues #970, #1012, #1358, and #1557.
# TODO: remove this try-except block when issues are resolved.
return
except TokenError as e:
if ( # Special-case logic for backslashes followed by newlines or end-of-input
e.args[0] == "EOF in multi-line statement"
and re.search(r"\\($|\r?\n)", src_contents) is not None
):
# This is a bug - if it's valid Python code, as above, Black should be
# able to cope with it. See issue #1012.
# TODO: remove this block when the issue is resolved.
return
raise
# And check that we got equivalent and stable output. # And check that we got equivalent and stable output.
black.assert_equivalent(src_contents, dst_contents) black.assert_equivalent(src_contents, dst_contents)
@ -76,10 +60,14 @@ def test_idempotent_any_syntatically_valid_python(
# (if you want only bounded fuzzing, just use `pytest fuzz.py`) # (if you want only bounded fuzzing, just use `pytest fuzz.py`)
try: try:
import sys import sys
import atheris import atheris
except ImportError: except ImportError:
pass pass
else: else:
test = test_idempotent_any_syntatically_valid_python test = test_idempotent_any_syntatically_valid_python
atheris.Setup(sys.argv, test.hypothesis.fuzz_one_input) atheris.Setup(
sys.argv,
test.hypothesis.fuzz_one_input, # type: ignore[attr-defined]
)
atheris.Fuzz() atheris.Fuzz()

74
scripts/generate_schema.py Executable file
View File

@ -0,0 +1,74 @@
import json
from typing import IO, Any
import click
import black
def generate_schema_from_click(
cmd: click.Command,
) -> dict[str, Any]:
result: dict[str, dict[str, Any]] = {}
for param in cmd.params:
if not isinstance(param, click.Option) or param.is_eager:
continue
assert param.name
name = param.name.replace("_", "-")
result[name] = {}
match param.type:
case click.types.IntParamType():
result[name]["type"] = "integer"
case click.types.StringParamType() | click.types.Path():
result[name]["type"] = "string"
case click.types.Choice(choices=choices):
result[name]["enum"] = choices
case click.types.BoolParamType():
result[name]["type"] = "boolean"
case _:
msg = f"{param.type!r} not a known type for {param}"
raise TypeError(msg)
if param.multiple:
result[name] = {"type": "array", "items": result[name]}
result[name]["description"] = param.help
if param.default is not None and not param.multiple:
result[name]["default"] = param.default
return result
@click.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.option("--schemastore", is_flag=True, help="SchemaStore format")
@click.option("--outfile", type=click.File(mode="w"), help="Write to file")
def main(schemastore: bool, outfile: IO[str]) -> None:
properties = generate_schema_from_click(black.main)
del properties["line-ranges"]
schema: dict[str, Any] = {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": (
"https://github.com/psf/black/blob/main/src/black/resources/black.schema.json"
),
"$comment": "tool.black table in pyproject.toml",
"type": "object",
"additionalProperties": False,
"properties": properties,
}
if schemastore:
schema["$id"] = "https://json.schemastore.org/partial-black.json"
# The precise list of unstable features may change frequently, so don't
# bother putting it in SchemaStore
schema["properties"]["enable-unstable-feature"]["items"] = {"type": "string"}
print(json.dumps(schema, indent=2), file=outfile)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,66 @@
"""Generates a width table for Unicode characters.
This script generates a width table for Unicode characters that are not
narrow (width 1). The table is written to src/black/_width_table.py (note
that although this file is generated, it is checked into Git) and is used
by the char_width() function in src/black/strings.py.
You should run this script when you upgrade wcwidth, which is expected to
happen when a new Unicode version is released. The generated table contains
the version of wcwidth and Unicode that it was generated for.
In order to run this script, you need to install the latest version of wcwidth.
You can do this by running:
pip install -U wcwidth
"""
import sys
from collections.abc import Iterable
from os.path import basename, dirname, join
import wcwidth # type: ignore[import-not-found]
def make_width_table() -> Iterable[tuple[int, int, int]]:
start_codepoint = -1
end_codepoint = -1
range_width = -2
for codepoint in range(0, sys.maxunicode + 1):
width = wcwidth.wcwidth(chr(codepoint))
if width <= 1:
# Ignore narrow characters along with zero-width characters so that
# they are treated as single-width. Note that treating zero-width
# characters as single-width is consistent with the heuristics built
# on top of str.isascii() in the str_width() function in strings.py.
continue
if start_codepoint < 0:
start_codepoint = codepoint
range_width = width
elif width != range_width or codepoint != end_codepoint + 1:
yield (start_codepoint, end_codepoint, range_width)
start_codepoint = codepoint
range_width = width
end_codepoint = codepoint
if start_codepoint >= 0:
yield (start_codepoint, end_codepoint, range_width)
def main() -> None:
table_path = join(dirname(__file__), "..", "src", "black", "_width_table.py")
with open(table_path, "w") as f:
f.write(f"""# Generated by {basename(__file__)}
# wcwidth {wcwidth.__version__}
# Unicode {wcwidth.list_versions()[-1]}
from typing import Final
WIDTH_TABLE: Final[list[tuple[int, int, int]]] = [
""")
for triple in make_width_table():
f.write(f" {triple!r},\n")
f.write("]\n")
if __name__ == "__main__":
main()

Some files were not shown because too many files have changed in this diff Show More