Commit Graph

265 Commits

Author SHA1 Message Date
Jelle Zijlstra
f1a2f92bba
Include --unstable in cache key (#4466)
Fixes #4465
2024-09-27 13:41:29 -07:00
Shantanu
b4d6d8632d
Drop Python 3.8 support (#4452) 2024-09-15 18:21:21 -07:00
Terence Honles
823a7b0ff0
fix: fix PEP 646 support of tuple unpacking (#4440)
This change fixes unpacking a tuple or generic type when *args is a type
variable tuple.
2024-08-26 08:09:59 -07:00
Kanishk Pachauri
14b6e61970
fix: Enhace black efficiently to skip directories listed in .gitignore (#4415) 2024-08-02 09:24:39 -07:00
Tomasz Kłoczko
0c033f3eb7
Upgrade some old syntax (#4338)
Signed-off-by: Tomasz Kłoczko <kloczek@github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-04-27 07:54:18 -07:00
Jelle Zijlstra
3f0f8f1956
Support PEP 696 (#4327) 2024-04-23 22:08:37 -07:00
Tushar Sadhwani
551ede2825
Add PEP 701 support (#3822)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-04-22 08:19:19 -07:00
Shantanu
836acad863
Improve AST safety check (#4290)
Fixes #4288, regressed by #4270
2024-03-22 20:13:53 -06:00
Shantanu
c9d2635b55
Remove mocking from tests (#4287)
Fixes #4275
2024-03-20 18:15:42 -07:00
Jelle Zijlstra
f000936726
Fix catastrophic performance in lines_with_leading_tabs_expanded() (#4278) 2024-03-15 12:06:12 -07:00
Kai Sforza
1abcffc818
Use regex where we ignore case on windows (#4252)
On windows the path `FoObAR` is the same as `foobar`, so the output
of `black` on a windows machine could output the path to `.gitignore`
with an upper or lower-case drive letter.
2024-03-12 21:22:10 -07:00
Jelle Zijlstra
6af7d11096
Fix AST safety check false negative (#4270)
Fixes #4268

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

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2024-03-09 17:42:29 -08:00
Shantanu
23dfc5b2c3
Fix ignoring input files for symlink reasons (#4222)
This relates to #4015, #4161 and the behaviour of os.getcwd()

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

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

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

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

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

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

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

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

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

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

There have been 1-2 issues about symlinks recently. Both over and under
resolving can cause problems. This makes a case where we resolve more
explicit and prevent a resolved path from leaking out via the return.
2024-02-10 23:55:01 -08:00
Shantanu
2623269dab
Ignore pyproject.toml missing tool.black section (#4204)
Fixes #2863

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

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

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

Finally, for the few who could be affected, the fix is to put an empty
`[tool.black]` in pyproject.toml
2024-02-01 21:50:45 -08:00
Jelle Zijlstra
ed770ba4dd
Fix cache file length (#4176)
- Ensure total file length stays under 96
- Hash the path only if it's too long
- Proceed normally (with a warning) if the cache can't be read

Fixes #4172
2024-01-26 11:54:49 -08:00
Jelle Zijlstra
4f47cac192
Add --unstable flag (#4096) 2024-01-25 17:00:47 -08:00
Daniel Krzeminski
bccec8adfb
Show warning on invalid toml configuration (#4165)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-01-25 16:41:37 -08:00
Daniel Krzeminski
8fe602b1fa
fix pathlib exception handling with symlinks (#4161)
Fixes #4077
2024-01-22 09:46:57 -08:00
Jelle Zijlstra
ebd543c0ac
Fix feature detection for parenthesized context managers (#4104) 2023-12-11 21:37:15 -08:00
Jelle Zijlstra
0c9899956d
Fix path in test message (#4102) 2023-12-11 14:29:33 -08:00
Shantanu
2e4fac9d87
Apply force exclude logic before symlink resolution (#4015) 2023-11-07 11:31:44 -08:00
Yilei Yang
46be1f8e54
Support formatting specified lines (#4020) 2023-11-06 18:05:25 -08:00
Shantanu
e2f2bd076f
Minor refactoring in get_sources and gen_python_files (#4013) 2023-11-01 06:20:14 -07:00
sth
c369e446f9
Fix matching of absolute paths in --include (#3976) 2023-10-27 00:43:51 -07:00
Shantanu
5d5bf6e087
Fix cache versioning when BLACK_CACHE_DIR is set (#3937) 2023-10-09 18:44:36 -07:00
Jelle Zijlstra
a69bda3b9b
Use inline flags for test cases (#3931)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2023-10-09 18:43:47 -07:00
John Litborn
9b82120ddb
add support for printing the diff of AST trees when running tests (#3902)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-28 07:03:24 -07:00
Jelle Zijlstra
f7917453c9
Re-export black.Mode (#3875) 2023-09-10 16:12:20 -07:00
Shantanu
4eebfd1a7a
Add mypyc test marks to new tests that patch (#3871)
This is enough for me to get a clean test run on Python 3.9 with mypyc.
I have not been able to repro the pickle failures on either Linux or
macOS.
2023-09-10 07:53:27 -07:00
Shantanu
df50fee7fd
Apply ignore logic before symlink resolution (#3846)
This means, for instance, that a gitignored symlink cannot affect your
formatting. Fixes #3527, fixes #3826
2023-09-06 21:06:07 -07:00
Shantanu
6310a405f6
Improve handling of root to get_sources (#3847)
This is a little more type safe and a little cleaner
2023-08-19 08:13:05 -07:00
Marc Mueller
c6a031e623
Improve caching by comparing file hashes as fallback for mtime and size (#3821)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2023-08-18 19:26:36 -07:00
Shantanu
2593af2c5d
Improve performance by skipping unnecessary normalisation (#3751)
This speeds up black by about 40% when the cache is full
2023-07-09 15:24:01 -07:00
Shantanu
114e8357e6
Remove click patch (#3768)
Apparently this was only needed on Python 3.6. We've now dropped support
for 3.6 and 3.7. It's also not needed on new enough click.
2023-07-09 13:29:47 -07:00
Zac Hatfield-Dodds
8e618f3869
Enable PYTHONWARNDEFAULTENCODING = 1 in CI (#3763) 2023-07-04 16:38:39 -07:00
Renan Santos
453828d17d
Fix not honouring pyproject.toml when using stdin and calling black from parent directory (#3719)
Co-authored-by: Renan Rodrigues <renan.rodrigues@appliedbiomath.com>
2023-06-22 21:21:49 -07:00
Ville Skyttä
898915d556
Use aware datetimes to represent UTC (#3728)
Avoids a Python 3.12 deprecation warning.

Subtle difference: previously, timestamps in diff filenames had the
`+0000` separated from the timestamp by space. With this, the space is
there no more, and there is a colon, as in `+00:00`.
2023-06-10 09:54:21 -07:00
Jelle Zijlstra
3aad6e385b
Add support for PEP 695 syntax (#3703) 2023-06-01 18:37:08 -07:00
Yilei "Dolee" Yang
e712e48e06
Do not wrap implicitly concatenated strings used as func args in parens (#3640) 2023-04-28 11:10:01 -07:00
Stijn de Gooijer
69ca0a4c7a
Infer target version based on project metadata (#3219)
Co-authored-by: Richard Si <sichard26@gmail.com>
2023-01-31 18:00:17 -08:00
Jelle Zijlstra
c4bd2e31ce
Draft for Black 2023 stable style (#3418) 2023-01-31 15:39:56 -08:00
Antonio Ossa-Guerra
18fb88486d
Fix false symlink detection claims in verbose output (#3385)
When trying to format a project from the outside, the verbose output
shows says that there are symbolic links that points outside of the
project, but displays the wrong project path, meaning that these
messages are false positives.

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

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

---

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

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

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2023-01-18 21:38:27 -05:00
Antonio Ossa-Guerra
d97b7898b3
Remove whitespaces of whitespace-only files (#3348)
Currently, empty and whitespace-only (with or without newlines) are
not modified. In some discussions (issues and pull requests) consensus
was to reformat whitespace-only files to empty or single-character
files, preserving line endings when possible. With that said, this
commit introduces the following behaviors:

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

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

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-11-11 20:05:36 -05:00
Antonio Ossa-Guerra
ffaaf48382
Compare each .gitignore found with an appropiate relative path (#3338)
* Apply .gitignore files considering their location

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

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

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

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

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

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

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

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

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

* Update CHANGES.md

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

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

* Small refactor to improve code readability

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

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

* Make nested function a top-level function

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

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

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

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

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

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-11-04 22:09:59 -07:00
Yilei "Dolee" Yang
b73b77a9b0
Wrap concatenated strings used as function args in parens (#3307)
Fixes #3292
2022-10-26 18:03:10 -07:00
Antonio Ossa-Guerra
4da0851809
Add option to skip the first line of source code (#3299)
* Add option to skip the first line in source file

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

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

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

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

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

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

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

* Support skip source first line option for blackd

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

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

* Add skip source first line option to blackd docs

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

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

* Update CHANGES.md

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

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

* Update skip first line test including valid syntax

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

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

* Skip first source line at `format_file_in_place`

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

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

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

* Test output newlines when skipping first line

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

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

* Test that Blackd also skips first line correctly

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

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

* Use the content encoding to decode the header

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

Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
2022-10-06 15:17:32 -07:00
KotlinIsland
0359b85b58
Preserve crlf line endings in blackd (#3257)
Co-authored-by: KotlinIsland <kotlinisland@users.noreply.github.com>
2022-10-04 13:10:11 -07:00
Martin de La Gorce
767604e03f
Use .gitignore files in the initial source directories (#3237)
Solves https://github.com/psf/black/issues/2598 where Black wouldn't
use .gitignore at folder/.gitignore if you ran `black folder` for
example.

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
2022-08-31 15:47:42 -04:00