pax_global_header 0000666 0000000 0000000 00000000064 13442505266 0014521 g ustar 00root root 0000000 0000000 52 comment=026c81b83454f176a9f9253cbfb70be2c159d822
black-19.3b0/ 0000775 0000000 0000000 00000000000 13442505266 0012753 5 ustar 00root root 0000000 0000000 black-19.3b0/.appveyor.yml 0000664 0000000 0000000 00000001211 13442505266 0015414 0 ustar 00root root 0000000 0000000 install:
- C:\Python36\python.exe -m pip install mypy
- C:\Python36\python.exe -m pip install -e .[d]
# Not a C# project
build: off
test_script:
- C:\Python36\python.exe tests/test_black.py
- C:\Python36\python.exe -m mypy black.py blackd.py tests/test_black.py
after_test:
- C:\Python36\python.exe -m pip install pyinstaller
- "%CMD_IN_ENV% C:\\Python36\\python.exe -m PyInstaller --clean -F --add-data blib2to3/;blib2to3 black.py"
artifacts:
- path: dist/black.exe
deploy:
provider: GitHub
description: ''
auth_token:
secure: caPP8BcGffPuTopDfdI4ZVKZkpD9l9UAcjO7rwm5/fFSMbsqh1v4S38nmMn4uSuD
on:
appveyor_repo_tag: true
black-19.3b0/.coveragerc 0000664 0000000 0000000 00000000061 13442505266 0015071 0 ustar 00root root 0000000 0000000 [report]
omit =
blib2to3/*
*/site-packages/*
black-19.3b0/.flake8 0000664 0000000 0000000 00000000367 13442505266 0014134 0 ustar 00root root 0000000 0000000 # This is an example .flake8 config, used when developing *Black* itself.
# Keep in sync with setup.cfg which is used for source packages.
[flake8]
ignore = E203, E266, E501, W503
max-line-length = 80
max-complexity = 18
select = B,C,E,F,W,T4,B9
black-19.3b0/.github/ 0000775 0000000 0000000 00000000000 13442505266 0014313 5 ustar 00root root 0000000 0000000 black-19.3b0/.github/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000001054 13442505266 0017112 0 ustar 00root root 0000000 0000000 # Treat each other well
Everyone participating in the *Black* project, and in particular in the
issue tracker, pull requests, and social media activity, is expected
to treat other people with respect and more generally to follow the
guidelines articulated in the [Python Community Code of
Conduct](https://www.python.org/psf/codeofconduct/).
At the same time, humor is encouraged. In fact, basic familiarity with
Monty Python's Flying Circus is expected. We are not savages.
And if you *really* need to slap somebody, do it with a fish while
dancing.
black-19.3b0/.github/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000001136 13442505266 0017021 0 ustar 00root root 0000000 0000000 Howdy! Sorry you're having trouble. To expedite your experience,
provide some basics for me:
Operating system:
Python version:
*Black* version:
Does also happen on master:
To answer the last question, you have two options:
1. Use the online formatter at https://black.now.sh/?version=master, which will use the latest master branch.
2. 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 .`;
* make sure it's sane by running `python setup.py test`; and
* run `black` like you did last time.
black-19.3b0/.gitignore 0000664 0000000 0000000 00000000171 13442505266 0014742 0 ustar 00root root 0000000 0000000 .coverage
_build
.DS_Store
.vscode
docs/_static/pypi.svg
.tox
__pycache__
black.egg-info
build/
dist/
pip-wheel-metadata/ black-19.3b0/.pre-commit-config.yaml 0000664 0000000 0000000 00000001006 13442505266 0017231 0 ustar 00root root 0000000 0000000 # Note: don't use this config for your own repositories. Instead, see
# "Version control integration" in README.md.
exclude: ^(blib2to3/|profiling/|tests/data/)
repos:
- repo: local
hooks:
- id: black
name: black
language: system
entry: black
types: [python]
- id: flake8
name: flake8
language: system
entry: flake8
types: [python]
- id: mypy
name: mypy
language: system
entry: mypy
types: [python]
exclude: ^docs/conf.py
black-19.3b0/.pre-commit-hooks.yaml 0000664 0000000 0000000 00000000322 13442505266 0017107 0 ustar 00root root 0000000 0000000 - id: black
name: black
description: 'Black: The uncompromising Python code formatter'
entry: black
language: python
language_version: python3
require_serial: true
types: [python]
black-19.3b0/.travis.yml 0000664 0000000 0000000 00000003457 13442505266 0015075 0 ustar 00root root 0000000 0000000 dist: xenial
language: python
cache: pip
env:
- TEST_CMD="coverage run tests/test_black.py"
install:
- pip install coverage coveralls flake8 flake8-bugbear mypy
- pip install -e '.[d]'
script:
- $TEST_CMD
after_success:
- coveralls
notifications:
on_success: change
on_failure: always
matrix:
include:
- name: "mypy"
python: 3.6
env:
- TEST_CMD="mypy black.py blackd.py tests/test_black.py"
- name: "black"
python: 3.7
env:
- TEST_CMD="black --check --verbose ."
- name: "flake8"
python: 3.7
env:
- TEST_CMD="flake8 black.py blackd.py tests/test_black.py"
- name: "3.6"
python: 3.6
- name: "3.7"
python: 3.7
- name: "3.8-dev"
python: 3.8-dev
# aiohttp currently has a bug affecting 3.8
allow_failures:
- name: "3.8-dev"
python: 3.8-dev
before_deploy:
- pip install pyinstaller
- pyinstaller --clean -F --add-data blib2to3/:blib2to3 black.py
deploy:
provider: releases
api_key:
secure: chYvcmnRqRKtfBcAZRj62rEv0ziWuHMl6MnfQbd1MOVQ4njntI8+CCPk118dW6MWSfwTqyMFy+t9gAgQYhjkLEHMS2aK9Z2wCWki1MkBrkMw5tYoLFvPu0KQ9rIVihxsr93a/am6Oh/Hp+1uuc4zWPUf1ubX+QlCzsxjCzVso1kTJjjdN04UxvkcFR+sY2d9Qyy9WcdifChnLwdmIJKIoVOE7Imm820nzImJHkJh8iSnjBjL98gvPPeC/nWTltsbErvf2mCv4NIjzjQZvHa87c7rSJGbliNrAxCSyyvBX+JNeS8U2fGLE83do0HieyjdPbTuc27e2nsrrihgPh+hXbiJerljclfp5hsJ5qGz5sS9MU1fR7sSLiQQ2v0TYB5RRwd34TgGiLwFAZZmgZOfMUCtefCKvP8qvELMSNd99+msfPEHiuhADF0bKPTbCUa6BgUHNr6woOLmHerjPHd6NI/a8Skz/uQB4xr3spLSmfUmX0fEqyYUDphkGPNH8IsvC1/F2isecW9kOzEWmB5oCmpMTGm4TIf3C01Nx+9PVwB2Z+30hhbfIEBxD4loRFmh/hU5TIQEpneF8yoIfe9EnMaoZbq86xhADZXvLIZvpXUdm1NQZDG6na2S1fwyOUKQsW6BWLcfoZZwZlrXrViD1jBsHBV++s+lxShTeTCszlo=
file:
- dist/black
skip_cleanup: true
on:
condition: $TRAVIS_PYTHON_VERSION == '3.6'
repo: ambv/black
tags: true
black-19.3b0/CONTRIBUTING.md 0000664 0000000 0000000 00000003600 13442505266 0015203 0 ustar 00root root 0000000 0000000 # Contributing to *Black*
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?
## 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/ambv/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.
## Technicalities
Development on the latest version of Python is preferred. As of this
writing it's 3.6.5. You can use any operating system. I am using macOS
myself and CentOS at work.
Install all development dependencies using:
```
$ pipenv install --dev
$ pre-commit install
```
If you haven't used `pipenv` before but are comfortable with virtualenvs,
just run `pip install pipenv` in the virtualenv you're already using and
invoke the command above from the cloned *Black* repo. It will do the
correct thing.
Before submitting pull requests, run tests with:
```
$ python setup.py test
```
## Hygiene
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.
If adding a new feature, add a test. In fact, always add a test. But
wait, before adding any large feature, first open an issue for us to
discuss the idea first.
## Finally
Thanks again for your interest in improving the project! You're taking
action when most people decide to sit and watch.
black-19.3b0/LICENSE 0000664 0000000 0000000 00000002070 13442505266 0013757 0 ustar 00root root 0000000 0000000 The MIT License (MIT)
Copyright (c) 2018 Łukasz Langa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
black-19.3b0/MANIFEST.in 0000664 0000000 0000000 00000000214 13442505266 0014506 0 ustar 00root root 0000000 0000000 include *.rst *.md LICENSE
recursive-include blib2to3 *.txt *.py LICENSE
recursive-include tests *.txt *.out *.diff *.py *.pyi *.pie *.toml
black-19.3b0/Pipfile 0000664 0000000 0000000 00000000744 13442505266 0014273 0 ustar 00root root 0000000 0000000 [[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
aiohttp = ">=3.3.2"
attrs = ">=18.1.0"
click = ">=6.5"
appdirs = "*"
toml = ">=0.9.4"
black = {path = ".",extras = ["d"],editable = true}
aiohttp-cors = "*"
[dev-packages]
pre-commit = "*"
coverage = "*"
flake8 = "*"
flake8-bugbear = "*"
flake8-mypy = "*"
mypy = ">=0.620"
readme_renderer = "*"
recommonmark = "*"
Sphinx = "*"
setuptools = ">=39.2.0"
twine = ">=1.11.0"
wheel = ">=0.31.1"
black-19.3b0/Pipfile.lock 0000664 0000000 0000000 00000075457 13442505266 0015237 0 ustar 00root root 0000000 0000000 {
"_meta": {
"hash": {
"sha256": "f620e8926ed3661fb9a061289198a9a401ee674bbfc3487fd6036c6d271480f9"
},
"pipfile-spec": 6,
"requires": {},
"sources": [
{
"name": "pypi",
"url": "https://pypi.python.org/simple",
"verify_ssl": true
}
]
},
"default": {
"aiohttp": {
"hashes": [
"sha256:00d198585474299c9c3b4f1d5de1a576cc230d562abc5e4a0e81d71a20a6ca55",
"sha256:0155af66de8c21b8dba4992aaeeabf55503caefae00067a3b1139f86d0ec50ed",
"sha256:09654a9eca62d1bd6d64aa44db2498f60a5c1e0ac4750953fdd79d5c88955e10",
"sha256:199f1d106e2b44b6dacdf6f9245493c7d716b01d0b7fbe1959318ba4dc64d1f5",
"sha256:296f30dedc9f4b9e7a301e5cc963012264112d78a1d3094cd83ef148fdf33ca1",
"sha256:368ed312550bd663ce84dc4b032a962fcb3c7cae099dbbd48663afc305e3b939",
"sha256:40d7ea570b88db017c51392349cf99b7aefaaddd19d2c78368aeb0bddde9d390",
"sha256:629102a193162e37102c50713e2e31dc9a2fe7ac5e481da83e5bb3c0cee700aa",
"sha256:6d5ec9b8948c3d957e75ea14d41e9330e1ac3fed24ec53766c780f82805140dc",
"sha256:87331d1d6810214085a50749160196391a712a13336cd02ce1c3ea3d05bcf8d5",
"sha256:9a02a04bbe581c8605ac423ba3a74999ec9d8bce7ae37977a3d38680f5780b6d",
"sha256:9c4c83f4fa1938377da32bc2d59379025ceeee8e24b89f72fcbccd8ca22dc9bf",
"sha256:9cddaff94c0135ee627213ac6ca6d05724bfe6e7a356e5e09ec57bd3249510f6",
"sha256:a25237abf327530d9561ef751eef9511ab56fd9431023ca6f4803f1994104d72",
"sha256:a5cbd7157b0e383738b8e29d6e556fde8726823dae0e348952a61742b21aeb12",
"sha256:a97a516e02b726e089cffcde2eea0d3258450389bbac48cbe89e0f0b6e7b0366",
"sha256:acc89b29b5f4e2332d65cd1b7d10c609a75b88ef8925d487a611ca788432dfa4",
"sha256:b05bd85cc99b06740aad3629c2585bda7b83bd86e080b44ba47faf905fdf1300",
"sha256:c2bec436a2b5dafe5eaeb297c03711074d46b6eb236d002c13c42f25c4a8ce9d",
"sha256:cc619d974c8c11fe84527e4b5e1c07238799a8c29ea1c1285149170524ba9303",
"sha256:d4392defd4648badaa42b3e101080ae3313e8f4787cb517efd3f5b8157eaefd6",
"sha256:e1c3c582ee11af7f63a34a46f0448fca58e59889396ffdae1f482085061a2889"
],
"index": "pypi",
"version": "==3.5.4"
},
"aiohttp-cors": {
"hashes": [
"sha256:0451ba59fdf6909d0e2cd21e4c0a43752bc0703d33fc78ae94d9d9321710193e",
"sha256:4d39c6d7100fd9764ed1caf8cebf0eb01bf5e3f24e2e073fda6234bc48b19f5d"
],
"index": "pypi",
"version": "==0.7.0"
},
"appdirs": {
"hashes": [
"sha256:9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92",
"sha256:d8b24664561d0d34ddfaec54636d502d7cea6e29c3eaf68f3df6180863e2166e"
],
"index": "pypi",
"version": "==1.4.3"
},
"async-timeout": {
"hashes": [
"sha256:0c3c816a028d47f659d6ff5c745cb2acf1f966da1fe5c19c77a70282b25f4c5f",
"sha256:4291ca197d287d274d0b6cb5d6f8f8f82d434ed288f962539ff18cc9012f9ea3"
],
"version": "==3.0.1"
},
"attrs": {
"hashes": [
"sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79",
"sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399"
],
"index": "pypi",
"version": "==19.1.0"
},
"black": {
"editable": true,
"extras": [
"d"
],
"path": "."
},
"chardet": {
"hashes": [
"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
],
"version": "==3.0.4"
},
"click": {
"hashes": [
"sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13",
"sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7"
],
"index": "pypi",
"version": "==7.0"
},
"idna": {
"hashes": [
"sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407",
"sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c"
],
"version": "==2.8"
},
"multidict": {
"hashes": [
"sha256:024b8129695a952ebd93373e45b5d341dbb87c17ce49637b34000093f243dd4f",
"sha256:041e9442b11409be5e4fc8b6a97e4bcead758ab1e11768d1e69160bdde18acc3",
"sha256:045b4dd0e5f6121e6f314d81759abd2c257db4634260abcfe0d3f7083c4908ef",
"sha256:047c0a04e382ef8bd74b0de01407e8d8632d7d1b4db6f2561106af812a68741b",
"sha256:068167c2d7bbeebd359665ac4fff756be5ffac9cda02375b5c5a7c4777038e73",
"sha256:148ff60e0fffa2f5fad2eb25aae7bef23d8f3b8bdaf947a65cdbe84a978092bc",
"sha256:1d1c77013a259971a72ddaa83b9f42c80a93ff12df6a4723be99d858fa30bee3",
"sha256:1d48bc124a6b7a55006d97917f695effa9725d05abe8ee78fd60d6588b8344cd",
"sha256:31dfa2fc323097f8ad7acd41aa38d7c614dd1960ac6681745b6da124093dc351",
"sha256:34f82db7f80c49f38b032c5abb605c458bac997a6c3142e0d6c130be6fb2b941",
"sha256:3d5dd8e5998fb4ace04789d1d008e2bb532de501218519d70bb672c4c5a2fc5d",
"sha256:4a6ae52bd3ee41ee0f3acf4c60ceb3f44e0e3bc52ab7da1c2b2aa6703363a3d1",
"sha256:4b02a3b2a2f01d0490dd39321c74273fed0568568ea0e7ea23e02bd1fb10a10b",
"sha256:4b843f8e1dd6a3195679d9838eb4670222e8b8d01bc36c9894d6c3538316fa0a",
"sha256:5de53a28f40ef3c4fd57aeab6b590c2c663de87a5af76136ced519923d3efbb3",
"sha256:61b2b33ede821b94fa99ce0b09c9ece049c7067a33b279f343adfe35108a4ea7",
"sha256:6a3a9b0f45fd75dc05d8e93dc21b18fc1670135ec9544d1ad4acbcf6b86781d0",
"sha256:76ad8e4c69dadbb31bad17c16baee61c0d1a4a73bed2590b741b2e1a46d3edd0",
"sha256:7ba19b777dc00194d1b473180d4ca89a054dd18de27d0ee2e42a103ec9b7d014",
"sha256:7c1b7eab7a49aa96f3db1f716f0113a8a2e93c7375dd3d5d21c4941f1405c9c5",
"sha256:7fc0eee3046041387cbace9314926aa48b681202f8897f8bff3809967a049036",
"sha256:8ccd1c5fff1aa1427100ce188557fc31f1e0a383ad8ec42c559aabd4ff08802d",
"sha256:8e08dd76de80539d613654915a2f5196dbccc67448df291e69a88712ea21e24a",
"sha256:c18498c50c59263841862ea0501da9f2b3659c00db54abfbf823a80787fde8ce",
"sha256:c49db89d602c24928e68c0d510f4fcf8989d77defd01c973d6cbe27e684833b1",
"sha256:ce20044d0317649ddbb4e54dab3c1bcc7483c78c27d3f58ab3d0c7e6bc60d26a",
"sha256:d1071414dd06ca2eafa90c85a079169bfeb0e5f57fd0b45d44c092546fcd6fd9",
"sha256:d3be11ac43ab1a3e979dac80843b42226d5d3cccd3986f2e03152720a4297cd7",
"sha256:db603a1c235d110c860d5f39988ebc8218ee028f07a7cbc056ba6424372ca31b"
],
"version": "==4.5.2"
},
"toml": {
"hashes": [
"sha256:229f81c57791a41d65e399fc06bf0848bab550a9dfd5ed66df18ce5f05e73d5c",
"sha256:235682dd292d5899d361a811df37e04a8828a5b1da3115886b73cf81ebc9100e"
],
"index": "pypi",
"version": "==0.10.0"
},
"yarl": {
"hashes": [
"sha256:024ecdc12bc02b321bc66b41327f930d1c2c543fa9a561b39861da9388ba7aa9",
"sha256:2f3010703295fbe1aec51023740871e64bb9664c789cba5a6bdf404e93f7568f",
"sha256:3890ab952d508523ef4881457c4099056546593fa05e93da84c7250516e632eb",
"sha256:3e2724eb9af5dc41648e5bb304fcf4891adc33258c6e14e2a7414ea32541e320",
"sha256:5badb97dd0abf26623a9982cd448ff12cb39b8e4c94032ccdedf22ce01a64842",
"sha256:73f447d11b530d860ca1e6b582f947688286ad16ca42256413083d13f260b7a0",
"sha256:7ab825726f2940c16d92aaec7d204cfc34ac26c0040da727cf8ba87255a33829",
"sha256:b25de84a8c20540531526dfbb0e2d2b648c13fd5dd126728c496d7c3fea33310",
"sha256:c6e341f5a6562af74ba55205dbd56d248daf1b5748ec48a0200ba227bb9e33f4",
"sha256:c9bb7c249c4432cd47e75af3864bc02d26c9594f49c82e2a28624417f0ae63b8",
"sha256:e060906c0c585565c718d1c3841747b61c5439af2211e185f6739a9412dfbde1"
],
"version": "==1.3.0"
}
},
"develop": {
"alabaster": {
"hashes": [
"sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359",
"sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02"
],
"version": "==0.7.12"
},
"aspy.yaml": {
"hashes": [
"sha256:ae249074803e8b957c83fdd82a99160d0d6d26dff9ba81ba608b42eebd7d8cd3",
"sha256:c7390d79f58eb9157406966201abf26da0d56c07e0ff0deadc39c8f4dbc13482"
],
"version": "==1.2.0"
},
"attrs": {
"hashes": [
"sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79",
"sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399"
],
"index": "pypi",
"version": "==19.1.0"
},
"babel": {
"hashes": [
"sha256:6778d85147d5d85345c14a26aada5e478ab04e39b078b0745ee6870c2b5cf669",
"sha256:8cba50f48c529ca3fa18cf81fa9403be176d374ac4d60738b839122dfaaa3d23"
],
"version": "==2.6.0"
},
"bleach": {
"hashes": [
"sha256:213336e49e102af26d9cde77dd2d0397afabc5a6bf2fed985dc35b5d1e285a16",
"sha256:3fdf7f77adcf649c9911387df51254b813185e32b2c6619f690b593a617e19fa"
],
"version": "==3.1.0"
},
"certifi": {
"hashes": [
"sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5",
"sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae"
],
"version": "==2019.3.9"
},
"cfgv": {
"hashes": [
"sha256:39f8475d8eca48639f900daffa3f8bd2f60a31d989df41a9f81c5ad1779a66eb",
"sha256:a6a4366d32799a6bfb6f577ebe113b27ba8d1bae43cb57133b1472c1c3dae227"
],
"version": "==1.5.0"
},
"chardet": {
"hashes": [
"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
],
"version": "==3.0.4"
},
"commonmark": {
"hashes": [
"sha256:9f6dda7876b2bb88dd784440166f4bc8e56cb2b2551264051123bacb0b6c1d8a",
"sha256:abcbc854e0eae5deaf52ae5e328501b78b4a0758bf98ac8bb792fce993006084"
],
"version": "==0.8.1"
},
"coverage": {
"hashes": [
"sha256:3684fabf6b87a369017756b551cef29e505cb155ddb892a7a29277b978da88b9",
"sha256:39e088da9b284f1bd17c750ac672103779f7954ce6125fd4382134ac8d152d74",
"sha256:3c205bc11cc4fcc57b761c2da73b9b72a59f8d5ca89979afb0c1c6f9e53c7390",
"sha256:465ce53a8c0f3a7950dfb836438442f833cf6663d407f37d8c52fe7b6e56d7e8",
"sha256:48020e343fc40f72a442c8a1334284620f81295256a6b6ca6d8aa1350c763bbe",
"sha256:5296fc86ab612ec12394565c500b412a43b328b3907c0d14358950d06fd83baf",
"sha256:5f61bed2f7d9b6a9ab935150a6b23d7f84b8055524e7be7715b6513f3328138e",
"sha256:68a43a9f9f83693ce0414d17e019daee7ab3f7113a70c79a3dd4c2f704e4d741",
"sha256:6b8033d47fe22506856fe450470ccb1d8ba1ffb8463494a15cfc96392a288c09",
"sha256:7ad7536066b28863e5835e8cfeaa794b7fe352d99a8cded9f43d1161be8e9fbd",
"sha256:7bacb89ccf4bedb30b277e96e4cc68cd1369ca6841bde7b005191b54d3dd1034",
"sha256:839dc7c36501254e14331bcb98b27002aa415e4af7ea039d9009409b9d2d5420",
"sha256:8f9a95b66969cdea53ec992ecea5406c5bd99c9221f539bca1e8406b200ae98c",
"sha256:932c03d2d565f75961ba1d3cec41ddde00e162c5b46d03f7423edcb807734eab",
"sha256:988529edadc49039d205e0aa6ce049c5ccda4acb2d6c3c5c550c17e8c02c05ba",
"sha256:998d7e73548fe395eeb294495a04d38942edb66d1fa61eb70418871bc621227e",
"sha256:9de60893fb447d1e797f6bf08fdf0dbcda0c1e34c1b06c92bd3a363c0ea8c609",
"sha256:9e80d45d0c7fcee54e22771db7f1b0b126fb4a6c0a2e5afa72f66827207ff2f2",
"sha256:a545a3dfe5082dc8e8c3eb7f8a2cf4f2870902ff1860bd99b6198cfd1f9d1f49",
"sha256:a5d8f29e5ec661143621a8f4de51adfb300d7a476224156a39a392254f70687b",
"sha256:aca06bfba4759bbdb09bf52ebb15ae20268ee1f6747417837926fae990ebc41d",
"sha256:bb23b7a6fd666e551a3094ab896a57809e010059540ad20acbeec03a154224ce",
"sha256:bfd1d0ae7e292105f29d7deaa9d8f2916ed8553ab9d5f39ec65bcf5deadff3f9",
"sha256:c62ca0a38958f541a73cf86acdab020c2091631c137bd359c4f5bddde7b75fd4",
"sha256:c709d8bda72cf4cd348ccec2a4881f2c5848fd72903c185f363d361b2737f773",
"sha256:c968a6aa7e0b56ecbd28531ddf439c2ec103610d3e2bf3b75b813304f8cb7723",
"sha256:df785d8cb80539d0b55fd47183264b7002077859028dfe3070cf6359bf8b2d9c",
"sha256:f406628ca51e0ae90ae76ea8398677a921b36f0bd71aab2099dfed08abd0322f",
"sha256:f46087bbd95ebae244a0eda01a618aff11ec7a069b15a3ef8f6b520db523dcf1",
"sha256:f8019c5279eb32360ca03e9fac40a12667715546eed5c5eb59eb381f2f501260",
"sha256:fc5f4d209733750afd2714e9109816a29500718b32dd9a5db01c0cb3a019b96a"
],
"index": "pypi",
"version": "==4.5.3"
},
"docutils": {
"hashes": [
"sha256:02aec4bd92ab067f6ff27a38a38a41173bf01bed8f89157768c1573f53e474a6",
"sha256:51e64ef2ebfb29cae1faa133b3710143496eca21c530f3f71424d77687764274",
"sha256:7a4bd47eaf6596e1295ecb11361139febe29b084a87bf005bf899f9a42edc3c6"
],
"version": "==0.14"
},
"entrypoints": {
"hashes": [
"sha256:589f874b313739ad35be6e0cd7efde2a4e9b6fea91edcc34e58ecbb8dbe56d19",
"sha256:c70dd71abe5a8c85e55e12c19bd91ccfeec11a6e99044204511f9ed547d48451"
],
"version": "==0.3"
},
"flake8": {
"hashes": [
"sha256:859996073f341f2670741b51ec1e67a01da142831aa1fdc6242dbf88dffbe661",
"sha256:a796a115208f5c03b18f332f7c11729812c8c3ded6c46319c59b53efd3819da8"
],
"index": "pypi",
"version": "==3.7.7"
},
"flake8-bugbear": {
"hashes": [
"sha256:07b6e769d7f4e168d590f7088eae40f6ddd9fa4952bed31602def65842682c83",
"sha256:0ccf56975f4db1d69dc1cf3598c99d768ebf95d0cad27d76087954aa399b515a"
],
"index": "pypi",
"version": "==18.8.0"
},
"flake8-mypy": {
"hashes": [
"sha256:47120db63aff631ee1f84bac6fe8e64731dc66da3efc1c51f85e15ade4a3ba18",
"sha256:cff009f4250e8391bf48990093cff85802778c345c8449d6498b62efefeebcbc"
],
"index": "pypi",
"version": "==17.8.0"
},
"future": {
"hashes": [
"sha256:67045236dcfd6816dc439556d009594abf643e5eb48992e36beac09c2ca659b8"
],
"version": "==0.17.1"
},
"identify": {
"hashes": [
"sha256:407cbb36e8b72b45cfa96a97ae13ccabca4c36557e03616958bd895dfcd3f77d",
"sha256:721abbbb1269fa1172799119981c22c5ace022544ce82eedc29b1b0d753baaa5"
],
"version": "==1.4.0"
},
"idna": {
"hashes": [
"sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407",
"sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c"
],
"version": "==2.8"
},
"imagesize": {
"hashes": [
"sha256:3f349de3eb99145973fefb7dbe38554414e5c30abd0c8e4b970a7c9d09f3a1d8",
"sha256:f3832918bc3c66617f92e35f5d70729187676313caa60c187eb0f28b8fe5e3b5"
],
"version": "==1.1.0"
},
"importlib-metadata": {
"hashes": [
"sha256:a17ce1a8c7bff1e8674cb12c992375d8d0800c9190177ecf0ad93e0097224095",
"sha256:b50191ead8c70adfa12495fba19ce6d75f2e0275c14c5a7beb653d6799b512bd"
],
"version": "==0.8"
},
"jinja2": {
"hashes": [
"sha256:74c935a1b8bb9a3947c50a54766a969d4846290e1e788ea44c1392163723c3bd",
"sha256:f84be1bb0040caca4cea721fcbbbbd61f9be9464ca236387158b0feea01914a4"
],
"version": "==2.10"
},
"markupsafe": {
"hashes": [
"sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473",
"sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161",
"sha256:09c4b7f37d6c648cb13f9230d847adf22f8171b1ccc4d5682398e77f40309235",
"sha256:1027c282dad077d0bae18be6794e6b6b8c91d58ed8a8d89a89d59693b9131db5",
"sha256:24982cc2533820871eba85ba648cd53d8623687ff11cbb805be4ff7b4c971aff",
"sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b",
"sha256:43a55c2930bbc139570ac2452adf3d70cdbb3cfe5912c71cdce1c2c6bbd9c5d1",
"sha256:46c99d2de99945ec5cb54f23c8cd5689f6d7177305ebff350a58ce5f8de1669e",
"sha256:500d4957e52ddc3351cabf489e79c91c17f6e0899158447047588650b5e69183",
"sha256:535f6fc4d397c1563d08b88e485c3496cf5784e927af890fb3c3aac7f933ec66",
"sha256:62fe6c95e3ec8a7fad637b7f3d372c15ec1caa01ab47926cfdf7a75b40e0eac1",
"sha256:6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1",
"sha256:717ba8fe3ae9cc0006d7c451f0bb265ee07739daf76355d06366154ee68d221e",
"sha256:79855e1c5b8da654cf486b830bd42c06e8780cea587384cf6545b7d9ac013a0b",
"sha256:7c1699dfe0cf8ff607dbdcc1e9b9af1755371f92a68f706051cc8c37d447c905",
"sha256:88e5fcfb52ee7b911e8bb6d6aa2fd21fbecc674eadd44118a9cc3863f938e735",
"sha256:8defac2f2ccd6805ebf65f5eeb132adcf2ab57aa11fdf4c0dd5169a004710e7d",
"sha256:98c7086708b163d425c67c7a91bad6e466bb99d797aa64f965e9d25c12111a5e",
"sha256:9add70b36c5666a2ed02b43b335fe19002ee5235efd4b8a89bfcf9005bebac0d",
"sha256:9bf40443012702a1d2070043cb6291650a0841ece432556f784f004937f0f32c",
"sha256:ade5e387d2ad0d7ebf59146cc00c8044acbd863725f887353a10df825fc8ae21",
"sha256:b00c1de48212e4cc9603895652c5c410df699856a2853135b3967591e4beebc2",
"sha256:b1282f8c00509d99fef04d8ba936b156d419be841854fe901d8ae224c59f0be5",
"sha256:b2051432115498d3562c084a49bba65d97cf251f5a331c64a12ee7e04dacc51b",
"sha256:ba59edeaa2fc6114428f1637ffff42da1e311e29382d81b339c1817d37ec93c6",
"sha256:c8716a48d94b06bb3b2524c2b77e055fb313aeb4ea620c8dd03a105574ba704f",
"sha256:cd5df75523866410809ca100dc9681e301e3c27567cf498077e8551b6d20e42f",
"sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7"
],
"version": "==1.1.1"
},
"mccabe": {
"hashes": [
"sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42",
"sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f"
],
"version": "==0.6.1"
},
"mypy": {
"hashes": [
"sha256:308c274eb8482fbf16006f549137ddc0d69e5a589465e37b99c4564414363ca7",
"sha256:e80fd6af34614a0e898a57f14296d0dacb584648f0339c2e000ddbf0f4cc2f8d"
],
"index": "pypi",
"version": "==0.670"
},
"mypy-extensions": {
"hashes": [
"sha256:37e0e956f41369209a3d5f34580150bcacfabaa57b33a15c0b25f4b5725e0812",
"sha256:b16cabe759f55e3409a7d231ebd2841378fb0c27a5d1994719e340e4f429ac3e"
],
"version": "==0.4.1"
},
"nodeenv": {
"hashes": [
"sha256:ad8259494cf1c9034539f6cced78a1da4840a4b157e23640bc4a0c0546b0cb7a"
],
"version": "==1.3.3"
},
"packaging": {
"hashes": [
"sha256:0c98a5d0be38ed775798ece1b9727178c4469d9c3b4ada66e8e6b7849f8732af",
"sha256:9e1cbf8c12b1f1ce0bb5344b8d7ecf66a6f8a6e91bcb0c84593ed6d3ab5c4ab3"
],
"version": "==19.0"
},
"pkginfo": {
"hashes": [
"sha256:7424f2c8511c186cd5424bbf31045b77435b37a8d604990b79d4e70d741148bb",
"sha256:a6d9e40ca61ad3ebd0b72fbadd4fba16e4c0e4df0428c041e01e06eb6ee71f32"
],
"version": "==1.5.0.1"
},
"pre-commit": {
"hashes": [
"sha256:d3d69c63ae7b7584c4b51446b0b583d454548f9df92575b2fe93a68ec800c4d3",
"sha256:fc512f129b9526e35e80d656a16a31c198f584c4fce3a5c739045b5140584917"
],
"index": "pypi",
"version": "==1.14.4"
},
"pycodestyle": {
"hashes": [
"sha256:95a2219d12372f05704562a14ec30bc76b05a5b297b21a5dfe3f6fac3491ae56",
"sha256:e40a936c9a450ad81df37f549d676d127b1b66000a6c500caa2b085bc0ca976c"
],
"version": "==2.5.0"
},
"pyflakes": {
"hashes": [
"sha256:17dbeb2e3f4d772725c777fabc446d5634d1038f234e77343108ce445ea69ce0",
"sha256:d976835886f8c5b31d47970ed689944a0262b5f3afa00a5a7b4dc81e5449f8a2"
],
"version": "==2.1.1"
},
"pygments": {
"hashes": [
"sha256:5ffada19f6203563680669ee7f53b64dabbeb100eb51b61996085e99c03b284a",
"sha256:e8218dd399a61674745138520d0d4cf2621d7e032439341bc3f647bff125818d"
],
"version": "==2.3.1"
},
"pyparsing": {
"hashes": [
"sha256:66c9268862641abcac4a96ba74506e594c884e3f57690a696d21ad8210ed667a",
"sha256:f6c5ef0d7480ad048c054c37632c67fca55299990fff127850181659eea33fc3"
],
"version": "==2.3.1"
},
"pytz": {
"hashes": [
"sha256:32b0891edff07e28efe91284ed9c31e123d84bea3fd98e1f72be2508f43ef8d9",
"sha256:d5f05e487007e29e03409f9398d074e158d920d36eb82eaf66fb1136b0c5374c"
],
"version": "==2018.9"
},
"pyyaml": {
"hashes": [
"sha256:1adecc22f88d38052fb787d959f003811ca858b799590a5eaa70e63dca50308c",
"sha256:436bc774ecf7c103814098159fbb84c2715d25980175292c648f2da143909f95",
"sha256:460a5a4248763f6f37ea225d19d5c205677d8d525f6a83357ca622ed541830c2",
"sha256:5a22a9c84653debfbf198d02fe592c176ea548cccce47553f35f466e15cf2fd4",
"sha256:7a5d3f26b89d688db27822343dfa25c599627bc92093e788956372285c6298ad",
"sha256:9372b04a02080752d9e6f990179a4ab840227c6e2ce15b95e1278456664cf2ba",
"sha256:a5dcbebee834eaddf3fa7366316b880ff4062e4bcc9787b78c7fbb4a26ff2dd1",
"sha256:aee5bab92a176e7cd034e57f46e9df9a9862a71f8f37cad167c6fc74c65f5b4e",
"sha256:c51f642898c0bacd335fc119da60baae0824f2cde95b0330b56c0553439f0673",
"sha256:c68ea4d3ba1705da1e0d85da6684ac657912679a649e8868bd850d2c299cce13",
"sha256:e23d0cc5299223dcc37885dae624f382297717e459ea24053709675a976a3e19"
],
"version": "==5.1"
},
"readme-renderer": {
"hashes": [
"sha256:bb16f55b259f27f75f640acf5e00cf897845a8b3e4731b5c1a436e4b8529202f",
"sha256:c8532b79afc0375a85f10433eca157d6b50f7d6990f337fa498c96cd4bfc203d"
],
"index": "pypi",
"version": "==24.0"
},
"recommonmark": {
"hashes": [
"sha256:a520b8d25071a51ae23a27cf6252f2fe387f51bdc913390d83b2b50617f5bb48",
"sha256:c85228b9b7aea7157662520e74b4e8791c5eacd375332ec68381b52bf10165be"
],
"index": "pypi",
"version": "==0.5.0"
},
"requests": {
"hashes": [
"sha256:502a824f31acdacb3a35b6690b5fbf0bc41d63a24a45c4004352b0242707598e",
"sha256:7bf2a778576d825600030a110f3c0e3e8edc51dfaafe1c146e39a2027784957b"
],
"version": "==2.21.0"
},
"requests-toolbelt": {
"hashes": [
"sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f",
"sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0"
],
"version": "==0.9.1"
},
"six": {
"hashes": [
"sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c",
"sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73"
],
"version": "==1.12.0"
},
"snowballstemmer": {
"hashes": [
"sha256:919f26a68b2c17a7634da993d91339e288964f93c274f1343e3bbbe2096e1128",
"sha256:9f3bcd3c401c3e862ec0ebe6d2c069ebc012ce142cce209c098ccb5b09136e89"
],
"version": "==1.2.1"
},
"sphinx": {
"hashes": [
"sha256:9f3e17c64b34afc653d7c5ec95766e03043cc6d80b0de224f59b6b6e19d37c3c",
"sha256:c7658aab75c920288a8cf6f09f244c6cfdae30d82d803ac1634d9f223a80ca08"
],
"index": "pypi",
"version": "==1.8.5"
},
"sphinxcontrib-websupport": {
"hashes": [
"sha256:68ca7ff70785cbe1e7bccc71a48b5b6d965d79ca50629606c7861a21b206d9dd",
"sha256:9de47f375baf1ea07cdb3436ff39d7a9c76042c10a769c52353ec46e4e8fc3b9"
],
"version": "==1.1.0"
},
"toml": {
"hashes": [
"sha256:229f81c57791a41d65e399fc06bf0848bab550a9dfd5ed66df18ce5f05e73d5c",
"sha256:235682dd292d5899d361a811df37e04a8828a5b1da3115886b73cf81ebc9100e"
],
"index": "pypi",
"version": "==0.10.0"
},
"tqdm": {
"hashes": [
"sha256:d385c95361699e5cf7622485d9b9eae2d4864b21cd5a2374a9c381ffed701021",
"sha256:e22977e3ebe961f72362f6ddfb9197cc531c9737aaf5f607ef09740c849ecd05"
],
"version": "==4.31.1"
},
"twine": {
"hashes": [
"sha256:0fb0bfa3df4f62076cab5def36b1a71a2e4acb4d1fa5c97475b048117b1a6446",
"sha256:d6c29c933ecfc74e9b1d9fa13aa1f87c5d5770e119f5a4ce032092f0ff5b14dc"
],
"index": "pypi",
"version": "==1.13.0"
},
"typed-ast": {
"hashes": [
"sha256:035a54ede6ce1380599b2ce57844c6554666522e376bd111eb940fbc7c3dad23",
"sha256:037c35f2741ce3a9ac0d55abfcd119133cbd821fffa4461397718287092d9d15",
"sha256:049feae7e9f180b64efacbdc36b3af64a00393a47be22fa9cb6794e68d4e73d3",
"sha256:19228f7940beafc1ba21a6e8e070e0b0bfd1457902a3a81709762b8b9039b88d",
"sha256:2ea681e91e3550a30c2265d2916f40a5f5d89b59469a20f3bad7d07adee0f7a6",
"sha256:3a6b0a78af298d82323660df5497bcea0f0a4a25a0b003afd0ce5af049bd1f60",
"sha256:5385da8f3b801014504df0852bf83524599df890387a3c2b17b7caa3d78b1773",
"sha256:606d8afa07eef77280c2bf84335e24390055b478392e1975f96286d99d0cb424",
"sha256:69245b5b23bbf7fb242c9f8f08493e9ecd7711f063259aefffaeb90595d62287",
"sha256:6f6d839ab09830d59b7fa8fb6917023d8cb5498ee1f1dbd82d37db78eb76bc99",
"sha256:730888475f5ac0e37c1de4bd05eeb799fdb742697867f524dc8a4cd74bcecc23",
"sha256:9819b5162ffc121b9e334923c685b0d0826154e41dfe70b2ede2ce29034c71d8",
"sha256:9e60ef9426efab601dd9aa120e4ff560f4461cf8442e9c0a2b92548d52800699",
"sha256:af5fbdde0690c7da68e841d7fc2632345d570768ea7406a9434446d7b33b0ee1",
"sha256:b64efdbdf3bbb1377562c179f167f3bf301251411eb5ac77dec6b7d32bcda463",
"sha256:bac5f444c118aeb456fac1b0b5d14c6a71ea2a42069b09c176f75e9bd4c186f6",
"sha256:bda9068aafb73859491e13b99b682bd299c1b5fd50644d697533775828a28ee0",
"sha256:d659517ca116e6750101a1326107d3479028c5191f0ecee3c7203c50f5b915b0",
"sha256:eddd3fb1f3e0f82e5915a899285a39ee34ce18fd25d89582bc89fc9fb16cd2c6"
],
"version": "==1.3.1"
},
"urllib3": {
"hashes": [
"sha256:61bf29cada3fc2fbefad4fdf059ea4bd1b4a86d2b6d15e1c7c0b582b9752fe39",
"sha256:de9529817c93f27c8ccbfead6985011db27bd0ddfcdb2d86f3f663385c6a9c22"
],
"version": "==1.24.1"
},
"virtualenv": {
"hashes": [
"sha256:6aebaf4dd2568a0094225ebbca987859e369e3e5c22dc7d52e5406d504890417",
"sha256:984d7e607b0a5d1329425dd8845bd971b957424b5ba664729fab51ab8c11bc39"
],
"version": "==16.4.3"
},
"webencodings": {
"hashes": [
"sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78",
"sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923"
],
"version": "==0.5.1"
},
"wheel": {
"hashes": [
"sha256:66a8fd76f28977bb664b098372daef2b27f60dc4d1688cfab7b37a09448f0e9d",
"sha256:8eb4a788b3aec8abf5ff68d4165441bc57420c9f64ca5f471f58c3969fe08668"
],
"index": "pypi",
"version": "==0.33.1"
},
"zipp": {
"hashes": [
"sha256:55ca87266c38af6658b84db8cfb7343cdb0bf275f93c7afaea0d8e7a209c7478",
"sha256:682b3e1c62b7026afe24eadf6be579fb45fec54c07ea218bded8092af07a68c4"
],
"version": "==0.3.3"
}
}
}
black-19.3b0/README.md 0000664 0000000 0000000 00000143446 13442505266 0014246 0 ustar 00root root 0000000 0000000 
The Uncompromising Code Formatter
> “Any color you like.”
*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.
Try it out now using the [Black Playground](https://black.now.sh).
---
*Contents:* **[Installation and usage](#installation-and-usage)** |
**[Code style](#the-black-code-style)** |
**[pyproject.toml](#pyprojecttoml)** |
**[Editor integration](#editor-integration)** |
**[blackd](#blackd)** |
**[Version control integration](#version-control-integration)** |
**[Ignoring unmodified files](#ignoring-unmodified-files)** |
**[Testimonials](#testimonials)** |
**[Show your style](#show-your-style)** |
**[Contributing](#contributing-to-black)** |
**[Change Log](#change-log)** |
**[Authors](#authors)**
---
## Installation and usage
### Installation
*Black* can be installed by running `pip install black`. It requires
Python 3.6.0+ to run but you can reformat Python 2 code with it, too.
### Usage
To get started right away with sensible defaults:
```
black {source_file_or_directory}
```
### Command line options
*Black* doesn't provide many options. You can list them by running
`black --help`:
```text
black [OPTIONS] [SRC]...
Options:
-l, --line-length INTEGER How many characters per line to allow.
[default: 88]
-t, --target-version [py27|py33|py34|py35|py36|py37|py38]
Python versions that should be supported by
Black's output. [default: per-file auto-
detection]
--py36 Allow using Python 3.6-only syntax on all
input files. This will put trailing commas
in function signatures and calls also after
*args and **kwargs. Deprecated; use
--target-version instead. [default: per-file
auto-detection]
--pyi Format all input files like typing stubs
regardless of file extension (useful when
piping source on standard input).
-S, --skip-string-normalization
Don't normalize string quotes or prefixes.
--check Don't write the files back, just return the
status. Return code 0 means nothing would
change. Return code 1 means some files
would be reformatted. Return code 123 means
there was an internal error.
--diff Don't write the files back, just output a
diff for each file on stdout.
--fast / --safe If --fast given, skip temporary sanity
checks. [default: --safe]
--include TEXT 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). Exclusions
are calculated first, inclusions later.
[default: \.pyi?$]
--exclude TEXT 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).
Exclusions are calculated first, inclusions
later. [default: /(\.eggs|\.git|\.hg|\.mypy
_cache|\.nox|\.tox|\.venv|_build|buck-
out|build|dist)/]
-q, --quiet Don't emit non-error messages to stderr.
Errors are still emitted, silence those with
2>/dev/null.
-v, --verbose Also emit messages to stderr about files
that were not changed or were ignored due to
--exclude=.
--version Show the version and exit.
--config PATH Read configuration from PATH.
-h, --help Show this message and exit.
```
*Black* is a well-behaved Unix-style command-line tool:
* it does nothing if no sources are passed to it;
* it will read from standard input and write to standard output if `-`
is used as the filename;
* it only outputs messages to users on standard error;
* exits with code 0 unless an internal error occurred (or `--check` was
used).
### NOTE: This is a beta product
*Black* is already successfully used by several projects, small and big.
It also sports a decent test suite. However, it is still very new.
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 temporary safety measure, *Black* will check that the
reformatted code still produces a valid AST that is equivalent to the
original. This slows it down. If you're feeling confident, use
``--fast``.
## The *Black* code style
*Black* reformats entire files in place. It is not configurable. It
doesn't take previous formatting into account. It doesn't reformat
blocks that start with `# fmt: off` and end with `# fmt: on`. `# fmt: on/off`
have to be on the same level of indentation. It also
recognizes [YAPF](https://github.com/google/yapf)'s block comments to
the same effect, as a courtesy for straddling code.
### How *Black* wraps lines
*Black* ignores previous formatting and applies uniform horizontal
and vertical 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 strict subset of
PEP 8.
As for vertical whitespace, *Black* tries to render one full expression
or simple statement per line. If this fits the allotted line length,
great.
```py3
# in:
l = [1,
2,
3,
]
# out:
l = [1, 2, 3]
```
If not, *Black* will look at the contents of the first outer matching
brackets and put that in a separate indented line.
```py3
# in:
ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
# out:
ImportantClass.important_method(
exc, limit, lookup_lines, capture_locals, extra_argument
)
```
If that still doesn't fit the bill, it will decompose the internal
expression further using the same rule, indenting matching brackets
every time. If the contents of the matching brackets pair are
comma-separated (like an argument list, or a dict literal, and so on)
then *Black* will first try to keep them on the same line with the
matching brackets. If that doesn't work, it will put all of them in
separate lines.
```py3
# in:
def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, 'w') as f:
...
# out:
def very_important_function(
template: str,
*variables,
file: os.PathLike,
engine: str,
header: bool = True,
debug: bool = False,
):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, "w") as f:
...
```
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).
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](https://pypi.org/p/isort/) with
the following configuration.
A compatible `.isort.cfg`
```
[settings]
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True
line_length=88
```
The equivalent command line is:
```
$ isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=88 [ file.py ]
```
### Line length
You probably noticed the peculiar default line length. *Black* defaults
to 88 characters per line, which happens to be 10% over 80. This number
was found to produce significantly shorter files than sticking with 80
(the most popular), or even 79 (used by the standard library). In
general, [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 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 limit.
You can also increase it, but remember that people with sight disabilities
find it harder to work with line lengths exceeding 100 characters.
It also adversely affects side-by-side diff review on typical screen
resolutions. Long lines also make it harder to present code neatly
in documentation or talk slides.
If you're using Flake8, you can bump `max-line-length` to 88 and forget
about it. Alternatively, use [Bugbear](https://github.com/PyCQA/flake8-bugbear)'s
B950 warning instead of E501 and keep the max line length at 80 which
you are probably already using. You'd do it like this:
```ini
[flake8]
max-line-length = 80
...
select = C,E,F,W,B,B950
ignore = E501
```
You'll find *Black*'s own .flake8 config file is configured like this.
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".
### Empty lines
*Black* avoids spurious vertical whitespace. This is in the spirit of
PEP 8 which says that in-function vertical whitespace should only be
used sparingly.
*Black* will allow single empty lines inside functions, and single and
double empty 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 space, this whitespace is lost.
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 and classes. *Black* will not put empty
lines between function/class definitions and standalone comments that
immediately precede the given function/class.
*Black* will enforce single empty lines between a class-level docstring
and the first following field or method. This conforms to
[PEP 257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings).
*Black* won't insert empty lines after function docstrings unless that
empty line is required due to an inner function starting immediately
after.
### Trailing commas
*Black* will add trailing commas to expressions that are split
by comma where each element is on its own line. This includes function
signatures.
Unnecessary trailing commas are removed if an expression fits in one
line. This makes it 1% more likely that your line won't exceed the
allotted line length limit. Moreover, in this scenario, if you added
another argument to your call, you'd probably fit it in the same line
anyway. That doesn't make diffs any larger.
One exception to removing trailing commas is tuple expressions with
just one element. In this case *Black* won't touch the single trailing
comma as this would unexpectedly change the underlying data type. Note
that this is also the case when commas are used while indexing. This is
a tuple in disguise: ```numpy_array[3, ]```.
One exception to adding trailing commas is function signatures
containing `*`, `*args`, or `**kwargs`. In this case a trailing comma
is only safe to use on Python 3.6. *Black* will detect if your file is
already 3.6+ only and use trailing commas in this situation. If you
wonder how it knows, it looks for f-strings and existing use of trailing
commas in function signatures that have stars in them. In other words,
if you'd like a trailing comma in this situation and *Black* didn't
recognize it was safe to do so, put it there manually and *Black* will
keep it.
### Strings
*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 escapes than before.
*Black* also standardizes string prefixes, making them always lowercase.
On top of that, if your code is already Python 3.6+ only or it's using
the `unicode_literals` future import, *Black* will remove `u` from the
string prefix as it is meaningless in those scenarios.
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 *Black* to merge consecutive
string literals that ended up on the same line (see
[#26](https://github.com/ambv/black/issues/26) for details).
Why settle on double quotes? They anticipate apostrophes in English
text. They match the docstring standard described in [PEP 257](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring).
An empty string in double quotes (`""`) is impossible to confuse with
a one double-quote regardless of fonts and syntax highlighting used.
On top of this, double quotes for strings are consistent with C which
Python interacts a lot with.
On certain keyboard layouts like US English, typing single quotes is
a bit easier than double quotes. The latter requires use of the Shift
key. My recommendation here is to keep using whatever is faster to type
and let *Black* handle the transformation.
If you are adopting *Black* in a large project with pre-existing string
conventions (like the popular ["single quotes for data, double quotes for
human-readable strings"](https://stackoverflow.com/a/56190)), you can
pass `--skip-string-normalization` on the command line. This is meant as
an adoption helper, avoid using this for new projects.
### Numeric literals
*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 `1e10` instead of `1E10`. Python 2 long literals are
styled as `2L` instead of `2l` to avoid confusion between `l` and `1`.
### Line breaks & binary operators
*Black* will break a line before a binary operator when splitting a block
of code over multiple lines. This is so that *Black* is compliant with the
recent changes in the [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.
This behaviour may raise ``W503 line break before binary operator`` warnings in
style guide enforcement tools like Flake8. Since ``W503`` is not PEP 8 compliant,
you should tell Flake8 to ignore these warnings.
### Slices
PEP 8 [recommends](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements)
to treat ``:`` in slices as a binary operator with the lowest priority, and to
leave an equal amount of space on either side, except if a parameter is omitted
(e.g. ``ham[1 + 1 :]``). It also states that for extended slices, both ``:``
operators have to have the same amount of spacing, except if a parameter is
omitted (``ham[1 + 1 ::]``). *Black* enforces these rules consistently.
This behaviour may raise ``E203 whitespace before ':'`` warnings in style guide
enforcement tools like Flake8. Since ``E203`` is not PEP 8 compliant, you should
tell Flake8 to ignore these warnings.
### Parentheses
Some parentheses are optional in the Python grammar. Any expression can
be wrapped in a pair of parentheses to form an atom. There are a few
interesting cases:
- `if (...):`
- `while (...):`
- `for (...) in (...):`
- `assert (...), (...)`
- `from X import (...)`
- assignments like:
- `target = (...)`
- `target: type = (...)`
- `some, *un, packing = (...)`
- `augmented += (...)`
In those cases, parentheses are removed when the entire statement fits
in one line, or if the inner expression doesn't have any delimiters to
further split on. If there is only a single delimiter and the expression
starts or ends with a bracket, the parenthesis can also be successfully
omitted since the existing bracket pair will organize the expression
neatly anyway. Otherwise, the parentheses are added.
Please note that *Black* does not add or remove any additional nested
parentheses that you might want to have for clarity or further
code organization. For example those parentheses are not going to be
removed:
```py3
return not (this or that)
decision = (maybe.this() and values > 0) or (maybe.that() and values < 0)
```
### Call chains
Some popular APIs, like ORMs, use call chaining. This API style is known
as a [fluent interface](https://en.wikipedia.org/wiki/Fluent_interface).
*Black* formats those by treating dots that follow a call or an indexing
operation like a very low priority delimiter. It's easier to show the
behavior than to explain it. Look at the example:
```py3
def example(session):
result = (
session.query(models.Customer.id)
.filter(
models.Customer.account_id == account_id,
models.Customer.email == email_address,
)
.order_by(models.Customer.id.asc())
.all()
)
```
### Typing stub files
PEP 484 describes the syntax for type hints in Python. One of the
use cases for typing is providing type annotations for modules which
cannot contain them directly (they might be written in C, or they might
be third-party, or their implementation may be overly dynamic, and so on).
To solve this, [stub files with the `.pyi` file
extension](https://www.python.org/dev/peps/pep-0484/#stub-files) can be
used to describe typing information for an external module. Those stub
files omit the implementation of classes and functions they
describe, instead they only contain the structure of the file (listing
globals, functions, and classes with their members). The recommended
code style for those files is more terse than PEP 8:
* prefer `...` on the same line as the class/function signature;
* avoid vertical whitespace between consecutive module-level functions,
names, or methods and fields within a single class;
* use a single blank line between top-level class definitions, or none
if the classes are very small.
*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:
* all function bodies should be empty (contain `...` instead of the body);
* do not use docstrings;
* 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 natively (like Python 3.7 code with `from __future__
import annotations`);
* use variable annotations instead of type comments, even for stubs that
target older versions of Python;
* for arguments that default to `None`, use `Optional[]` explicitly;
* use `float` instead of `Union[int, float]`.
## pyproject.toml
*Black* is able to read project-specific default values for its
command line options from a `pyproject.toml` file. This is
especially useful for specifying custom `--include` and `--exclude`
patterns for your project.
**Pro-tip**: If you're asking yourself "Do I need to configure anything?"
the answer is "No". *Black* is all about sensible defaults.
### What on Earth is a `pyproject.toml` file?
[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 of tools
like [Poetry](https://poetry.eustace.io/) or
[Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the
need for `setup.py` and `setup.cfg` files.
### Where *Black* looks for the file
By default *Black* looks for `pyproject.toml` starting from the common
base directory of all files and directories passed on the command line.
If it's not there, it looks in parent directories. It stops looking
when 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 the current working directory.
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.
If you're running with `--verbose`, you will see a blue message if
a file was found and used.
Please note `blackd` will not use `pyproject.toml` configuration.
### Configuration format
As the file extension suggests, `pyproject.toml` is a [TOML](https://github.com/toml-lang/toml) file. It contains separate
sections for different tools. *Black* is using the `[tool.black]`
section. The option keys are the same as long names of options on
the command line.
Note that you have to use single-quoted strings in TOML for regular
expressions. It's the equivalent of r-strings in Python. Multiline
strings are treated as verbose regular expressions by Black. Use `[ ]`
to denote a significant space character.
Example `pyproject.toml`
```toml
[tool.black]
line-length = 88
target_version = ['py37']
include = '\.pyi?$'
exclude = '''
(
/(
\.eggs # exclude a few common directories in the
| \.git # root of the project
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
| foo.py # also separately exclude a file named foo.py in
# the root of the project
)
'''
```
### Lookup hierarchy
Command-line options have defaults that you can see in `--help`.
A `pyproject.toml` can override those defaults. Finally, options
provided by the user on the command line override both.
*Black* will only ever use one `pyproject.toml` file during an entire
run. It doesn't look for multiple files, and doesn't compose
configuration from different levels of the file hierarchy.
## Editor integration
### Emacs
Use [proofit404/blacken](https://github.com/proofit404/blacken).
### PyCharm/IntelliJ IDEA
1. Install `black`.
```console
$ pip install black
```
2. Locate your `black` installation folder.
On macOS / Linux / BSD:
```console
$ which black
/usr/local/bin/black # possible location
```
On Windows:
```console
$ where black
%LocalAppData%\Programs\Python\Python36-32\Scripts\black.exe # possible location
```
3. Open External tools in PyCharm/IntelliJ IDEA
On macOS:
```PyCharm -> Preferences -> Tools -> External Tools```
On Windows / Linux / BSD:
```File -> Settings -> Tools -> External Tools```
4. Click the + icon to add a new external tool with the following values:
- Name: Black
- Description: Black is the uncompromising Python code formatter.
- Program:
- Arguments: `"$FilePath$"`
5. Format the currently opened file by selecting `Tools -> External Tools -> black`.
- Alternatively, you can set a keyboard shortcut by navigating to `Preferences or Settings -> Keymap -> External Tools -> External Tools - Black`.
6. Optionally, run Black on every file save:
1. Make sure you have the [File Watcher](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin installed.
2. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a new watcher:
- Name: Black
- File type: Python
- Scope: Project Files
- Program:
- Arguments: `$FilePath$`
- Output paths to refresh: `$FilePath$`
- Working directory: `$ProjectFileDir$`
- Uncheck "Auto-save edited files to trigger the watcher"
### Vim
Commands and shortcuts:
* `:Black` to format the entire file (ranges not supported);
* `:BlackUpgrade` to upgrade *Black* inside the virtualenv;
* `:BlackVersion` to get the current version of *Black* inside the
virtualenv.
Configuration:
* `g:black_fast` (defaults to `0`)
* `g:black_linelength` (defaults to `88`)
* `g:black_skip_string_normalization` (defaults to `0`)
* `g:black_virtualenv` (defaults to `~/.vim/black`)
To install with [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'ambv/black'
```
or with [Vundle](https://github.com/VundleVim/Vundle.vim):
```
Plugin 'ambv/black'
```
or you can copy the plugin from [plugin/black.vim](https://github.com/ambv/black/tree/master/plugin/black.vim).
Let me know if this requires any changes to work with Vim 8's builtin
`packadd`, or Pathogen, and so on.
This plugin **requires Vim 7.0+ built with Python 3.6+ support**. It
needs Python 3.6 to 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 automatically installs *Black*. You can upgrade it later
by calling `:BlackUpgrade` and restarting Vim.
If you need to do anything special to make your virtualenv work and
install *Black* (for example you want to run a version from master),
create a virtualenv manually and point `g:black_virtualenv` to it.
The plugin will use it.
To run *Black* on save, add the following line to `.vimrc` or `init.vim`:
```
autocmd BufWritePre *.py execute ':Black'
```
**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 --with-python3`.
When building Vim from source, use:
`./configure --enable-python3interp=yes`. There's many guides online how
to do this.
### Visual Studio Code
Use the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
([instructions](https://code.visualstudio.com/docs/python/editing#_formatting)).
### SublimeText 3
Use [sublack plugin](https://github.com/jgirardet/sublack).
### Jupyter Notebook Magic
Use [blackcellmagic](https://github.com/csurfer/blackcellmagic).
### Python Language Server
If your editor supports the [Language Server Protocol](https://langserver.org/)
(Atom, Sublime Text, Visual Studio Code and many more), you can use
the [Python Language Server](https://github.com/palantir/python-language-server) with the
[pyls-black](https://github.com/rupert/pyls-black) plugin.
### Atom/Nuclide
Use [python-black](https://atom.io/packages/python-black).
### Other editors
Other editors will require external contributions.
Patches welcome! ✨ 🍰 ✨
Any tool that 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).
## blackd
`blackd` is a small HTTP server that exposes *Black*'s functionality over
a simple protocol. The main benefit of using it is to avoid paying the
cost of starting up a new *Black* process every time you want to blacken
a file.
### Usage
`blackd` is not packaged alongside *Black* by default because it has additional
dependencies. You will need to do `pip install black[d]` to install it.
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 host and port it's listening on. `blackd` will then print an access log
similar to most web servers on standard output, merged with any exception traces
caused by invalid formatting requests.
`blackd` provides even less options than *Black*. You can see them by running
`blackd --help`:
```text
Usage: blackd [OPTIONS]
Options:
--bind-host TEXT Address to bind the server to.
--bind-port INTEGER Port to listen on
--version Show the version and exit.
-h, --help Show this message and exit.
```
### Protocol
`blackd` only accepts `POST` requests at the `/` path. The body of the request
should contain the python source code to be formatted, encoded
according to the `charset` field in the `Content-Type` request header. If no
`charset` is specified, `blackd` assumes `UTF-8`.
There are a few HTTP headers that control how the source is formatted. These
correspond to command line flags for *Black*. There is one exception to this:
`X-Protocol-Version` which if present, should have the value `1`, otherwise the
request is rejected with `HTTP 501` (Not Implemented).
The headers controlling how code is formatted are:
- `X-Line-Length`: corresponds to the `--line-length` command line flag.
- `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
normalization will be performed.
- `X-Fast-Or-Safe`: if set to `fast`, `blackd` will act as *Black* does when
passed the `--fast` command line flag.
- `X-Python-Variant`: if set to `pyi`, `blackd` will act as *Black* does when
passed the `--pyi` command line flag. Otherwise, its value must correspond to
a Python version or a set of comma-separated Python versions, optionally
prefixed with `py`. For example, to request code that is compatible
with Python 3.5 and 3.6, set the header to `py3.5,py3.6`.
If any of these headers are set to invalid values, `blackd` returns a `HTTP 400`
error response, mentioning the name of the problematic header in the message body.
Apart from the above, `blackd` can produce the following response codes:
- `HTTP 204`: If the input is already well-formatted. The response body is
empty.
- `HTTP 200`: If formatting was needed on the input. The response body
contains the blackened Python code, and the `Content-Type` header is set
accordingly.
- `HTTP 400`: If the input contains a syntax error. Details of the error are
returned in the response body.
- `HTTP 500`: If there was any kind of error while trying to format the input.
The response body contains a textual representation of the error.
## Version control integration
Use [pre-commit](https://pre-commit.com/). Once you [have it
installed](https://pre-commit.com/#install), add this to the
`.pre-commit-config.yaml` in your repository:
```yaml
repos:
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3.6
```
Then run `pre-commit install` and you're ready to go.
Avoid using `args` in the hook. Instead, store necessary configuration
in `pyproject.toml` so that editors and command-line usage of Black all
behave consistently for your project. See *Black*'s own `pyproject.toml`
for an example.
If you're already using Python 3.7, switch the `language_version`
accordingly. Finally, `stable` is a tag that is pinned to the latest
release on PyPI. If you'd rather run on master, this is also an option.
## Ignoring unmodified files
*Black* remembers files it has already formatted, unless the `--diff` flag is used or
code is passed via standard input. This information is stored per-user. The exact
location of the file depends on the *Black* version and the system on which *Black*
is run. The file is non-portable. The standard location on common operating systems
is:
* Windows: `C:\\Users\\AppData\Local\black\black\Cache\\cache...pickle`
* macOS: `/Users//Library/Caches/black//cache...pickle`
* Linux: `/home//.cache/black//cache...pickle`
`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.
## Testimonials
**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:
```markdown
[](https://github.com/ambv/black)
```
Using the badge in README.rst:
```
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
```
Looks like this: [](https://github.com/ambv/black)
## License
MIT
## Contributing to *Black*
In terms of inspiration, *Black* is about as configurable as *gofmt*.
This is deliberate.
Bug reports and fixes are always welcome! However, 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.
More details can be found in [CONTRIBUTING](CONTRIBUTING.md).
## Change Log
### 19.3b0
* new option `--target-version` to control which Python versions
*Black*-formatted code should target (#618)
* deprecated `--py36` (use `--target-version=py36` instead) (#724)
* *Black* no longer normalizes numeric literals to include `_` separators (#696)
* long `del` statements are now split into multiple lines (#698)
* type comments are no longer mangled in function signatures
* improved performance of formatting deeply nested data structures (#509)
* *Black* now properly formats multiple files in parallel on
Windows (#632)
* *Black* now creates cache files atomically which allows it to be used
in parallel pipelines (like `xargs -P8`) (#673)
* *Black* now correctly indents comments in files that were previously
formatted with tabs (#262)
* `blackd` now supports CORS (#622)
### 18.9b0
* numeric literals are now formatted by *Black* (#452, #461, #464, #469):
* numeric literals are normalized to include `_` separators on Python 3.6+ code
* added `--skip-numeric-underscore-normalization` to disable the above behavior and
leave numeric underscores as they were in the input
* code with `_` in numeric literals is recognized as Python 3.6+
* most letters in numeric literals are lowercased (e.g., in `1e10`, `0x01`)
* hexadecimal digits are always uppercased (e.g. `0xBADC0DE`)
* added `blackd`, see [its documentation](#blackd) for more info (#349)
* adjacent string literals are now correctly split into multiple lines (#463)
* trailing comma is now added to single imports that don't fit on a line (#250)
* cache is now populated when `--check` is successful for a file which speeds up
consecutive checks of properly formatted unmodified files (#448)
* whitespace at the beginning of the file is now removed (#399)
* fixed mangling [pweave](http://mpastell.com/pweave/) and
[Spyder IDE](https://pythonhosted.org/spyder/) special comments (#532)
* fixed unstable formatting when unpacking big tuples (#267)
* fixed parsing of `__future__` imports with renames (#389)
* fixed scope of `# fmt: off` when directly preceding `yield` and other nodes (#385)
* fixed formatting of lambda expressions with default arguments (#468)
* fixed ``async for`` statements: *Black* no longer breaks them into separate
lines (#372)
* note: the Vim plugin stopped registering ``,=`` as a default chord as it turned out
to be a bad idea (#415)
### 18.6b4
* hotfix: don't freeze when multiple comments directly precede `# fmt: off` (#371)
### 18.6b3
* typing stub files (`.pyi`) now have blank lines added after constants (#340)
* `# fmt: off` and `# fmt: on` are now much more dependable:
* they now work also within bracket pairs (#329)
* they now correctly work across function/class boundaries (#335)
* they now work when an indentation block starts with empty lines or misaligned
comments (#334)
* made Click not fail on invalid environments; note that Click is right but the
likelihood we'll need to access non-ASCII file paths when dealing with Python source
code is low (#277)
* fixed improper formatting of f-strings with quotes inside interpolated
expressions (#322)
* fixed unnecessary slowdown when long list literals where found in a file
* fixed unnecessary slowdown on AST nodes with very many siblings
* fixed cannibalizing backslashes during string normalization
* fixed a crash due to symbolic links pointing outside of the project directory (#338)
### 18.6b2
* added `--config` (#65)
* added `-h` equivalent to `--help` (#316)
* fixed improper unmodified file caching when `-S` was used
* fixed extra space in string unpacking (#305)
* fixed formatting of empty triple quoted strings (#313)
* fixed unnecessary slowdown in comment placement calculation on lines without
comments
### 18.6b1
* hotfix: don't output human-facing information on stdout (#299)
* hotfix: don't output cake emoji on non-zero return code (#300)
### 18.6b0
* added `--include` and `--exclude` (#270)
* added `--skip-string-normalization` (#118)
* added `--verbose` (#283)
* the header output in `--diff` now actually conforms to the unified diff spec
* fixed long trivial assignments being wrapped in unnecessary parentheses (#273)
* fixed unnecessary parentheses when a line contained multiline strings (#232)
* fixed stdin handling not working correctly if an old version of Click was
used (#276)
* *Black* now preserves line endings when formatting a file in place (#258)
### 18.5b1
* added `--pyi` (#249)
* added `--py36` (#249)
* Python grammar pickle caches are stored with the formatting caches, making
*Black* work in environments where site-packages is not user-writable (#192)
* *Black* now enforces a PEP 257 empty line after a class-level docstring
(and/or fields) and the first method
* fixed invalid code produced when standalone comments were present in a trailer
that was omitted from line splitting on a large expression (#237)
* fixed optional parentheses being removed within `# fmt: off` sections (#224)
* fixed invalid code produced when stars in very long imports were incorrectly
wrapped in optional parentheses (#234)
* fixed unstable formatting when inline comments were moved around in
a trailer that was omitted from line splitting on a large expression
(#238)
* fixed extra empty line between a class declaration and the first
method if no class docstring or fields are present (#219)
* fixed extra empty line between a function signature and an inner
function or inner class (#196)
### 18.5b0
* call chains are now formatted according to the
[fluent interfaces](https://en.wikipedia.org/wiki/Fluent_interface)
style (#67)
* data structure literals (tuples, lists, dictionaries, and sets) are
now also always exploded like imports when they don't fit in a single
line (#152)
* slices are now formatted according to PEP 8 (#178)
* parentheses are now also managed automatically on the right-hand side
of assignments and return statements (#140)
* math operators now use their respective priorities for delimiting multiline
expressions (#148)
* optional parentheses are now omitted on expressions that start or end
with a bracket and only contain a single operator (#177)
* empty parentheses in a class definition are now removed (#145, #180)
* string prefixes are now standardized to lowercase and `u` is removed
on Python 3.6+ only code and Python 2.7+ code with the `unicode_literals`
future import (#188, #198, #199)
* typing stub files (`.pyi`) are now formatted in a style that is consistent
with PEP 484 (#207, #210)
* progress when reformatting many files is now reported incrementally
* fixed trailers (content with brackets) being unnecessarily exploded
into their own lines after a dedented closing bracket (#119)
* fixed an invalid trailing comma sometimes left in imports (#185)
* fixed non-deterministic formatting when multiple pairs of removable parentheses
were used (#183)
* fixed multiline strings being unnecessarily wrapped in optional
parentheses in long assignments (#215)
* fixed not splitting long from-imports with only a single name
* fixed Python 3.6+ file discovery by also looking at function calls with
unpacking. This fixed non-deterministic formatting if trailing commas
where used both in function signatures with stars and function calls
with stars but the former would be reformatted to a single line.
* fixed crash on dealing with optional parentheses (#193)
* fixed "is", "is not", "in", and "not in" not considered operators for
splitting purposes
* fixed crash when dead symlinks where encountered
### 18.4a4
* don't populate the cache on `--check` (#175)
### 18.4a3
* added a "cache"; files already reformatted that haven't changed on disk
won't be reformatted again (#109)
* `--check` and `--diff` are no longer mutually exclusive (#149)
* generalized star expression handling, including double stars; this
fixes multiplication making expressions "unsafe" for trailing commas (#132)
* *Black* no longer enforces putting empty lines behind control flow statements
(#90)
* *Black* now splits imports like "Mode 3 + trailing comma" of isort (#127)
* fixed comment indentation when a standalone comment closes a block (#16, #32)
* fixed standalone comments receiving extra empty lines if immediately preceding
a class, def, or decorator (#56, #154)
* fixed `--diff` not showing entire path (#130)
* fixed parsing of complex expressions after star and double stars in
function calls (#2)
* fixed invalid splitting on comma in lambda arguments (#133)
* fixed missing splits of ternary expressions (#141)
### 18.4a2
* fixed parsing of unaligned standalone comments (#99, #112)
* fixed placement of dictionary unpacking inside dictionary literals (#111)
* Vim plugin now works on Windows, too
* fixed unstable formatting when encountering unnecessarily escaped quotes
in a string (#120)
### 18.4a1
* added `--quiet` (#78)
* added automatic parentheses management (#4)
* added [pre-commit](https://pre-commit.com) integration (#103, #104)
* fixed reporting on `--check` with multiple files (#101, #102)
* fixed removing backslash escapes from raw strings (#100, #105)
### 18.4a0
* added `--diff` (#87)
* add line breaks before all delimiters, except in cases like commas, to
better comply with PEP 8 (#73)
* standardize string literals to use double quotes (almost) everywhere
(#75)
* fixed handling of standalone comments within nested bracketed
expressions; *Black* will no longer produce super long lines or put all
standalone comments at the end of the expression (#22)
* fixed 18.3a4 regression: don't crash and burn on empty lines with
trailing whitespace (#80)
* fixed 18.3a4 regression: `# yapf: disable` usage as trailing comment
would cause *Black* to not emit the rest of the file (#95)
* when CTRL+C is pressed while formatting many files, *Black* no longer
freaks out with a flurry of asyncio-related exceptions
* only allow up to two empty lines on module level and only single empty
lines within functions (#74)
### 18.3a4
* `# fmt: off` and `# fmt: on` are implemented (#5)
* automatic detection of deprecated Python 2 forms of print statements
and exec statements in the formatted file (#49)
* use proper spaces for complex expressions in default values of typed
function arguments (#60)
* only return exit code 1 when --check is used (#50)
* don't remove single trailing commas from square bracket indexing
(#59)
* don't omit whitespace if the previous factor leaf wasn't a math
operator (#55)
* omit extra space in kwarg unpacking if it's the first argument (#46)
* omit extra space in [Sphinx auto-attribute comments](http://www.sphinx-doc.org/en/stable/ext/autodoc.html#directive-autoattribute)
(#68)
### 18.3a3
* don't remove single empty lines outside of bracketed expressions
(#19)
* added ability to pipe formatting from stdin to stdin (#25)
* restored ability to format code with legacy usage of `async` as
a name (#20, #42)
* even better handling of numpy-style array indexing (#33, again)
### 18.3a2
* changed positioning of binary operators to occur at beginning of lines
instead of at the end, following [a recent change to PEP 8](https://github.com/python/peps/commit/c59c4376ad233a62ca4b3a6060c81368bd21e85b)
(#21)
* ignore empty bracket pairs while splitting. This avoids very weirdly
looking formattings (#34, #35)
* remove a trailing comma if there is a single argument to a call
* if top level functions were separated by a comment, don't put four
empty lines after the upper function
* fixed unstable formatting of newlines with imports
* fixed unintentional folding of post scriptum standalone comments
into last statement if it was a simple statement (#18, #28)
* fixed missing space in numpy-style array indexing (#33)
* fixed spurious space after star-based unary expressions (#31)
### 18.3a1
* added `--check`
* only put trailing commas in function signatures and calls if it's
safe to do so. If the file is Python 3.6+ it's always safe, otherwise
only safe if there are no `*args` or `**kwargs` used in the signature
or call. (#8)
* fixed invalid spacing of dots in relative imports (#6, #13)
* fixed invalid splitting after comma on unpacked variables in for-loops
(#23)
* fixed spurious space in parenthesized set expressions (#7)
* fixed spurious space after opening parentheses and in default
arguments (#14, #17)
* fixed spurious space after unary operators when the operand was
a complex expression (#15)
### 18.3a0
* first published version, Happy 🍰 Day 2018!
* alpha quality
* date-versioned (see: https://calver.org/)
## Authors
Glued together by [Łukasz Langa](mailto:lukasz@langa.pl).
Maintained with [Carol Willing](mailto:carolcode@willingconsulting.com),
[Carl Meyer](mailto:carl@oddbird.net),
[Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com),
[Mika Naylor](mailto:mail@autophagy.io), and
[Zsolt Dollenstein](mailto:zsol.zsol@gmail.com).
Multiple contributions by:
* [Anthony Sottile](mailto:asottile@umich.edu)
* [Artem Malyshev](mailto:proofit404@gmail.com)
* [Christian Heimes](mailto:christian@python.org)
* [Daniel M. Capella](mailto:polycitizen@gmail.com)
* [Eli Treuherz](mailto:eli@treuherz.com)
* hauntsaninja
* Hugo van Kemenade
* [Ivan Katanić](mailto:ivan.katanic@gmail.com)
* [Jonas Obrist](mailto:ojiidotch@gmail.com)
* [Luka Sterbic](mailto:luka.sterbic@gmail.com)
* [Miguel Gaiowski](mailto:miggaiowski@gmail.com)
* [Miroslav Shubernetskiy](mailto:miroslav@miki725.com)
* [Neraste](mailto:neraste.herr10@gmail.com)
* [Osaetin Daniel](mailto:osaetindaniel@gmail.com)
* [Peter Bengtsson](mailto:mail@peterbe.com)
* [Stavros Korokithakis](mailto:hi@stavros.io)
* [Sunil Kapil](mailto:snlkapil@gmail.com)
* [Utsav Shah](mailto:ukshah2@illinois.edu)
* [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com)
* [Chuck Wooters](mailto:chuck.wooters@microsoft.com)
black-19.3b0/black.py 0000664 0000000 0000000 00000364764 13442505266 0014425 0 ustar 00root root 0000000 0000000 import asyncio
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from datetime import datetime
from enum import Enum
from functools import lru_cache, partial, wraps
import io
import itertools
import logging
from multiprocessing import Manager, freeze_support
import os
from pathlib import Path
import pickle
import re
import signal
import sys
import tempfile
import tokenize
from typing import (
Any,
Callable,
Collection,
Dict,
Generator,
Generic,
Iterable,
Iterator,
List,
Optional,
Pattern,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
)
from appdirs import user_cache_dir
from attr import dataclass, evolve, Factory
import click
import toml
# lib2to3 fork
from blib2to3.pytree import Node, Leaf, type_repr
from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
__version__ = "19.3b0"
DEFAULT_LINE_LENGTH = 88
DEFAULT_EXCLUDES = (
r"/(\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist)/"
)
DEFAULT_INCLUDES = r"\.pyi?$"
CACHE_DIR = Path(user_cache_dir("black", version=__version__))
# types
FileContent = str
Encoding = str
NewLine = str
Depth = int
NodeType = int
LeafID = int
Priority = int
Index = int
LN = Union[Leaf, Node]
SplitFunc = Callable[["Line", bool], Iterator["Line"]]
Timestamp = float
FileSize = int
CacheInfo = Tuple[Timestamp, FileSize]
Cache = Dict[Path, CacheInfo]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg="red", err=True)
pygram.initialize(CACHE_DIR)
syms = pygram.python_symbols
class NothingChanged(UserWarning):
"""Raised when reformatted code is the same as source."""
class CannotSplit(Exception):
"""A readable split that fits the allotted line length is impossible."""
class InvalidInput(ValueError):
"""Raised when input source code fails all parse attempts."""
class WriteBack(Enum):
NO = 0
YES = 1
DIFF = 2
CHECK = 3
@classmethod
def from_configuration(cls, *, check: bool, diff: bool) -> "WriteBack":
if check and not diff:
return cls.CHECK
return cls.DIFF if diff else cls.YES
class Changed(Enum):
NO = 0
CACHED = 1
YES = 2
class TargetVersion(Enum):
PY27 = 2
PY33 = 3
PY34 = 4
PY35 = 5
PY36 = 6
PY37 = 7
PY38 = 8
def is_python2(self) -> bool:
return self is TargetVersion.PY27
PY36_VERSIONS = {TargetVersion.PY36, TargetVersion.PY37, TargetVersion.PY38}
class Feature(Enum):
# All string literals are unicode
UNICODE_LITERALS = 1
F_STRINGS = 2
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA = 4
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
TargetVersion.PY27: set(),
TargetVersion.PY33: {Feature.UNICODE_LITERALS},
TargetVersion.PY34: {Feature.UNICODE_LITERALS},
TargetVersion.PY35: {Feature.UNICODE_LITERALS, Feature.TRAILING_COMMA},
TargetVersion.PY36: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA,
},
TargetVersion.PY37: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA,
},
}
@dataclass
class FileMode:
target_versions: Set[TargetVersion] = Factory(set)
line_length: int = DEFAULT_LINE_LENGTH
string_normalization: bool = True
is_pyi: bool = False
def get_cache_key(self) -> str:
if self.target_versions:
version_str = ",".join(
str(version.value)
for version in sorted(self.target_versions, key=lambda v: v.value)
)
else:
version_str = "-"
parts = [
version_str,
str(self.line_length),
str(int(self.string_normalization)),
str(int(self.is_pyi)),
]
return ".".join(parts)
def supports_feature(target_versions: Set[TargetVersion], feature: Feature) -> bool:
return all(feature in VERSION_TO_FEATURES[version] for version in target_versions)
def read_pyproject_toml(
ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
) -> Optional[str]:
"""Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
Returns the path to a successfully found and read configuration file, None
otherwise.
"""
assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
if not value:
root = find_project_root(ctx.params.get("src", ()))
path = root / "pyproject.toml"
if path.is_file():
value = str(path)
else:
return None
try:
pyproject_toml = toml.load(value)
config = pyproject_toml.get("tool", {}).get("black", {})
except (toml.TomlDecodeError, OSError) as e:
raise click.FileError(
filename=value, hint=f"Error reading configuration file: {e}"
)
if not config:
return None
if ctx.default_map is None:
ctx.default_map = {}
ctx.default_map.update( # type: ignore # bad types in .pyi
{k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
)
return value
@click.command(context_settings=dict(help_option_names=["-h", "--help"]))
@click.option(
"-l",
"--line-length",
type=int,
default=DEFAULT_LINE_LENGTH,
help="How many characters per line to allow.",
show_default=True,
)
@click.option(
"-t",
"--target-version",
type=click.Choice([v.name.lower() for v in TargetVersion]),
callback=lambda c, p, v: [TargetVersion[val.upper()] for val in v],
multiple=True,
help=(
"Python versions that should be supported by Black's output. [default: "
"per-file auto-detection]"
),
)
@click.option(
"--py36",
is_flag=True,
help=(
"Allow using Python 3.6-only syntax on all input files. This will put "
"trailing commas in function signatures and calls also after *args and "
"**kwargs. Deprecated; use --target-version instead. "
"[default: per-file auto-detection]"
),
)
@click.option(
"--pyi",
is_flag=True,
help=(
"Format all input files like typing stubs regardless of file extension "
"(useful when piping source on standard input)."
),
)
@click.option(
"-S",
"--skip-string-normalization",
is_flag=True,
help="Don't normalize string quotes or prefixes.",
)
@click.option(
"--check",
is_flag=True,
help=(
"Don't write the files back, just return the status. Return code 0 "
"means nothing would change. Return code 1 means some files would be "
"reformatted. Return code 123 means there was an internal error."
),
)
@click.option(
"--diff",
is_flag=True,
help="Don't write the files back, just output a diff for each file on stdout.",
)
@click.option(
"--fast/--safe",
is_flag=True,
help="If --fast given, skip temporary sanity checks. [default: --safe]",
)
@click.option(
"--include",
type=str,
default=DEFAULT_INCLUDES,
help=(
"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). Exclusions are calculated first, inclusions "
"later."
),
show_default=True,
)
@click.option(
"--exclude",
type=str,
default=DEFAULT_EXCLUDES,
help=(
"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). "
"Exclusions are calculated first, inclusions later."
),
show_default=True,
)
@click.option(
"-q",
"--quiet",
is_flag=True,
help=(
"Don't emit non-error messages to stderr. Errors are still emitted, "
"silence those with 2>/dev/null."
),
)
@click.option(
"-v",
"--verbose",
is_flag=True,
help=(
"Also emit messages to stderr about files that were not changed or were "
"ignored due to --exclude=."
),
)
@click.version_option(version=__version__)
@click.argument(
"src",
nargs=-1,
type=click.Path(
exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
),
is_eager=True,
)
@click.option(
"--config",
type=click.Path(
exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
),
is_eager=True,
callback=read_pyproject_toml,
help="Read configuration from PATH.",
)
@click.pass_context
def main(
ctx: click.Context,
line_length: int,
target_version: List[TargetVersion],
check: bool,
diff: bool,
fast: bool,
pyi: bool,
py36: bool,
skip_string_normalization: bool,
quiet: bool,
verbose: bool,
include: str,
exclude: str,
src: Tuple[str],
config: Optional[str],
) -> None:
"""The uncompromising code formatter."""
write_back = WriteBack.from_configuration(check=check, diff=diff)
if target_version:
if py36:
err(f"Cannot use both --target-version and --py36")
ctx.exit(2)
else:
versions = set(target_version)
elif py36:
err(
"--py36 is deprecated and will be removed in a future version. "
"Use --target-version py36 instead."
)
versions = PY36_VERSIONS
else:
# We'll autodetect later.
versions = set()
mode = FileMode(
target_versions=versions,
line_length=line_length,
is_pyi=pyi,
string_normalization=not skip_string_normalization,
)
if config and verbose:
out(f"Using configuration from {config}.", bold=False, fg="blue")
try:
include_regex = re_compile_maybe_verbose(include)
except re.error:
err(f"Invalid regular expression for include given: {include!r}")
ctx.exit(2)
try:
exclude_regex = re_compile_maybe_verbose(exclude)
except re.error:
err(f"Invalid regular expression for exclude given: {exclude!r}")
ctx.exit(2)
report = Report(check=check, quiet=quiet, verbose=verbose)
root = find_project_root(src)
sources: Set[Path] = set()
for s in src:
p = Path(s)
if p.is_dir():
sources.update(
gen_python_files_in_dir(p, root, include_regex, exclude_regex, report)
)
elif p.is_file() or s == "-":
# if a file was explicitly given, we don't care about its extension
sources.add(p)
else:
err(f"invalid path: {s}")
if len(sources) == 0:
if verbose or not quiet:
out("No paths given. Nothing to do 😴")
ctx.exit(0)
if len(sources) == 1:
reformat_one(
src=sources.pop(),
fast=fast,
write_back=write_back,
mode=mode,
report=report,
)
else:
loop = asyncio.get_event_loop()
executor = ProcessPoolExecutor(max_workers=os.cpu_count())
try:
loop.run_until_complete(
schedule_formatting(
sources=sources,
fast=fast,
write_back=write_back,
mode=mode,
report=report,
loop=loop,
executor=executor,
)
)
finally:
shutdown(loop)
if verbose or not quiet:
bang = "💥 💔 💥" if report.return_code else "✨ 🍰 ✨"
out(f"All done! {bang}")
click.secho(str(report), err=True)
ctx.exit(report.return_code)
def reformat_one(
src: Path, fast: bool, write_back: WriteBack, mode: FileMode, report: "Report"
) -> None:
"""Reformat a single file under `src` without spawning child processes.
If `quiet` is True, non-error messages are not output. `line_length`,
`write_back`, `fast` and `pyi` options are passed to
:func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
"""
try:
changed = Changed.NO
if not src.is_file() and str(src) == "-":
if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
changed = Changed.YES
else:
cache: Cache = {}
if write_back != WriteBack.DIFF:
cache = read_cache(mode)
res_src = src.resolve()
if res_src in cache and cache[res_src] == get_cache_info(res_src):
changed = Changed.CACHED
if changed is not Changed.CACHED and format_file_in_place(
src, fast=fast, write_back=write_back, mode=mode
):
changed = Changed.YES
if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
write_back is WriteBack.CHECK and changed is Changed.NO
):
write_cache(cache, [src], mode)
report.done(src, changed)
except Exception as exc:
report.failed(src, str(exc))
async def schedule_formatting(
sources: Set[Path],
fast: bool,
write_back: WriteBack,
mode: FileMode,
report: "Report",
loop: BaseEventLoop,
executor: Executor,
) -> None:
"""Run formatting of `sources` in parallel using the provided `executor`.
(Use ProcessPoolExecutors for actual parallelism.)
`line_length`, `write_back`, `fast`, and `pyi` options are passed to
:func:`format_file_in_place`.
"""
cache: Cache = {}
if write_back != WriteBack.DIFF:
cache = read_cache(mode)
sources, cached = filter_cached(cache, sources)
for src in sorted(cached):
report.done(src, Changed.CACHED)
if not sources:
return
cancelled = []
sources_to_cache = []
lock = None
if write_back == WriteBack.DIFF:
# For diff output, we need locks to ensure we don't interleave output
# from different processes.
manager = Manager()
lock = manager.Lock()
tasks = {
loop.run_in_executor(
executor, format_file_in_place, src, fast, mode, write_back, lock
): src
for src in sorted(sources)
}
pending: Iterable[asyncio.Task] = tasks.keys()
try:
loop.add_signal_handler(signal.SIGINT, cancel, pending)
loop.add_signal_handler(signal.SIGTERM, cancel, pending)
except NotImplementedError:
# There are no good alternatives for these on Windows.
pass
while pending:
done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for task in done:
src = tasks.pop(task)
if task.cancelled():
cancelled.append(task)
elif task.exception():
report.failed(src, str(task.exception()))
else:
changed = Changed.YES if task.result() else Changed.NO
# If the file was written back or was successfully checked as
# well-formatted, store this information in the cache.
if write_back is WriteBack.YES or (
write_back is WriteBack.CHECK and changed is Changed.NO
):
sources_to_cache.append(src)
report.done(src, changed)
if cancelled:
await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
if sources_to_cache:
write_cache(cache, sources_to_cache, mode)
def format_file_in_place(
src: Path,
fast: bool,
mode: FileMode,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
"""Format file under `src` path. Return True if changed.
If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
code to the file.
`line_length` and `fast` options are passed to :func:`format_file_contents`.
"""
if src.suffix == ".pyi":
mode = evolve(mode, is_pyi=True)
then = datetime.utcfromtimestamp(src.stat().st_mtime)
with open(src, "rb") as buf:
src_contents, encoding, newline = decode_bytes(buf.read())
try:
dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
except NothingChanged:
return False
if write_back == write_back.YES:
with open(src, "w", encoding=encoding, newline=newline) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
now = datetime.utcnow()
src_name = f"{src}\t{then} +0000"
dst_name = f"{src}\t{now} +0000"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
if lock:
lock.acquire()
try:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(diff_contents)
f.detach()
finally:
if lock:
lock.release()
return True
def format_stdin_to_stdout(
fast: bool, *, write_back: WriteBack = WriteBack.NO, mode: FileMode
) -> bool:
"""Format file on stdin. Return True if changed.
If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
write a diff to stdout. The `mode` argument is passed to
:func:`format_file_contents`.
"""
then = datetime.utcnow()
src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
dst = src
try:
dst = format_file_contents(src, fast=fast, mode=mode)
return True
except NothingChanged:
return False
finally:
f = io.TextIOWrapper(
sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
)
if write_back == WriteBack.YES:
f.write(dst)
elif write_back == WriteBack.DIFF:
now = datetime.utcnow()
src_name = f"STDIN\t{then} +0000"
dst_name = f"STDOUT\t{now} +0000"
f.write(diff(src, dst, src_name, dst_name))
f.detach()
def format_file_contents(
src_contents: str, *, fast: bool, mode: FileMode
) -> FileContent:
"""Reformat contents a file and return new contents.
If `fast` is False, additionally confirm that the reformatted code is
valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
`line_length` is passed to :func:`format_str`.
"""
if src_contents.strip() == "":
raise NothingChanged
dst_contents = format_str(src_contents, mode=mode)
if src_contents == dst_contents:
raise NothingChanged
if not fast:
assert_equivalent(src_contents, dst_contents)
assert_stable(src_contents, dst_contents, mode=mode)
return dst_contents
def format_str(src_contents: str, *, mode: FileMode) -> FileContent:
"""Reformat a string and return new contents.
`line_length` determines how many characters per line are allowed.
"""
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
dst_contents = ""
future_imports = get_future_imports(src_node)
if mode.target_versions:
versions = mode.target_versions
else:
versions = detect_target_versions(src_node)
normalize_fmt_off(src_node)
lines = LineGenerator(
remove_u_prefix="unicode_literals" in future_imports
or supports_feature(versions, Feature.UNICODE_LITERALS),
is_pyi=mode.is_pyi,
normalize_strings=mode.string_normalization,
)
elt = EmptyLineTracker(is_pyi=mode.is_pyi)
empty_line = Line()
after = 0
for current_line in lines.visit(src_node):
for _ in range(after):
dst_contents += str(empty_line)
before, after = elt.maybe_empty_lines(current_line)
for _ in range(before):
dst_contents += str(empty_line)
for line in split_line(
current_line,
line_length=mode.line_length,
supports_trailing_commas=supports_feature(versions, Feature.TRAILING_COMMA),
):
dst_contents += str(line)
return dst_contents
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""Return a tuple of (decoded_contents, encoding, newline).
`newline` is either CRLF or LF but `decoded_contents` is decoded with
universal newlines (i.e. only contains LF).
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
if not lines:
return "", encoding, "\n"
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextIOWrapper(srcbuf, encoding) as tiow:
return tiow.read(), encoding, newline
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
pygram.python_grammar,
]
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
return GRAMMARS
elif all(not version.is_python2() for version in target_versions):
# Python 2-compatible code, so don't try Python 3 grammar.
return [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
]
else:
return [pygram.python_grammar]
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
"""Given a string with source, return the lib2to3 Node."""
if src_txt[-1:] != "\n":
src_txt += "\n"
for grammar in get_grammars(set(target_versions)):
drv = driver.Driver(grammar, pytree.convert)
try:
result = drv.parse_string(src_txt, True)
break
except ParseError as pe:
lineno, column = pe.context[1]
lines = src_txt.splitlines()
try:
faulty_line = lines[lineno - 1]
except IndexError:
faulty_line = ""
exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")
else:
raise exc from None
if isinstance(result, Leaf):
result = Node(syms.file_input, [result])
return result
def lib2to3_unparse(node: Node) -> str:
"""Given a lib2to3 node, return its string representation."""
code = str(node)
return code
T = TypeVar("T")
class Visitor(Generic[T]):
"""Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
def visit(self, node: LN) -> Iterator[T]:
"""Main method to visit `node` and its children.
It tries to find a `visit_*()` method for the given `node.type`, like
`visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
If no dedicated `visit_*()` method is found, chooses `visit_default()`
instead.
Then yields objects of type `T` from the selected visitor.
"""
if node.type < 256:
name = token.tok_name[node.type]
else:
name = type_repr(node.type)
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
def visit_default(self, node: LN) -> Iterator[T]:
"""Default `visit_*()` implementation. Recurses to children of `node`."""
if isinstance(node, Node):
for child in node.children:
yield from self.visit(child)
@dataclass
class DebugVisitor(Visitor[T]):
tree_depth: int = 0
def visit_default(self, node: LN) -> Iterator[T]:
indent = " " * (2 * self.tree_depth)
if isinstance(node, Node):
_type = type_repr(node.type)
out(f"{indent}{_type}", fg="yellow")
self.tree_depth += 1
for child in node.children:
yield from self.visit(child)
self.tree_depth -= 1
out(f"{indent}/{_type}", fg="yellow", bold=False)
else:
_type = token.tok_name.get(node.type, str(node.type))
out(f"{indent}{_type}", fg="blue", nl=False)
if node.prefix:
# We don't have to handle prefixes for `Node` objects since
# that delegates to the first child anyway.
out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: Union[str, Leaf, Node]) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
if isinstance(code, str):
code = lib2to3_parse(code)
list(v.visit(code))
WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
STATEMENT = {
syms.if_stmt,
syms.while_stmt,
syms.for_stmt,
syms.try_stmt,
syms.except_clause,
syms.with_stmt,
syms.funcdef,
syms.classdef,
}
STANDALONE_COMMENT = 153
token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
LOGIC_OPERATORS = {"and", "or"}
COMPARATORS = {
token.LESS,
token.GREATER,
token.EQEQUAL,
token.NOTEQUAL,
token.LESSEQUAL,
token.GREATEREQUAL,
}
MATH_OPERATORS = {
token.VBAR,
token.CIRCUMFLEX,
token.AMPER,
token.LEFTSHIFT,
token.RIGHTSHIFT,
token.PLUS,
token.MINUS,
token.STAR,
token.SLASH,
token.DOUBLESLASH,
token.PERCENT,
token.AT,
token.TILDE,
token.DOUBLESTAR,
}
STARS = {token.STAR, token.DOUBLESTAR}
VARARGS_PARENTS = {
syms.arglist,
syms.argument, # double star in arglist
syms.trailer, # single argument to call
syms.typedargslist,
syms.varargslist, # lambdas
}
UNPACKING_PARENTS = {
syms.atom, # single element of a list or set literal
syms.dictsetmaker,
syms.listmaker,
syms.testlist_gexp,
syms.testlist_star_expr,
}
TEST_DESCENDANTS = {
syms.test,
syms.lambdef,
syms.or_test,
syms.and_test,
syms.not_test,
syms.comparison,
syms.star_expr,
syms.expr,
syms.xor_expr,
syms.and_expr,
syms.shift_expr,
syms.arith_expr,
syms.trailer,
syms.term,
syms.power,
}
ASSIGNMENTS = {
"=",
"+=",
"-=",
"*=",
"@=",
"/=",
"%=",
"&=",
"|=",
"^=",
"<<=",
">>=",
"**=",
"//=",
}
COMPREHENSION_PRIORITY = 20
COMMA_PRIORITY = 18
TERNARY_PRIORITY = 16
LOGIC_PRIORITY = 14
STRING_PRIORITY = 12
COMPARATOR_PRIORITY = 10
MATH_PRIORITIES = {
token.VBAR: 9,
token.CIRCUMFLEX: 8,
token.AMPER: 7,
token.LEFTSHIFT: 6,
token.RIGHTSHIFT: 6,
token.PLUS: 5,
token.MINUS: 5,
token.STAR: 4,
token.SLASH: 4,
token.DOUBLESLASH: 4,
token.PERCENT: 4,
token.AT: 4,
token.TILDE: 3,
token.DOUBLESTAR: 2,
}
DOT_PRIORITY = 1
@dataclass
class BracketTracker:
"""Keeps track of brackets on a line."""
depth: int = 0
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_depths: List[int] = Factory(list)
_lambda_argument_depths: List[int] = Factory(list)
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with bracket-related metadata. Keep track of delimiters.
All leaves receive an int `bracket_depth` field that stores how deep
within brackets a given leaf is. 0 means there are no enclosing brackets
that started on this line.
If a leaf is itself a closing bracket, it receives an `opening_bracket`
field that it forms a pair with. This is a one-directional link to
avoid reference cycles.
If a leaf is a delimiter (a token on which Black can split the line if
needed) and it's on depth 0, its `id()` is stored in the tracker's
`delimiters` field.
"""
if leaf.type == token.COMMENT:
return
self.maybe_decrement_after_for_loop_variable(leaf)
self.maybe_decrement_after_lambda_arguments(leaf)
if leaf.type in CLOSING_BRACKETS:
self.depth -= 1
opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
leaf.opening_bracket = opening_bracket
leaf.bracket_depth = self.depth
if self.depth == 0:
delim = is_split_before_delimiter(leaf, self.previous)
if delim and self.previous is not None:
self.delimiters[id(self.previous)] = delim
else:
delim = is_split_after_delimiter(leaf, self.previous)
if delim:
self.delimiters[id(leaf)] = delim
if leaf.type in OPENING_BRACKETS:
self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
self.depth += 1
self.previous = leaf
self.maybe_increment_lambda_arguments(leaf)
self.maybe_increment_for_loop_variable(leaf)
def any_open_brackets(self) -> bool:
"""Return True if there is an yet unmatched open bracket on the line."""
return bool(self.bracket_match)
def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
"""Return the highest priority of a delimiter found on the line.
Values are consistent with what `is_split_*_delimiter()` return.
Raises ValueError on no delimiters.
"""
return max(v for k, v in self.delimiters.items() if k not in exclude)
def delimiter_count_with_priority(self, priority: int = 0) -> int:
"""Return the number of delimiters with the given `priority`.
If no `priority` is passed, defaults to max priority on the line.
"""
if not self.delimiters:
return 0
priority = priority or self.max_delimiter_priority()
return sum(1 for p in self.delimiters.values() if p == priority)
def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
"""In a for loop, or comprehension, the variables are often unpacks.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `for` and `in`.
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_depths.append(self.depth)
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for_loop_variable` above for explanation."""
if (
self._for_loop_depths
and self._for_loop_depths[-1] == self.depth
and leaf.type == token.NAME
and leaf.value == "in"
):
self.depth -= 1
self._for_loop_depths.pop()
return True
return False
def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
"""In a lambda expression, there might be more than one argument.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `lambda` and `:`.
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_argument_depths.append(self.depth)
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_lambda_arguments` above for explanation."""
if (
self._lambda_argument_depths
and self._lambda_argument_depths[-1] == self.depth
and leaf.type == token.COLON
):
self.depth -= 1
self._lambda_argument_depths.pop()
return True
return False
def get_open_lsqb(self) -> Optional[Leaf]:
"""Return the most recent opening square bracket (if any)."""
return self.bracket_match.get((self.depth - 1, token.RSQB))
@dataclass
class Line:
"""Holds leaves and comments. Can be printed with `str(line)`."""
depth: int = 0
leaves: List[Leaf] = Factory(list)
comments: Dict[LeafID, List[Leaf]] = Factory(dict) # keys ordered like `leaves`
bracket_tracker: BracketTracker = Factory(BracketTracker)
inside_brackets: bool = False
should_explode: bool = False
def append(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Add a new `leaf` to the end of the line.
Unless `preformatted` is True, the `leaf` will receive a new consistent
whitespace prefix and metadata applied by :class:`BracketTracker`.
Trailing commas are maybe removed, unpacked for loop variables are
demoted from being delimiters.
Inline comments are put aside.
"""
has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
if not has_value:
return
if token.COLON == leaf.type and self.is_class_paren_empty:
del self.leaves[-2:]
if self.leaves and not preformatted:
# Note: at this point leaf.prefix should be empty except for
# imports, for which we only preserve newlines.
leaf.prefix += whitespace(
leaf, complex_subscript=self.is_complex_subscript(leaf)
)
if self.inside_brackets or not preformatted:
self.bracket_tracker.mark(leaf)
self.maybe_remove_trailing_comma(leaf)
if not self.append_comment(leaf):
self.leaves.append(leaf)
def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Like :func:`append()` but disallow invalid standalone comment structure.
Raises ValueError when any `leaf` is appended after a standalone comment
or when a standalone comment is not the first leaf on the line.
"""
if self.bracket_tracker.depth == 0:
if self.is_comment:
raise ValueError("cannot append to standalone comments")
if self.leaves and leaf.type == STANDALONE_COMMENT:
raise ValueError(
"cannot append standalone comments to a populated line"
)
self.append(leaf, preformatted=preformatted)
@property
def is_comment(self) -> bool:
"""Is this line a standalone comment?"""
return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
@property
def is_decorator(self) -> bool:
"""Is this line a decorator?"""
return bool(self) and self.leaves[0].type == token.AT
@property
def is_import(self) -> bool:
"""Is this an import line?"""
return bool(self) and is_import(self.leaves[0])
@property
def is_class(self) -> bool:
"""Is this line a class definition?"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value == "class"
)
@property
def is_stub_class(self) -> bool:
"""Is this line a class definition with a body consisting only of "..."?"""
return self.is_class and self.leaves[-3:] == [
Leaf(token.DOT, ".") for _ in range(3)
]
@property
def is_def(self) -> bool:
"""Is this a function definition? (Also returns True for async defs.)"""
try:
first_leaf = self.leaves[0]
except IndexError:
return False
try:
second_leaf: Optional[Leaf] = self.leaves[1]
except IndexError:
second_leaf = None
return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
first_leaf.type == token.ASYNC
and second_leaf is not None
and second_leaf.type == token.NAME
and second_leaf.value == "def"
)
@property
def is_class_paren_empty(self) -> bool:
"""Is this a class with no base classes but using parentheses?
Those are unnecessary and should be removed.
"""
return (
bool(self)
and len(self.leaves) == 4
and self.is_class
and self.leaves[2].type == token.LPAR
and self.leaves[2].value == "("
and self.leaves[3].type == token.RPAR
and self.leaves[3].value == ")"
)
@property
def is_triple_quoted_string(self) -> bool:
"""Is the line a triple quoted string?"""
return (
bool(self)
and self.leaves[0].type == token.STRING
and self.leaves[0].value.startswith(('"""', "'''"))
)
def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
"""If so, needs to be split before emitting."""
for leaf in self.leaves:
if leaf.type == STANDALONE_COMMENT:
if leaf.bracket_depth <= depth_limit:
return True
return False
def contains_inner_type_comments(self) -> bool:
ignored_ids = set()
try:
last_leaf = self.leaves[-1]
ignored_ids.add(id(last_leaf))
if last_leaf.type == token.COMMA:
# When trailing commas are inserted by Black for consistency, comments
# after the previous last element are not moved (they don't have to,
# rendering will still be correct). So we ignore trailing commas.
last_leaf = self.leaves[-2]
ignored_ids.add(id(last_leaf))
except IndexError:
return False
for leaf_id, comments in self.comments.items():
if leaf_id in ignored_ids:
continue
for comment in comments:
if is_type_comment(comment):
return True
return False
def contains_multiline_strings(self) -> bool:
for leaf in self.leaves:
if is_multiline_string(leaf):
return True
return False
def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
"""Remove trailing comma if there is one and it's safe."""
if not (
self.leaves
and self.leaves[-1].type == token.COMMA
and closing.type in CLOSING_BRACKETS
):
return False
if closing.type == token.RBRACE:
self.remove_trailing_comma()
return True
if closing.type == token.RSQB:
comma = self.leaves[-1]
if comma.parent and comma.parent.type == syms.listmaker:
self.remove_trailing_comma()
return True
# For parens let's check if it's safe to remove the comma.
# Imports are always safe.
if self.is_import:
self.remove_trailing_comma()
return True
# Otherwise, if the trailing one is the only one, we might mistakenly
# change a tuple into a different type by removing the comma.
depth = closing.bracket_depth + 1
commas = 0
opening = closing.opening_bracket
for _opening_index, leaf in enumerate(self.leaves):
if leaf is opening:
break
else:
return False
for leaf in self.leaves[_opening_index + 1 :]:
if leaf is closing:
break
bracket_depth = leaf.bracket_depth
if bracket_depth == depth and leaf.type == token.COMMA:
commas += 1
if leaf.parent and leaf.parent.type == syms.arglist:
commas += 1
break
if commas > 1:
self.remove_trailing_comma()
return True
return False
def append_comment(self, comment: Leaf) -> bool:
"""Add an inline or standalone comment to the line."""
if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
comment.prefix = ""
return False
if comment.type != token.COMMENT:
return False
if not self.leaves:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
self.comments.setdefault(id(self.leaves[-1]), []).append(comment)
return True
def comments_after(self, leaf: Leaf) -> List[Leaf]:
"""Generate comments that should appear directly after `leaf`."""
return self.comments.get(id(leaf), [])
def remove_trailing_comma(self) -> None:
"""Remove the trailing comma and moves the comments attached to it."""
trailing_comma = self.leaves.pop()
trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
self.comments.setdefault(id(self.leaves[-1]), []).extend(
trailing_comma_comments
)
def is_complex_subscript(self, leaf: Leaf) -> bool:
"""Return True iff `leaf` is part of a slice with non-trivial exprs."""
open_lsqb = self.bracket_tracker.get_open_lsqb()
if open_lsqb is None:
return False
subscript_start = open_lsqb.next_sibling
if isinstance(subscript_start, Node):
if subscript_start.type == syms.listmaker:
return False
if subscript_start.type == syms.subscriptlist:
subscript_start = child_towards(subscript_start, leaf)
return subscript_start is not None and any(
n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
)
def __str__(self) -> str:
"""Render the line."""
if not self:
return "\n"
indent = " " * self.depth
leaves = iter(self.leaves)
first = next(leaves)
res = f"{first.prefix}{indent}{first.value}"
for leaf in leaves:
res += str(leaf)
for comment in itertools.chain.from_iterable(self.comments.values()):
res += str(comment)
return res + "\n"
def __bool__(self) -> bool:
"""Return True if the line has leaves or comments."""
return bool(self.leaves or self.comments)
@dataclass
class EmptyLineTracker:
"""Provides a stateful method that returns the number of potential extra
empty lines needed before and after the currently processed line.
Note: this tracker works on lines that haven't been split yet. It assumes
the prefix of the first leaf consists of optional newlines. Those newlines
are consumed by `maybe_empty_lines()` and included in the computation.
"""
is_pyi: bool = False
previous_line: Optional[Line] = None
previous_after: int = 0
previous_defs: List[int] = Factory(list)
def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
"""Return the number of extra empty lines before and after the `current_line`.
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after
self.previous_line = current_line
return before, after
def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
max_allowed = 1
if current_line.depth == 0:
max_allowed = 1 if self.is_pyi else 2
if current_line.leaves:
# Consume the first leaf's extra newlines.
first_leaf = current_line.leaves[0]
before = first_leaf.prefix.count("\n")
before = min(before, max_allowed)
first_leaf.prefix = ""
else:
before = 0
depth = current_line.depth
while self.previous_defs and self.previous_defs[-1] >= depth:
self.previous_defs.pop()
if self.is_pyi:
before = 0 if depth else 1
else:
before = 1 if depth else 2
if current_line.is_decorator or current_line.is_def or current_line.is_class:
return self._maybe_empty_lines_for_class_or_def(current_line, before)
if (
self.previous_line
and self.previous_line.is_import
and not current_line.is_import
and depth == self.previous_line.depth
):
return (before or 1), 0
if (
self.previous_line
and self.previous_line.is_class
and current_line.is_triple_quoted_string
):
return before, 1
return before, 0
def _maybe_empty_lines_for_class_or_def(
self, current_line: Line, before: int
) -> Tuple[int, int]:
if not current_line.is_decorator:
self.previous_defs.append(current_line.depth)
if self.previous_line is None:
# Don't insert empty lines before the first line in the file.
return 0, 0
if self.previous_line.is_decorator:
return 0, 0
if self.previous_line.depth < current_line.depth and (
self.previous_line.is_class or self.previous_line.is_def
):
return 0, 0
if (
self.previous_line.is_comment
and self.previous_line.depth == current_line.depth
and before == 0
):
return 0, 0
if self.is_pyi:
if self.previous_line.depth > current_line.depth:
newlines = 1
elif current_line.is_class or self.previous_line.is_class:
if current_line.is_stub_class and self.previous_line.is_stub_class:
# No blank line between classes with an empty body
newlines = 0
else:
newlines = 1
elif current_line.is_def and not self.previous_line.is_def:
# Blank line between a block of functions and a block of non-functions
newlines = 1
else:
newlines = 0
else:
newlines = 2
if current_line.depth and newlines:
newlines -= 1
return newlines, 0
@dataclass
class LineGenerator(Visitor[Line]):
"""Generates reformatted Line objects. Empty lines are not emitted.
Note: destroys the tree it's visiting by mutating prefixes of its leaves
in ways that will no longer stringify to valid Python code on the tree.
"""
is_pyi: bool = False
normalize_strings: bool = True
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense.
If the line is too long, split it first and then generate.
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
self.current_line.depth += indent
return # Line is empty, don't emit. Creating a new one unnecessary.
complete_line = self.current_line
self.current_line = Line(depth=complete_line.depth + indent)
yield complete_line
def visit_default(self, node: LN) -> Iterator[Line]:
"""Default `visit_*()` implementation. Recurses to children of `node`."""
if isinstance(node, Leaf):
any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
for comment in generate_comments(node):
if any_open_brackets:
# any comment within brackets is subject to splitting
self.current_line.append(comment)
elif comment.type == token.COMMENT:
# regular trailing comment
self.current_line.append(comment)
yield from self.line()
else:
# regular standalone comment
yield from self.line()
self.current_line.append(comment)
yield from self.line()
normalize_prefix(node, inside_brackets=any_open_brackets)
if self.normalize_strings and node.type == token.STRING:
normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
normalize_string_quotes(node)
if node.type == token.NUMBER:
normalize_numeric_literal(node)
if node.type not in WHITESPACE:
self.current_line.append(node)
yield from super().visit_default(node)
def visit_INDENT(self, node: Node) -> Iterator[Line]:
"""Increase indentation level, maybe yield a line."""
# In blib2to3 INDENT never holds comments.
yield from self.line(+1)
yield from self.visit_default(node)
def visit_DEDENT(self, node: Node) -> Iterator[Line]:
"""Decrease indentation level, maybe yield a line."""
# The current line might still wait for trailing comments. At DEDENT time
# there won't be any (they would be prefixes on the preceding NEWLINE).
# Emit the line then.
yield from self.line()
# While DEDENT has no value, its prefix may contain standalone comments
# that belong to the current indentation level. Get 'em.
yield from self.visit_default(node)
# Finally, emit the dedent.
yield from self.line(-1)
def visit_stmt(
self, node: Node, keywords: Set[str], parens: Set[str]
) -> Iterator[Line]:
"""Visit a statement.
This implementation is shared for `if`, `while`, `for`, `try`, `except`,
`def`, `with`, `class`, `assert` and assignments.
The relevant Python language `keywords` for a given statement will be
NAME leaves within it. This methods puts those on a separate line.
`parens` holds a set of string leaf values immediately after which
invisible parens should be put.
"""
normalize_invisible_parens(node, parens_after=parens)
for child in node.children:
if child.type == token.NAME and child.value in keywords: # type: ignore
yield from self.line()
yield from self.visit(child)
def visit_suite(self, node: Node) -> Iterator[Line]:
"""Visit a suite."""
if self.is_pyi and is_stub_suite(node):
yield from self.visit(node.children[2])
else:
yield from self.visit_default(node)
def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
"""Visit a statement without nested statements."""
is_suite_like = node.parent and node.parent.type in STATEMENT
if is_suite_like:
if self.is_pyi and is_stub_body(node):
yield from self.visit_default(node)
else:
yield from self.line(+1)
yield from self.visit_default(node)
yield from self.line(-1)
else:
if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
yield from self.line()
yield from self.visit_default(node)
def visit_async_stmt(self, node: Node) -> Iterator[Line]:
"""Visit `async def`, `async for`, `async with`."""
yield from self.line()
children = iter(node.children)
for child in children:
yield from self.visit(child)
if child.type == token.ASYNC:
break
internal_stmt = next(children)
for child in internal_stmt.children:
yield from self.visit(child)
def visit_decorators(self, node: Node) -> Iterator[Line]:
"""Visit decorators."""
for child in node.children:
yield from self.line()
yield from self.visit(child)
def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
"""Remove a semicolon and put the other statement on a separate line."""
yield from self.line()
def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
"""End of file. Process outstanding comments and end with a newline."""
yield from self.visit_default(leaf)
yield from self.line()
def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
if not self.current_line.bracket_tracker.any_open_brackets():
yield from self.line()
yield from self.visit_default(leaf)
def __attrs_post_init__(self) -> None:
"""You are in a twisty little maze of passages."""
v = self.visit_stmt
Ø: Set[str] = set()
self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
self.visit_if_stmt = partial(
v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
)
self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
self.visit_try_stmt = partial(
v, keywords={"try", "except", "else", "finally"}, parens=Ø
)
self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
self.visit_async_funcdef = self.visit_async_stmt
self.visit_decorated = self.visit_decorators
IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
OPENING_BRACKETS = set(BRACKET.keys())
CLOSING_BRACKETS = set(BRACKET.values())
BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
"""Return whitespace prefix if needed for the given `leaf`.
`complex_subscript` signals whether the given leaf is part of a subscription
which has non-trivial arguments, like arithmetic expressions or function calls.
"""
NO = ""
SPACE = " "
DOUBLESPACE = " "
t = leaf.type
p = leaf.parent
v = leaf.value
if t in ALWAYS_NO_SPACE:
return NO
if t == token.COMMENT:
return DOUBLESPACE
assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
if t == token.COLON and p.type not in {
syms.subscript,
syms.subscriptlist,
syms.sliceop,
}:
return NO
prev = leaf.prev_sibling
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type in OPENING_BRACKETS:
return NO
if t == token.COLON:
if prevp.type == token.COLON:
return NO
elif prevp.type != token.COMMA and not complex_subscript:
return NO
return SPACE
if prevp.type == token.EQUAL:
if prevp.parent:
if prevp.parent.type in {
syms.arglist,
syms.argument,
syms.parameters,
syms.varargslist,
}:
return NO
elif prevp.parent.type == syms.typedargslist:
# A bit hacky: if the equal sign has whitespace, it means we
# previously found it's a typed argument. So, we're using
# that, too.
return prevp.prefix
elif prevp.type in STARS:
if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
return NO
elif prevp.type == token.COLON:
if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
return SPACE if complex_subscript else NO
elif (
prevp.parent
and prevp.parent.type == syms.factor
and prevp.type in MATH_OPERATORS
):
return NO
elif (
prevp.type == token.RIGHTSHIFT
and prevp.parent
and prevp.parent.type == syms.shift_expr
and prevp.prev_sibling
and prevp.prev_sibling.type == token.NAME
and prevp.prev_sibling.value == "print" # type: ignore
):
# Python 2 print chevron
return NO
elif prev.type in OPENING_BRACKETS:
return NO
if p.type in {syms.parameters, syms.arglist}:
# untyped function signatures or calls
if not prev or prev.type != token.COMMA:
return NO
elif p.type == syms.varargslist:
# lambdas
if prev and prev.type != token.COMMA:
return NO
elif p.type == syms.typedargslist:
# typed function signatures
if not prev:
return NO
if t == token.EQUAL:
if prev.type != syms.tname:
return NO
elif prev.type == token.EQUAL:
# A bit hacky: if the equal sign has whitespace, it means we
# previously found it's a typed argument. So, we're using that, too.
return prev.prefix
elif prev.type != token.COMMA:
return NO
elif p.type == syms.tname:
# type names
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type != token.COMMA:
return NO
elif p.type == syms.trailer:
# attributes and calls
if t == token.LPAR or t == token.RPAR:
return NO
if not prev:
if t == token.DOT:
prevp = preceding_leaf(p)
if not prevp or prevp.type != token.NUMBER:
return NO
elif t == token.LSQB:
return NO
elif prev.type != token.COMMA:
return NO
elif p.type == syms.argument:
# single argument
if t == token.EQUAL:
return NO
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type == token.LPAR:
return NO
elif prev.type in {token.EQUAL} | STARS:
return NO
elif p.type == syms.decorator:
# decorators
return NO
elif p.type == syms.dotted_name:
if prev:
return NO
prevp = preceding_leaf(p)
if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
return NO
elif p.type == syms.classdef:
if t == token.LPAR:
return NO
if prev and prev.type == token.LPAR:
return NO
elif p.type in {syms.subscript, syms.sliceop}:
# indexing
if not prev:
assert p.parent is not None, "subscripts are always parented"
if p.parent.type == syms.subscriptlist:
return SPACE
return NO
elif not complex_subscript:
return NO
elif p.type == syms.atom:
if prev and t == token.DOT:
# dots, but not the first one.
return NO
elif p.type == syms.dictsetmaker:
# dict unpacking
if prev and prev.type == token.DOUBLESTAR:
return NO
elif p.type in {syms.factor, syms.star_expr}:
# unary ops
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type in OPENING_BRACKETS:
return NO
prevp_parent = prevp.parent
assert prevp_parent is not None
if prevp.type == token.COLON and prevp_parent.type in {
syms.subscript,
syms.sliceop,
}:
return NO
elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
return NO
elif t in {token.NAME, token.NUMBER, token.STRING}:
return NO
elif p.type == syms.import_from:
if t == token.DOT:
if prev and prev.type == token.DOT:
return NO
elif t == token.NAME:
if v == "import":
return SPACE
if prev and prev.type == token.DOT:
return NO
elif p.type == syms.sliceop:
return NO
return SPACE
def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
"""Return the first leaf that precedes `node`, if any."""
while node:
res = node.prev_sibling
if res:
if isinstance(res, Leaf):
return res
try:
return list(res.leaves())[-1]
except IndexError:
return None
node = node.parent
return None
def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
"""Return the child of `ancestor` that contains `descendant`."""
node: Optional[LN] = descendant
while node and node.parent != ancestor:
node = node.parent
return node
def container_of(leaf: Leaf) -> LN:
"""Return `leaf` or one of its ancestors that is the topmost container of it.
By "container" we mean a node where `leaf` is the very first child.
"""
same_prefix = leaf.prefix
container: LN = leaf
while container:
parent = container.parent
if parent is None:
break
if parent.children[0].prefix != same_prefix:
break
if parent.type == syms.file_input:
break
if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
break
container = parent
return container
def is_split_after_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> int:
"""Return the priority of the `leaf` delimiter, given a line break after it.
The delimiter priorities returned here are from those delimiters that would
cause a line break after themselves.
Higher numbers are higher priority.
"""
if leaf.type == token.COMMA:
return COMMA_PRIORITY
return 0
def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> int:
"""Return the priority of the `leaf` delimiter, given a line break before it.
The delimiter priorities returned here are from those delimiters that would
cause a line break before themselves.
Higher numbers are higher priority.
"""
if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
# * and ** might also be MATH_OPERATORS but in this case they are not.
# Don't treat them as a delimiter.
return 0
if (
leaf.type == token.DOT
and leaf.parent
and leaf.parent.type not in {syms.import_from, syms.dotted_name}
and (previous is None or previous.type in CLOSING_BRACKETS)
):
return DOT_PRIORITY
if (
leaf.type in MATH_OPERATORS
and leaf.parent
and leaf.parent.type not in {syms.factor, syms.star_expr}
):
return MATH_PRIORITIES[leaf.type]
if leaf.type in COMPARATORS:
return COMPARATOR_PRIORITY
if (
leaf.type == token.STRING
and previous is not None
and previous.type == token.STRING
):
return STRING_PRIORITY
if leaf.type not in {token.NAME, token.ASYNC}:
return 0
if (
leaf.value == "for"
and leaf.parent
and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
or leaf.type == token.ASYNC
):
if (
not isinstance(leaf.prev_sibling, Leaf)
or leaf.prev_sibling.value != "async"
):
return COMPREHENSION_PRIORITY
if (
leaf.value == "if"
and leaf.parent
and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
):
return COMPREHENSION_PRIORITY
if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
return TERNARY_PRIORITY
if leaf.value == "is":
return COMPARATOR_PRIORITY
if (
leaf.value == "in"
and leaf.parent
and leaf.parent.type in {syms.comp_op, syms.comparison}
and not (
previous is not None
and previous.type == token.NAME
and previous.value == "not"
)
):
return COMPARATOR_PRIORITY
if (
leaf.value == "not"
and leaf.parent
and leaf.parent.type == syms.comp_op
and not (
previous is not None
and previous.type == token.NAME
and previous.value == "is"
)
):
return COMPARATOR_PRIORITY
if leaf.value in LOGIC_OPERATORS and leaf.parent:
return LOGIC_PRIORITY
return 0
FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""Clean the prefix of the `leaf` and generate comments from it, if any.
Comments in lib2to3 are shoved into the whitespace prefix. This happens
in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
move because it does away with modifying the grammar to include all the
possible places in which comments can be placed.
The sad consequence for us though is that comments don't "belong" anywhere.
This is why this function generates simple parentless Leaf objects for
comments. We simply don't know what the correct parent should be.
No matter though, we can live without this. We really only need to
differentiate between inline and standalone comments. The latter don't
share the line with any code.
Inline comments are emitted as regular token.COMMENT leaves. Standalone
are emitted with a fake STANDALONE_COMMENT token identifier.
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
@dataclass
class ProtoComment:
"""Describes a piece of syntax that is a comment.
It's not a :class:`blib2to3.pytree.Leaf` so that:
* it can be cached (`Leaf` objects should not be reused more than once as
they store their lineno, column, prefix, and parent information);
* `newlines` and `consumed` fields are kept separate from the `value`. This
simplifies handling of special marker comments like ``# fmt: off/on``.
"""
type: int # token.COMMENT or STANDALONE_COMMENT
value: str # content of the comment
newlines: int # how many newlines before the comment
consumed: int # how many characters of the original leaf's prefix did we consume
@lru_cache(maxsize=4096)
def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
"""Return a list of :class:`ProtoComment` objects parsed from the given `prefix`."""
result: List[ProtoComment] = []
if not prefix or "#" not in prefix:
return result
consumed = 0
nlines = 0
for index, line in enumerate(prefix.split("\n")):
consumed += len(line) + 1 # adding the length of the split '\n'
line = line.lstrip()
if not line:
nlines += 1
if not line.startswith("#"):
continue
if index == 0 and not is_endmarker:
comment_type = token.COMMENT # simple trailing comment
else:
comment_type = STANDALONE_COMMENT
comment = make_comment(line)
result.append(
ProtoComment(
type=comment_type, value=comment, newlines=nlines, consumed=consumed
)
)
nlines = 0
return result
def make_comment(content: str) -> str:
"""Return a consistently formatted comment from the given `content` string.
All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
space between the hash sign and the content.
If `content` didn't start with a hash sign, one is provided.
"""
content = content.rstrip()
if not content:
return "#"
if content[0] == "#":
content = content[1:]
if content and content[0] not in " !:#'%":
content = " " + content
return "#" + content
def split_line(
line: Line,
line_length: int,
inner: bool = False,
supports_trailing_commas: bool = False,
) -> Iterator[Line]:
"""Split a `line` into potentially many lines.
They should fit in the allotted `line_length` but might not be able to.
`inner` signifies that there were a pair of brackets somewhere around the
current `line`, possibly transitively. This means we can fallback to splitting
by delimiters if the LHS/RHS don't yield any results.
If `supports_trailing_commas` is True, splitting may use the TRAILING_COMMA feature.
"""
if line.is_comment:
yield line
return
line_str = str(line).strip("\n")
if (
not line.contains_inner_type_comments()
and not line.should_explode
and is_line_short_enough(line, line_length=line_length, line_str=line_str)
):
yield line
return
split_funcs: List[SplitFunc]
if line.is_def:
split_funcs = [left_hand_split]
else:
def rhs(line: Line, supports_trailing_commas: bool = False) -> Iterator[Line]:
for omit in generate_trailers_to_omit(line, line_length):
lines = list(
right_hand_split(
line, line_length, supports_trailing_commas, omit=omit
)
)
if is_line_short_enough(lines[0], line_length=line_length):
yield from lines
return
# All splits failed, best effort split with no omits.
# This mostly happens to multiline strings that are by definition
# reported as not fitting a single line.
yield from right_hand_split(line, supports_trailing_commas)
if line.inside_brackets:
split_funcs = [delimiter_split, standalone_comment_split, rhs]
else:
split_funcs = [rhs]
for split_func in split_funcs:
# We are accumulating lines in `result` because we might want to abort
# mission and return the original line in the end, or attempt a different
# split altogether.
result: List[Line] = []
try:
for l in split_func(line, supports_trailing_commas):
if str(l).strip("\n") == line_str:
raise CannotSplit("Split function returned an unchanged result")
result.extend(
split_line(
l,
line_length=line_length,
inner=True,
supports_trailing_commas=supports_trailing_commas,
)
)
except CannotSplit:
continue
else:
yield from result
break
else:
yield line
def left_hand_split(
line: Line, supports_trailing_commas: bool = False
) -> Iterator[Line]:
"""Split line into many lines, starting with the first matching bracket pair.
Note: this usually looks weird, only use this for function definitions.
Prefer RHS otherwise. This is why this function is not symmetrical with
:func:`right_hand_split` which also handles optional parentheses.
"""
tail_leaves: List[Leaf] = []
body_leaves: List[Leaf] = []
head_leaves: List[Leaf] = []
current_leaves = head_leaves
matching_bracket = None
for leaf in line.leaves:
if (
current_leaves is body_leaves
and leaf.type in CLOSING_BRACKETS
and leaf.opening_bracket is matching_bracket
):
current_leaves = tail_leaves if body_leaves else head_leaves
current_leaves.append(leaf)
if current_leaves is head_leaves:
if leaf.type in OPENING_BRACKETS:
matching_bracket = leaf
current_leaves = body_leaves
if not matching_bracket:
raise CannotSplit("No brackets found")
head = bracket_split_build_line(head_leaves, line, matching_bracket)
body = bracket_split_build_line(body_leaves, line, matching_bracket, is_body=True)
tail = bracket_split_build_line(tail_leaves, line, matching_bracket)
bracket_split_succeeded_or_raise(head, body, tail)
for result in (head, body, tail):
if result:
yield result
def right_hand_split(
line: Line,
line_length: int,
supports_trailing_commas: bool = False,
omit: Collection[LeafID] = (),
) -> Iterator[Line]:
"""Split line into many lines, starting with the last matching bracket pair.
If the split was by optional parentheses, attempt splitting without them, too.
`omit` is a collection of closing bracket IDs that shouldn't be considered for
this split.
Note: running this function modifies `bracket_depth` on the leaves of `line`.
"""
tail_leaves: List[Leaf] = []
body_leaves: List[Leaf] = []
head_leaves: List[Leaf] = []
current_leaves = tail_leaves
opening_bracket = None
closing_bracket = None
for leaf in reversed(line.leaves):
if current_leaves is body_leaves:
if leaf is opening_bracket:
current_leaves = head_leaves if body_leaves else tail_leaves
current_leaves.append(leaf)
if current_leaves is tail_leaves:
if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
opening_bracket = leaf.opening_bracket
closing_bracket = leaf
current_leaves = body_leaves
if not (opening_bracket and closing_bracket and head_leaves):
# If there is no opening or closing_bracket that means the split failed and
# all content is in the tail. Otherwise, if `head_leaves` are empty, it means
# the matching `opening_bracket` wasn't available on `line` anymore.
raise CannotSplit("No brackets found")
tail_leaves.reverse()
body_leaves.reverse()
head_leaves.reverse()
head = bracket_split_build_line(head_leaves, line, opening_bracket)
body = bracket_split_build_line(body_leaves, line, opening_bracket, is_body=True)
tail = bracket_split_build_line(tail_leaves, line, opening_bracket)
bracket_split_succeeded_or_raise(head, body, tail)
if (
# the body shouldn't be exploded
not body.should_explode
# the opening bracket is an optional paren
and opening_bracket.type == token.LPAR
and not opening_bracket.value
# the closing bracket is an optional paren
and closing_bracket.type == token.RPAR
and not closing_bracket.value
# it's not an import (optional parens are the only thing we can split on
# in this case; attempting a split without them is a waste of time)
and not line.is_import
# there are no standalone comments in the body
and not body.contains_standalone_comments(0)
# and we can actually remove the parens
and can_omit_invisible_parens(body, line_length)
):
omit = {id(closing_bracket), *omit}
try:
yield from right_hand_split(
line,
line_length,
supports_trailing_commas=supports_trailing_commas,
omit=omit,
)
return
except CannotSplit:
if not (
can_be_split(body)
or is_line_short_enough(body, line_length=line_length)
):
raise CannotSplit(
"Splitting failed, body is still too long and can't be split."
)
elif head.contains_multiline_strings() or tail.contains_multiline_strings():
raise CannotSplit(
"The current optional pair of parentheses is bound to fail to "
"satisfy the splitting algorithm because the head or the tail "
"contains multiline strings which by definition never fit one "
"line."
)
ensure_visible(opening_bracket)
ensure_visible(closing_bracket)
for result in (head, body, tail):
if result:
yield result
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
"""Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
Do nothing otherwise.
A left- or right-hand split is based on a pair of brackets. Content before
(and including) the opening bracket is left on one line, content inside the
brackets is put on a separate line, and finally content starting with and
following the closing bracket is put on a separate line.
Those are called `head`, `body`, and `tail`, respectively. If the split
produced the same line (all content in `head`) or ended up with an empty `body`
and the `tail` is just the closing bracket, then it's considered failed.
"""
tail_len = len(str(tail).strip())
if not body:
if tail_len == 0:
raise CannotSplit("Splitting brackets produced the same line")
elif tail_len < 3:
raise CannotSplit(
f"Splitting brackets on an empty body to save "
f"{tail_len} characters is not worth it"
)
def bracket_split_build_line(
leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
) -> Line:
"""Return a new line with given `leaves` and respective comments from `original`.
If `is_body` is True, the result line is one-indented inside brackets and as such
has its first leaf's prefix normalized and a trailing comma added when expected.
"""
result = Line(depth=original.depth)
if is_body:
result.inside_brackets = True
result.depth += 1
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma when expected.
if original.is_import:
if leaves[-1].type != token.COMMA:
leaves.append(Leaf(token.COMMA, ","))
# Populate the line
for leaf in leaves:
result.append(leaf, preformatted=True)
for comment_after in original.comments_after(leaf):
result.append(comment_after, preformatted=True)
if is_body:
result.should_explode = should_explode(result, opening_bracket)
return result
def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
"""Normalize prefix of the first leaf in every line returned by `split_func`.
This is a decorator over relevant split functions.
"""
@wraps(split_func)
def split_wrapper(
line: Line, supports_trailing_commas: bool = False
) -> Iterator[Line]:
for l in split_func(line, supports_trailing_commas):
normalize_prefix(l.leaves[0], inside_brackets=True)
yield l
return split_wrapper
@dont_increase_indentation
def delimiter_split(
line: Line, supports_trailing_commas: bool = False
) -> Iterator[Line]:
"""Split according to delimiters of the highest priority.
If `supports_trailing_commas` is True, the split will add trailing commas
also in function signatures that contain `*` and `**`.
"""
try:
last_leaf = line.leaves[-1]
except IndexError:
raise CannotSplit("Line empty")
bt = line.bracket_tracker
try:
delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
except ValueError:
raise CannotSplit("No delimiters found")
if delimiter_priority == DOT_PRIORITY:
if bt.delimiter_count_with_priority(delimiter_priority) == 1:
raise CannotSplit("Splitting a single attribute from its owner looks wrong")
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
lowest_depth = sys.maxsize
trailing_comma_safe = True
def append_to_line(leaf: Leaf) -> Iterator[Line]:
"""Append `leaf` to current line or to new line if appending impossible."""
nonlocal current_line
try:
current_line.append_safe(leaf, preformatted=True)
except ValueError:
yield current_line
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
current_line.append(leaf)
for leaf in line.leaves:
yield from append_to_line(leaf)
for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)
lowest_depth = min(lowest_depth, leaf.bracket_depth)
if leaf.bracket_depth == lowest_depth and is_vararg(
leaf, within=VARARGS_PARENTS
):
trailing_comma_safe = trailing_comma_safe and supports_trailing_commas
leaf_priority = bt.delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
yield current_line
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
if current_line:
if (
trailing_comma_safe
and delimiter_priority == COMMA_PRIORITY
and current_line.leaves[-1].type != token.COMMA
and current_line.leaves[-1].type != STANDALONE_COMMENT
):
current_line.append(Leaf(token.COMMA, ","))
yield current_line
@dont_increase_indentation
def standalone_comment_split(
line: Line, supports_trailing_commas: bool = False
) -> Iterator[Line]:
"""Split standalone comments from the rest of the line."""
if not line.contains_standalone_comments(0):
raise CannotSplit("Line does not have any standalone comments")
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
def append_to_line(leaf: Leaf) -> Iterator[Line]:
"""Append `leaf` to current line or to new line if appending impossible."""
nonlocal current_line
try:
current_line.append_safe(leaf, preformatted=True)
except ValueError:
yield current_line
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
current_line.append(leaf)
for leaf in line.leaves:
yield from append_to_line(leaf)
for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)
if current_line:
yield current_line
def is_import(leaf: Leaf) -> bool:
"""Return True if the given leaf starts an import statement."""
p = leaf.parent
t = leaf.type
v = leaf.value
return bool(
t == token.NAME
and (
(v == "import" and p and p.type == syms.import_name)
or (v == "from" and p and p.type == syms.import_from)
)
)
def is_type_comment(leaf: Leaf) -> bool:
"""Return True if the given leaf is a special comment.
Only returns true for type comments for now."""
t = leaf.type
v = leaf.value
return t in {token.COMMENT, t == STANDALONE_COMMENT} and v.startswith("# type:")
def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
"""Leave existing extra newlines if not `inside_brackets`. Remove everything
else.
Note: don't use backslashes for formatting or you'll lose your voting rights.
"""
if not inside_brackets:
spl = leaf.prefix.split("#")
if "\\" not in spl[0]:
nl_count = spl[-1].count("\n")
if len(spl) > 1:
nl_count -= 1
leaf.prefix = "\n" * nl_count
return
leaf.prefix = ""
def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
"""Make all string prefixes lowercase.
If remove_u_prefix is given, also removes any u prefix from the string.
Note: Mutates its argument.
"""
match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
assert match is not None, f"failed to match string {leaf.value!r}"
orig_prefix = match.group(1)
new_prefix = orig_prefix.lower()
if remove_u_prefix:
new_prefix = new_prefix.replace("u", "")
leaf.value = f"{new_prefix}{match.group(2)}"
def normalize_string_quotes(leaf: Leaf) -> None:
"""Prefer double quotes but only if it doesn't cause more escaping.
Adds or removes backslashes as appropriate. Doesn't parse and fix
strings nested in f-strings (yet).
Note: Mutates its argument.
"""
value = leaf.value.lstrip("furbFURB")
if value[:3] == '"""':
return
elif value[:3] == "'''":
orig_quote = "'''"
new_quote = '"""'
elif value[0] == '"':
orig_quote = '"'
new_quote = "'"
else:
orig_quote = "'"
new_quote = '"'
first_quote_pos = leaf.value.find(orig_quote)
if first_quote_pos == -1:
return # There's an internal error
prefix = leaf.value[:first_quote_pos]
unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
if "r" in prefix.casefold():
if unescaped_new_quote.search(body):
# There's at least one unescaped new_quote in this raw string
# so converting is impossible
return
# Do not introduce or remove backslashes in raw strings
new_body = body
else:
# remove unnecessary escapes
new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
if body != new_body:
# Consider the string without unnecessary escapes as the original
body = new_body
leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
if "f" in prefix.casefold():
matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
for m in matches:
if "\\" in str(m):
# Do not introduce backslashes in interpolated expressions
return
if new_quote == '"""' and new_body[-1:] == '"':
# edge case:
new_body = new_body[:-1] + '\\"'
orig_escape_count = body.count("\\")
new_escape_count = new_body.count("\\")
if new_escape_count > orig_escape_count:
return # Do not introduce more escaping
if new_escape_count == orig_escape_count and orig_quote == '"':
return # Prefer double quotes
leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
def normalize_numeric_literal(leaf: Leaf) -> None:
"""Normalizes numeric (float, int, and complex) literals.
All letters used in the representation are normalized to lowercase (except
in Python 2 long literals).
"""
text = leaf.value.lower()
if text.startswith(("0o", "0b")):
# Leave octal and binary literals alone.
pass
elif text.startswith("0x"):
# Change hex literals to upper case.
before, after = text[:2], text[2:]
text = f"{before}{after.upper()}"
elif "e" in text:
before, after = text.split("e")
sign = ""
if after.startswith("-"):
after = after[1:]
sign = "-"
elif after.startswith("+"):
after = after[1:]
before = format_float_or_int_string(before)
text = f"{before}e{sign}{after}"
elif text.endswith(("j", "l")):
number = text[:-1]
suffix = text[-1]
# Capitalize in "2L" because "l" looks too similar to "1".
if suffix == "l":
suffix = "L"
text = f"{format_float_or_int_string(number)}{suffix}"
else:
text = format_float_or_int_string(text)
leaf.value = text
def format_float_or_int_string(text: str) -> str:
"""Formats a float string like "1.0"."""
if "." not in text:
return text
before, after = text.split(".")
return f"{before or 0}.{after or 0}"
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
"""Make existing optional parentheses invisible or create new ones.
`parens_after` is a set of string leaf values immeditely after which parens
should be put.
Standardizes on visible parentheses for single-element tuples, and keeps
existing visible parentheses for other tuples and generator expressions.
"""
for pc in list_comments(node.prefix, is_endmarker=False):
if pc.value in FMT_OFF:
# This `node` has a prefix with `# fmt: off`, don't mess with parens.
return
check_lpar = False
for index, child in enumerate(list(node.children)):
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child):
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
elif is_one_tuple(child):
# wrap child in visible parentheses
lpar = Leaf(token.LPAR, "(")
rpar = Leaf(token.RPAR, ")")
child.remove()
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
elif node.type == syms.import_from:
# "import from" nodes store parentheses directly as part of
# the statement
if child.type == token.LPAR:
# make parentheses invisible
child.value = "" # type: ignore
node.children[-1].value = "" # type: ignore
elif child.type != token.STAR:
# insert invisible parentheses
node.insert_child(index, Leaf(token.LPAR, ""))
node.append_child(Leaf(token.RPAR, ""))
break
elif not (isinstance(child, Leaf) and is_multiline_string(child)):
# wrap child in invisible parentheses
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
check_lpar = isinstance(child, Leaf) and child.value in parens_after
def normalize_fmt_off(node: Node) -> None:
"""Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
try_again = True
while try_again:
try_again = convert_one_fmt_off_pair(node)
def convert_one_fmt_off_pair(node: Node) -> bool:
"""Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
Returns True if a pair was converted.
"""
for leaf in node.leaves():
previous_consumed = 0
for comment in list_comments(leaf.prefix, is_endmarker=False):
if comment.value in FMT_OFF:
# We only want standalone comments. If there's no previous leaf or
# the previous leaf is indentation, it's a standalone comment in
# disguise.
if comment.type != STANDALONE_COMMENT:
prev = preceding_leaf(leaf)
if prev and prev.type not in WHITESPACE:
continue
ignored_nodes = list(generate_ignored_nodes(leaf))
if not ignored_nodes:
continue
first = ignored_nodes[0] # Can be a container node with the `leaf`.
parent = first.parent
prefix = first.prefix
first.prefix = prefix[comment.consumed :]
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
if hidden_value.endswith("\n"):
# That happens when one of the `ignored_nodes` ended with a NEWLINE
# leaf (possibly followed by a DEDENT).
hidden_value = hidden_value[:-1]
first_idx = None
for ignored in ignored_nodes:
index = ignored.remove()
if first_idx is None:
first_idx = index
assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
parent.insert_child(
first_idx,
Leaf(
STANDALONE_COMMENT,
hidden_value,
prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
),
)
return True
previous_consumed = comment.consumed
return False
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.type != token.ENDMARKER:
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FMT_ON:
return
yield container
container = container.next_sibling
def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
"""If it's safe, make the parens in the atom `node` invisible, recursively.
Returns whether the node should itself be wrapped in invisible parentheses.
"""
if (
node.type != syms.atom
or is_empty_tuple(node)
or is_one_tuple(node)
or is_yield(node)
or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
):
return False
first = node.children[0]
last = node.children[-1]
if first.type == token.LPAR and last.type == token.RPAR:
# make parentheses invisible
first.value = "" # type: ignore
last.value = "" # type: ignore
if len(node.children) > 1:
maybe_make_parens_invisible_in_atom(node.children[1])
return False
return True
def is_empty_tuple(node: LN) -> bool:
"""Return True if `node` holds an empty tuple."""
return (
node.type == syms.atom
and len(node.children) == 2
and node.children[0].type == token.LPAR
and node.children[1].type == token.RPAR
)
def is_one_tuple(node: LN) -> bool:
"""Return True if `node` holds a tuple with one element, with or without parens."""
if node.type == syms.atom:
if len(node.children) != 3:
return False
lpar, gexp, rpar = node.children
if not (
lpar.type == token.LPAR
and gexp.type == syms.testlist_gexp
and rpar.type == token.RPAR
):
return False
return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
return (
node.type in IMPLICIT_TUPLE
and len(node.children) == 2
and node.children[1].type == token.COMMA
)
def is_yield(node: LN) -> bool:
"""Return True if `node` holds a `yield` or `yield from` expression."""
if node.type == syms.yield_expr:
return True
if node.type == token.NAME and node.value == "yield": # type: ignore
return True
if node.type != syms.atom:
return False
if len(node.children) != 3:
return False
lpar, expr, rpar = node.children
if lpar.type == token.LPAR and rpar.type == token.RPAR:
return is_yield(expr)
return False
def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
"""Return True if `leaf` is a star or double star in a vararg or kwarg.
If `within` includes VARARGS_PARENTS, this applies to function signatures.
If `within` includes UNPACKING_PARENTS, it applies to right hand-side
extended iterable unpacking (PEP 3132) and additional unpacking
generalizations (PEP 448).
"""
if leaf.type not in STARS or not leaf.parent:
return False
p = leaf.parent
if p.type == syms.star_expr:
# Star expressions are also used as assignment targets in extended
# iterable unpacking (PEP 3132). See what its parent is instead.
if not p.parent:
return False
p = p.parent
return p.type in within
def is_multiline_string(leaf: Leaf) -> bool:
"""Return True if `leaf` is a multiline string that actually spans many lines."""
value = leaf.value.lstrip("furbFURB")
return value[:3] in {'"""', "'''"} and "\n" in value
def is_stub_suite(node: Node) -> bool:
"""Return True if `node` is a suite with a stub body."""
if (
len(node.children) != 4
or node.children[0].type != token.NEWLINE
or node.children[1].type != token.INDENT
or node.children[3].type != token.DEDENT
):
return False
return is_stub_body(node.children[2])
def is_stub_body(node: LN) -> bool:
"""Return True if `node` is a simple statement containing an ellipsis."""
if not isinstance(node, Node) or node.type != syms.simple_stmt:
return False
if len(node.children) != 2:
return False
child = node.children[0]
return (
child.type == syms.atom
and len(child.children) == 3
and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
)
def max_delimiter_priority_in_atom(node: LN) -> int:
"""Return maximum delimiter priority inside `node`.
This is specific to atoms with contents contained in a pair of parentheses.
If `node` isn't an atom or there are no enclosing parentheses, returns 0.
"""
if node.type != syms.atom:
return 0
first = node.children[0]
last = node.children[-1]
if not (first.type == token.LPAR and last.type == token.RPAR):
return 0
bt = BracketTracker()
for c in node.children[1:-1]:
if isinstance(c, Leaf):
bt.mark(c)
else:
for leaf in c.leaves():
bt.mark(leaf)
try:
return bt.max_delimiter_priority()
except ValueError:
return 0
def ensure_visible(leaf: Leaf) -> None:
"""Make sure parentheses are visible.
They could be invisible as part of some statements (see
:func:`normalize_invible_parens` and :func:`visit_import_from`).
"""
if leaf.type == token.LPAR:
leaf.value = "("
elif leaf.type == token.RPAR:
leaf.value = ")"
def should_explode(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` immediately be split with `delimiter_split()` after RHS?"""
if not (
opening_bracket.parent
and opening_bracket.parent.type in {syms.atom, syms.import_from}
and opening_bracket.value in "[{("
):
return False
try:
last_leaf = line.leaves[-1]
exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
except (IndexError, ValueError):
return False
return max_priority == COMMA_PRIORITY
def get_features_used(node: Node) -> Set[Feature]:
"""Return a set of (relatively) new Python features used in this file.
Currently looking for:
- f-strings;
- underscores in numeric literals; and
- trailing commas after * or ** in function signatures and calls.
"""
features: Set[Feature] = set()
for n in node.pre_order():
if n.type == token.STRING:
value_head = n.value[:2] # type: ignore
if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
features.add(Feature.F_STRINGS)
elif n.type == token.NUMBER:
if "_" in n.value: # type: ignore
features.add(Feature.NUMERIC_UNDERSCORES)
elif (
n.type in {syms.typedargslist, syms.arglist}
and n.children
and n.children[-1].type == token.COMMA
):
for ch in n.children:
if ch.type in STARS:
features.add(Feature.TRAILING_COMMA)
if ch.type == syms.argument:
for argch in ch.children:
if argch.type in STARS:
features.add(Feature.TRAILING_COMMA)
return features
def detect_target_versions(node: Node) -> Set[TargetVersion]:
"""Detect the version to target based on the nodes used."""
features = get_features_used(node)
return {
version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
}
def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
"""Generate sets of closing bracket IDs that should be omitted in a RHS.
Brackets can be omitted if the entire trailer up to and including
a preceding closing bracket fits in one line.
Yielded sets are cumulative (contain results of previous yields, too). First
set is empty.
"""
omit: Set[LeafID] = set()
yield omit
length = 4 * line.depth
opening_bracket = None
closing_bracket = None
inner_brackets: Set[LeafID] = set()
for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
length += leaf_length
if length > line_length:
break
has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
if leaf.type == STANDALONE_COMMENT or has_inline_comment:
break
if opening_bracket:
if leaf is opening_bracket:
opening_bracket = None
elif leaf.type in CLOSING_BRACKETS:
inner_brackets.add(id(leaf))
elif leaf.type in CLOSING_BRACKETS:
if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
# Empty brackets would fail a split so treat them as "inner"
# brackets (e.g. only add them to the `omit` set if another
# pair of brackets was good enough.
inner_brackets.add(id(leaf))
continue
if closing_bracket:
omit.add(id(closing_bracket))
omit.update(inner_brackets)
inner_brackets.clear()
yield omit
if leaf.value:
opening_bracket = leaf.opening_bracket
closing_bracket = leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports: Set[str] = set()
def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
for child in children:
if isinstance(child, Leaf):
if child.type == token.NAME:
yield child.value
elif child.type == syms.import_as_name:
orig_name = child.children[0]
assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
yield orig_name.value
elif child.type == syms.import_as_names:
yield from get_imports_from_children(child.children)
else:
assert False, "Invalid syntax parsing imports"
for child in node.children:
if child.type != syms.simple_stmt:
break
first_child = child.children[0]
if isinstance(first_child, Leaf):
# Continue looking if we see a docstring; otherwise stop.
if (
len(child.children) == 2
and first_child.type == token.STRING
and child.children[1].type == token.NEWLINE
):
continue
else:
break
elif first_child.type == syms.import_from:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
imports |= set(get_imports_from_children(first_child.children[3:]))
else:
break
return imports
def gen_python_files_in_dir(
path: Path,
root: Path,
include: Pattern[str],
exclude: Pattern[str],
report: "Report",
) -> Iterator[Path]:
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
Symbolic links pointing outside of the `root` directory are ignored.
`report` is where output about exclusions goes.
"""
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
for child in path.iterdir():
try:
normalized_path = "/" + child.resolve().relative_to(root).as_posix()
except ValueError:
if child.is_symlink():
report.path_ignored(
child, f"is a symbolic link that points outside {root}"
)
continue
raise
if child.is_dir():
normalized_path += "/"
exclude_match = exclude.search(normalized_path)
if exclude_match and exclude_match.group(0):
report.path_ignored(child, f"matches the --exclude regular expression")
continue
if child.is_dir():
yield from gen_python_files_in_dir(child, root, include, exclude, report)
elif child.is_file():
include_match = include.search(normalized_path)
if include_match:
yield child
@lru_cache()
def find_project_root(srcs: Iterable[str]) -> Path:
"""Return a directory containing .git, .hg, or pyproject.toml.
That directory can be one of the directories passed in `srcs` or their
common parent.
If no directory in the tree contains a marker that would specify it's the
project root, the root of the file system is returned.
"""
if not srcs:
return Path("/").resolve()
common_base = min(Path(src).resolve() for src in srcs)
if common_base.is_dir():
# Append a fake file so `parents` below returns `common_base_dir`, too.
common_base /= "fake-file"
for directory in common_base.parents:
if (directory / ".git").is_dir():
return directory
if (directory / ".hg").is_dir():
return directory
if (directory / "pyproject.toml").is_file():
return directory
return directory
@dataclass
class Report:
"""Provides a reformatting counter. Can be rendered with `str(report)`."""
check: bool = False
quiet: bool = False
verbose: bool = False
change_count: int = 0
same_count: int = 0
failure_count: int = 0
def done(self, src: Path, changed: Changed) -> None:
"""Increment the counter for successful reformatting. Write out a message."""
if changed is Changed.YES:
reformatted = "would reformat" if self.check else "reformatted"
if self.verbose or not self.quiet:
out(f"{reformatted} {src}")
self.change_count += 1
else:
if self.verbose:
if changed is Changed.NO:
msg = f"{src} already well formatted, good job."
else:
msg = f"{src} wasn't modified on disk since last run."
out(msg, bold=False)
self.same_count += 1
def failed(self, src: Path, message: str) -> None:
"""Increment the counter for failed reformatting. Write out a message."""
err(f"error: cannot format {src}: {message}")
self.failure_count += 1
def path_ignored(self, path: Path, message: str) -> None:
if self.verbose:
out(f"{path} ignored: {message}", bold=False)
@property
def return_code(self) -> int:
"""Return the exit code that the app should use.
This considers the current state of changed files and failures:
- if there were any failures, return 123;
- if any files were changed and --check is being used, return 1;
- otherwise return 0.
"""
# According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
# 126 we have special return codes reserved by the shell.
if self.failure_count:
return 123
elif self.change_count and self.check:
return 1
return 0
def __str__(self) -> str:
"""Render a color report of the current state.
Use `click.unstyle` to remove colors.
"""
if self.check:
reformatted = "would be reformatted"
unchanged = "would be left unchanged"
failed = "would fail to reformat"
else:
reformatted = "reformatted"
unchanged = "left unchanged"
failed = "failed to reformat"
report = []
if self.change_count:
s = "s" if self.change_count > 1 else ""
report.append(
click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
)
if self.same_count:
s = "s" if self.same_count > 1 else ""
report.append(f"{self.same_count} file{s} {unchanged}")
if self.failure_count:
s = "s" if self.failure_count > 1 else ""
report.append(
click.style(f"{self.failure_count} file{s} {failed}", fg="red")
)
return ", ".join(report) + "."
def assert_equivalent(src: str, dst: str) -> None:
"""Raise AssertionError if `src` and `dst` aren't equivalent."""
import ast
import traceback
def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
"""Simple visitor generating strings to compare ASTs by content."""
yield f"{' ' * depth}{node.__class__.__name__}("
for field in sorted(node._fields):
try:
value = getattr(node, field)
except AttributeError:
continue
yield f"{' ' * (depth+1)}{field}="
if isinstance(value, list):
for item in value:
# Ignore nested tuples within del statements, because we may insert
# parentheses and they change the AST.
if (
field == "targets"
and isinstance(node, ast.Delete)
and isinstance(item, ast.Tuple)
):
for item in item.elts:
yield from _v(item, depth + 2)
elif isinstance(item, ast.AST):
yield from _v(item, depth + 2)
elif isinstance(value, ast.AST):
yield from _v(value, depth + 2)
else:
yield f"{' ' * (depth+2)}{value!r}, # {value.__class__.__name__}"
yield f"{' ' * depth}) # /{node.__class__.__name__}"
try:
src_ast = ast.parse(src)
except Exception as exc:
major, minor = sys.version_info[:2]
raise AssertionError(
f"cannot use --safe with this file; failed to parse source file "
f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
)
try:
dst_ast = ast.parse(dst)
except Exception as exc:
log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
raise AssertionError(
f"INTERNAL ERROR: Black produced invalid code: {exc}. "
f"Please report a bug on https://github.com/ambv/black/issues. "
f"This invalid output might be helpful: {log}"
) from None
src_ast_str = "\n".join(_v(src_ast))
dst_ast_str = "\n".join(_v(dst_ast))
if src_ast_str != dst_ast_str:
log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
raise AssertionError(
f"INTERNAL ERROR: Black produced code that is not equivalent to "
f"the source. "
f"Please report a bug on https://github.com/ambv/black/issues. "
f"This diff might be helpful: {log}"
) from None
def assert_stable(src: str, dst: str, mode: FileMode) -> None:
"""Raise AssertionError if `dst` reformats differently the second time."""
newdst = format_str(dst, mode=mode)
if dst != newdst:
log = dump_to_file(
diff(src, dst, "source", "first pass"),
diff(dst, newdst, "first pass", "second pass"),
)
raise AssertionError(
f"INTERNAL ERROR: Black produced different code on the second pass "
f"of the formatter. "
f"Please report a bug on https://github.com/ambv/black/issues. "
f"This diff might be helpful: {log}"
) from None
def dump_to_file(*output: str) -> str:
"""Dump `output` to a temporary file. Return path to the file."""
import tempfile
with tempfile.NamedTemporaryFile(
mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
) as f:
for lines in output:
f.write(lines)
if lines and lines[-1] != "\n":
f.write("\n")
return f.name
def diff(a: str, b: str, a_name: str, b_name: str) -> str:
"""Return a unified diff string between strings `a` and `b`."""
import difflib
a_lines = [line + "\n" for line in a.split("\n")]
b_lines = [line + "\n" for line in b.split("\n")]
return "".join(
difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
)
def cancel(tasks: Iterable[asyncio.Task]) -> None:
"""asyncio signal handler that cancels all `tasks` and reports to stderr."""
err("Aborted!")
for task in tasks:
task.cancel()
def shutdown(loop: BaseEventLoop) -> None:
"""Cancel all pending tasks on `loop`, wait for them, and close the loop."""
try:
if sys.version_info[:2] >= (3, 7):
all_tasks = asyncio.all_tasks
else:
all_tasks = asyncio.Task.all_tasks
# This part is borrowed from asyncio/runners.py in Python 3.7b2.
to_cancel = [task for task in all_tasks(loop) if not task.done()]
if not to_cancel:
return
for task in to_cancel:
task.cancel()
loop.run_until_complete(
asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
)
finally:
# `concurrent.futures.Future` objects cannot be cancelled once they
# are already running. There might be some when the `shutdown()` happened.
# Silence their logger's spew about the event loop being closed.
cf_logger = logging.getLogger("concurrent.futures")
cf_logger.setLevel(logging.CRITICAL)
loop.close()
def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
"""Replace `regex` with `replacement` twice on `original`.
This is used by string normalization to perform replaces on
overlapping matches.
"""
return regex.sub(replacement, regex.sub(replacement, original))
def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
"""Compile a regular expression string in `regex`.
If it contains newlines, use verbose mode.
"""
if "\n" in regex:
regex = "(?x)" + regex
return re.compile(regex)
def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
"""Like `reversed(enumerate(sequence))` if that were possible."""
index = len(sequence) - 1
for element in reversed(sequence):
yield (index, element)
index -= 1
def enumerate_with_length(
line: Line, reversed: bool = False
) -> Iterator[Tuple[Index, Leaf, int]]:
"""Return an enumeration of leaves with their length.
Stops prematurely on multiline strings and standalone comments.
"""
op = cast(
Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
enumerate_reversed if reversed else enumerate,
)
for index, leaf in op(line.leaves):
length = len(leaf.prefix) + len(leaf.value)
if "\n" in leaf.value:
return # Multiline strings, we can't continue.
comment: Optional[Leaf]
for comment in line.comments_after(leaf):
length += len(comment.value)
yield index, leaf, length
def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
"""Return True if `line` is no longer than `line_length`.
Uses the provided `line_str` rendering, if any, otherwise computes a new one.
"""
if not line_str:
line_str = str(line).strip("\n")
return (
len(line_str) <= line_length
and "\n" not in line_str # multiline strings
and not line.contains_standalone_comments()
)
def can_be_split(line: Line) -> bool:
"""Return False if the line cannot be split *for sure*.
This is not an exhaustive search but a cheap heuristic that we can use to
avoid some unfortunate formattings (mostly around wrapping unsplittable code
in unnecessary parentheses).
"""
leaves = line.leaves
if len(leaves) < 2:
return False
if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
call_count = 0
dot_count = 0
next = leaves[-1]
for leaf in leaves[-2::-1]:
if leaf.type in OPENING_BRACKETS:
if next.type not in CLOSING_BRACKETS:
return False
call_count += 1
elif leaf.type == token.DOT:
dot_count += 1
elif leaf.type == token.NAME:
if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
return False
elif leaf.type not in CLOSING_BRACKETS:
return False
if dot_count > 1 and call_count > 1:
return False
return True
def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
"""Does `line` have a shape safe to reformat without optional parens around it?
Returns True for only a subset of potentially nice looking formattings but
the point is to not return false positives that end up producing lines that
are too long.
"""
bt = line.bracket_tracker
if not bt.delimiters:
# Without delimiters the optional parentheses are useless.
return True
max_priority = bt.max_delimiter_priority()
if bt.delimiter_count_with_priority(max_priority) > 1:
# With more than one delimiter of a kind the optional parentheses read better.
return False
if max_priority == DOT_PRIORITY:
# A single stranded method call doesn't require optional parentheses.
return True
assert len(line.leaves) >= 2, "Stranded delimiter"
first = line.leaves[0]
second = line.leaves[1]
penultimate = line.leaves[-2]
last = line.leaves[-1]
# With a single delimiter, omit if the expression starts or ends with
# a bracket.
if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
remainder = False
length = 4 * line.depth
for _index, leaf, leaf_length in enumerate_with_length(line):
if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
remainder = True
if remainder:
length += leaf_length
if length > line_length:
break
if leaf.type in OPENING_BRACKETS:
# There are brackets we can further split on.
remainder = False
else:
# checked the entire string and line length wasn't exceeded
if len(line.leaves) == _index + 1:
return True
# Note: we are not returning False here because a line might have *both*
# a leading opening bracket and a trailing closing bracket. If the
# opening bracket doesn't match our rule, maybe the closing will.
if (
last.type == token.RPAR
or last.type == token.RBRACE
or (
# don't use indexing for omitting optional parentheses;
# it looks weird
last.type == token.RSQB
and last.parent
and last.parent.type != syms.trailer
)
):
if penultimate.type in OPENING_BRACKETS:
# Empty brackets don't help.
return False
if is_multiline_string(first):
# Additional wrapping of a multiline string in this situation is
# unnecessary.
return True
length = 4 * line.depth
seen_other_brackets = False
for _index, leaf, leaf_length in enumerate_with_length(line):
length += leaf_length
if leaf is last.opening_bracket:
if seen_other_brackets or length <= line_length:
return True
elif leaf.type in OPENING_BRACKETS:
# There are brackets we can further split on.
seen_other_brackets = True
return False
def get_cache_file(mode: FileMode) -> Path:
return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"
def read_cache(mode: FileMode) -> Cache:
"""Read the cache if it exists and is well formed.
If it is not well formed, the call to write_cache later should resolve the issue.
"""
cache_file = get_cache_file(mode)
if not cache_file.exists():
return {}
with cache_file.open("rb") as fobj:
try:
cache: Cache = pickle.load(fobj)
except pickle.UnpicklingError:
return {}
return cache
def get_cache_info(path: Path) -> CacheInfo:
"""Return the information used to check if a file is already formatted or not."""
stat = path.stat()
return stat.st_mtime, stat.st_size
def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
"""Split an iterable of paths in `sources` into two sets.
The first contains paths of files that modified on disk or are not in the
cache. The other contains paths to non-modified files.
"""
todo, done = set(), set()
for src in sources:
src = src.resolve()
if cache.get(src) != get_cache_info(src):
todo.add(src)
else:
done.add(src)
return todo, done
def write_cache(cache: Cache, sources: Iterable[Path], mode: FileMode) -> None:
"""Update the cache file."""
cache_file = get_cache_file(mode)
try:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
with tempfile.NamedTemporaryFile(dir=str(cache_file.parent), delete=False) as f:
pickle.dump(new_cache, f, protocol=pickle.HIGHEST_PROTOCOL)
os.replace(f.name, cache_file)
except OSError:
pass
def patch_click() -> None:
"""Make Click not crash.
On certain misconfigured environments, Python 3 selects the ASCII encoding as the
default which restricts paths that it can access during the lifetime of the
application. Click refuses to work in this scenario by raising a RuntimeError.
In case of Black the likelihood that non-ASCII characters are going to be used in
file paths is minimal since it's Python source code. Moreover, this crash was
spurious on Python 3.7 thanks to PEP 538 and PEP 540.
"""
try:
from click import core
from click import _unicodefun # type: ignore
except ModuleNotFoundError:
return
for module in (core, _unicodefun):
if hasattr(module, "_verify_python3_env"):
module._verify_python3_env = lambda: None
def patched_main() -> None:
freeze_support()
patch_click()
main()
if __name__ == "__main__":
patched_main()
black-19.3b0/blackd.py 0000664 0000000 0000000 00000012756 13442505266 0014560 0 ustar 00root root 0000000 0000000 import asyncio
from concurrent.futures import Executor, ProcessPoolExecutor
from functools import partial
import logging
from multiprocessing import freeze_support
from typing import Set, Tuple
from aiohttp import web
import aiohttp_cors
import black
import click
# This is used internally by tests to shut down the server prematurely
_stop_signal = asyncio.Event()
VERSION_HEADER = "X-Protocol-Version"
LINE_LENGTH_HEADER = "X-Line-Length"
PYTHON_VARIANT_HEADER = "X-Python-Variant"
SKIP_STRING_NORMALIZATION_HEADER = "X-Skip-String-Normalization"
FAST_OR_SAFE_HEADER = "X-Fast-Or-Safe"
BLACK_HEADERS = [
VERSION_HEADER,
LINE_LENGTH_HEADER,
PYTHON_VARIANT_HEADER,
SKIP_STRING_NORMALIZATION_HEADER,
FAST_OR_SAFE_HEADER,
]
class InvalidVariantHeader(Exception):
pass
@click.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.option(
"--bind-host", type=str, help="Address to bind the server to.", default="localhost"
)
@click.option("--bind-port", type=int, help="Port to listen on", default=45484)
@click.version_option(version=black.__version__)
def main(bind_host: str, bind_port: int) -> None:
logging.basicConfig(level=logging.INFO)
app = make_app()
ver = black.__version__
black.out(f"blackd version {ver} listening on {bind_host} port {bind_port}")
web.run_app(app, host=bind_host, port=bind_port, handle_signals=True, print=None)
def make_app() -> web.Application:
app = web.Application()
executor = ProcessPoolExecutor()
cors = aiohttp_cors.setup(app)
resource = cors.add(app.router.add_resource("/"))
cors.add(
resource.add_route("POST", partial(handle, executor=executor)),
{
"*": aiohttp_cors.ResourceOptions(
allow_headers=(*BLACK_HEADERS, "Content-Type"), expose_headers="*"
)
},
)
return app
async def handle(request: web.Request, executor: Executor) -> web.Response:
try:
if request.headers.get(VERSION_HEADER, "1") != "1":
return web.Response(
status=501, text="This server only supports protocol version 1"
)
try:
line_length = int(
request.headers.get(LINE_LENGTH_HEADER, black.DEFAULT_LINE_LENGTH)
)
except ValueError:
return web.Response(status=400, text="Invalid line length header value")
if PYTHON_VARIANT_HEADER in request.headers:
value = request.headers[PYTHON_VARIANT_HEADER]
try:
pyi, versions = parse_python_variant_header(value)
except InvalidVariantHeader as e:
return web.Response(
status=400,
text=f"Invalid value for {PYTHON_VARIANT_HEADER}: {e.args[0]}",
)
else:
pyi = False
versions = set()
skip_string_normalization = bool(
request.headers.get(SKIP_STRING_NORMALIZATION_HEADER, False)
)
fast = False
if request.headers.get(FAST_OR_SAFE_HEADER, "safe") == "fast":
fast = True
mode = black.FileMode(
target_versions=versions,
is_pyi=pyi,
line_length=line_length,
string_normalization=not skip_string_normalization,
)
req_bytes = await request.content.read()
charset = request.charset if request.charset is not None else "utf8"
req_str = req_bytes.decode(charset)
loop = asyncio.get_event_loop()
formatted_str = await loop.run_in_executor(
executor, partial(black.format_file_contents, req_str, fast=fast, mode=mode)
)
return web.Response(
content_type=request.content_type, charset=charset, text=formatted_str
)
except black.NothingChanged:
return web.Response(status=204)
except black.InvalidInput as e:
return web.Response(status=400, text=str(e))
except Exception as e:
logging.exception("Exception during handling a request")
return web.Response(status=500, text=str(e))
def parse_python_variant_header(value: str) -> Tuple[bool, Set[black.TargetVersion]]:
if value == "pyi":
return True, set()
else:
versions = set()
for version in value.split(","):
if version.startswith("py"):
version = version[len("py") :]
major_str, *rest = version.split(".")
try:
major = int(major_str)
if major not in (2, 3):
raise InvalidVariantHeader("major version must be 2 or 3")
if len(rest) > 0:
minor = int(rest[0])
if major == 2 and minor != 7:
raise InvalidVariantHeader(
"minor version must be 7 for Python 2"
)
else:
# Default to lowest supported minor version.
minor = 7 if major == 2 else 3
version_str = f"PY{major}{minor}"
if major == 3 and not hasattr(black.TargetVersion, version_str):
raise InvalidVariantHeader(f"3.{minor} is not supported")
versions.add(black.TargetVersion[version_str])
except (KeyError, ValueError):
raise InvalidVariantHeader("expected e.g. '3.7', 'py3.5'")
return False, versions
def patched_main() -> None:
freeze_support()
black.patch_click()
main()
if __name__ == "__main__":
patched_main()
black-19.3b0/blib2to3/ 0000775 0000000 0000000 00000000000 13442505266 0014373 5 ustar 00root root 0000000 0000000 black-19.3b0/blib2to3/Grammar.txt 0000664 0000000 0000000 00000016544 13442505266 0016534 0 ustar 00root root 0000000 0000000 # Grammar for 2to3. This grammar supports Python 2.x and 3.x.
# NOTE WELL: You should also follow all the steps listed at
# https://devguide.python.org/grammar/
# Start symbols for the grammar:
# file_input is a module or sequence of commands read from an input file;
# single_input is a single interactive statement;
# eval_input is the input for the eval() and input() functions.
# NB: compound_stmt in single_input is followed by extra NEWLINE!
file_input: (NEWLINE | stmt)* ENDMARKER
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
eval_input: testlist NEWLINE* ENDMARKER
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
decorated: decorators (classdef | funcdef | async_funcdef)
async_funcdef: ASYNC funcdef
funcdef: 'def' NAME parameters ['->' test] ':' suite
parameters: '(' [typedargslist] ')'
typedargslist: ((tfpdef ['=' test] ',')*
('*' [tname] (',' tname ['=' test])* [',' ['**' tname [',']]] | '**' tname [','])
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
tname: NAME [':' test]
tfpdef: tname | '(' tfplist ')'
tfplist: tfpdef (',' tfpdef)* [',']
varargslist: ((vfpdef ['=' test] ',')*
('*' [vname] (',' vname ['=' test])* [',' ['**' vname [',']]] | '**' vname [','])
| vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
vname: NAME
vfpdef: vname | '(' vfplist ')'
vfplist: vfpdef (',' vfpdef)* [',']
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))*)
annassign: ':' test ['=' test]
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
# For normal and annotated assignments, additional restrictions enforced by the interpreter
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] )
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: ('from' ('.'* dotted_name | '.'+)
'import' ('*' | '(' import_as_names ')' | import_as_names))
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
import_as_names: import_as_name (',' import_as_name)* [',']
dotted_as_names: dotted_as_name (',' dotted_as_name)*
dotted_name: NAME ('.' NAME)*
global_stmt: ('global' | 'nonlocal') NAME (',' NAME)*
exec_stmt: 'exec' expr ['in' test [',' test]]
assert_stmt: 'assert' test [',' test]
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
async_stmt: ASYNC (funcdef | with_stmt | for_stmt)
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
while_stmt: 'while' test ':' suite ['else' ':' suite]
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
try_stmt: ('try' ':' suite
((except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite] |
'finally' ':' suite))
with_stmt: 'with' with_item (',' with_item)* ':' suite
with_item: test ['as' expr]
with_var: 'as' expr
# NB compile.c makes sure that the default except clause is last
except_clause: 'except' [test [(',' | 'as') test]]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
# Backward compatibility cruft to support:
# [ x for x in lambda: True, lambda: False if x() ]
# even while also allowing:
# lambda x: 5 if x else 2
# (But not a mix of the two)
testlist_safe: old_test [(',' old_test)+ [',']]
old_test: or_test | old_lambdef
old_lambdef: 'lambda' [varargslist] ':' old_test
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
star_expr: '*' expr
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: [AWAIT] atom trailer* ['**' factor]
atom: ('(' [yield_expr|testlist_gexp] ')' |
'[' [listmaker] ']' |
'{' [dictsetmaker] '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+ | '.' '.' '.')
listmaker: (test|star_expr) ( old_comp_for | (',' (test|star_expr))* [','] )
testlist_gexp: (test|star_expr) ( old_comp_for | (',' (test|star_expr))* [','] )
lambdef: 'lambda' [varargslist] ':' test
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
testlist: test (',' test)* [',']
dictsetmaker: ( ((test ':' test | '**' expr)
(comp_for | (',' (test ':' test | '**' expr))* [','])) |
((test | star_expr)
(comp_for | (',' (test | star_expr))* [','])) )
classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
arglist: argument (',' argument)* [',']
# "test '=' test" is really "keyword '=' test", but we have no such token.
# These need to be in a single rule to avoid grammar that is ambiguous
# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
# we explicitly match '*' here, too, to give it proper precedence.
# Illegal combinations and orderings are blocked in ast.c:
# multiple (test comp_for) arguments are blocked; keyword unpackings
# that precede iterable unpackings are blocked; etc.
argument: ( test [comp_for] |
test '=' test |
'**' test |
'*' test )
comp_iter: comp_for | comp_if
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
comp_if: 'if' old_test [comp_iter]
# As noted above, testlist_safe extends the syntax allowed in list
# comprehensions and generators. We can't use it indiscriminately in all
# derivations using a comp_for-like pattern because the testlist_safe derivation
# contains comma which clashes with trailing comma in arglist.
#
# This was an issue because the parser would not follow the correct derivation
# when parsing syntactically valid Python code. Since testlist_safe was created
# specifically to handle list comprehensions and generator expressions enclosed
# with parentheses, it's safe to only use it in those. That avoids the issue; we
# can parse code like set(x for x in [],).
#
# The syntax supported by this set of rules is not a valid Python 3 syntax,
# hence the prefix "old".
#
# See https://bugs.python.org/issue27494
old_comp_iter: old_comp_for | old_comp_if
old_comp_for: [ASYNC] 'for' exprlist 'in' testlist_safe [old_comp_iter]
old_comp_if: 'if' old_test [old_comp_iter]
testlist1: test (',' test)*
# not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
yield_expr: 'yield' [yield_arg]
yield_arg: 'from' test | testlist
black-19.3b0/blib2to3/LICENSE 0000664 0000000 0000000 00000030732 13442505266 0015405 0 ustar 00root root 0000000 0000000 A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see https://opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI yes (2)
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
because its license has a choice of law clause. According to
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Python Software Foundation; All
Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
black-19.3b0/blib2to3/PatternGrammar.txt 0000664 0000000 0000000 00000001431 13442505266 0020057 0 ustar 00root root 0000000 0000000 # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
# A grammar to describe tree matching patterns.
# Not shown here:
# - 'TOKEN' stands for any token (leaf node)
# - 'any' stands for any node (leaf or interior)
# With 'any' we can still specify the sub-structure.
# The start symbol is 'Matcher'.
Matcher: Alternatives ENDMARKER
Alternatives: Alternative ('|' Alternative)*
Alternative: (Unit | NegatedUnit)+
Unit: [NAME '='] ( STRING [Repeater]
| NAME [Details] [Repeater]
| '(' Alternatives ')' [Repeater]
| '[' Alternatives ']'
)
NegatedUnit: 'not' (STRING | NAME [Details] | '(' Alternatives ')')
Repeater: '*' | '+' | '{' NUMBER [',' NUMBER] '}'
Details: '<' Alternatives '>'
black-19.3b0/blib2to3/README 0000664 0000000 0000000 00000001113 13442505266 0015247 0 ustar 00root root 0000000 0000000 A subset of lib2to3 taken from Python 3.7.0b2.
Commit hash: 9c17e3a1987004b8bcfbe423953aad84493a7984
Reasons for forking:
- consistent handling of f-strings for users of Python < 3.6.2
- backport of BPO-33064 that fixes parsing files with trailing commas after
*args and **kwargs
- backport of GH-6143 that restores the ability to reformat legacy usage of
`async`
- support all types of string literals
- better ability to debug (better reprs)
- INDENT and DEDENT don't hold whitespace and comment prefixes
- ability to Cythonize
Change Log:
- Changes default logger used by Driver black-19.3b0/blib2to3/__init__.py 0000664 0000000 0000000 00000000007 13442505266 0016501 0 ustar 00root root 0000000 0000000 #empty
black-19.3b0/blib2to3/__init__.pyi 0000664 0000000 0000000 00000000041 13442505266 0016650 0 ustar 00root root 0000000 0000000 # Stubs for lib2to3 (Python 3.6)
black-19.3b0/blib2to3/pgen2/ 0000775 0000000 0000000 00000000000 13442505266 0015406 5 ustar 00root root 0000000 0000000 black-19.3b0/blib2to3/pgen2/__init__.py 0000664 0000000 0000000 00000000217 13442505266 0017517 0 ustar 00root root 0000000 0000000 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""The pgen2 package."""
black-19.3b0/blib2to3/pgen2/__init__.pyi 0000664 0000000 0000000 00000000270 13442505266 0017667 0 ustar 00root root 0000000 0000000 # Stubs for lib2to3.pgen2 (Python 3.6)
import os
import sys
from typing import Text, Union
if sys.version_info >= (3, 6):
_Path = Union[Text, os.PathLike]
else:
_Path = Text
black-19.3b0/blib2to3/pgen2/conv.py 0000664 0000000 0000000 00000022652 13442505266 0016734 0 ustar 00root root 0000000 0000000 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Convert graminit.[ch] spit out by pgen to Python code.
Pgen is the Python parser generator. It is useful to quickly create a
parser from a grammar file in Python's grammar notation. But I don't
want my parsers to be written in C (yet), so I'm translating the
parsing tables to Python data structures and writing a Python parse
engine.
Note that the token numbers are constants determined by the standard
Python tokenizer. The standard token module defines these numbers and
their names (the names are not used much). The token numbers are
hardcoded into the Python tokenizer and into pgen. A Python
implementation of the Python tokenizer is also available, in the
standard tokenize module.
On the other hand, symbol numbers (representing the grammar's
non-terminals) are assigned by pgen based on the actual grammar
input.
Note: this module is pretty much obsolete; the pgen module generates
equivalent grammar tables directly from the Grammar.txt input file
without having to invoke the Python pgen C program.
"""
# Python imports
import re
# Local imports
from pgen2 import grammar, token
class Converter(grammar.Grammar):
"""Grammar subclass that reads classic pgen output files.
The run() method reads the tables as produced by the pgen parser
generator, typically contained in two C files, graminit.h and
graminit.c. The other methods are for internal use only.
See the base class for more documentation.
"""
def run(self, graminit_h, graminit_c):
"""Load the grammar tables from the text files written by pgen."""
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off()
def parse_graminit_h(self, filename):
"""Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.
"""
try:
f = open(filename)
except OSError as err:
print("Can't open %s: %s" % (filename, err))
return False
self.symbol2number = {}
self.number2symbol = {}
lineno = 0
for line in f:
lineno += 1
mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line)
if not mo and line.strip():
print("%s(%s): can't parse %s" % (filename, lineno,
line.strip()))
else:
symbol, number = mo.groups()
number = int(number)
assert symbol not in self.symbol2number
assert number not in self.number2symbol
self.symbol2number[symbol] = number
self.number2symbol[number] = symbol
return True
def parse_graminit_c(self, filename):
"""Parse the .c file written by pgen. (Internal)
The file looks as follows. The first two lines are always this:
#include "pgenheaders.h"
#include "grammar.h"
After that come four blocks:
1) one or more state definitions
2) a table defining dfas
3) a table defining labels
4) a struct defining the grammar
A state definition has the following form:
- one or more arc arrays, each of the form:
static arc arcs__[] = {
{, },
...
};
- followed by a state array, of the form:
static state states_[] = {
{, arcs__},
...
};
"""
try:
f = open(filename)
except OSError as err:
print("Can't open %s: %s" % (filename, err))
return False
# The code below essentially uses f's iterator-ness!
lineno = 0
# Expect the two #include lines
lineno, line = lineno+1, next(f)
assert line == '#include "pgenheaders.h"\n', (lineno, line)
lineno, line = lineno+1, next(f)
assert line == '#include "grammar.h"\n', (lineno, line)
# Parse the state definitions
lineno, line = lineno+1, next(f)
allarcs = {}
states = []
while line.startswith("static arc "):
while line.startswith("static arc "):
mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$",
line)
assert mo, (lineno, line)
n, m, k = list(map(int, mo.groups()))
arcs = []
for _ in range(k):
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+{(\d+), (\d+)},$", line)
assert mo, (lineno, line)
i, j = list(map(int, mo.groups()))
arcs.append((i, j))
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
allarcs[(n, m)] = arcs
lineno, line = lineno+1, next(f)
mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line)
assert mo, (lineno, line)
s, t = list(map(int, mo.groups()))
assert s == len(states), (lineno, line)
state = []
for _ in range(t):
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line)
assert mo, (lineno, line)
k, n, m = list(map(int, mo.groups()))
arcs = allarcs[n, m]
assert k == len(arcs), (lineno, line)
state.append(arcs)
states.append(state)
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
lineno, line = lineno+1, next(f)
self.states = states
# Parse the dfas
dfas = {}
mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
assert mo, (lineno, line)
ndfas = int(mo.group(1))
for i in range(ndfas):
lineno, line = lineno+1, next(f)
mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$',
line)
assert mo, (lineno, line)
symbol = mo.group(2)
number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
assert self.symbol2number[symbol] == number, (lineno, line)
assert self.number2symbol[number] == symbol, (lineno, line)
assert x == 0, (lineno, line)
state = states[z]
assert y == len(state), (lineno, line)
lineno, line = lineno+1, next(f)
mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
assert mo, (lineno, line)
first = {}
rawbitset = eval(mo.group(1))
for i, c in enumerate(rawbitset):
byte = ord(c)
for j in range(8):
if byte & (1<