]> git.madduck.net Git - etc/vim.git/blob - docs/usage_and_configuration/the_basics.md

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Cover more in the usage docs (#2208)
[etc/vim.git] / docs / usage_and_configuration / the_basics.md
1 # The basics
2
3 Foundational knowledge on using and configuring Black.
4
5 _Black_ is a well-behaved Unix-style command-line tool:
6
7 - it does nothing if no sources are passed to it;
8 - it will read from standard input and write to standard output if `-` is used as the
9   filename;
10 - it only outputs messages to users on standard error;
11 - exits with code 0 unless an internal error occurred (or `--check` was used).
12
13 ## Usage
14
15 To get started right away with sensible defaults:
16
17 ```sh
18 black {source_file_or_directory}
19 ```
20
21 You can run _Black_ as a package if running it as a script doesn't work:
22
23 ```sh
24 python -m black {source_file_or_directory}
25 ```
26
27 ### Command line options
28
29 _Black_ has quite a few knobs these days, although _Black_ is opinionated so style
30 configuration options are deliberately limited and rarely added. You can list them by
31 running `black --help`.
32
33 <details>
34
35 <summary>Help output</summary>
36
37 ```{program-output} black --help
38
39 ```
40
41 </details>
42
43 ### Code input alternatives
44
45 #### Standard Input
46
47 _Black_ supports formatting code via stdin, with the result being printed to stdout.
48 Just let _Black_ know with `-` as the path.
49
50 ```console
51 $ echo "print ( 'hello, world' )" | black -
52 print("hello, world")
53 reformatted -
54 All done! ✨ 🍰 ✨
55 1 file reformatted.
56 ```
57
58 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
59 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
60 option on some editors that rely on using stdin.
61
62 #### As a string
63
64 You can also pass code as a string using the `-c` / `--code` option.
65
66 ```console
67 $ black --code "print ( 'hello, world' )"
68 print("hello, world")
69 ```
70
71 ```{warning}
72 --check, --diff, and --safe / --fast have no effect when using -c / --code. Safety
73 checks normally turned on by default that verify _Black_'s output are disabled as well.
74 This is a bug which we intend to fix eventually. More details can be found in this [bug
75 report](https://github.com/psf/black/issues/2104).
76 ```
77
78 ### Writeback and reporting
79
80 By default _Black_ reformats the files given and/or found in place. Sometimes you need
81 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
82
83 There's two variations to this mode that are independently enabled by their respective
84 flags. Both variations can be enabled at once.
85
86 #### Exit code
87
88 Passing `--check` will make _Black_ exit with:
89
90 - code 0 if nothing would change;
91 - code 1 if some files would be reformatted; or
92 - code 123 if there was an internal error
93
94 ```console
95 $ black test.py --check
96 All done! ✨ 🍰 ✨
97 1 file would be left unchanged.
98 $ echo $?
99 0
100
101 $ black test.py --check
102 would reformat test.py
103 Oh no! 💥 💔 💥
104 1 file would be reformatted.
105 $ echo $?
106 1
107
108 $ black test.py --check
109 error: cannot format test.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_kjdr1oog.log
110 Oh no! 💥 💔 💥
111 1 file would fail to reformat.
112 $ echo $?
113 123
114 ```
115
116 #### Diffs
117
118 Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_
119 would've made. They are printed to stdout so capturing them is simple.
120
121 If you'd like colored diffs, you can enable them with the `--color`.
122
123 ```console
124 $ black test.py --diff
125 --- test.py     2021-03-08 22:23:40.848954 +0000
126 +++ test.py     2021-03-08 22:23:47.126319 +0000
127 @@ -1 +1 @@
128 -print ( 'hello, world' )
129 +print("hello, world")
130 would reformat test.py
131 All done! ✨ 🍰 ✨
132 1 file would be reformatted.
133 ```
134
135 ### Output verbosity
136
137 _Black_ in general tries to produce the right amount of output, balancing between
138 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
139 plus a short summary.
140
141 ```console
142 $ black src/
143 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
144 reformatted src/black_primer/lib.py
145 reformatted src/blackd/__init__.py
146 reformatted src/black/__init__.py
147 Oh no! 💥 💔 💥
148 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
149 ```
150
151 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
152 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
153 configuration file, a blue message detailing which one it is using will be emitted.
154
155 ```console
156 $ black src/ -v
157 Using configuration from /tmp/pyproject.toml.
158 src/blib2to3 ignored: matches the --extend-exclude regular expression
159 src/_black_version.py wasn't modified on disk since last run.
160 src/black/__main__.py wasn't modified on disk since last run.
161 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
162 reformatted src/black_primer/lib.py
163 reformatted src/blackd/__init__.py
164 reformatted src/black/__init__.py
165 Oh no! 💥 💔 💥
166 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
167 ```
168
169 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critial output.
170 Error messages will still be emitted (which can silenced by `2>/dev/null`).
171
172 ```console
173 $ black src/ -q
174 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
175 ```
176
177 ### Getting the version
178
179 You can check the version of _Black_ you have installed using the `--version` flag.
180
181 ```console
182 $ black --version
183 black, version 21.5b0
184 ```
185
186 ## Configuration via a file
187
188 _Black_ is able to read project-specific default values for its command line options
189 from a `pyproject.toml` file. This is especially useful for specifying custom
190 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
191 project.
192
193 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
194 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
195 code in compliance with many other _Black_ formatted projects.
196
197 ### What on Earth is a `pyproject.toml` file?
198
199 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
200 configuration file to store build system requirements for Python projects. With the help
201 of tools like [Poetry](https://python-poetry.org/) or
202 [Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the need for
203 `setup.py` and `setup.cfg` files.
204
205 ### Where _Black_ looks for the file
206
207 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
208 all files and directories passed on the command line. If it's not there, it looks in
209 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
210 `.hg` directory, or the root of the file system, whichever comes first.
211
212 If you're formatting standard input, _Black_ will look for configuration starting from
213 the current working directory.
214
215 You can use a "global" configuration, stored in a specific location in your home
216 directory. This will be used as a fallback configuration, that is, it will be used if
217 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
218 operating system, this configuration file should be stored as:
219
220 - Windows: `~\.black`
221 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
222   `XDG_CONFIG_HOME` environment variable is not set)
223
224 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
225 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
226 refers to the path to your home directory. On Windows, this will be something like
227 `C:\\Users\UserName`.
228
229 You can also explicitly specify the path to a particular file that you want with
230 `--config`. In this situation _Black_ will not look for any other file.
231
232 If you're running with `--verbose`, you will see a blue message if a file was found and
233 used.
234
235 Please note `blackd` will not use `pyproject.toml` configuration.
236
237 ### Configuration format
238
239 As the file extension suggests, `pyproject.toml` is a
240 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
241 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
242 same as long names of options on the command line.
243
244 Note that you have to use single-quoted strings in TOML for regular expressions. It's
245 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
246 expressions by Black. Use `[ ]` to denote a significant space character.
247
248 <details>
249 <summary>Example <code>pyproject.toml</code></summary>
250
251 ```toml
252 [tool.black]
253 line-length = 88
254 target-version = ['py37']
255 include = '\.pyi?$'
256 extend-exclude = '''
257 # A regex preceded with ^/ will apply only to files and directories
258 # in the root of the project.
259 ^/foo.py  # exclude a file named foo.py in the root of the project (in addition to the defaults)
260 '''
261 ```
262
263 </details>
264
265 ### Lookup hierarchy
266
267 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
268 override those defaults. Finally, options provided by the user on the command line
269 override both.
270
271 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
272 look for multiple files, and doesn't compose configuration from different levels of the
273 file hierarchy.
274
275 ## Next steps
276
277 You've probably noted that not all of the options you can pass to _Black_ have been
278 covered. Don't worry, the rest will be covered in a later section.
279
280 A good next step would be configuring auto-discovery so `black .` is all you need
281 instead of laborously listing every file or directory. You can get started by heading
282 over to [File collection and discovery](./file_collection_and_discovery.md).
283
284 Another good choice would be setting up an
285 [integration with your editor](../integrations/editors.md) of choice or with
286 [pre-commit for source version control](../integrations/source_version_control.md).