From 62bfbd6a63dcac2f6f31eb014f69397c9eb967d2 Mon Sep 17 00:00:00 2001 From: Richard Si <63936253+ichard26@users.noreply.github.com> Date: Sat, 8 May 2021 15:17:38 -0400 Subject: [PATCH] Reorganize docs v2 (GH-2174) MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit I know I know, this is the second reorganization of the docs. I'm not saying the first one was bad or anything... but.. actually wait nah, *it was bad*. Anyway, welcome to probably my biggest commit. The main thing with this reorganization was to introduce nesting to the documentation! Having all of the docs be part of the main TOC was becoming too much. There wasn't much room to expand either. Finally, the old setup required a documentation generation step which was just annoying. The goals of this reorganization was to: 1. Significantly restructure the docs to be discoverable and understandable 2. Add room for further docs (like guides or contributing docs) 3. Get rid of the doc generation step (it was slow and frustrating) 4. Unblock other improvements and also just make contributing to the docs easier Another important change with this is that we are no longer using GitHub as a documentation host. While GitHub does support Markdown based docs actually pretty well, the lack of any features outside of GitHub Flavoured Markdown is quite limiting. ReadTheDocs is just much better suited for documentation. You can use reST, MyST, CommonMark, and all of their great features like toctrees and admonitions. Related to this change, we're adopting MyST as our flavour of Markdown. MyST introduces neat syntax extensions to Markdown that pretty much gives us the best of both worlds. The ease of use and simplicity of MD and the flexibility and expressiveness of reST. Also recommonmark is deprecated now. This switch was possible now we don't use GH as a docs host. MyST docs have to be built to really be usable / pretty, so the MD docs are going to look pretty bad on GH, but that's fine now! Another thing that should be noted is that the README has been stripped of most content since it was confusing. Users would read the README and then think some feature or bug was fixed already and is available in a release when in reality, they weren't. They were reading effectively the latest docs without knowing. See also: https://github.com/psf/black/issues/1759 FYI: CommonMark is a rationalized version of Markdown syntax -- Commit history before merge: * Switch to MyST-Parser + doc config cleanup recommonmark is being deprecated in favour of MyST-Parser. This change is welcomed, especially since MyST-Parser has syntax extensions for the Commonmark standard. Effectively we get to use a language that's powerful and expressive like ReST, but get the simplicity of Markdown. The rest of this effort will be using some MyST features. This reorganization efforts aims to remove as much duplication as possible. The regeneration step once needed is gone, significantly simplifing our Sphinx documentation configuration. * Tell pipenv we replaced recommonmark for MyST-Parser Also update `docs/requirements.txt` * Delete all auto generated content * Switch prettier for mdformat (plus a few plugins) **FYI: THIS WAS EFFECTIVELY REVERTED, SEE THIRD TO LAST COMMIT** prettier doesn't support MyST's syntax extensions which are going to be used in this reorganization effort so we have to switch formatter. Unfortanately mdformat's style is different from prettier's so time to reformat the whole repo too. We're excluding .github/ISSUE_TEMPLATE because I have no idea whether its changes are safe, so let's play it safe. * Fix the heading levels in CHANGES.md + a link MyST-Parser / sphinx's linkcheck complains otherwise. * Move reference docs into a docs/contributing dir They're for contributors of Black anyway. Also added a note in the summary document warning about the lack of attention the reference has been dealing with. * Rewrite and setup the new landing page + main TOC - add some more detail about Black's beta status - add licensing info - add external links in the main TOC for GitHub, PyPI, and IRC - prepare main TOC for new structure * Break out AUTHORS into its own file Not only was the AUTHORS list quite long, this makes it easy to include it in the Sphinx docs with just a simple symlink. * Add license to docs via a simple include Yes the document is orphaned but it is linked to in the landing page (docs/index.rst). * Add "The Black Code Style" section This mostly was a restructuring commit, there has been a few updates but not many. The main goal was to split "current style" and "planned changes to the style that haven't happened yet" to avoid confusion. * Add "Getting Started" page This is basically a quick start + even more. This commit is certainly one of most creatively involved in this effort. * Add "Usage and Configuration" section This commit was as much restructuring as new content. Instead of being in one giant file, usage and configuration documentation can expand without bloating a single file. * Add "Integrations" section Just a restructuring commit ... * Add "Guides" section This is a promising area of documentation that could easily grow in the future, let's prepare for that! * Add "Contributing" section This is also another area that I expect to see significant growth in. Contributors to Black could definitely do with some more specific docs that clears up certain parts of our slightly confusing project (it's only confusing because we're getting big and old!). * Rewrite CONTRIBUTING.md to just point to RTD * Rewrite README.md to delegate most info to RTD * Address feedback + a lot of corrections and edits I know I said I wanted to do these after landing this but given there's going to be no time between this being merged and a release getting pushed, I want these changes to make it in. - drop the number flag for mdformat - to reduce diffs, see also: https://mdformat.readthedocs.io/en/stable/users/style.html#ordered-lists - the GH issue templates should be safe by mdformat, so get rid of the exclude - clarify our configuration position - i.e. stop claiming we don't have many options, instead say we want as little formatting knobs as possible - lots and lots of punctuation, spelling, and grammar corrections (thanks Jelle!) - use RTD as the source for the CHANGELOG too - visual style cleanups - add docs about our .gitignore behaviour - expand GHA Action docs - clarify we want the PR number in the CHANGELOG entry - claify Black's behaviour for with statements post Python 3.9 - italicize a bunch of "Black"s Thank you goes to Jelle, Taneli (hukkinj1 on GH), Felix (felix-hilden on GH), and Wouter (wbolster on GH) for the feedback! * Merge remote-tracking branch 'upstream/master' into reorganize-docs-v2 merge conflicts suck, although these ones weren't too bad. * Add changelog entry + fix merge conflict resolution error I consider this important enough to be worthy of a changelog entry :) * Merge branch 'master' into reorganize-docs-v2 Co-authored-by: Łukasz Langa * Actually let's continue using prettier Prettier works fine for all of the default MyST syntax so let's not rock the boat as much. Dropping the mdformat commit was merge-conflict filled so here's additional commit instead. * Address Cooper's, Taneli's, and Jelle's feedback Lots of wording improvements by Cooper. Taneli suggested to disable the enabled by default MyST syntax not supported by Prettier and I agreed. And Jelle found one more spelling error! * More minor fixes --- .github/ISSUE_TEMPLATE/bug_report.md | 14 +- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- AUTHORS.md | 184 ++++++ CHANGES.md | 94 +-- CONTRIBUTING.md | 114 +--- Pipfile | 2 +- Pipfile.lock | 131 +++- README.md | 621 ++---------------- docs/authors.md | 188 +----- docs/black_primer.md | 120 ---- docs/conf.py | 229 +------ docs/contributing/gauging_changes.md | 61 ++ docs/contributing/index.rst | 39 ++ .../reference/reference_classes.rst | 0 .../reference/reference_exceptions.rst | 0 .../reference/reference_functions.rst | 0 .../reference/reference_summary.rst | 5 + .../the_basics.md} | 35 +- docs/getting_started.md | 49 ++ docs/github_actions.md | 27 - docs/guides/index.rst | 14 + .../introducing_black_to_your_project.md | 50 ++ .../using_black_with_other_tools.md} | 36 +- docs/index.rst | 85 ++- docs/installation_and_usage.md | 195 ------ .../editors.md} | 52 +- docs/integrations/github_actions.md | 35 + docs/integrations/index.rst | 28 + docs/integrations/source_version_control.md | 14 + docs/license.rst | 6 + docs/pyproject_toml.md | 91 --- docs/requirements.txt | 5 +- docs/show_your_style.md | 19 - .../current_style.md} | 59 +- docs/the_black_code_style/future_style.md | 35 + docs/the_black_code_style/index.rst | 19 + .../black_as_a_server.md} | 6 +- .../file_collection_and_discovery.md} | 18 +- docs/usage_and_configuration/index.rst | 24 + docs/usage_and_configuration/the_basics.md | 227 +++++++ docs/version_control_integration.md | 28 - 41 files changed, 1200 insertions(+), 1761 deletions(-) create mode 100644 AUTHORS.md mode change 100644 => 120000 docs/authors.md delete mode 100644 docs/black_primer.md create mode 100644 docs/contributing/gauging_changes.md create mode 100644 docs/contributing/index.rst rename docs/{ => contributing}/reference/reference_classes.rst (100%) rename docs/{ => contributing}/reference/reference_exceptions.rst (100%) rename docs/{ => contributing}/reference/reference_functions.rst (100%) rename docs/{ => contributing}/reference/reference_summary.rst (51%) rename docs/{contributing_to_black.md => contributing/the_basics.md} (68%) create mode 100644 docs/getting_started.md delete mode 100644 docs/github_actions.md create mode 100644 docs/guides/index.rst create mode 100644 docs/guides/introducing_black_to_your_project.md rename docs/{compatible_configs.md => guides/using_black_with_other_tools.md} (92%) delete mode 100644 docs/installation_and_usage.md rename docs/{editor_integration.md => integrations/editors.md} (85%) create mode 100644 docs/integrations/github_actions.md create mode 100644 docs/integrations/index.rst create mode 100644 docs/integrations/source_version_control.md create mode 100644 docs/license.rst delete mode 100644 docs/pyproject_toml.md delete mode 100644 docs/show_your_style.md rename docs/{the_black_code_style.md => the_black_code_style/current_style.md} (91%) create mode 100644 docs/the_black_code_style/future_style.md create mode 100644 docs/the_black_code_style/index.rst rename docs/{blackd.md => usage_and_configuration/black_as_a_server.md} (98%) rename docs/{ignoring_unmodified_files.md => usage_and_configuration/file_collection_and_discovery.md} (61%) create mode 100644 docs/usage_and_configuration/index.rst create mode 100644 docs/usage_and_configuration/the_basics.md delete mode 100644 docs/version_control_integration.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index f4a4386..3b59906 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -11,21 +11,21 @@ assignees: "" **To Reproduce** Steps to reproduce the behavior: 1. Take this file '...' -2. Run _Black_ on it with these arguments '....' -3. See error +1. Run _Black_ on it with these arguments '....' +1. See error **Expected behavior** A clear and concise description of what you expected to happen. **Environment (please complete the following information):** -- Version: [e.g. master] -- OS and Python version: [e.g. Linux/Python 3.7.4rc1] +- Version: \[e.g. master\] +- OS and Python version: \[e.g. Linux/Python 3.7.4rc1\] **Does this bug also happen on master?** To answer this, 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: +1. Use the online formatter at , which will + use the latest master branch. +1. Or run _Black_ on your machine: - create a new virtualenv (make sure it's the same Python version); - clone this repository; - run `pip install -e .[d,python2]`; diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 00dd5dd..56c2f0d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,7 +7,7 @@ assignees: "" --- **Is your feature request related to a problem? Please describe.** A clear and concise -description of what the problem is. Ex. I'm always frustrated when [...] +description of what the problem is. Ex. I'm always frustrated when \[...\] **Describe the solution you'd like** A clear and concise description of what you want to happen. diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..cb79dec --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,184 @@ +# 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), +[Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), +[Cooper Lees](mailto:me@cooperlees.com), and Richard Si. + +Multiple contributions by: + +- [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com) +- [Adam Johnson](mailto:me@adamj.eu) +- [Adam Williamson](mailto:adamw@happyassassin.net) +- [Alexander Huynh](mailto:github@grande.coffee) +- [Alex Vandiver](mailto:github@chmrr.net) +- [Allan Simon](mailto:allan.simon@supinfo.com) +- Anders-Petter Ljungquist +- [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com) +- [Andrew Zhou](mailto:andrewfzhou@gmail.com) +- [Andrey](mailto:dyuuus@yandex.ru) +- [Andy Freeland](mailto:andy@andyfreeland.net) +- [Anthony Sottile](mailto:asottile@umich.edu) +- [Arjaan Buijk](mailto:arjaan.buijk@gmail.com) +- [Arnav Borbornah](mailto:arnavborborah11@gmail.com) +- [Artem Malyshev](mailto:proofit404@gmail.com) +- [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com) +- [Augie Fackler](mailto:raf@durin42.com) +- [Aviskar KC](mailto:aviskarkc10@gmail.com) +- Batuhan Taşkaya +- [Benjamin Wohlwend](mailto:bw@piquadrat.ch) +- [Benjamin Woodruff](mailto:github@benjam.info) +- [Bharat Raghunathan](mailto:bharatraghunthan9767@gmail.com) +- [Brandt Bucher](mailto:brandtbucher@gmail.com) +- [Brett Cannon](mailto:brett@python.org) +- [Bryan Bugyi](mailto:bryan.bugyi@rutgers.edu) +- [Bryan Forbes](mailto:bryan@reigndropsfall.net) +- [Calum Lind](mailto:calumlind@gmail.com) +- [Charles](mailto:peacech@gmail.com) +- Charles Reid +- [Christian Clauss](mailto:cclauss@bluewin.ch) +- [Christian Heimes](mailto:christian@python.org) +- [Chuck Wooters](mailto:chuck.wooters@microsoft.com) +- [Chris Rose](mailto:offline@offby1.net) +- Codey Oxley +- [Cong](mailto:congusbongus@gmail.com) +- [Cooper Ry Lees](mailto:me@cooperlees.com) +- [Dan Davison](mailto:dandavison7@gmail.com) +- [Daniel Hahler](mailto:github@thequod.de) +- [Daniel M. Capella](mailto:polycitizen@gmail.com) +- Daniele Esposti +- [David Hotham](mailto:david.hotham@metaswitch.com) +- [David Lukes](mailto:dafydd.lukes@gmail.com) +- [David Szotten](mailto:davidszotten@gmail.com) +- [Denis Laxalde](mailto:denis@laxalde.org) +- [Douglas Thor](mailto:dthor@transphormusa.com) +- dylanjblack +- [Eli Treuherz](mailto:eli@treuherz.com) +- [Emil Hessman](mailto:emil@hessman.se) +- [Felix Kohlgrüber](mailto:felix.kohlgrueber@gmail.com) +- [Florent Thiery](mailto:fthiery@gmail.com) +- Francisco +- [Giacomo Tagliabue](mailto:giacomo.tag@gmail.com) +- [Greg Gandenberger](mailto:ggandenberger@shoprunner.com) +- [Gregory P. Smith](mailto:greg@krypto.org) +- Gustavo Camargo +- hauntsaninja +- [Hadi Alqattan](mailto:alqattanhadizaki@gmail.com) +- [Heaford](mailto:dan@heaford.com) +- [Hugo Barrera](mailto::hugo@barrera.io) +- Hugo van Kemenade +- [Hynek Schlawack](mailto:hs@ox.cx) +- [Ivan Katanić](mailto:ivan.katanic@gmail.com) +- [Jakub Kadlubiec](mailto:jakub.kadlubiec@skyscanner.net) +- [Jakub Warczarek](mailto:jakub.warczarek@gmail.com) +- [Jan Hnátek](mailto:jan.hnatek@gmail.com) +- [Jason Fried](mailto:me@jasonfried.info) +- [Jason Friedland](mailto:jason@friedland.id.au) +- [jgirardet](mailto:ijkl@netc.fr) +- Jim Brännlund +- [Jimmy Jia](mailto:tesrin@gmail.com) +- [Joe Antonakakis](mailto:jma353@cornell.edu) +- [Jon Dufresne](mailto:jon.dufresne@gmail.com) +- [Jonas Obrist](mailto:ojiidotch@gmail.com) +- [Jonty Wareing](mailto:jonty@jonty.co.uk) +- [Jose Nazario](mailto:jose.monkey.org@gmail.com) +- [Joseph Larson](mailto:larson.joseph@gmail.com) +- [Josh Bode](mailto:joshbode@fastmail.com) +- [Josh Holland](mailto:anowlcalledjosh@gmail.com) +- [Joshua Cannon](mailto:joshdcannon@gmail.com) +- [José Padilla](mailto:jpadilla@webapplicate.com) +- [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space) +- [kaiix](mailto:kvn.hou@gmail.com) +- [Katie McLaughlin](mailto:katie@glasnt.com) +- Katrin Leinweber +- [Keith Smiley](mailto:keithbsmiley@gmail.com) +- [Kenyon Ralph](mailto:kenyon@kenyonralph.com) +- [Kevin Kirsche](mailto:Kev.Kirsche+GitHub@gmail.com) +- [Kyle Hausmann](mailto:kyle.hausmann@gmail.com) +- [Kyle Sunden](mailto:sunden@wisc.edu) +- Lawrence Chan +- [Linus Groh](mailto:mail@linusgroh.de) +- [Loren Carvalho](mailto:comradeloren@gmail.com) +- [Luka Sterbic](mailto:luka.sterbic@gmail.com) +- [LukasDrude](mailto:mail@lukas-drude.de) +- Mahmoud Hossam +- Mariatta +- [Matt VanEseltine](mailto:vaneseltine@gmail.com) +- [Matthew Clapp](mailto:itsayellow+dev@gmail.com) +- [Matthew Walster](mailto:matthew@walster.org) +- Max Smolens +- [Michael Aquilina](mailto:michaelaquilina@gmail.com) +- [Michael Flaxman](mailto:michael.flaxman@gmail.com) +- [Michael J. Sullivan](mailto:sully@msully.net) +- [Michael McClimon](mailto:michael@mcclimon.org) +- [Miguel Gaiowski](mailto:miggaiowski@gmail.com) +- [Mike](mailto:roshi@fedoraproject.org) +- [mikehoyio](mailto:mikehoy@gmail.com) +- [Min ho Kim](mailto:minho42@gmail.com) +- [Miroslav Shubernetskiy](mailto:miroslav@miki725.com) +- MomIsBestFriend +- [Nathan Goldbaum](mailto:ngoldbau@illinois.edu) +- [Nathan Hunt](mailto:neighthan.hunt@gmail.com) +- [Neraste](mailto:neraste.herr10@gmail.com) +- [Nikolaus Waxweiler](mailto:madigens@gmail.com) +- [Ofek Lev](mailto:ofekmeister@gmail.com) +- [Osaetin Daniel](mailto:osaetindaniel@gmail.com) +- [otstrel](mailto:otstrel@gmail.com) +- [Pablo Galindo](mailto:Pablogsal@gmail.com) +- [Paul Ganssle](mailto:p.ganssle@gmail.com) +- [Paul Meinhardt](mailto:mnhrdt@gmail.com) +- [Peter Bengtsson](mailto:mail@peterbe.com) +- [Peter Grayson](mailto:pete@jpgrayson.net) +- [Peter Stensmyr](mailto:peter.stensmyr@gmail.com) +- pmacosta +- [Quentin Pradet](mailto:quentin@pradet.me) +- [Ralf Schmitt](mailto:ralf@systemexit.de) +- [Ramón Valles](mailto:mroutis@protonmail.com) +- [Richard Fearn](mailto:richardfearn@gmail.com) +- [Rishikesh Jha](mailto:rishijha424@gmail.com) +- [Rupert Bedford](mailto:rupert@rupertb.com) +- Russell Davis +- [Rémi Verschelde](mailto:rverschelde@gmail.com) +- [Sami Salonen](mailto:sakki@iki.fi) +- [Samuel Cormier-Iijima](mailto:samuel@cormier-iijima.com) +- [Sanket Dasgupta](mailto:sanketdasgupta@gmail.com) +- Sergi +- [Scott Stevenson](mailto:scott@stevenson.io) +- Shantanu +- [shaoran](mailto:shaoran@sakuranohana.org) +- [Shinya Fujino](mailto:shf0811@gmail.com) +- springstan +- [Stavros Korokithakis](mailto:hi@stavros.io) +- [Stephen Rosen](mailto:sirosen@globus.org) +- [Steven M. Vascellaro](mailto:S.Vascellaro@gmail.com) +- [Sunil Kapil](mailto:snlkapil@gmail.com) +- [Sébastien Eustace](mailto:sebastien.eustace@gmail.com) +- [Tal Amuyal](mailto:TalAmuyal@gmail.com) +- [Terrance](mailto:git@terrance.allofti.me) +- [Thom Lu](mailto:thomas.c.lu@gmail.com) +- [Thomas Grainger](mailto:tagrain@gmail.com) +- [Tim Gates](mailto:tim.gates@iress.com) +- [Tim Swast](mailto:swast@google.com) +- [Timo](mailto:timo_tk@hotmail.com) +- Toby Fleming +- [Tom Christie](mailto:tom@tomchristie.com) +- [Tony Narlock](mailto:tony@git-pull.com) +- [Tsuyoshi Hombashi](mailto:tsuyoshi.hombashi@gmail.com) +- [Tushar Chandra](mailto:tusharchandra2018@u.northwestern.edu) +- [Tzu-ping Chung](mailto:uranusjr@gmail.com) +- [Utsav Shah](mailto:ukshah2@illinois.edu) +- utsav-dbx +- vezeli +- [Ville Skyttä](mailto:ville.skytta@iki.fi) +- [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com) +- [Vlad Emelianov](mailto:volshebnyi@gmail.com) +- [williamfzc](mailto:178894043@qq.com) +- [wouter bolsterlee](mailto:wouter@bolsterl.ee) +- Yazdan +- [Yngve Høiseth](mailto:yngve@hoiseth.net) +- [Yurii Karabas](mailto:1998uriyyo@gmail.com) +- [Zac Hatfield-Dodds](mailto:zac@zhd.dev) diff --git a/CHANGES.md b/CHANGES.md index 8cbdeca..9b15592 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,26 +1,32 @@ -## Change Log +# Change Log -### Unreleased +## Unreleased -#### _Black_ +### _Black_ - Refactor `src/black/__init__.py` into many files (#2206) -### 21.5b0 +### Documentation -#### _Black_ +- Sigificantly reorganized the documentation to make much more sense. Check them out by + heading over to [the stable docs on RTD](https://black.readthedocs.io/en/stable/). + (#2174) + +## 21.5b0 + +### _Black_ - Set `--pyi` mode if `--stdin-filename` ends in `.pyi` (#2169) - Stop detecting target version as Python 3.9+ with pre-PEP-614 decorators that are being called but with no arguments (#2182) -#### _Black-Primer_ +### _Black-Primer_ - Add `--no-diff` to black-primer to suppress formatting changes (#2187) -### 21.4b2 +## 21.4b2 -#### _Black_ +### _Black_ - Fix crash if the user configuration directory is inaccessible. (#2158) @@ -31,15 +37,15 @@ - Allow `.gitignore` rules to be overridden by specifying `exclude` in `pyproject.toml` or on the command line. (#2170) -#### _Packaging_ +### _Packaging_ - Install `primer.json` (used by `black-primer` by default) with black. (#2154) -### 21.4b1 +## 21.4b1 -#### _Black_ +### _Black_ -- Fix crash on docstrings ending with "\ ". (#2142) +- Fix crash on docstrings ending with "\\ ". (#2142) - Fix crash when atypical whitespace is cleaned out of dostrings (#2120) @@ -50,13 +56,13 @@ - Don't remove necessary parentheses from assignment expression containing assert / return statements. (#2143) -#### _Packaging_ +### _Packaging_ - Bump pathspec to >= 0.8.1 to solve invalid .gitignore exclusion handling -### 21.4b0 +## 21.4b0 -#### _Black_ +### _Black_ - Fixed a rare but annoying formatting instability created by the combination of optional trailing commas inserted by `Black` and optional parentheses looking at @@ -112,21 +118,21 @@ - Fixed "Black produced code that is not equivalent to the source" when formatting Python 2 docstrings (#2037) -#### _Packaging_ +### _Packaging_ - Self-contained native _Black_ binaries are now provided for releases via GitHub Releases (#1743) -### 20.8b1 +## 20.8b1 -#### _Packaging_ +### _Packaging_ - explicitly depend on Click 7.1.2 or newer as `Black` no longer works with versions older than 7.0 -### 20.8b0 +## 20.8b0 -#### _Black_ +### _Black_ - re-implemented support for explicit trailing commas: now it works consistently within any bracket pair, including nested structures (#1288 and duplicates) @@ -170,11 +176,11 @@ this is an undocumented and unsupported feature, you lose Internet points for depending on it (#1609) -#### Vim plugin +### Vim plugin - prefer virtualenv packages over global packages (#1383) -### 19.10b0 +## 19.10b0 - added support for PEP 572 assignment expressions (#711) @@ -233,7 +239,7 @@ - `blackd` can now output the diff of formats on source code when the `X-Diff` header is provided (#969) -### 19.3b0 +## 19.3b0 - new option `--target-version` to control which Python versions _Black_-formatted code should target (#618) @@ -258,7 +264,7 @@ - `blackd` now supports CORS (#622) -### 18.9b0 +## 18.9b0 - numeric literals are now formatted by _Black_ (#452, #461, #464, #469): @@ -273,7 +279,9 @@ - hexadecimal digits are always uppercased (e.g. `0xBADC0DE`) -- added `blackd`, see [its documentation](#blackd) for more info (#349) +- added `blackd`, see + [its documentation](https://github.com/psf/black/blob/18.9b0/README.md#blackd) for + more info (#349) - adjacent string literals are now correctly split into multiple lines (#463) @@ -300,11 +308,11 @@ - note: the Vim plugin stopped registering `,=` as a default chord as it turned out to be a bad idea (#415) -### 18.6b4 +## 18.6b4 - hotfix: don't freeze when multiple comments directly precede `# fmt: off` (#371) -### 18.6b3 +## 18.6b3 - typing stub files (`.pyi`) now have blank lines added after constants (#340) @@ -332,7 +340,7 @@ - fixed a crash due to symbolic links pointing outside of the project directory (#338) -### 18.6b2 +## 18.6b2 - added `--config` (#65) @@ -346,13 +354,13 @@ - fixed unnecessary slowdown in comment placement calculation on lines without comments -### 18.6b1 +## 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 +## 18.6b0 - added `--include` and `--exclude` (#270) @@ -370,7 +378,7 @@ - _Black_ now preserves line endings when formatting a file in place (#258) -### 18.5b1 +## 18.5b1 - added `--pyi` (#249) @@ -399,7 +407,7 @@ - fixed extra empty line between a function signature and an inner function or inner class (#196) -### 18.5b0 +## 18.5b0 - call chains are now formatted according to the [fluent interfaces](https://en.wikipedia.org/wiki/Fluent_interface) style (#67) @@ -454,11 +462,11 @@ - fixed crash when dead symlinks where encountered -### 18.4a4 +## 18.4a4 - don't populate the cache on `--check` (#175) -### 18.4a3 +## 18.4a3 - added a "cache"; files already reformatted that haven't changed on disk won't be reformatted again (#109) @@ -486,7 +494,7 @@ - fixed missing splits of ternary expressions (#141) -### 18.4a2 +## 18.4a2 - fixed parsing of unaligned standalone comments (#99, #112) @@ -497,7 +505,7 @@ - fixed unstable formatting when encountering unnecessarily escaped quotes in a string (#120) -### 18.4a1 +## 18.4a1 - added `--quiet` (#78) @@ -509,7 +517,7 @@ - fixed removing backslash escapes from raw strings (#100, #105) -### 18.4a0 +## 18.4a0 - added `--diff` (#87) @@ -534,7 +542,7 @@ - only allow up to two empty lines on module level and only single empty lines within functions (#74) -### 18.3a4 +## 18.3a4 - `# fmt: off` and `# fmt: on` are implemented (#5) @@ -556,7 +564,7 @@ [Sphinx auto-attribute comments](http://www.sphinx-doc.org/en/stable/ext/autodoc.html#directive-autoattribute) (#68) -### 18.3a3 +## 18.3a3 - don't remove single empty lines outside of bracketed expressions (#19) @@ -566,7 +574,7 @@ - even better handling of numpy-style array indexing (#33, again) -### 18.3a2 +## 18.3a2 - changed positioning of binary operators to occur at beginning of lines instead of at the end, following @@ -590,7 +598,7 @@ - fixed spurious space after star-based unary expressions (#31) -### 18.3a1 +## 18.3a1 - added `--check` @@ -609,10 +617,10 @@ - fixed spurious space after unary operators when the operand was a complex expression (#15) -### 18.3a0 +## 18.3a0 - first published version, Happy 🍰 Day 2018! - alpha quality -- date-versioned (see: https://calver.org/) +- date-versioned (see: ) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f2a4ee2..10f6042 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,114 +3,8 @@ 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 +Our [contributing documentation](https://black.readthedocs.org/en/latest/contributing/) +contains details on all you need to know about contributing to _Black_, the basics to +the internals of _Black_. -In terms of inspiration, _Black_ is about as configurable as _gofmt_. This is -deliberate. - -Bug reports and fixes are always welcome! Please follow the -[issue template on GitHub](https://github.com/psf/black/issues/new) for best results. - -Before you suggest a new feature or configuration knob, ask yourself why you want it. If -it enables better integration with some workflow, fixes an inconsistency, speeds things -up, and so on - go for it! On the other hand, if your answer is "because I don't like a -particular formatting" then you're not ready to embrace _Black_ yet. Such changes are -unlikely to get accepted. You can still try but prepare to be disappointed. - -## Technicalities - -Development on the latest version of Python is preferred. As of this writing it's 3.9. -You can use any operating system. I am using macOS myself and CentOS at work. - -Install all development dependencies using: - -```console -$ pipenv install --dev -$ pipenv shell -$ 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. - -Non pipenv install works too: - -```console -$ pip install -r test_requirements -$ pip install -e .[d] -``` - -Before submitting pull requests, run lints and tests with the following commands from -the root of the black repo: - -```console -# Linting -$ pre-commit run -a - -# Unit tests -$ tox -e py - -# Optional Fuzz testing -$ tox -e fuzz - -# Optional CI run to test your changes on many popular python projects -$ black-primer [-k -w /tmp/black_test_repos] -``` - -### News / Changelog Requirement - -`Black` has CI that will check for an entry corresponding to your PR in `CHANGES.md`. If -you feel this PR not require a changelog entry please state that in a comment and a -maintainer can add a `skip news` label to make the CI pass. Otherwise, please ensure you -have a line in the following format: - -```md -- `Black` is now more awesome (#X) -``` - -To workout X, please use -[Next PR Number](https://ichard26.github.io/next-pr-number/?owner=psf&name=black). This -is not perfect but saves a lot of release overhead as now the releaser does not need to -go back and workout what to add to the `CHANGES.md` for each release. - -### Style Changes - -If a change would affect the advertised code style, please modify the documentation (The -_Black_ code style) to reflect that change. Patches that fix unintended bugs in -formatting don't need to be mentioned separately though. - -### Docs Testing - -If you make changes to docs, you can test they still build locally too. - -```console -$ pip install -r docs/requirements.txt -$ pip install [-e] .[d] -$ sphinx-build -a -b html -W docs/ docs/_build/ -``` - -## black-primer - -`black-primer` is used by CI to pull down well-known _Black_ formatted projects and see -if we get source code changes. It will error on formatting changes or errors. Please run -before pushing your PR to see if you get the actions you would expect from _Black_ with -your PR. You may need to change -[primer.json](https://github.com/psf/black/blob/master/src/black_primer/primer.json) -configuration for it to pass. - -For more `black-primer` information visit the -[documentation](https://github.com/psf/black/blob/master/docs/black_primer.md). - -## 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. +We look forward to your contributions! diff --git a/Pipfile b/Pipfile index 68562f5..d1842ff 100644 --- a/Pipfile +++ b/Pipfile @@ -12,7 +12,7 @@ flake8-bugbear = "*" mypy = ">=0.812" pre-commit = "*" readme_renderer = "*" -recommonmark = "*" +MyST-Parser = ">=0.13.7" setuptools = ">=39.2.0" setuptools-scm = "*" twine = ">=1.11.0" diff --git a/Pipfile.lock b/Pipfile.lock index 8a16a75..f973c84 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "1b075e0e344dad54944ed4474351c3f311accb67cbea2e0c381da3700b71f415" + "sha256": "62bc4bdb0117234d1f374b2dc0685369f6df7c7192d16409cc9c42a429770166" }, "pipfile-spec": 6, "requires": {}, @@ -428,11 +428,11 @@ }, "babel": { "hashes": [ - "sha256:9d35c22fcc79893c3ecc85ac4a56cde1ecf3f19c540bba0922308a6c06ca6fa5", - "sha256:da031ab54472314f210b0adcff1588ee5d1d1d0ba4dbd07b94dba82bde791e05" + "sha256:ab49e12b91d937cd11f0b67cb259a57ab4ad2b59ac7a3b41d6c06c0ac5b0def9", + "sha256:bc0c176f9f6a994582230df350aa6e05ba2ebe4b3ac317eab29d9be5d2768da0" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.9.0" + "version": "==2.9.1" }, "black": { "editable": true, @@ -456,6 +456,48 @@ ], "version": "==2020.12.5" }, + "cffi": { + "hashes": [ + "sha256:005a36f41773e148deac64b08f233873a4d0c18b053d37da83f6af4d9087b813", + "sha256:0857f0ae312d855239a55c81ef453ee8fd24136eaba8e87a2eceba644c0d4c06", + "sha256:1071534bbbf8cbb31b498d5d9db0f274f2f7a865adca4ae429e147ba40f73dea", + "sha256:158d0d15119b4b7ff6b926536763dc0714313aa59e320ddf787502c70c4d4bee", + "sha256:1f436816fc868b098b0d63b8920de7d208c90a67212546d02f84fe78a9c26396", + "sha256:2894f2df484ff56d717bead0a5c2abb6b9d2bf26d6960c4604d5c48bbc30ee73", + "sha256:29314480e958fd8aab22e4a58b355b629c59bf5f2ac2492b61e3dc06d8c7a315", + "sha256:34eff4b97f3d982fb93e2831e6750127d1355a923ebaeeb565407b3d2f8d41a1", + "sha256:35f27e6eb43380fa080dccf676dece30bef72e4a67617ffda586641cd4508d49", + "sha256:3d3dd4c9e559eb172ecf00a2a7517e97d1e96de2a5e610bd9b68cea3925b4892", + "sha256:43e0b9d9e2c9e5d152946b9c5fe062c151614b262fda2e7b201204de0b99e482", + "sha256:48e1c69bbacfc3d932221851b39d49e81567a4d4aac3b21258d9c24578280058", + "sha256:51182f8927c5af975fece87b1b369f722c570fe169f9880764b1ee3bca8347b5", + "sha256:58e3f59d583d413809d60779492342801d6e82fefb89c86a38e040c16883be53", + "sha256:5de7970188bb46b7bf9858eb6890aad302577a5f6f75091fd7cdd3ef13ef3045", + "sha256:65fa59693c62cf06e45ddbb822165394a288edce9e276647f0046e1ec26920f3", + "sha256:69e395c24fc60aad6bb4fa7e583698ea6cc684648e1ffb7fe85e3c1ca131a7d5", + "sha256:6c97d7350133666fbb5cf4abdc1178c812cb205dc6f41d174a7b0f18fb93337e", + "sha256:6e4714cc64f474e4d6e37cfff31a814b509a35cb17de4fb1999907575684479c", + "sha256:72d8d3ef52c208ee1c7b2e341f7d71c6fd3157138abf1a95166e6165dd5d4369", + "sha256:8ae6299f6c68de06f136f1f9e69458eae58f1dacf10af5c17353eae03aa0d827", + "sha256:8b198cec6c72df5289c05b05b8b0969819783f9418e0409865dac47288d2a053", + "sha256:99cd03ae7988a93dd00bcd9d0b75e1f6c426063d6f03d2f90b89e29b25b82dfa", + "sha256:9cf8022fb8d07a97c178b02327b284521c7708d7c71a9c9c355c178ac4bbd3d4", + "sha256:9de2e279153a443c656f2defd67769e6d1e4163952b3c622dcea5b08a6405322", + "sha256:9e93e79c2551ff263400e1e4be085a1210e12073a31c2011dbbda14bda0c6132", + "sha256:9ff227395193126d82e60319a673a037d5de84633f11279e336f9c0f189ecc62", + "sha256:a465da611f6fa124963b91bf432d960a555563efe4ed1cc403ba5077b15370aa", + "sha256:ad17025d226ee5beec591b52800c11680fca3df50b8b29fe51d882576e039ee0", + "sha256:afb29c1ba2e5a3736f1c301d9d0abe3ec8b86957d04ddfa9d7a6a42b9367e396", + "sha256:b85eb46a81787c50650f2392b9b4ef23e1f126313b9e0e9013b35c15e4288e2e", + "sha256:bb89f306e5da99f4d922728ddcd6f7fcebb3241fc40edebcb7284d7514741991", + "sha256:cbde590d4faaa07c72bf979734738f328d239913ba3e043b1e98fe9a39f8b2b6", + "sha256:cd2868886d547469123fadc46eac7ea5253ea7fcb139f12e1dfc2bbd406427d1", + "sha256:d42b11d692e11b6634f7613ad8df5d6d5f8875f5d48939520d351007b3c13406", + "sha256:f2d45f97ab6bb54753eab54fffe75aaf3de4ff2341c9daee1987ee1837636f1d", + "sha256:fd78e5fee591709f32ef6edb9a015b4aa1a5022598e36227500c8f4e02328d9c" + ], + "version": "==1.14.5" + }, "cfgv": { "hashes": [ "sha256:32e43d604bbe7896fe7c248a9c2276447dbef840feb28fe20494f62af110211d", @@ -488,13 +530,6 @@ "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'", "version": "==0.4.4" }, - "commonmark": { - "hashes": [ - "sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60", - "sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9" - ], - "version": "==0.9.1" - }, "coverage": { "hashes": [ "sha256:004d1880bed2d97151facef49f08e255a20ceb6f9432df75f4eef018fdd5a78c", @@ -553,6 +588,24 @@ "index": "pypi", "version": "==5.5" }, + "cryptography": { + "hashes": [ + "sha256:0f1212a66329c80d68aeeb39b8a16d54ef57071bf22ff4e521657b27372e327d", + "sha256:1e056c28420c072c5e3cb36e2b23ee55e260cb04eee08f702e0edfec3fb51959", + "sha256:240f5c21aef0b73f40bb9f78d2caff73186700bf1bc6b94285699aff98cc16c6", + "sha256:26965837447f9c82f1855e0bc8bc4fb910240b6e0d16a664bb722df3b5b06873", + "sha256:37340614f8a5d2fb9aeea67fd159bfe4f5f4ed535b1090ce8ec428b2f15a11f2", + "sha256:3d10de8116d25649631977cb37da6cbdd2d6fa0e0281d014a5b7d337255ca713", + "sha256:3d8427734c781ea5f1b41d6589c293089704d4759e34597dce91014ac125aad1", + "sha256:7ec5d3b029f5fa2b179325908b9cd93db28ab7b85bb6c1db56b10e0b54235177", + "sha256:8e56e16617872b0957d1c9742a3f94b43533447fd78321514abbe7db216aa250", + "sha256:de4e5f7f68220d92b7637fc99847475b59154b7a1b3868fb7385337af54ac9ca", + "sha256:eb8cc2afe8b05acbd84a43905832ec78e7b3873fb124ca190f574dca7389a87d", + "sha256:ee77aa129f481be46f8d92a1a7db57269a2f23052d5f2433b4621bb457081cc9" + ], + "markers": "python_version >= '3.6'", + "version": "==3.4.7" + }, "distlib": { "hashes": [ "sha256:8c09de2c67b3e7deef7184574fc060ab8a793e7adbb183d942c389c8b13c52fb", @@ -624,6 +677,14 @@ "markers": "python_version >= '3.6'", "version": "==4.0.1" }, + "jeepney": { + "hashes": [ + "sha256:7d59b6622675ca9e993a6bd38de845051d315f8b0c72cca3aef733a20b648657", + "sha256:aec56c0eb1691a841795111e184e13cad504f7703b9a64f63020816afa79a8ae" + ], + "markers": "sys_platform == 'linux'", + "version": "==0.6.0" + }, "jinja2": { "hashes": [ "sha256:03e47ad063331dd6a3f04a43eddca8a966a26ba0c5b7207a9a9e4e08f1b29419", @@ -640,6 +701,14 @@ "markers": "python_version >= '3.6'", "version": "==23.0.1" }, + "markdown-it-py": { + "hashes": [ + "sha256:30b3e9f8198dc82a5df0dcb73fd31d56cd9a43bf8a747feb10b2ba74f962bcb1", + "sha256:c3b9f995be0792cbbc8ab2f53d74072eb7ff8a8b622be8d61d38ab879709eca3" + ], + "markers": "python_version ~= '3.6'", + "version": "==0.6.2" + }, "markupsafe": { "hashes": [ "sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473", @@ -705,6 +774,14 @@ ], "version": "==0.6.1" }, + "mdit-py-plugins": { + "hashes": [ + "sha256:1e467ca2ea056e8065cbd5d6c61e5052bb50826bde84c40f6a5ed77e82125710", + "sha256:77fd75dad81109ee91f30eb49146196f79afbbae041f298ae4886c8c2b5e23d7" + ], + "markers": "python_version ~= '3.6'", + "version": "==0.2.6" + }, "multidict": { "hashes": [ "sha256:018132dbd8688c7a69ad89c4a3f39ea2f9f33302ebe567a879da8f4ca73f0d0a", @@ -784,6 +861,14 @@ "index": "pypi", "version": "==0.4.3" }, + "myst-parser": { + "hashes": [ + "sha256:260355b4da8e8865fe080b0638d7f1ab1791dc4bed02a7a48630b6bad4249219", + "sha256:e4bc99e43e19f70d22e528de8e7cce59f7e8e7c4c34dcba203de92de7a7c7c85" + ], + "index": "pypi", + "version": "==0.13.7" + }, "nodeenv": { "hashes": [ "sha256:3ef13ff90291ba2a4a7a4ff9a979b63ffdd00a464dbe04acf0ea6471517a4c2b", @@ -830,6 +915,14 @@ "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.7.0" }, + "pycparser": { + "hashes": [ + "sha256:2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0", + "sha256:7582ad22678f0fcd81102833f60ef8d0e57288b6b5fb00323d101be910e35705" + ], + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==2.20" + }, "pyflakes": { "hashes": [ "sha256:7893783d01b8a89811dd72d7dfd4d84ff098e5eed95cfa8905b22bbffe52efc3", @@ -904,14 +997,6 @@ "index": "pypi", "version": "==29.0" }, - "recommonmark": { - "hashes": [ - "sha256:1b1db69af0231efce3fa21b94ff627ea33dee7079a01dd0a7f8482c3da148b3f", - "sha256:bdb4db649f2222dcd8d2d844f0006b958d627f732415d399791ee436a3686d67" - ], - "index": "pypi", - "version": "==0.7.1" - }, "regex": { "hashes": [ "sha256:01afaf2ec48e196ba91b37451aa353cb7eda77efe518e481707e0515025f0cd5", @@ -981,6 +1066,14 @@ ], "version": "==1.4.0" }, + "secretstorage": { + "hashes": [ + "sha256:422d82c36172d88d6a0ed5afdec956514b189ddbfb72fefab0c8a1cee4eaf71f", + "sha256:fd666c51a6bf200643495a04abb261f83229dcb6fd8472ec393df7ffc8b6f195" + ], + "markers": "sys_platform == 'linux'", + "version": "==3.3.1" + }, "setuptools-scm": { "hashes": [ "sha256:c3bd5f701c8def44a5c0bfe8d407bef3f80342217ef3492b951f3777bd2d915c", diff --git a/README.md b/README.md index 6443569..ceccbb7 100644 --- a/README.md +++ b/README.md @@ -26,21 +26,12 @@ 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). Watch the +Try it out now using the [Black Playground](https://black.vercel.app). Watch the [PyCon 2019 talk](https://youtu.be/esZLCuWs_2Y) to learn more. --- -_Contents:_ **[Installation and usage](#installation-and-usage)** | -**[Code style](#the-black-code-style)** | **[Pragmatism](#pragmatism)** | -**[pyproject.toml](#pyprojecttoml)** | **[Editor integration](#editor-integration)** | -**[blackd](#blackd)** | **[black-primer](#black-primer)** | -**[Version control integration](#version-control-integration)** | -**[GitHub Actions](#github-actions)** | -**[Ignoring unmodified files](#ignoring-unmodified-files)** | **[Used by](#used-by)** | -**[Testimonials](#testimonials)** | **[Show your style](#show-your-style)** | -**[Contributing](#contributing-to-black)** | **[Change log](#change-log)** | -**[Authors](#authors)** +**[Read the documentation on ReadTheDocs!](https://black.readthedocs.io/en/stable)** --- @@ -52,8 +43,6 @@ _Black_ can be installed by running `pip install black`. It requires Python 3.6. run. If you want to format Python 2 code as well, install with `pip install black[python2]`. -#### Install from GitHub - If you can't wait for the latest _hotness_ and want to install from GitHub, use: `pip install git+git://github.com/psf/black` @@ -72,392 +61,72 @@ You can run _Black_ as a package if running it as a script doesn't work: python -m black {source_file_or_directory} ``` -### Command line options - -_Black_ doesn't provide many options. You can list them by running `black --help`: - -```text -Usage: black [OPTIONS] [SRC]... - - The uncompromising code formatter. - -Options: - -c, --code TEXT Format the code passed in as a string. - -l, --line-length INTEGER How many characters per line to allow. - [default: 88] - - -t, --target-version [py27|py33|py34|py35|py36|py37|py38|py39] - Python versions that should be supported by - Black's output. [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. - -C, --skip-magic-trailing-comma - Don't use trailing commas as a reason to - split lines. - - --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. - - --color / --no-color Show colored diff. Only applies when - `--diff` is given. - - --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: /(\.direnv|\.eggs|\.git|\. - hg|\.mypy_cache|\.nox|\.tox|\.venv|venv|\.sv - n|_build|buck-out|build|dist)/] - - --extend-exclude TEXT Like --exclude, but adds additional files - and directories on top of the excluded - ones (useful if you simply want to add to - the default). - - --force-exclude TEXT Like --exclude, but files and directories - matching this regex will be excluded even - when they are passed explicitly as - arguments. - - - --stdin-filename TEXT The name of the file when passing it through - stdin. Useful to make sure Black will - respect --force-exclude option on some - editors that rely on using stdin. - - -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 - exclusion patterns. - - --version Show the version and exit. - --config FILE Read configuration from FILE 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). - -### Using _Black_ with other tools - -While _Black_ enforces formatting that conforms to PEP 8, other tools may raise warnings -about _Black_'s changes or will overwrite _Black_'s changes. A good example of this is -[isort](https://pypi.org/p/isort). Since _Black_ is barely configurable, these tools -should be configured to neither warn about nor overwrite _Black_'s changes. - -Actual details on _Black_ compatible configurations for various tools can be found in -[compatible_configs](https://github.com/psf/black/blob/master/docs/compatible_configs.md#black-compatible-configurations). - -### Migrating your code style without ruining git blame - -A long-standing argument against moving to automated code formatters like _Black_ is -that the migration will clutter up the output of `git blame`. This was a valid argument, -but since Git version 2.23, Git natively supports -[ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt) -with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore -using the `--ignore-revs-file` option. The changes made by the revision will be ignored -when assigning blame. Lines modified by an ignored revision will be blamed on the -previous revision that modified those lines. - -So when migrating your project's code style to _Black_, reformat everything and commit -the changes (preferably in one massive commit). Then put the full 40 characters commit -identifier(s) into a file. - -``` -# Migrate code style to Black -5b4ab991dede475d393e9d69ec388fd6bd949699 -``` - -Afterwards, you can pass that file to `git blame` and see clean and meaningful blame -information. - -```console -$ git blame important.py --ignore-revs-file .git-blame-ignore-revs -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file): -abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip() -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f: -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted) -``` - -You can even configure `git` to automatically ignore revisions listed in a file on every -call to `git blame`. - -```console -$ git config blame.ignoreRevsFile .git-blame-ignore-revs -``` +Further information can be found in our docs: -**The one caveat is that GitHub and GitLab do not yet support ignoring revisions using -their native UI of blame.** So blame information will be cluttered with a reformatting -commit on those platforms. (If you'd like this feature, there's an open issue for -[GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub -know!) +- [Usage and Configuration](https://black.readthedocs.io/en/stable/usage_and_configuration/index.html) ### NOTE: This is a beta product _Black_ is already [successfully used](https://github.com/psf/black#used-by) by many -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. +projects, small and big. Black has a comprehensive test suite, with efficient parallel +tests, and our own auto formatting and parallel Continuous Integration runner. However, +_Black_ is still beta. Things will probably be wonky for a while. This is made explicit +by the "Beta" trove classifier, as well as by the "b" in the version number. What this +means for you is that **until the formatter becomes stable, you should expect some +formatting to change in the future**. That being said, no drastic stylistic changes are +planned, mostly responses to bug reports. Also, as a safety measure which slows down processing, _Black_ will check that the reformatted code still produces a valid AST that is effectively equivalent to the original (see the -[Pragmatism](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#pragmatism) +[Pragmatism](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#ast-before-and-after-formatting) section for details). If you're feeling confident, use `--fast`. ## The _Black_ code style _Black_ is a PEP 8 compliant opinionated formatter. _Black_ reformats entire files in -place. It is not configurable. It doesn't take previous formatting into account. Your -main option of configuring _Black_ is that it doesn't reformat blocks that start with -`# fmt: off` and end with `# fmt: on`, or lines that ends with `# fmt: skip`. Pay -attention that `# fmt: on/off` have to be on the same level of indentation. To learn -more about _Black_'s opinions, to go -[the_black_code_style](https://github.com/psf/black/blob/master/docs/the_black_code_style.md). +place. Style configuration options are deliberately limited and rarely added. It doesn't +take previous formatting into account (see [Pragmatism](#pragmatism) for exceptions). + +Our documentation covers the current _Black_ code style, but planned changes to it are +also documented. They're both worth taking a look: + +- [The _Black_ Code Style: Current style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html) +- [The _Black_ Code Style: Future style](https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html) Please refer to this document before submitting an issue. What seems like a bug might be intended behaviour. -## Pragmatism +### Pragmatism Early versions of _Black_ used to be absolutist in some respects. They took after its initial author. This was fine at the time as it made the implementation simpler and there were not many users anyway. Not many edge cases were reported. As a mature tool, -_Black_ does make some exceptions to rules it otherwise holds. This -[section](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#pragmatism) -of `the_black_code_style` describes what those exceptions are and why this is the case. +_Black_ does make some exceptions to rules it otherwise holds. + +- [The _Black_ code style: Pragmatism](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#pragmatism) Please refer to this document before submitting an issue just like with the document above. What seems like a bug might be intended behaviour. -## pyproject.toml +## Configuration _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`/`--extend-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://python-poetry.org/) 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 use a "global" configuration, stored in a specific location in your home -directory. This will be used as a fallback configuration, that is, it will be used if -and only if _Black_ doesn't find any configuration as mentioned above. Depending on your -operating system, this configuration file should be stored as: - -- Windows: `~\.black` -- Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the - `XDG_CONFIG_HOME` environment variable is not set) - -Note that these are paths to the TOML file itself (meaning that they shouldn't be named -as `pyproject.toml`), not directories where you store the configuration. Here, `~` -refers to the path to your home directory. On Windows, this will be something like -`C:\\Users\UserName`. - -You can also explicitly specify the path to a particular file that you want with -`--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. +`--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your +project. -
-Example pyproject.toml +You can find more details in our documentation: -```toml -[tool.black] -line-length = 88 -target-version = ['py37'] -include = '\.pyi?$' -extend-exclude = ''' -# A regex preceded with ^/ will apply only to files and directories -# in the root of the project. -^/foo.py # exclude a file named foo.py in the root of the project (in addition to the defaults) -''' -``` - -
- -### 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 - -_Black_ can be integrated into many editors with plugins. They let you run _Black_ on -your code with the ease of doing it in your editor. To get started using _Black_ in your -editor of choice, please see -[editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md). - -Patches are welcome for editors without an editor integration or plugin! More -information can be found in -[editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md#other-editors). - -## 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. Please refer to -[blackd](https://github.com/psf/black/blob/master/docs/blackd.md) to get the ball -rolling. - -## black-primer - -`black-primer` is a tool built for CI (and humans) to have _Black_ `--check` a number of -(configured in `primer.json`) Git accessible projects in parallel. -[black_primer](https://github.com/psf/black/blob/master/docs/black_primer.md) has more -information regarding its usage and configuration. - -(A PR adding Mercurial support will be accepted.) - -## 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/psf/black - rev: 20.8b1 # Replace by any tag/version: https://github.com/psf/black/tags - hooks: - - id: black - language_version: python3 # Should be a command that runs 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](https://github.com/psf/black/blob/master/pyproject.toml) for an -example. +- [The basics: Configuration via a file](https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#configuration-via-a-file) -If you're already using Python 3.7, switch the `language_version` accordingly. Finally, -`stable` is a branch that tracks the latest release on PyPI. If you'd rather run on -master, this is also an option. +And if you're looking for more general configuration documentation: -## GitHub Actions +- [Usage and Configuration](https://black.readthedocs.io/en/stable/usage_and_configuration/index.html) -Create a file named `.github/workflows/black.yml` inside your repository with: - -```yaml -name: Lint - -on: [push, pull_request] - -jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - uses: psf/black@stable -``` - -You may use `options` (Default is `'--check --diff'`) and `src` (Default is `'.'`) as -follows: - -```yaml -- uses: psf/black@stable - with: - options: "--check --verbose" - src: "./src" -``` - -## 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. - -To override the location of these files on macOS or Linux, set the environment variable -`XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache -in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will -then write the above files to `.cache/black//`. +**Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is +"No". _Black_ is all about sensible defaults. Applying those defaults will have your +code in compliance with many other _Black_ formatted projects. ## Used by @@ -513,209 +182,39 @@ Looks like this: MIT -## Contributing to _Black_ +## Contributing -In terms of inspiration, _Black_ is about as configurable as _gofmt_. This is -deliberate. +Welcome! Happy to see you willing to make the project better. You can get started by +reading this: -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. +- [Contributing: The basics](https://black.readthedocs.io/en/latest/contributing/the_basics.html) -More details can be found in -[CONTRIBUTING](https://github.com/psf/black/blob/master/CONTRIBUTING.md). +You can also take a look at the rest of the contributing docs or talk with the +developers: + +- [Contributing documentation](https://black.readthedocs.io/en/latest/contributing/index.html) +- [IRC channel on Freenode](https://webchat.freenode.net/?channels=%23blackformatter) ## Change log -The log's become rather long. It moved to its own file. +The log has become rather long. It moved to its own file. -See [CHANGES](https://github.com/psf/black/blob/master/CHANGES.md). +See [CHANGES](https://black.readthedocs.io/en/latest/change_log.html). ## 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), -[Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), -[Cooper Lees](mailto:me@cooperlees.com), and Richard Si. - -Multiple contributions by: - -- [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com) -- [Adam Johnson](mailto:me@adamj.eu) -- [Adam Williamson](mailto:adamw@happyassassin.net) -- [Alexander Huynh](mailto:github@grande.coffee) -- [Alex Vandiver](mailto:github@chmrr.net) -- [Allan Simon](mailto:allan.simon@supinfo.com) -- Anders-Petter Ljungquist -- [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com) -- [Andrew Zhou](mailto:andrewfzhou@gmail.com) -- [Andrey](mailto:dyuuus@yandex.ru) -- [Andy Freeland](mailto:andy@andyfreeland.net) -- [Anthony Sottile](mailto:asottile@umich.edu) -- [Arjaan Buijk](mailto:arjaan.buijk@gmail.com) -- [Arnav Borbornah](mailto:arnavborborah11@gmail.com) -- [Artem Malyshev](mailto:proofit404@gmail.com) -- [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com) -- [Augie Fackler](mailto:raf@durin42.com) -- [Aviskar KC](mailto:aviskarkc10@gmail.com) -- Batuhan Taşkaya -- [Benjamin Wohlwend](mailto:bw@piquadrat.ch) -- [Benjamin Woodruff](mailto:github@benjam.info) -- [Bharat Raghunathan](mailto:bharatraghunthan9767@gmail.com) -- [Brandt Bucher](mailto:brandtbucher@gmail.com) -- [Brett Cannon](mailto:brett@python.org) -- [Bryan Bugyi](mailto:bryan.bugyi@rutgers.edu) -- [Bryan Forbes](mailto:bryan@reigndropsfall.net) -- [Calum Lind](mailto:calumlind@gmail.com) -- [Charles](mailto:peacech@gmail.com) -- Charles Reid -- [Christian Clauss](mailto:cclauss@bluewin.ch) -- [Christian Heimes](mailto:christian@python.org) -- [Chuck Wooters](mailto:chuck.wooters@microsoft.com) -- [Chris Rose](mailto:offline@offby1.net) -- Codey Oxley -- [Cong](mailto:congusbongus@gmail.com) -- [Cooper Ry Lees](mailto:me@cooperlees.com) -- [Dan Davison](mailto:dandavison7@gmail.com) -- [Daniel Hahler](mailto:github@thequod.de) -- [Daniel M. Capella](mailto:polycitizen@gmail.com) -- Daniele Esposti -- [David Hotham](mailto:david.hotham@metaswitch.com) -- [David Lukes](mailto:dafydd.lukes@gmail.com) -- [David Szotten](mailto:davidszotten@gmail.com) -- [Denis Laxalde](mailto:denis@laxalde.org) -- [Douglas Thor](mailto:dthor@transphormusa.com) -- dylanjblack -- [Eli Treuherz](mailto:eli@treuherz.com) -- [Emil Hessman](mailto:emil@hessman.se) -- [Felix Kohlgrüber](mailto:felix.kohlgrueber@gmail.com) -- [Florent Thiery](mailto:fthiery@gmail.com) -- Francisco -- [Giacomo Tagliabue](mailto:giacomo.tag@gmail.com) -- [Greg Gandenberger](mailto:ggandenberger@shoprunner.com) -- [Gregory P. Smith](mailto:greg@krypto.org) -- Gustavo Camargo -- hauntsaninja -- [Hadi Alqattan](mailto:alqattanhadizaki@gmail.com) -- [Heaford](mailto:dan@heaford.com) -- [Hugo Barrera](mailto::hugo@barrera.io) -- Hugo van Kemenade -- [Hynek Schlawack](mailto:hs@ox.cx) -- [Ivan Katanić](mailto:ivan.katanic@gmail.com) -- [Jakub Kadlubiec](mailto:jakub.kadlubiec@skyscanner.net) -- [Jakub Warczarek](mailto:jakub.warczarek@gmail.com) -- [Jan Hnátek](mailto:jan.hnatek@gmail.com) -- [Jason Fried](mailto:me@jasonfried.info) -- [Jason Friedland](mailto:jason@friedland.id.au) -- [jgirardet](mailto:ijkl@netc.fr) -- Jim Brännlund -- [Jimmy Jia](mailto:tesrin@gmail.com) -- [Joe Antonakakis](mailto:jma353@cornell.edu) -- [Jon Dufresne](mailto:jon.dufresne@gmail.com) -- [Jonas Obrist](mailto:ojiidotch@gmail.com) -- [Jonty Wareing](mailto:jonty@jonty.co.uk) -- [Jose Nazario](mailto:jose.monkey.org@gmail.com) -- [Joseph Larson](mailto:larson.joseph@gmail.com) -- [Josh Bode](mailto:joshbode@fastmail.com) -- [Josh Holland](mailto:anowlcalledjosh@gmail.com) -- [Joshua Cannon](mailto:joshdcannon@gmail.com) -- [José Padilla](mailto:jpadilla@webapplicate.com) -- [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space) -- [kaiix](mailto:kvn.hou@gmail.com) -- [Katie McLaughlin](mailto:katie@glasnt.com) -- Katrin Leinweber -- [Keith Smiley](mailto:keithbsmiley@gmail.com) -- [Kenyon Ralph](mailto:kenyon@kenyonralph.com) -- [Kevin Kirsche](mailto:Kev.Kirsche+GitHub@gmail.com) -- [Kyle Hausmann](mailto:kyle.hausmann@gmail.com) -- [Kyle Sunden](mailto:sunden@wisc.edu) -- Lawrence Chan -- [Linus Groh](mailto:mail@linusgroh.de) -- [Loren Carvalho](mailto:comradeloren@gmail.com) -- [Luka Sterbic](mailto:luka.sterbic@gmail.com) -- [LukasDrude](mailto:mail@lukas-drude.de) -- Mahmoud Hossam -- Mariatta -- [Matt VanEseltine](mailto:vaneseltine@gmail.com) -- [Matthew Clapp](mailto:itsayellow+dev@gmail.com) -- [Matthew Walster](mailto:matthew@walster.org) -- Max Smolens -- [Michael Aquilina](mailto:michaelaquilina@gmail.com) -- [Michael Flaxman](mailto:michael.flaxman@gmail.com) -- [Michael J. Sullivan](mailto:sully@msully.net) -- [Michael McClimon](mailto:michael@mcclimon.org) -- [Miguel Gaiowski](mailto:miggaiowski@gmail.com) -- [Mike](mailto:roshi@fedoraproject.org) -- [mikehoyio](mailto:mikehoy@gmail.com) -- [Min ho Kim](mailto:minho42@gmail.com) -- [Miroslav Shubernetskiy](mailto:miroslav@miki725.com) -- MomIsBestFriend -- [Nathan Goldbaum](mailto:ngoldbau@illinois.edu) -- [Nathan Hunt](mailto:neighthan.hunt@gmail.com) -- [Neraste](mailto:neraste.herr10@gmail.com) -- [Nikolaus Waxweiler](mailto:madigens@gmail.com) -- [Ofek Lev](mailto:ofekmeister@gmail.com) -- [Osaetin Daniel](mailto:osaetindaniel@gmail.com) -- [otstrel](mailto:otstrel@gmail.com) -- [Pablo Galindo](mailto:Pablogsal@gmail.com) -- [Paul Ganssle](mailto:p.ganssle@gmail.com) -- [Paul Meinhardt](mailto:mnhrdt@gmail.com) -- [Peter Bengtsson](mailto:mail@peterbe.com) -- [Peter Grayson](mailto:pete@jpgrayson.net) -- [Peter Stensmyr](mailto:peter.stensmyr@gmail.com) -- pmacosta -- [Quentin Pradet](mailto:quentin@pradet.me) -- [Ralf Schmitt](mailto:ralf@systemexit.de) -- [Ramón Valles](mailto:mroutis@protonmail.com) -- [Richard Fearn](mailto:richardfearn@gmail.com) -- Richard Si -- [Rishikesh Jha](mailto:rishijha424@gmail.com) -- [Rupert Bedford](mailto:rupert@rupertb.com) -- Russell Davis -- [Rémi Verschelde](mailto:rverschelde@gmail.com) -- [Sami Salonen](mailto:sakki@iki.fi) -- [Samuel Cormier-Iijima](mailto:samuel@cormier-iijima.com) -- [Sanket Dasgupta](mailto:sanketdasgupta@gmail.com) -- Sergi -- [Scott Stevenson](mailto:scott@stevenson.io) -- Shantanu -- [shaoran](mailto:shaoran@sakuranohana.org) -- [Shinya Fujino](mailto:shf0811@gmail.com) -- springstan -- [Stavros Korokithakis](mailto:hi@stavros.io) -- [Stephen Rosen](mailto:sirosen@globus.org) -- [Steven M. Vascellaro](mailto:S.Vascellaro@gmail.com) -- [Sunil Kapil](mailto:snlkapil@gmail.com) -- [Sébastien Eustace](mailto:sebastien.eustace@gmail.com) -- [Tal Amuyal](mailto:TalAmuyal@gmail.com) -- [Terrance](mailto:git@terrance.allofti.me) -- [Thom Lu](mailto:thomas.c.lu@gmail.com) -- [Thomas Grainger](mailto:tagrain@gmail.com) -- [Tim Gates](mailto:tim.gates@iress.com) -- [Tim Swast](mailto:swast@google.com) -- [Timo](mailto:timo_tk@hotmail.com) -- Toby Fleming -- [Tom Christie](mailto:tom@tomchristie.com) -- [Tony Narlock](mailto:tony@git-pull.com) -- [Tsuyoshi Hombashi](mailto:tsuyoshi.hombashi@gmail.com) -- [Tushar Chandra](mailto:tusharchandra2018@u.northwestern.edu) -- [Tzu-ping Chung](mailto:uranusjr@gmail.com) -- [Utsav Shah](mailto:ukshah2@illinois.edu) -- utsav-dbx -- vezeli -- [Ville Skyttä](mailto:ville.skytta@iki.fi) -- [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com) -- [Vlad Emelianov](mailto:volshebnyi@gmail.com) -- [williamfzc](mailto:178894043@qq.com) -- [wouter bolsterlee](mailto:wouter@bolsterl.ee) -- Yazdan -- [Yngve Høiseth](mailto:yngve@hoiseth.net) -- [Yurii Karabas](mailto:1998uriyyo@gmail.com) -- [Zac Hatfield-Dodds](mailto:zac@zhd.dev) +The author list is quite long nowadays, so it lives in its own file. + +See [AUTHORS.md](./AUTHORS.md) + +## Code of Conduct + +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. diff --git a/docs/authors.md b/docs/authors.md deleted file mode 100644 index 9f2ea05..0000000 --- a/docs/authors.md +++ /dev/null @@ -1,187 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# 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), -[Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), and -[Cooper Lees](mailto:me@cooperlees.com). - -Multiple contributions by: - -- [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com) -- [Adam Johnson](mailto:me@adamj.eu) -- [Adam Williamson](mailto:adamw@happyassassin.net) -- [Alexander Huynh](mailto:github@grande.coffee) -- [Alex Vandiver](mailto:github@chmrr.net) -- [Allan Simon](mailto:allan.simon@supinfo.com) -- Anders-Petter Ljungquist -- [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com) -- [Andrew Zhou](mailto:andrewfzhou@gmail.com) -- [Andrey](mailto:dyuuus@yandex.ru) -- [Andy Freeland](mailto:andy@andyfreeland.net) -- [Anthony Sottile](mailto:asottile@umich.edu) -- [Arjaan Buijk](mailto:arjaan.buijk@gmail.com) -- [Arnav Borbornah](mailto:arnavborborah11@gmail.com) -- [Artem Malyshev](mailto:proofit404@gmail.com) -- [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com) -- [Augie Fackler](mailto:raf@durin42.com) -- [Aviskar KC](mailto:aviskarkc10@gmail.com) -- Batuhan Taşkaya -- [Benjamin Wohlwend](mailto:bw@piquadrat.ch) -- [Benjamin Woodruff](mailto:github@benjam.info) -- [Bharat Raghunathan](mailto:bharatraghunthan9767@gmail.com) -- [Brandt Bucher](mailto:brandtbucher@gmail.com) -- [Brett Cannon](mailto:brett@python.org) -- [Bryan Bugyi](mailto:bryan.bugyi@rutgers.edu) -- [Bryan Forbes](mailto:bryan@reigndropsfall.net) -- [Calum Lind](mailto:calumlind@gmail.com) -- [Charles](mailto:peacech@gmail.com) -- Charles Reid -- [Christian Clauss](mailto:cclauss@bluewin.ch) -- [Christian Heimes](mailto:christian@python.org) -- [Chuck Wooters](mailto:chuck.wooters@microsoft.com) -- [Chris Rose](mailto:offline@offby1.net) -- Codey Oxley -- [Cong](mailto:congusbongus@gmail.com) -- [Cooper Ry Lees](mailto:me@cooperlees.com) -- [Dan Davison](mailto:dandavison7@gmail.com) -- [Daniel Hahler](mailto:github@thequod.de) -- [Daniel M. Capella](mailto:polycitizen@gmail.com) -- Daniele Esposti -- [David Hotham](mailto:david.hotham@metaswitch.com) -- [David Lukes](mailto:dafydd.lukes@gmail.com) -- [David Szotten](mailto:davidszotten@gmail.com) -- [Denis Laxalde](mailto:denis@laxalde.org) -- [Douglas Thor](mailto:dthor@transphormusa.com) -- dylanjblack -- [Eli Treuherz](mailto:eli@treuherz.com) -- [Emil Hessman](mailto:emil@hessman.se) -- [Felix Kohlgrüber](mailto:felix.kohlgrueber@gmail.com) -- [Florent Thiery](mailto:fthiery@gmail.com) -- Francisco -- [Giacomo Tagliabue](mailto:giacomo.tag@gmail.com) -- [Greg Gandenberger](mailto:ggandenberger@shoprunner.com) -- [Gregory P. Smith](mailto:greg@krypto.org) -- Gustavo Camargo -- hauntsaninja -- [Hadi Alqattan](mailto:alqattanhadizaki@gmail.com) -- [Heaford](mailto:dan@heaford.com) -- [Hugo Barrera](mailto::hugo@barrera.io) -- Hugo van Kemenade -- [Hynek Schlawack](mailto:hs@ox.cx) -- [Ivan Katanić](mailto:ivan.katanic@gmail.com) -- [Jakub Kadlubiec](mailto:jakub.kadlubiec@skyscanner.net) -- [Jakub Warczarek](mailto:jakub.warczarek@gmail.com) -- [Jan Hnátek](mailto:jan.hnatek@gmail.com) -- [Jason Fried](mailto:me@jasonfried.info) -- [Jason Friedland](mailto:jason@friedland.id.au) -- [jgirardet](mailto:ijkl@netc.fr) -- Jim Brännlund -- [Jimmy Jia](mailto:tesrin@gmail.com) -- [Joe Antonakakis](mailto:jma353@cornell.edu) -- [Jon Dufresne](mailto:jon.dufresne@gmail.com) -- [Jonas Obrist](mailto:ojiidotch@gmail.com) -- [Jonty Wareing](mailto:jonty@jonty.co.uk) -- [Jose Nazario](mailto:jose.monkey.org@gmail.com) -- [Joseph Larson](mailto:larson.joseph@gmail.com) -- [Josh Bode](mailto:joshbode@fastmail.com) -- [Josh Holland](mailto:anowlcalledjosh@gmail.com) -- [José Padilla](mailto:jpadilla@webapplicate.com) -- [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space) -- [kaiix](mailto:kvn.hou@gmail.com) -- [Katie McLaughlin](mailto:katie@glasnt.com) -- Katrin Leinweber -- [Keith Smiley](mailto:keithbsmiley@gmail.com) -- [Kenyon Ralph](mailto:kenyon@kenyonralph.com) -- [Kevin Kirsche](mailto:Kev.Kirsche+GitHub@gmail.com) -- [Kyle Hausmann](mailto:kyle.hausmann@gmail.com) -- [Kyle Sunden](mailto:sunden@wisc.edu) -- Lawrence Chan -- [Linus Groh](mailto:mail@linusgroh.de) -- [Loren Carvalho](mailto:comradeloren@gmail.com) -- [Luka Sterbic](mailto:luka.sterbic@gmail.com) -- [LukasDrude](mailto:mail@lukas-drude.de) -- Mahmoud Hossam -- Mariatta -- [Matt VanEseltine](mailto:vaneseltine@gmail.com) -- [Matthew Clapp](mailto:itsayellow+dev@gmail.com) -- [Matthew Walster](mailto:matthew@walster.org) -- Max Smolens -- [Michael Aquilina](mailto:michaelaquilina@gmail.com) -- [Michael Flaxman](mailto:michael.flaxman@gmail.com) -- [Michael J. Sullivan](mailto:sully@msully.net) -- [Michael McClimon](mailto:michael@mcclimon.org) -- [Miguel Gaiowski](mailto:miggaiowski@gmail.com) -- [Mike](mailto:roshi@fedoraproject.org) -- [mikehoyio](mailto:mikehoy@gmail.com) -- [Min ho Kim](mailto:minho42@gmail.com) -- [Miroslav Shubernetskiy](mailto:miroslav@miki725.com) -- MomIsBestFriend -- [Nathan Goldbaum](mailto:ngoldbau@illinois.edu) -- [Nathan Hunt](mailto:neighthan.hunt@gmail.com) -- [Neraste](mailto:neraste.herr10@gmail.com) -- [Nikolaus Waxweiler](mailto:madigens@gmail.com) -- [Ofek Lev](mailto:ofekmeister@gmail.com) -- [Osaetin Daniel](mailto:osaetindaniel@gmail.com) -- [otstrel](mailto:otstrel@gmail.com) -- [Pablo Galindo](mailto:Pablogsal@gmail.com) -- [Paul Ganssle](mailto:p.ganssle@gmail.com) -- [Paul Meinhardt](mailto:mnhrdt@gmail.com) -- [Paul "TBBle" Hampson](mailto:Paul.Hampson@Pobox.com) -- [Peter Bengtsson](mailto:mail@peterbe.com) -- [Peter Grayson](mailto:pete@jpgrayson.net) -- [Peter Stensmyr](mailto:peter.stensmyr@gmail.com) -- pmacosta -- [Quentin Pradet](mailto:quentin@pradet.me) -- [Ralf Schmitt](mailto:ralf@systemexit.de) -- [Ramón Valles](mailto:mroutis@protonmail.com) -- [Richard Fearn](mailto:richardfearn@gmail.com) -- Richard Si -- [Rishikesh Jha](mailto:rishijha424@gmail.com) -- [Rupert Bedford](mailto:rupert@rupertb.com) -- Russell Davis -- [Rémi Verschelde](mailto:rverschelde@gmail.com) -- [Sami Salonen](mailto:sakki@iki.fi) -- [Samuel Cormier-Iijima](mailto:samuel@cormier-iijima.com) -- [Sanket Dasgupta](mailto:sanketdasgupta@gmail.com) -- Sergi -- [Scott Stevenson](mailto:scott@stevenson.io) -- Shantanu -- [shaoran](mailto:shaoran@sakuranohana.org) -- [Shinya Fujino](mailto:shf0811@gmail.com) -- springstan -- [Stavros Korokithakis](mailto:hi@stavros.io) -- [Stephen Rosen](mailto:sirosen@globus.org) -- [Steven M. Vascellaro](mailto:S.Vascellaro@gmail.com) -- [Sunil Kapil](mailto:snlkapil@gmail.com) -- [Sébastien Eustace](mailto:sebastien.eustace@gmail.com) -- [Tal Amuyal](mailto:TalAmuyal@gmail.com) -- [Terrance](mailto:git@terrance.allofti.me) -- [Thom Lu](mailto:thomas.c.lu@gmail.com) -- [Thomas Grainger](mailto:tagrain@gmail.com) -- [Tim Gates](mailto:tim.gates@iress.com) -- [Tim Swast](mailto:swast@google.com) -- [Timo](mailto:timo_tk@hotmail.com) -- Toby Fleming -- [Tom Christie](mailto:tom@tomchristie.com) -- [Tony Narlock](mailto:tony@git-pull.com) -- [Tsuyoshi Hombashi](mailto:tsuyoshi.hombashi@gmail.com) -- [Tushar Chandra](mailto:tusharchandra2018@u.northwestern.edu) -- [Tzu-ping Chung](mailto:uranusjr@gmail.com) -- [Utsav Shah](mailto:ukshah2@illinois.edu) -- utsav-dbx -- vezeli -- [Ville Skyttä](mailto:ville.skytta@iki.fi) -- [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com) -- [Vlad Emelianov](mailto:volshebnyi@gmail.com) -- [williamfzc](mailto:178894043@qq.com) -- [wouter bolsterlee](mailto:wouter@bolsterl.ee) -- Yazdan -- [Yngve Høiseth](mailto:yngve@hoiseth.net) -- [Yurii Karabas](mailto:1998uriyyo@gmail.com) -- [Zac Hatfield-Dodds](mailto:zac@zhd.dev) diff --git a/docs/authors.md b/docs/authors.md new file mode 120000 index 0000000..3234d6e --- /dev/null +++ b/docs/authors.md @@ -0,0 +1 @@ +../AUTHORS.md \ No newline at end of file diff --git a/docs/black_primer.md b/docs/black_primer.md deleted file mode 100644 index a2dd964..0000000 --- a/docs/black_primer.md +++ /dev/null @@ -1,120 +0,0 @@ -# black-primer - -`black-primer` is a tool built for CI (and humans) to have _Black_ `--check` a number of -(configured in `primer.json`) Git accessible projects in parallel. _(A PR will be -accepted to add Mercurial support.)_ - -## Run flow - -- Ensure we have a `black` + `git` in PATH -- Load projects from `primer.json` -- Run projects in parallel with `--worker` workers (defaults to CPU count / 2) - - Checkout projects - - Run black and record result - - Clean up repository checkout _(can optionally be disabled via `--keep`)_ -- Display results summary to screen -- Default to cleaning up `--work-dir` (which defaults to tempfile schemantics) -- Return - - 0 for successful run - - < 0 for environment / internal error - - \> 0 for each project with an error - -## Speed up runs 🏎 - -If you're running locally yourself to test black on lots of code try: - -- Using `-k` / `--keep` + `-w` / `--work-dir` so you don't have to re-checkout the repo - each run - -## CLI arguments - -```text -Usage: black-primer [OPTIONS] - - primer - prime projects for blackening... 🏴 - -Options: - -c, --config PATH JSON config file path [default: /Users/cooper/repos/ - black/src/black_primer/primer.json] - - --debug Turn on debug logging [default: False] - -k, --keep Keep workdir + repos post run [default: False] - -L, --long-checkouts Pull big projects to test [default: False] - -R, --rebase Rebase project if already checked out [default: - False] - - -w, --workdir PATH Directory path for repo checkouts [default: /var/fol - ders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/primer.20200 - 517125229] - - -W, --workers INTEGER Number of parallel worker coroutines [default: 2] - -h, --help Show this message and exit. -``` - -## Primer config file - -The config file is in JSON format. Its main element is the `"projects"` dictionary and -each parameter is explained below: - -```json -{ - "projects": { - "00_Example": { - "cli_arguments": "List of extra CLI arguments to pass Black for this project", - "expect_formatting_changes": "Boolean to indicate that the version of Black is expected to cause changes", - "git_clone_url": "URL you would pass `git clone` to check out this repo", - "long_checkout": "Boolean to have repo skipped by default unless `--long-checkouts` is specified", - "py_versions": "List of major Python versions to run this project with - all will do as you'd expect - run on ALL versions" - }, - "aioexabgp": { - "cli_arguments": [], - "expect_formatting_changes": true, - "git_clone_url": "https://github.com/cooperlees/aioexabgp.git", - "long_checkout": false, - "py_versions": ["all", "3.8"] - } - } -} -``` - -An example primer config file is used by Black -[here](https://github.com/psf/black/blob/master/src/black_primer/primer.json) - -## Example run - -```console -cooper-mbp:black cooper$ ~/venvs/b/bin/black-primer -[2020-05-17 13:06:40,830] INFO: 4 projects to run Black over (lib.py:270) -[2020-05-17 13:06:44,215] INFO: Analyzing results (lib.py:285) --- primer results 📊 -- - -3 / 4 succeeded (75.0%) ✅ -1 / 4 FAILED (25.0%) 💩 - - 0 projects disabled by config - - 0 projects skipped due to Python version - - 0 skipped due to long checkout - -Failed projects: - -## flake8-bugbear: - - Returned 1 - - stdout: ---- tests/b303_b304.py 2020-05-17 20:04:09.991227 +0000 -+++ tests/b303_b304.py 2020-05-17 20:06:42.753851 +0000 -@@ -26,11 +26,11 @@ - maxint = 5 # this is okay - # the following should not crash - (a, b, c) = list(range(3)) - # it is different than this - a, b, c = list(range(3)) -- a, b, c, = list(range(3)) -+ a, b, c = list(range(3)) - # and different than this - (a, b), c = list(range(3)) - a, *b, c = [1, 2, 3, 4, 5] - b[1:3] = [0, 0] - -would reformat tests/b303_b304.py -Oh no! 💥 💔 💥 -1 file would be reformatted, 22 files would be left unchanged. -``` diff --git a/docs/conf.py b/docs/conf.py index 9e03d05..d567373 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -13,60 +13,11 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. # from pathlib import Path -import re import string -from typing import Callable, Dict, List, Optional, Pattern, Tuple, Set -from dataclasses import dataclass -import logging from pkg_resources import get_distribution -logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO) - -LOG = logging.getLogger(__name__) - CURRENT_DIR = Path(__file__).parent -README = CURRENT_DIR / ".." / "README.md" -REFERENCE_DIR = CURRENT_DIR / "reference" -STATIC_DIR = CURRENT_DIR / "_static" - - -@dataclass -class SrcRange: - """Tracks which part of a file to get a section's content. - - Data: - start_line: The line where the section starts (i.e. its sub-header) (inclusive). - end_line: The line where the section ends (usually next sub-header) (exclusive). - """ - - start_line: int - end_line: int - - -@dataclass -class DocSection: - """Tracks information about a section of documentation. - - Data: - name: The section's name. This will used to detect duplicate sections. - src: The filepath to get its contents. - processors: The processors to run before writing the section to CURRENT_DIR. - out_filename: The filename to use when writing the section to CURRENT_DIR. - src_range: The line range of SRC to gets its contents. - """ - - name: str - src: Path - src_range: SrcRange = SrcRange(0, 1_000_000) - out_filename: str = "" - processors: Tuple[Callable, ...] = () - - def get_out_filename(self) -> str: - if not self.out_filename: - return self.name + ".md" - else: - return self.out_filename def make_pypi_svg(version: str) -> None: @@ -78,131 +29,10 @@ def make_pypi_svg(version: str) -> None: f.write(svg) -def make_filename(line: str) -> str: - non_letters: Pattern = re.compile(r"[^a-z]+") - filename: str = line[3:].rstrip().lower() - filename = non_letters.sub("_", filename) - if filename.startswith("_"): - filename = filename[1:] - if filename.endswith("_"): - filename = filename[:-1] - return filename + ".md" - - -def get_contents(section: DocSection) -> str: - """Gets the contents for the DocSection.""" - contents: List[str] = [] - src: Path = section.src - start_line: int = section.src_range.start_line - end_line: int = section.src_range.end_line - with open(src, "r", encoding="utf-8") as f: - for lineno, line in enumerate(f, start=1): - if lineno >= start_line and lineno < end_line: - contents.append(line) - result = "".join(contents) - # Let's make Prettier happy with the amount of trailing newlines in the sections. - if result.endswith("\n\n"): - result = result[:-1] - if not result.endswith("\n"): - result = result + "\n" - return result - - -def get_sections_from_readme() -> List[DocSection]: - """Gets the sections from README so they can be processed by process_sections. - - It opens README and goes down line by line looking for sub-header lines which - denotes a section. Once it finds a sub-header line, it will create a DocSection - object with all of the information currently available. Then on every line, it will - track the ending line index of the section. And it repeats this for every sub-header - line it finds. - """ - sections: List[DocSection] = [] - section: Optional[DocSection] = None - with open(README, "r", encoding="utf-8") as f: - for lineno, line in enumerate(f, start=1): - if line.startswith("## "): - filename = make_filename(line) - section_name = filename[:-3] - section = DocSection( - name=str(section_name), - src=README, - src_range=SrcRange(lineno, lineno), - out_filename=filename, - processors=(fix_headers,), - ) - sections.append(section) - if section is not None: - section.src_range.end_line += 1 - return sections - - -def fix_headers(contents: str) -> str: - """Fixes the headers of sections copied from README. - - Removes one octothorpe (#) from all headers since the contents are no longer nested - in a root document (i.e. the README). - """ - lines: List[str] = contents.splitlines() - fixed_contents: List[str] = [] - for line in lines: - if line.startswith("##"): - line = line[1:] - fixed_contents.append(line + "\n") # splitlines strips the leading newlines - return "".join(fixed_contents) - - -def process_sections( - custom_sections: List[DocSection], readme_sections: List[DocSection] -) -> None: - """Reads, processes, and writes sections to CURRENT_DIR. - - For each section, the contents will be fetched, processed by processors - required by the section, and written to CURRENT_DIR. If it encounters duplicate - sections (i.e. shares the same name attribute), it will skip processing the - duplicates. - - It processes custom sections before the README generated sections so sections in the - README can be overwritten with custom options. - """ - processed_sections: Dict[str, DocSection] = {} - modified_files: Set[Path] = set() - sections: List[DocSection] = custom_sections - sections.extend(readme_sections) - for section in sections: - if section.name in processed_sections: - LOG.warning( - f"Skipping '{section.name}' from '{section.src}' as it is a duplicate" - f" of a custom section from '{processed_sections[section.name].src}'" - ) - continue - - LOG.info(f"Processing '{section.name}' from '{section.src}'") - target_path: Path = CURRENT_DIR / section.get_out_filename() - if target_path in modified_files: - LOG.warning( - f"{target_path} has been already written to, its contents will be" - " OVERWRITTEN and notices will be duplicated" - ) - contents: str = get_contents(section) - - # processors goes here - if fix_headers in section.processors: - contents = fix_headers(contents) - - with open(target_path, "w", encoding="utf-8") as f: - if section.src.suffix == ".md" and section.src != target_path: - rel = section.src.resolve().relative_to(CURRENT_DIR.parent) - f.write(f'[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM {rel}"\n\n') - f.write(contents) - processed_sections[section.name] = section - modified_files.add(target_path) - - # -- Project information ----------------------------------------------------- project = "Black" -copyright = "2020, Łukasz Langa and contributors to Black" +copyright = "2018-Present, Łukasz Langa and contributors to Black" author = "Łukasz Langa and contributors to Black" # Autopopulate version @@ -213,33 +43,7 @@ version = release for sp in "abcfr": version = version.split(sp)[0] -custom_sections = [ - DocSection("the_black_code_style", CURRENT_DIR / "the_black_code_style.md"), - DocSection("editor_integration", CURRENT_DIR / "editor_integration.md"), - DocSection("blackd", CURRENT_DIR / "blackd.md"), - DocSection("black_primer", CURRENT_DIR / "black_primer.md"), - DocSection("contributing_to_black", CURRENT_DIR / ".." / "CONTRIBUTING.md"), -] - -# Sphinx complains when there is a source file that isn't referenced in any of the docs. -# Since some sections autogenerated from the README are unused warnings will appear. -# -# Sections must be listed to what their name is when passed through make_filename(). -blocklisted_sections_from_readme = { - "license", - "pragmatism", - "testimonials", - "used_by", - "change_log", -} - make_pypi_svg(release) -readme_sections = get_sections_from_readme() -readme_sections = [ - x for x in readme_sections if x.name not in blocklisted_sections_from_readme -] - -process_sections(custom_sections, readme_sections) # -- General configuration --------------------------------------------------- @@ -254,11 +58,11 @@ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", - "recommonmark", + "myst_parser", ] # If you need extensions of a certain version or higher, list them here. -needs_extensions = {"recommonmark": "0.5"} +needs_extensions = {"myst_parser": "0.13.7"} # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] @@ -286,6 +90,17 @@ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" +# We need headers to be linkable to so ask MyST-Parser to autogenerate anchor IDs for +# headers up to and including level 3. +myst_heading_anchors = 3 + +# Prettier support formatting some MyST syntax but not all, so let's disable the +# unsupported yet still enabled by default ones. +myst_disable_syntax = [ + "myst_block_break", + "myst_line_comment", + "math_block", +] # -- Options for HTML output ------------------------------------------------- @@ -299,7 +114,6 @@ html_sidebars = { "about.html", "navigation.html", "relations.html", - "sourcelink.html", "searchbox.html", ] } @@ -341,21 +155,6 @@ htmlhelp_basename = "blackdoc" # -- Options for LaTeX output ------------------------------------------------ -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). diff --git a/docs/contributing/gauging_changes.md b/docs/contributing/gauging_changes.md new file mode 100644 index 0000000..6b70e0b --- /dev/null +++ b/docs/contributing/gauging_changes.md @@ -0,0 +1,61 @@ +# Gauging changes + +A lot of the time, your change will affect formatting and/or performance. Quantifying +these changes is hard, so we have tooling to help make it easier. + +It's recommended you evaluate the quantifiable changes your _Black_ formatting +modification causes before submitting a PR. Think about if the change seems disruptive +enough to cause frustration to projects that are already "black formatted". + +## black-primer + +`black-primer` is a tool built for CI (and humans) to have _Black_ `--check` a number of +Git accessible projects in parallel. (configured in `primer.json`) _(A PR will be +accepted to add Mercurial support.)_ + +### Run flow + +- Ensure we have a `black` + `git` in PATH +- Load projects from `primer.json` +- Run projects in parallel with `--worker` workers (defaults to CPU count / 2) + - Checkout projects + - Run black and record result + - Clean up repository checkout _(can optionally be disabled via `--keep`)_ +- Display results summary to screen +- Default to cleaning up `--work-dir` (which defaults to tempfile schemantics) +- Return + - 0 for successful run + - \< 0 for environment / internal error + - \> 0 for each project with an error + +### Speed up runs 🏎 + +If you're running locally yourself to test black on lots of code try: + +- Using `-k` / `--keep` + `-w` / `--work-dir` so you don't have to re-checkout the repo + each run + +### CLI arguments + +```text +Usage: black-primer [OPTIONS] + + primer - prime projects for blackening... 🏴 + +Options: + -c, --config PATH JSON config file path [default: /Users/cooper/repos/ + black/src/black_primer/primer.json] + + --debug Turn on debug logging [default: False] + -k, --keep Keep workdir + repos post run [default: False] + -L, --long-checkouts Pull big projects to test [default: False] + -R, --rebase Rebase project if already checked out [default: + False] + + -w, --workdir PATH Directory path for repo checkouts [default: /var/fol + ders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/primer.20200 + 517125229] + + -W, --workers INTEGER Number of parallel worker coroutines [default: 2] + -h, --help Show this message and exit. +``` diff --git a/docs/contributing/index.rst b/docs/contributing/index.rst new file mode 100644 index 0000000..68dfcd6 --- /dev/null +++ b/docs/contributing/index.rst @@ -0,0 +1,39 @@ +Contributing +============ + +.. toctree:: + :hidden: + + the_basics + gauging_changes + reference/reference_summary + +Welcome! Happy to see you willing to make the project better. Have you read the entire +`user documentation `_ yet? + +.. rubric:: Bird's eye view + +In terms of inspiration, *Black* is about as configurable as *gofmt*. This is +deliberate. + +Bug reports and fixes are always welcome! Please follow the +`issue template on GitHub `_ for best results. + +Before you suggest a new feature or configuration knob, ask yourself why you want it. If +it enables better integration with some workflow, fixes an inconsistency, speeds things +up, and so on - go for it! On the other hand, if your answer is "because I don't like a +particular formatting" then you're not ready to embrace *Black* yet. Such changes are +unlikely to get accepted. You can still try but prepare to be disappointed. + +.. rubric:: Contents + +This section covers the following topics: + +- :doc:`the_basics` +- :doc:`gauging_changes` +- :doc:`reference/reference_summary` + +For an overview on contributing to the *Black*, please checkout :doc:`the_basics`. + +If you need a reference of the functions, classes, etc. available to you while +developing *Black*, there's the :doc:`reference/reference_summary` docs. diff --git a/docs/reference/reference_classes.rst b/docs/contributing/reference/reference_classes.rst similarity index 100% rename from docs/reference/reference_classes.rst rename to docs/contributing/reference/reference_classes.rst diff --git a/docs/reference/reference_exceptions.rst b/docs/contributing/reference/reference_exceptions.rst similarity index 100% rename from docs/reference/reference_exceptions.rst rename to docs/contributing/reference/reference_exceptions.rst diff --git a/docs/reference/reference_functions.rst b/docs/contributing/reference/reference_functions.rst similarity index 100% rename from docs/reference/reference_functions.rst rename to docs/contributing/reference/reference_functions.rst diff --git a/docs/reference/reference_summary.rst b/docs/contributing/reference/reference_summary.rst similarity index 51% rename from docs/reference/reference_summary.rst rename to docs/contributing/reference/reference_summary.rst index 780a4b4..f6ff468 100644 --- a/docs/reference/reference_summary.rst +++ b/docs/contributing/reference/reference_summary.rst @@ -1,6 +1,11 @@ Developer reference =================== +.. note:: + + The documentation here is quite outdated and has been neglected. Many objects worthy + of inclusion aren't documented. Contributions are appreciated! + *Contents are subject to change.* .. toctree:: diff --git a/docs/contributing_to_black.md b/docs/contributing/the_basics.md similarity index 68% rename from docs/contributing_to_black.md rename to docs/contributing/the_basics.md index b911b46..461bff9 100644 --- a/docs/contributing_to_black.md +++ b/docs/contributing/the_basics.md @@ -1,28 +1,11 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM CONTRIBUTING.md" +# The basics -# 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/psf/black/issues/new) for best results. - -Before you suggest a new feature or configuration knob, ask yourself why you want it. If -it enables better integration with some workflow, fixes an inconsistency, speeds things -up, and so on - go for it! On the other hand, if your answer is "because I don't like a -particular formatting" then you're not ready to embrace _Black_ yet. Such changes are -unlikely to get accepted. You can still try but prepare to be disappointed. +An overview on contributing to the _Black_ project. ## Technicalities Development on the latest version of Python is preferred. As of this writing it's 3.9. -You can use any operating system. I am using macOS myself and CentOS at work. +You can use any operating system. Install all development dependencies using: @@ -63,7 +46,7 @@ $ black-primer [-k -w /tmp/black_test_repos] ### News / Changelog Requirement `Black` has CI that will check for an entry corresponding to your PR in `CHANGES.md`. If -you feel this PR not require a changelog entry please state that in a comment and a +you feel this PR does not require a changelog entry please state that in a comment and a maintainer can add a `skip news` label to make the CI pass. Otherwise, please ensure you have a line in the following format: @@ -71,11 +54,17 @@ have a line in the following format: - `Black` is now more awesome (#X) ``` -To workout X, please use +Note that X should be your PR number, not issue number! To workout X, please use [Next PR Number](https://ichard26.github.io/next-pr-number/?owner=psf&name=black). This is not perfect but saves a lot of release overhead as now the releaser does not need to go back and workout what to add to the `CHANGES.md` for each release. +### Style Changes + +If a change would affect the advertised code style, please modify the documentation (The +_Black_ code style) to reflect that change. Patches that fix unintended bugs in +formatting don't need to be mentioned separately though. + ### Docs Testing If you make changes to docs, you can test they still build locally too. @@ -96,7 +85,7 @@ your PR. You may need to change configuration for it to pass. For more `black-primer` information visit the -[documentation](https://github.com/psf/black/blob/master/docs/black_primer.md). +[documentation](./gauging_changes.md#black-primer). ## Hygiene diff --git a/docs/getting_started.md b/docs/getting_started.md new file mode 100644 index 0000000..a509d34 --- /dev/null +++ b/docs/getting_started.md @@ -0,0 +1,49 @@ +# Getting Started + +New to _Black_? Don't worry, you've found the perfect place to get started! + +## Do you like the _Black_ code style? + +Before using _Black_ on some of your code, it might be a good idea to first understand +how _Black_ will format your code. _Black_ isn't for everyone and you may find something +that is a dealbreaker for you personally, which is okay! The current _Black_ code style +[is described here](./the_black_code_style/current_style.md). + +## Try it out online + +Also, you can try out _Black_ online for minimal fuss on the +[Black Playground](https://black.vercel.app) generously created by José Padilla. + +## Installation + +_Black_ can be installed by running `pip install black`. It requires Python 3.6.2+ to +run, but can format Python 2 code too. Python 2 support needs the `typed_ast` +dependency, which be installed with `pip install black[python2]`. + +If you can't wait for the latest _hotness_ and want to install from GitHub, use: + +`pip install git+git://github.com/psf/black` + +## Basic usage + +To get started right away with sensible defaults: + +```sh +black {source_file_or_directory}... +``` + +You can run _Black_ as a package if running it as a script doesn't work: + +```sh +python -m black {source_file_or_directory}... +``` + +## Next steps + +Took a look at [the _Black_ code style](./the_black_code_style/current_style.md) and +tried out _Black_? Fantastic, you're ready for more. Why not explore some more on using +_Black_ by reading +[Usage and Configuration: The basics](./usage_and_configuration/the_basics.md). +Alternatively, you can check out the +[Introducing _Black_ to your project](./guides/introducing_black_to_your_project.md) +guide. diff --git a/docs/github_actions.md b/docs/github_actions.md deleted file mode 100644 index bd46809..0000000 --- a/docs/github_actions.md +++ /dev/null @@ -1,27 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# GitHub Actions - -Create a file named `.github/workflows/black.yml` inside your repository with: - -```yaml -name: Lint - -on: [push, pull_request] - -jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - uses: psf/black@stable - with: - black_args: ". --check" -``` - -## Inputs - -### `black_args` - -**optional**: Black input arguments. Defaults to `. --check --diff`. diff --git a/docs/guides/index.rst b/docs/guides/index.rst new file mode 100644 index 0000000..717c5c4 --- /dev/null +++ b/docs/guides/index.rst @@ -0,0 +1,14 @@ +Guides +====== + +.. toctree:: + :hidden: + + introducing_black_to_your_project + using_black_with_other_tools + +Wondering how to do something specific? You've found the right place! Listed below +are topic specific guides available: + +- :doc:`introducing_black_to_your_project` +- :doc:`using_black_with_other_tools` diff --git a/docs/guides/introducing_black_to_your_project.md b/docs/guides/introducing_black_to_your_project.md new file mode 100644 index 0000000..71ccf7c --- /dev/null +++ b/docs/guides/introducing_black_to_your_project.md @@ -0,0 +1,50 @@ +# Introducing _Black_ to your project + +```{note} +This guide is incomplete. Contributions are welcomed and would be deeply +appreciated! +``` + +## Avoiding ruining git blame + +A long-standing argument against moving to automated code formatters like _Black_ is +that the migration will clutter up the output of `git blame`. This was a valid argument, +but since Git version 2.23, Git natively supports +[ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt) +with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore +using the `--ignore-revs-file` option. The changes made by the revision will be ignored +when assigning blame. Lines modified by an ignored revision will be blamed on the +previous revision that modified those lines. + +So when migrating your project's code style to _Black_, reformat everything and commit +the changes (preferably in one massive commit). Then put the full 40 characters commit +identifier(s) into a file. + +```text +# Migrate code style to Black +5b4ab991dede475d393e9d69ec388fd6bd949699 +``` + +Afterwards, you can pass that file to `git blame` and see clean and meaningful blame +information. + +```console +$ git blame important.py --ignore-revs-file .git-blame-ignore-revs +7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file): +abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip() +7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f: +7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted) +``` + +You can even configure `git` to automatically ignore revisions listed in a file on every +call to `git blame`. + +```console +$ git config blame.ignoreRevsFile .git-blame-ignore-revs +``` + +**The one caveat is that GitHub and GitLab do not yet support ignoring revisions using +their native UI of blame.** So blame information will be cluttered with a reformatting +commit on those platforms. (If you'd like this feature, there's an open issue for +[GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub +know!) diff --git a/docs/compatible_configs.md b/docs/guides/using_black_with_other_tools.md similarity index 92% rename from docs/compatible_configs.md rename to docs/guides/using_black_with_other_tools.md index de81769..4b22f67 100644 --- a/docs/compatible_configs.md +++ b/docs/guides/using_black_with_other_tools.md @@ -1,4 +1,6 @@ -# _Black_ compatible configurations +# Using _Black_ with other tools + +## Black compatible configurations All of Black's changes are harmless (or at least, they should be), but a few do conflict against other tools. It is not uncommon to be using other tools alongside _Black_ like @@ -13,13 +15,13 @@ tools, using **their** supported file formats. Compatible configuration files can be [found here](https://github.com/psf/black/blob/master/docs/compatible_configs/). -## isort +### isort [isort](https://pypi.org/p/isort/) helps to sort and format imports in your Python code. _Black_ also formats imports, but in a different way from isort's defaults which leads to conflicting changes. -### Profile +#### Profile Since version 5.0.0, isort supports [profiles](https://pycqa.github.io/isort/docs/configuration/profiles/) to allow easy @@ -32,7 +34,7 @@ by isort. Below, an example for `pyproject.toml`: profile = "black" ``` -### Custom Configuration +#### Custom Configuration If you're using an isort version that is older than 5.0.0 or you have some custom configuration for _Black_, you can tweak your isort configuration to make it compatible @@ -47,12 +49,12 @@ ensure_newline_before_comments = True line_length = 88 ``` -### Why those options above? +#### Why those options above? _Black_ wraps imports that surpass `line-length` by moving identifiers into their own indented line. If that still doesn't fit the bill, it will put all of them in separate lines and put a trailing comma. A more detailed explanation of this behaviour can be -[found here](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#how-black-wraps-lines). +[found here](../the_black_code_style/current_style.md#how-black-wraps-lines). isort's default mode of wrapping imports that extend past the `line_length` limit is "Grid". @@ -90,7 +92,7 @@ works the same as with _Black_. **Please note** `ensure_newline_before_comments = True` only works since isort >= 5 but does not break older versions so you can keep it if you are running previous versions. -### Formats +#### Formats
.isort.cfg @@ -132,21 +134,21 @@ profile = black
-## Flake8 +### Flake8 [Flake8](https://pypi.org/p/flake8/) is a code linter. It warns you of syntax errors, possible bugs, stylistic errors, etc. For the most part, Flake8 follows [PEP 8](https://www.python.org/dev/peps/pep-0008/) when warning about stylistic errors. There are a few deviations that cause incompatibilities with _Black_. -### Configuration +#### Configuration ``` max-line-length = 88 extend-ignore = E203 ``` -### Why those options above? +#### Why those options above? In some cases, as determined by PEP 8, _Black_ will enforce an equal amount of whitespace around slice operators. Due to this, Flake8 will raise @@ -163,7 +165,7 @@ in your configuration. Also, as like with isort, flake8 should be configured to allow lines up to the length limit of `88`, _Black_'s default. This explains `max-line-length = 88`. -### Formats +#### Formats
.flake8 @@ -198,24 +200,24 @@ extend-ignore = E203
-## Pylint +### Pylint [Pylint](https://pypi.org/p/pylint/) is also a code linter like Flake8. It has the same checks as flake8 and more. In particular, it has more formatting checks regarding style conventions like variable naming. With so many checks, Pylint is bound to have some mixed feelings about _Black_'s formatting style. -### Configuration +#### Configuration ``` disable = C0330, C0326 max-line-length = 88 ``` -### Why those options above? +#### Why those options above? When _Black_ is folding very long expressions, the closing brackets will -[be dedented](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#how-black-wraps-lines). +[be dedented](../the_black_code_style/current_style.md#how-black-wraps-lines). ```py3 ImportantClass.important_method( @@ -223,7 +225,7 @@ ImportantClass.important_method( ) ``` -Although, this style is PEP 8 compliant, Pylint will raise +Although this style is PEP 8 compliant, Pylint will raise `C0330: Wrong hanging indentation before block (add 4 spaces)` warnings. Since _Black_ isn't configurable on this style, Pylint should be told to ignore these warnings via `disable = C0330`. @@ -234,7 +236,7 @@ warning `C0326: Bad whitespace` should be disabled using `disable = C0326`. And as usual, Pylint should be configured to only complain about lines that surpass `88` characters via `max-line-length = 88`. -### Formats +#### Formats
pylintrc diff --git a/docs/index.rst b/docs/index.rst index f03d247..a7a7160 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -14,12 +14,27 @@ possible. Blackened code looks the same regardless of the project you're reading. Formatting becomes transparent after a while and you can focus on the content instead. -Try it out now using the `Black Playground `_. +Try it out now using the `Black Playground `_. -.. note:: +.. admonition:: Note - this is a beta product + + *Black* is already `successfully used `_ by + many projects, small and big. *Black* has a comprehensive test suite, with efficient + parallel tests, our own auto formatting and parallel Continuous Integration runner. + However, *Black* is still beta. Things will probably be wonky for a while. This is + made explicit by the "Beta" trove classifier, as well as by the "b" in the versio + 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. - `Black is beta `_. + Also, as a safety measure which slows down processing, *Black* will check that the + reformatted code still produces a valid AST that is effectively equivalent to the + original (see the + `Pragmatism <./the_black_code_style/current_style.html#pragmatism>`_ + section for details). If you're feeling confident, use ``--fast``. +.. note:: + :doc:`Black is licensed under the MIT license `. Testimonials ------------ @@ -42,28 +57,62 @@ and `pipenv `_: *This vastly improves the formatting of our code. Thanks a ton!* + +Show your style +--------------- + +Use the badge in your project's README.md: + +.. code-block:: md + + [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + + +Using the badge in README.rst: + +.. code-block:: rst + + .. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black + +Looks like this: + +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black + Contents -------- .. toctree:: - :maxdepth: 2 - - installation_and_usage - the_black_code_style - pyproject_toml - compatible_configs - editor_integration - blackd - black_primer - version_control_integration - github_actions - ignoring_unmodified_files - contributing_to_black - show_your_style + :maxdepth: 3 + :includehidden: + + the_black_code_style/index + +.. toctree:: + :maxdepth: 3 + :includehidden: + + getting_started + usage_and_configuration/index + integrations/index + guides/index + +.. toctree:: + :maxdepth: 3 + :includehidden: + + contributing/index change_log - reference/reference_summary authors +.. toctree:: + :hidden: + + GitHub ↪ + PyPI ↪ + IRC ↪ + Indices and tables ================== diff --git a/docs/installation_and_usage.md b/docs/installation_and_usage.md deleted file mode 100644 index fcde49f..0000000 --- a/docs/installation_and_usage.md +++ /dev/null @@ -1,195 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# 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. - -### Install from GitHub - -If you can't wait for the latest _hotness_ and want to install from GitHub, use: - -`pip install git+git://github.com/psf/black` - -## Usage - -To get started right away with sensible defaults: - -```sh -black {source_file_or_directory} -``` - -You can run _Black_ as a package if running it as a script doesn't work: - -```sh -python -m black {source_file_or_directory} -``` - -## Command line options - -_Black_ doesn't provide many options. You can list them by running `black --help`: - -```text -Usage: black [OPTIONS] [SRC]... - - The uncompromising code formatter. - -Options: - -c, --code TEXT Format the code passed in as a string. - -l, --line-length INTEGER How many characters per line to allow. - [default: 88] - - -t, --target-version [py27|py33|py34|py35|py36|py37|py38|py39] - Python versions that should be supported by - Black's output. [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. - -C, --skip-magic-trailing-comma - Don't use trailing commas as a reason to - split lines. - - --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. - - --color / --no-color Show colored diff. Only applies when - `--diff` is given. - - --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: /(\.direnv|\.eggs|\.git|\. - hg|\.mypy_cache|\.nox|\.tox|\.venv|venv|\.sv - n|_build|buck-out|build|dist)/] - - --force-exclude TEXT Like --exclude, but files and directories - matching this regex will be excluded even - when they are passed explicitly as - arguments. - - --extend-exclude TEXT Like --exclude, but adds additional files - and directories on top of the excluded - ones. (useful if you simply want to add to - the default) - - --stdin-filename TEXT The name of the file when passing it through - stdin. Useful to make sure Black will - respect --force-exclude option on some - editors that rely on using stdin. - - -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 - exclusion patterns. - - --version Show the version and exit. - --config FILE Read configuration from FILE 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). - -## Using _Black_ with other tools - -While _Black_ enforces formatting that conforms to PEP 8, other tools may raise warnings -about _Black_'s changes or will overwrite _Black_'s changes. A good example of this is -[isort](https://pypi.org/p/isort). Since _Black_ is barely configurable, these tools -should be configured to neither warn about nor overwrite _Black_'s changes. - -Actual details on _Black_ compatible configurations for various tools can be found in -[compatible_configs](https://github.com/psf/black/blob/master/docs/compatible_configs.md#black-compatible-configurations). - -## Migrating your code style without ruining git blame - -A long-standing argument against moving to automated code formatters like _Black_ is -that the migration will clutter up the output of `git blame`. This was a valid argument, -but since Git version 2.23, Git natively supports -[ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt) -with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore -using the `--ignore-revs-file` option. The changes made by the revision will be ignored -when assigning blame. Lines modified by an ignored revision will be blamed on the -previous revision that modified those lines. - -So when migrating your project's code style to _Black_, reformat everything and commit -the changes (preferably in one massive commit). Then put the full 40 characters commit -identifier(s) into a file. - -``` -# Migrate code style to Black -5b4ab991dede475d393e9d69ec388fd6bd949699 -``` - -Afterwards, you can pass that file to `git blame` and see clean and meaningful blame -information. - -```console -$ git blame important.py --ignore-revs-file .git-blame-ignore-revs -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file): -abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip() -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f: -7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted) -``` - -You can even configure `git` to automatically ignore revisions listed in a file on every -call to `git blame`. - -```console -$ git config blame.ignoreRevsFile .git-blame-ignore-revs -``` - -**The one caveat is that GitHub and GitLab do not yet support ignoring revisions using -their native UI of blame.** So blame information will be cluttered with a reformatting -commit on those platforms. (If you'd like this feature, there's an open issue for -[GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub -know!) - -## NOTE: This is a beta product - -_Black_ is already [successfully used](https://github.com/psf/black#used-by) by many -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`. diff --git a/docs/editor_integration.md b/docs/integrations/editors.md similarity index 85% rename from docs/editor_integration.md rename to docs/integrations/editors.md index f2d21f2..6a69e9e 100644 --- a/docs/editor_integration.md +++ b/docs/integrations/editors.md @@ -4,7 +4,7 @@ Options include the following: -- [purcell/reformatter.el](https://github.com/purcell/reformatter.el) +- [wbolster/emacs-python-black](https://github.com/wbolster/emacs-python-black) - [proofit404/blacken](https://github.com/pythonic-emacs/blacken) - [Elpy](https://github.com/jorgenschaefer/elpy). @@ -16,7 +16,7 @@ Options include the following: $ pip install black ``` -2. Locate your `black` installation folder. +1. Locate your `black` installation folder. On macOS / Linux / BSD: @@ -35,7 +35,7 @@ Options include the following: Note that if you are using a virtual environment detected by PyCharm, this is an unneeded step. In this case the path to `black` is `$PyInterpreterDirectory$/black`. -3. Open External tools in PyCharm/IntelliJ IDEA +1. Open External tools in PyCharm/IntelliJ IDEA On macOS: @@ -45,29 +45,29 @@ Options include the following: `File -> Settings -> Tools -> External Tools` -4. Click the + icon to add a new external tool with the following values: +1. Click the + icon to add a new external tool with the following values: - Name: Black - Description: Black is the uncompromising Python code formatter. - - Program: + - Program: \ - Arguments: `"$FilePath$"` -5. Format the currently opened file by selecting `Tools -> External Tools -> black`. +1. 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. Optionally, run _Black_ on every file save: 1. Make sure you have the [File Watchers](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin installed. - 2. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a + 1. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a new watcher: - Name: Black - File type: Python - Scope: Project Files - - Program: + - Program: \ - Arguments: `$FilePath$` - Output paths to refresh: `$FilePath$` - Working directory: `$ProjectFileDir$` @@ -87,13 +87,13 @@ Wing supports black via the OS Commands tool, as explained in the Wing documenta $ pip install black ``` -2. Make sure it runs from the command line, e.g. +1. Make sure it runs from the command line, e.g. ```console $ black --help ``` -3. In Wing IDE, activate the **OS Commands** panel and define the command **black** to +1. In Wing IDE, activate the **OS Commands** panel and define the command **black** to execute black on the currently selected file: - Use the Tools -> OS Commands menu selection @@ -106,7 +106,7 @@ Wing supports black via the OS Commands tool, as explained in the Wing documenta - [x] Auto-save files before execution - [x] Line mode -4. Select a file in the editor and press **F1** , or whatever key binding you selected +1. Select a file in the editor and press **F1** , or whatever key binding you selected in step 3, to reformat the file. ## Vim @@ -238,8 +238,10 @@ $ pip install -U black --no-binary regex,typed-ast ### With ALE 1. Install [`ale`](https://github.com/dense-analysis/ale) -2. Install `black` -3. Add this to your vimrc: + +1. Install `black` + +1. Add this to your vimrc: ```vim let g:ale_fixers = {} @@ -256,10 +258,10 @@ $ gedit ``` 1. `Go to edit > preferences > plugins` -2. Search for `external tools` and activate it. -3. In `Tools menu -> Manage external tools` -4. Add a new tool using `+` button. -5. Copy the below content to the code window. +1. Search for `external tools` and activate it. +1. In `Tools menu -> Manage external tools` +1. Add a new tool using `+` button. +1. Copy the below content to the code window. ```console #!/bin/bash @@ -319,17 +321,3 @@ hook global WinSetOption filetype=python %{ ## Thonny Use [Thonny-black-code-format](https://github.com/Franccisco/thonny-black-code-format). - -## Other integrations - -Other editors and tools 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). diff --git a/docs/integrations/github_actions.md b/docs/integrations/github_actions.md new file mode 100644 index 0000000..9e8cf43 --- /dev/null +++ b/docs/integrations/github_actions.md @@ -0,0 +1,35 @@ +# GitHub Actions integration + +You can use _Black_ within a GitHub Actions workflow without setting your own Python +environment. Great for enforcing that your code matches the _Black_ code style. + +## Usage + +Create a file named `.github/workflows/black.yml` inside your repository with: + +```yaml +name: Lint + +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - uses: psf/black@stable +``` + +We recommend the use of the `@stable` tag, but per version tags also exist if you prefer +that. + +You may use `options` (Default is `'--check --diff'`) and `src` (Default is `'.'`) as +follows: + +```yaml +- uses: psf/black@stable + with: + options: "--check --verbose" + src: "./src" +``` diff --git a/docs/integrations/index.rst b/docs/integrations/index.rst new file mode 100644 index 0000000..ed62ebc --- /dev/null +++ b/docs/integrations/index.rst @@ -0,0 +1,28 @@ +Integrations +============ + +.. toctree:: + :hidden: + + editors + github_actions + source_version_control + +*Black* can be integrated into many environments, providing a better and smoother experience. Documentation for integrating *Black* with a tool can be found for the +following areas: + +- :doc:`Editor / IDE <./editors>` +- :doc:`GitHub Actions <./github_actions>` +- :doc:`Source version control <./source_version_control>` + +Editors and tools not listed will require external contributions. + +Patches welcome! ✨ 🍰 ✨ + +Any tool can pipe code through *Black* using its stdio mode (just +`use \`-\` as the file name `_). +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 `_. diff --git a/docs/integrations/source_version_control.md b/docs/integrations/source_version_control.md new file mode 100644 index 0000000..1ca6161 --- /dev/null +++ b/docs/integrations/source_version_control.md @@ -0,0 +1,14 @@ +# 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/psf/black + rev: stable # Replace by any tag/version: https://github.com/psf/black/tags + hooks: + - id: black + language_version: python3 # Should be a command that runs python3.6+ +``` diff --git a/docs/license.rst b/docs/license.rst new file mode 100644 index 0000000..2dc20a2 --- /dev/null +++ b/docs/license.rst @@ -0,0 +1,6 @@ +:orphan: + +License +======= + +.. include:: ../LICENSE diff --git a/docs/pyproject_toml.md b/docs/pyproject_toml.md deleted file mode 100644 index ed88f37..0000000 --- a/docs/pyproject_toml.md +++ /dev/null @@ -1,91 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# 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`/`--force-exclude`/`--extend-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://python-poetry.org/) 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 use a "global" configuration, stored in a specific location in your home -directory. This will be used as a fallback configuration, that is, it will be used if -and only if _Black_ doesn't find any configuration as mentioned above. Depending on your -operating system, this configuration file should be stored as: - -- Windows: `~\.black` -- Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the - `XDG_CONFIG_HOME` environment variable is not set) - -Note that these are paths to the TOML file itself (meaning that they shouldn't be named -as `pyproject.toml`), not directories where you store the configuration. Here, `~` -refers to the path to your home directory. On Windows, this will be something like -`C:\\Users\UserName`. - -You can also explicitly specify the path to a particular file that you want with -`--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. - -Files listed within a projects `.gitignore` file will not be formatted by _Black_. - -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?$' -extend-exclude = ''' -# A regex preceded with ^/ will apply only to files and directories -# in the root of the project. -^/foo.py # exclude a file named foo.py in the root of the project (in addition to the defaults) -''' -``` - -
- -## 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. diff --git a/docs/requirements.txt b/docs/requirements.txt index fcb6809..6c34e1f 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,3 +1,2 @@ -recommonmark==0.6.0 -Sphinx==3.2.1 -Pygments==2.7.4 \ No newline at end of file +MyST-Parser==0.13.7 +Sphinx==3.5.4 diff --git a/docs/show_your_style.md b/docs/show_your_style.md deleted file mode 100644 index 67b213c..0000000 --- a/docs/show_your_style.md +++ /dev/null @@ -1,19 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# Show your style - -Use the badge in your project's README.md: - -```md -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) -``` - -Using the badge in README.rst: - -``` -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black -``` - -Looks like this: -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) diff --git a/docs/the_black_code_style.md b/docs/the_black_code_style/current_style.md similarity index 91% rename from docs/the_black_code_style.md rename to docs/the_black_code_style/current_style.md index 39a452f..7d08bc9 100644 --- a/docs/the_black_code_style.md +++ b/docs/the_black_code_style/current_style.md @@ -2,11 +2,13 @@ ## 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. +_Black_ reformats entire files in place. Style configuration options are deliberately +limited and rarely added. It doesn't take previous formatting into account, except for +the magic trailing comma and preserving newlines. It doesn't reformat blocks that start +with `# fmt: off` and end with `# fmt: on`, or lines that ends with `# fmt: skip`. +`# 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 @@ -75,6 +77,8 @@ def very_important_function( ... ``` +(labels/why-no-backslashes)= + _Black_ prefers parentheses over backslashes, and will remove backslashes if found. ```py3 @@ -115,29 +119,6 @@ If you're reaching for backslashes, that's a clear signal that you can do better slightly refactor your code. I hope some of the examples above show you that there are many ways in which you can do it. -However there is one exception: `with` statements using multiple context managers. -Python's grammar does not allow organizing parentheses around the series of context -managers. - -We don't want formatting like: - -```py3 -with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4: - ... # nothing to split on - line too long -``` - -So _Black_ will now format it like this: - -```py3 -with \ - make_context_manager(1) as cm1, \ - make_context_manager(2) as cm2, \ - make_context_manager(3) as cm3, \ - make_context_manager(4) as cm4 \ -: - ... # backslashes and an ugly stranded colon -``` - 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 @@ -289,13 +270,13 @@ If you are adopting _Black_ in a large project with pre-existing string conventi you can pass `--skip-string-normalization` on the command line. This is meant as an adoption helper, avoid using this for new projects. -As an experimental option, _Black_ splits long strings (using parentheses where -appropriate) and merges short ones. When split, parts of f-strings that don't need -formatting are converted to plain strings. User-made splits are respected when they do -not exceed the line length limit. Line continuation backslashes are converted into -parenthesized strings. Unnecessary parentheses are stripped. To enable experimental -string processing, pass `--experimental-string-processing` on the command line. Because -the functionality is experimental, feedback and issue reports are highly encouraged! +As an experimental option (can be enabled by `--experimental-string-processing`), +_Black_ splits long strings (using parentheses where appropriate) and merges short ones. +When split, parts of f-strings that don't need formatting are converted to plain +strings. User-made splits are respected when they do not exceed the line length limit. +Line continuation backslashes are converted into parenthesized strings. Unnecessary +parentheses are stripped. Because the functionality is experimental, feedback and issue +reports are highly encouraged! _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected for both quotations and the text within, although relative indentation in the text is @@ -354,7 +335,7 @@ pair of parentheses to form an atom. There are a few interesting cases: 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 +parentheses 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 @@ -453,7 +434,7 @@ into one item per line. How do you make it stop? Just delete that trailing comma and _Black_ will collapse your collection into one line if it fits. -If you must, you can recover the behaviour of early versions of Black with the option +If you must, you can recover the behaviour of early versions of _Black_ with the option `--skip-magic-trailing-comma` / `-C`. ### r"strings" and R"strings" @@ -478,11 +459,11 @@ target. There are three limited cases in which the AST does differ: of docstrings that we're aware of sanitizes indentation and leading/trailing whitespace anyway. -2. _Black_ manages optional parentheses for some statements. In the case of the `del` +1. _Black_ manages optional parentheses for some statements. In the case of the `del` statement, presence of wrapping parentheses or lack of thereof changes the resulting AST but is semantically equivalent in the interpreter. -3. _Black_ might move comments around, which includes type comments. Those are part of +1. _Black_ might move comments around, which includes type comments. Those are part of the AST as of Python 3.8. While the tool implements a number of special cases for those comments, there is no guarantee they will remain where they were in the source. Note that this doesn't change runtime behavior of the source code. diff --git a/docs/the_black_code_style/future_style.md b/docs/the_black_code_style/future_style.md new file mode 100644 index 0000000..aca9fe0 --- /dev/null +++ b/docs/the_black_code_style/future_style.md @@ -0,0 +1,35 @@ +# The (future of the) Black code style + +```{warning} +Changes to this document often aren't tied and don't relate to releases of +_Black_. It's recommended that you read the latest version available. +``` + +## Using backslashes for with statements + +[Backslashes are bad and should be never be used](labels/why-no-backslashes) however +there is one exception: `with` statements using multiple context managers. Before Python +3.9 Python's grammar does not allow organizing parentheses around the series of context +managers. + +We don't want formatting like: + +```py3 +with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4: + ... # nothing to split on - line too long +``` + +So _Black_ will eventually format it like this: + +```py3 +with \ + make_context_manager(1) as cm1, \ + make_context_manager(2) as cm2, \ + make_context_manager(3) as cm3, \ + make_context_manager(4) as cm4 \ +: + ... # backslashes and an ugly stranded colon +``` + +Although when the target version is Python 3.9 or higher, _Black_ will use parentheses +instead since they're allowed in Python 3.9 and higher. diff --git a/docs/the_black_code_style/index.rst b/docs/the_black_code_style/index.rst new file mode 100644 index 0000000..4693437 --- /dev/null +++ b/docs/the_black_code_style/index.rst @@ -0,0 +1,19 @@ +The Black Code Style +==================== + +.. toctree:: + :hidden: + + Current style + Future style + +*Black* is a PEP 8 compliant opinionated formatter with its own style. + +It should be noted that while keeping the style unchanged throughout releases is a +goal, the *Black* code style isn't set in stone. Sometimes it's modified in response to +user feedback or even changes to the Python language! + +Documentation for both the current and future styles can be found: + +- :doc:`current_style` +- :doc:`future_style` diff --git a/docs/blackd.md b/docs/usage_and_configuration/black_as_a_server.md similarity index 98% rename from docs/blackd.md rename to docs/usage_and_configuration/black_as_a_server.md index c8058ee..0c0382b 100644 --- a/docs/blackd.md +++ b/docs/usage_and_configuration/black_as_a_server.md @@ -1,10 +1,10 @@ -## blackd +# Black as a server (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 the cost of starting up a new _Black_ process every time you want to blacken a file. -### Usage +## Usage `blackd` is not packaged alongside _Black_ by default because it has additional dependencies. You will need to execute `pip install black[d]` to install it. @@ -36,7 +36,7 @@ blackd --bind-port 9090 & # or let blackd choose a port curl -s -XPOST "localhost:9090" -d "print('valid')" ``` -### Protocol +## 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 diff --git a/docs/ignoring_unmodified_files.md b/docs/usage_and_configuration/file_collection_and_discovery.md similarity index 61% rename from docs/ignoring_unmodified_files.md rename to docs/usage_and_configuration/file_collection_and_discovery.md index a915f4e..54c76cd 100644 --- a/docs/ignoring_unmodified_files.md +++ b/docs/usage_and_configuration/file_collection_and_discovery.md @@ -1,6 +1,11 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" +# File collection and discovery -# Ignoring unmodified files +You can directly pass _Black_ files, but you can also pass directories and _Black_ will +walk them, collecting files to format. It determines what files to format or skip +automatically using the inclusion and exclusion regexes and as well their modification +time. + +## 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 @@ -21,3 +26,12 @@ To override the location of these files on macOS or Linux, set the environment v `XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will then write the above files to `.cache/black//`. + +## .gitignore + +If `--exclude` is not set, _Black_ will automatically ignore files and directories in +`.gitignore` file, if present. The `.gitignore` file must be in the project root to be +used and nested `.gitignore` aren't supported. + +If you want _Black_ to continue using `.gitignore` while also configuring the exclusion +rules, please use `--extend-exclude`. diff --git a/docs/usage_and_configuration/index.rst b/docs/usage_and_configuration/index.rst new file mode 100644 index 0000000..84a9c0c --- /dev/null +++ b/docs/usage_and_configuration/index.rst @@ -0,0 +1,24 @@ +Usage and Configuration +======================= + +.. toctree:: + :hidden: + + the_basics + file_collection_and_discovery + black_as_a_server + +Sometimes, running *Black* with its defaults and passing filepaths to it just won't cut +it. Passing each file using paths will become burdensome, and maybe you would like +*Black* to not touch your files and just output diffs. And yes, you *can* tweak certain +parts of *Black*'s style, but please know that configurability in this area is +purposefully limited. + +Using many of these more advanced features of *Black* will require some configuration. +Configuration that will either live on the command line or in a TOML configuration file. + +This section covers features of *Black* and configuring *Black* in detail: + +- :doc:`The basics <./the_basics>` +- :doc:`File collection and discovery ` +- :doc:`Black as a server (blackd) <./black_as_a_server>` diff --git a/docs/usage_and_configuration/the_basics.md b/docs/usage_and_configuration/the_basics.md new file mode 100644 index 0000000..6fd8769 --- /dev/null +++ b/docs/usage_and_configuration/the_basics.md @@ -0,0 +1,227 @@ +# The basics + +Foundational knowledge on using and configuring Black. + +_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). + +## Usage + +To get started right away with sensible defaults: + +```sh +black {source_file_or_directory} +``` + +You can run _Black_ as a package if running it as a script doesn't work: + +```sh +python -m black {source_file_or_directory} +``` + +### Command line options + +_Black_ has quite a few knobs these days, although _Black_ is opinionated so style +configuration options are deliberately limited and rarely added. You can list them by +running `black --help`. + +
+ +Help output + +``` + Usage: black [OPTIONS] [SRC]... + + The uncompromising code formatter. + + Options: + -c, --code TEXT Format the code passed in as a string. + -l, --line-length INTEGER How many characters per line to allow. + [default: 88] + + -t, --target-version [py27|py33|py34|py35|py36|py37|py38|py39] + Python versions that should be supported by + Black's output. [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. + -C, --skip-magic-trailing-comma + Don't use trailing commas as a reason to + split lines. + + --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. + + --color / --no-color Show colored diff. Only applies when + `--diff` is given. + + --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: /(\.direnv|\.eggs|\.git|\. + hg|\.mypy_cache|\.nox|\.tox|\.venv|venv|\.svn|_bu + ild|buck-out|build|dist)/] + + --extend-exclude TEXT Like --exclude, but adds additional files + and directories on top of the excluded + ones (useful if you simply want to add to + the default). + + --force-exclude TEXT Like --exclude, but files and directories + matching this regex will be excluded even + when they are passed explicitly as + arguments. + + + --stdin-filename TEXT The name of the file when passing it through + stdin. Useful to make sure Black will + respect --force-exclude option on some + editors that rely on using stdin. + + -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 + exclusion patterns. + + --version Show the version and exit. + --config FILE Read configuration from FILE path. + -h, --help Show this message and exit. +``` + +
+ +## Configuration via a file + +_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`/`--force-exclude`/`--extend-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. Applying those defaults will have your +code in compliance with many other _Black_ formatted projects. + +### 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://python-poetry.org/) 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 use a "global" configuration, stored in a specific location in your home +directory. This will be used as a fallback configuration, that is, it will be used if +and only if _Black_ doesn't find any configuration as mentioned above. Depending on your +operating system, this configuration file should be stored as: + +- Windows: `~\.black` +- Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the + `XDG_CONFIG_HOME` environment variable is not set) + +Note that these are paths to the TOML file itself (meaning that they shouldn't be named +as `pyproject.toml`), not directories where you store the configuration. Here, `~` +refers to the path to your home directory. On Windows, this will be something like +`C:\\Users\UserName`. + +You can also explicitly specify the path to a particular file that you want with +`--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?$' +extend-exclude = ''' +# A regex preceded with ^/ will apply only to files and directories +# in the root of the project. +^/foo.py # exclude a file named foo.py in the root of the project (in addition to the defaults) +''' +``` + +
+ +### 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. + +## Next steps + +You've probably noted that not all of the options you can pass to _Black_ have been +covered. Don't worry, the rest will be covered in a later section. + +A good next step would be configuring auto-discovery so `black .` is all you need +instead of laborously listing every file or directory. You can get started by heading +over to [File collection and discovery](./file_collection_and_discovery.md). + +Another good choice would be setting up an +[integration with your editor](../integrations/editors.md) of choice or with +[pre-commit for source version control](../integrations/source_version_control.md). diff --git a/docs/version_control_integration.md b/docs/version_control_integration.md deleted file mode 100644 index 2d8bc17..0000000 --- a/docs/version_control_integration.md +++ /dev/null @@ -1,28 +0,0 @@ -[//]: # "NOTE: THIS FILE WAS AUTOGENERATED FROM README.md" - -# 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/psf/black - rev: 20.8b1 # Replace by any tag/version: https://github.com/psf/black/tags - hooks: - - id: black - language_version: python3 # Should be a command that runs 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](https://github.com/psf/black/blob/master/pyproject.toml) for an -example. - -If you're already using Python 3.7, switch the `language_version` accordingly. Finally, -`stable` is a branch that tracks the latest release on PyPI. If you'd rather run on -master, this is also an option. -- 2.39.5