From 42680b97429721cd17e1821d75b2a7b8cb1e66d4 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Mon, 13 Feb 2023 22:05:35 -0500 Subject: [PATCH] Create remaining simple_cases fixtures (#12) Removes all the other fixtures, runs the conversion script over all remaining cases, and removes the `.bak` files. --- convert_to_insta.py | 61 - .../fixtures/black/conditional_expression.py | 160 --- .../test/fixtures/black/empty_pyproject.toml | 2 - .../fast/pep_572_do_not_remove_parens.py | 25 - .../.gitignore | 1 - .../dir1/a.py | 0 .../dir1/b.py | 0 .../dir2/a.py | 0 .../dir2/b.py | 0 .../ignore_subfolders_gitignore_tests/a.py | 0 .../subdir/.gitignore | 1 - .../subdir/b.py | 0 .../subdir/subdir/c.py | 0 .../black/include_exclude_tests/.gitignore | 1 - .../b/.definitely_exclude/a.pie | 0 .../b/.definitely_exclude/a.py | 0 .../b/.definitely_exclude/a.pyi | 0 .../b/dont_exclude/a.pie | 0 .../include_exclude_tests/b/dont_exclude/a.py | 0 .../b/dont_exclude/a.pyi | 0 .../include_exclude_tests/b/exclude/a.pie | 0 .../include_exclude_tests/b/exclude/a.py | 0 .../include_exclude_tests/b/exclude/a.pyi | 0 .../include_exclude_tests/pyproject.toml | 3 - .../black/invalid_gitignore_tests/.gitignore | 1 - .../black/invalid_gitignore_tests/a.py | 0 .../invalid_gitignore_tests/pyproject.toml | 1 - .../black/invalid_nested_gitignore_tests/a.py | 0 .../a/.gitignore | 1 - .../invalid_nested_gitignore_tests/a/a.py | 0 .../pyproject.toml | 1 - .../black/jupyter/non_python_notebook.ipynb | 31 - .../jupyter/notebook_empty_metadata.ipynb | 27 - .../notebook_no_trailing_newline.ipynb | 39 - .../jupyter/notebook_trailing_newline.ipynb | 39 - .../notebook_which_cant_be_parsed.ipynb | 1 - .../jupyter/notebook_without_changes.ipynb | 46 - .../miscellaneous/async_as_identifier.py | 49 - .../black/miscellaneous/blackd_diff.diff | 13 - .../black/miscellaneous/blackd_diff.py | 6 - .../black/miscellaneous/debug_visitor.out | 810 ----------- .../black/miscellaneous/debug_visitor.py | 32 - .../black/miscellaneous/decorators.py | 182 --- .../docstring_no_string_normalization.py | 249 ---- ...cstring_preview_no_string_normalization.py | 10 - .../expression_skip_magic_trailing_comma.diff | 447 ------ .../black/miscellaneous/force_py36.py | 16 - .../fixtures/black/miscellaneous/force_pyi.py | 65 - .../black/miscellaneous/invalid_header.py | 2 - .../black/miscellaneous/linelength6.py | 5 - .../long_strings_flag_disabled.py | 292 ---- .../miscellaneous/missing_final_newline.diff | 8 - .../miscellaneous/missing_final_newline.py | 3 - .../miscellaneous/pattern_matching_invalid.py | 18 - .../black/miscellaneous/power_op_newline.py | 10 - .../black/miscellaneous/python2_detection.py | 90 -- .../black/miscellaneous/string_quotes.py | 112 -- .../fixtures/black/miscellaneous/stub.pyi | 151 -- .../nested_gitignore_tests/pyproject.toml | 3 - .../nested_gitignore_tests/root/.gitignore | 1 - .../black/nested_gitignore_tests/root/a.py | 1 - .../black/nested_gitignore_tests/root/b.py | 1 - .../black/nested_gitignore_tests/root/c.py | 1 - .../root/child/.gitignore | 1 - .../nested_gitignore_tests/root/child/a.py | 1 - .../nested_gitignore_tests/root/child/b.py | 1 - .../nested_gitignore_tests/root/child/c.py | 1 - .../black/nested_gitignore_tests/x.py | 0 .../test/fixtures/black/preview/cantfit.py | 111 -- .../test/fixtures/black/preview/comments7.py | 285 ---- .../test/fixtures/black/preview/comments8.py | 15 - .../test/fixtures/black/preview/comments9.py | 305 ---- .../black/preview/docstring_preview.py | 103 -- .../black/preview/long_dict_values.py | 90 -- .../fixtures/black/preview/long_strings.py | 861 ------------ .../black/preview/long_strings__edge_case.py | 140 -- .../black/preview/long_strings__regression.py | 1237 ----------------- .../preview/long_strings__type_annotations.py | 59 - .../black/preview/one_element_subscript.py | 36 - .../black/preview/percent_precedence.py | 41 - .../black/preview/prefer_rhs_split.py | 85 -- .../preview/prefer_rhs_split_reformatted.py | 38 - .../black/preview/remove_await_parens.py | 169 --- .../black/preview/remove_except_parens.py | 79 -- .../black/preview/remove_for_brackets.py | 48 - .../remove_newline_after_code_block_open.py | 189 --- .../preview/return_annotation_brackets.py | 222 --- .../preview/skip_magic_trailing_comma.py | 74 - .../trailing_commas_in_leading_parts.py | 88 -- .../test/fixtures/black/preview/whitespace.py | 6 - .../preview_310/remove_newline_after_match.py | 34 - .../black/preview_39/remove_with_brackets.py | 119 -- .../auto_detect/features_3_10.py | 35 - .../auto_detect/features_3_11.py | 37 - .../auto_detect/features_3_8.py | 30 - .../auto_detect/features_3_9.py | 34 - .../targeting_py38.py | 38 - .../targeting_py39.py | 104 -- .../py_310/parenthesized_context_managers.py | 21 - .../black/py_310/pattern_matching_complex.py | 144 -- .../black/py_310/pattern_matching_extras.py | 119 -- .../black/py_310/pattern_matching_generic.py | 107 -- .../black/py_310/pattern_matching_simple.py | 92 -- .../black/py_310/pattern_matching_style.py | 91 -- .../fixtures/black/py_310/pep_572_py310.py | 15 - .../black/py_310/starred_for_target.py | 27 - .../test/fixtures/black/py_311/pep_646.py | 194 --- .../test/fixtures/black/py_311/pep_654.py | 53 - .../fixtures/black/py_311/pep_654_style.py | 111 -- .../fixtures/black/py_36/numeric_literals.py | 44 - .../numeric_literals_skip_underscores.py | 23 - .../test/fixtures/black/py_37/python37.py | 65 - .../test/fixtures/black/py_38/pep_570.py | 44 - .../test/fixtures/black/py_38/pep_572.py | 47 - .../black/py_38/pep_572_remove_parens.py | 145 -- .../test/fixtures/black/py_38/python38.py | 45 - .../test/fixtures/black/py_39/pep_572_py39.py | 7 - .../test/fixtures/black/py_39/python39.py | 37 - .../attribute_access_on_number_literals.py | 25 - .../simple_cases/beginning_backslash.bak | 12 - .../black/simple_cases/bracketmatch.bak | 15 - .../simple_cases/class_blank_parentheses.bak | 58 - .../simple_cases/class_methods_new_line.bak | 270 ---- .../black/simple_cases/collections.bak | 174 --- .../comment_after_escaped_newline.bak | 18 - .../fixtures/black/simple_cases/comments.bak | 96 -- .../fixtures/black/simple_cases/comments2.py | 177 --- .../fixtures/black/simple_cases/comments3.py | 2 +- .../comments_non_breaking_space.py | 25 - .../composition_no_trailing_comma.py | 186 --- .../fixtures/black/simple_cases/docstring.py | 223 --- .../black/simple_cases/empty_lines.bak | 187 --- .../black/simple_cases/expression.bak | 630 --------- .../black/simple_cases/expression.diff | 466 ------- .../fixtures/black/simple_cases/fmtonoff.py | 227 --- .../fixtures/black/simple_cases/fmtonoff3.py | 18 - .../fixtures/black/simple_cases/fmtonoff4.py | 23 - .../fixtures/black/simple_cases/fmtonoff5.py | 92 -- .../fixtures/black/simple_cases/fmtskip2.py | 14 - .../fixtures/black/simple_cases/fmtskip3.py | 13 - .../fixtures/black/simple_cases/fmtskip4.py | 10 - .../fixtures/black/simple_cases/fmtskip5.py | 13 - .../fixtures/black/simple_cases/fmtskip6.py | 8 - .../fixtures/black/simple_cases/fmtskip7.py | 7 - .../fixtures/black/simple_cases/fstring.py | 12 - .../fixtures/black/simple_cases/function.bak | 247 ---- .../fixtures/black/simple_cases/function2.bak | 121 -- .../simple_cases/function_trailing_comma.bak | 182 --- .../black/simple_cases/import_spacing.bak | 118 -- .../black/simple_cases/power_op_spacing.bak | 131 -- .../black/simple_cases/string_prefixes.py | 25 - .../fixtures/black/simple_cases/torture.py | 62 - .../trailing_comma_optional_parens1.py | 38 - .../trailing_comma_optional_parens2.py | 9 - .../trailing_comma_optional_parens3.py | 13 - .../black/simple_cases/tupleassign.bak | 23 - ...ttribute_access_on_number_literals.py.snap | 28 + ...ses__comment_after_escaped_newline.py.snap | 7 +- ...mt__tests__simple_cases__comments2.py.snap | 178 +++ ...mt__tests__simple_cases__comments3.py.snap | 53 + ...mt__tests__simple_cases__comments4.py.snap | 100 ++ ...mt__tests__simple_cases__comments5.py.snap | 77 + ...mt__tests__simple_cases__comments6.py.snap | 124 ++ ...cases__comments_non_breaking_space.py.snap | 29 + ...__tests__simple_cases__composition.py.snap | 187 +++ ...ses__composition_no_trailing_comma.py.snap | 187 +++ ...mt__tests__simple_cases__docstring.py.snap | 225 +++ ...ing_no_extra_empty_line_before_eof.py.snap | 10 + ...__tests__simple_cases__empty_lines.py.snap | 20 +- ...sts__simple_cases__empty_lines.py.snap.new | 102 -- ...t__tests__simple_cases__expression.py.snap | 281 ++-- ...ests__simple_cases__expression.py.snap.new | 369 ----- ...fmt__tests__simple_cases__fmtonoff.py.snap | 229 +++ ...mt__tests__simple_cases__fmtonoff2.py.snap | 46 + ...mt__tests__simple_cases__fmtonoff3.py.snap | 21 + ...mt__tests__simple_cases__fmtonoff4.py.snap | 26 + ...mt__tests__simple_cases__fmtonoff5.py.snap | 93 ++ ..._fmt__tests__simple_cases__fmtskip.py.snap | 9 + ...fmt__tests__simple_cases__fmtskip2.py.snap | 17 + ...fmt__tests__simple_cases__fmtskip3.py.snap | 16 + ...fmt__tests__simple_cases__fmtskip4.py.snap | 13 + ...fmt__tests__simple_cases__fmtskip5.py.snap | 15 + ...fmt__tests__simple_cases__fmtskip6.py.snap | 11 + ...fmt__tests__simple_cases__fmtskip7.py.snap | 10 + ...fmt__tests__simple_cases__fmtskip8.py.snap | 68 + ..._fmt__tests__simple_cases__fstring.py.snap | 15 + ...fmt__tests__simple_cases__function.py.snap | 141 +- ..._tests__simple_cases__function.py.snap.new | 148 -- ...mt__tests__simple_cases__function2.py.snap | 20 +- ...ple_cases__function_trailing_comma.py.snap | 91 +- ...cases__function_trailing_comma.py.snap.new | 118 -- ...ts__simple_cases__power_op_spacing.py.snap | 4 +- ...simple_cases__power_op_spacing.py.snap.new | 68 - ...ests__simple_cases__remove_parens.py.snap} | 91 +- ...f_fmt__tests__simple_cases__slices.py.snap | 37 + ...sts__simple_cases__string_prefixes.py.snap | 26 + ..._fmt__tests__simple_cases__torture.py.snap | 64 + ...s__trailing_comma_optional_parens1.py.snap | 40 + ...s__trailing_comma_optional_parens2.py.snap | 12 + ...s__trailing_comma_optional_parens3.py.snap | 14 + ...mple_cases__tricky_unicode_symbols.py.snap | 15 + ...__tests__simple_cases__tupleassign.py.snap | 10 +- ...sts__simple_cases__tupleassign.py.snap.new | 17 - 203 files changed, 2169 insertions(+), 14448 deletions(-) delete mode 100644 convert_to_insta.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/conditional_expression.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/empty_pyproject.toml delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/fast/pep_572_do_not_remove_parens.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/b.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/b.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/b.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/subdir/c.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pie delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pyi delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pie delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pyi delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pie delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pyi delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/pyproject.toml delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/pyproject.toml delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/pyproject.toml delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/non_python_notebook.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_empty_metadata.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_no_trailing_newline.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_trailing_newline.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_which_cant_be_parsed.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_without_changes.ipynb delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/async_as_identifier.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.diff delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.out delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/decorators.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_no_string_normalization.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_preview_no_string_normalization.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/expression_skip_magic_trailing_comma.diff delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_py36.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_pyi.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/invalid_header.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/linelength6.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/long_strings_flag_disabled.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.diff delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/pattern_matching_invalid.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/power_op_newline.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/python2_detection.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/string_quotes.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/stub.pyi delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/pyproject.toml delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/b.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/c.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/.gitignore delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/a.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/b.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/c.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/x.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/cantfit.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/comments7.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/comments8.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/comments9.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/docstring_preview.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/long_dict_values.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__edge_case.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__regression.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__type_annotations.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/one_element_subscript.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/percent_precedence.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split_reformatted.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/remove_await_parens.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/remove_except_parens.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/remove_for_brackets.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/remove_newline_after_code_block_open.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/return_annotation_brackets.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/skip_magic_trailing_comma.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/trailing_commas_in_leading_parts.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview/whitespace.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_310/remove_newline_after_match.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_39/remove_with_brackets.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_10.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_11.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_8.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_9.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py38.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py39.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/parenthesized_context_managers.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_complex.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_extras.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_generic.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_simple.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_style.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/pep_572_py310.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_310/starred_for_target.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_646.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654_style.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals_skip_underscores.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_37/python37.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_570.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572_remove_parens.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_38/python38.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_39/pep_572_py39.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/py_39/python39.py delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/beginning_backslash.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/bracketmatch.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_blank_parentheses.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_methods_new_line.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/collections.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comment_after_escaped_newline.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/empty_lines.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.diff delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function2.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function_trailing_comma.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/import_spacing.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/power_op_spacing.bak delete mode 100644 crates/ruff_fmt/resources/test/fixtures/black/simple_cases/tupleassign.bak create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__attribute_access_on_number_literals.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments2.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments3.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments4.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments5.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments6.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments_non_breaking_space.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition_no_trailing_comma.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring_no_extra_empty_line_before_eof.py.snap delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap.new delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap.new create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff2.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff3.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff4.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff5.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip2.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip3.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip4.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip5.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip6.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip7.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip8.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fstring.py.snap delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap.new delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap.new delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap.new rename crates/ruff_fmt/{resources/test/fixtures/black/simple_cases/remove_parens.bak => src/snapshots/ruff_fmt__tests__simple_cases__remove_parens.py.snap} (52%) create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__slices.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__string_prefixes.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__torture.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens1.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens2.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens3.py.snap create mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tricky_unicode_symbols.py.snap delete mode 100644 crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap.new diff --git a/convert_to_insta.py b/convert_to_insta.py deleted file mode 100644 index 1ae9ab85276812..00000000000000 --- a/convert_to_insta.py +++ /dev/null @@ -1,61 +0,0 @@ -import argparse -from pathlib import Path - -EMPTY_LINE = "# EMPTY LINE WITH WHITESPACE (this comment will be removed)" - - -def read_data_from_file(file_name: Path) -> tuple[str, str]: - with open(file_name, "r", encoding="utf8") as test: - lines = test.readlines() - _input: list[str] = [] - _output: list[str] = [] - result = _input - for line in lines: - line = line.replace(EMPTY_LINE, "") - if line.rstrip() == "# output": - result = _output - continue - - result.append(line) - if _input and not _output: - # If there's no output marker, treat the entire file as already pre-formatted. - _output = _input[:] - return "".join(_input).strip() + "\n", "".join(_output).strip() + "\n" - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("file", type=Path) - args = parser.parse_args() - - file_name: Path = args.file - (input_content, output_content) = read_data_from_file(file_name) - - with open(file_name, "r", encoding="utf8") as fp1: - with open(file_name.with_suffix(".bak"), "w+", encoding="utf8") as fp2: - fp2.write(fp1.read()) - - with open(file_name, "w+", encoding="utf8") as fp: - fp.write(input_content) - - relative_name = str( - file_name.relative_to("crates/ruff_fmt/resources/test/fixtures/black") - ) - suffix = relative_name.replace("/", "__") - snapshot_path = ( - Path("crates/ruff_fmt/src/snapshots") / f"ruff_fmt__tests__{suffix}.snap" - ) - with open(snapshot_path, "w+", encoding="utf8") as fp: - fp.write( - f"""--- -source: src/source_code/mod.rs -assertion_line: 0 -expression: formatted ---- -{output_content} -""" - ) - - -if __name__ == "__main__": - main() diff --git a/crates/ruff_fmt/resources/test/fixtures/black/conditional_expression.py b/crates/ruff_fmt/resources/test/fixtures/black/conditional_expression.py deleted file mode 100644 index 620a12dc986a86..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/conditional_expression.py +++ /dev/null @@ -1,160 +0,0 @@ -long_kwargs_single_line = my_function( - foo="test, this is a sample value", - bar=some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz, - baz="hello, this is a another value", -) - -multiline_kwargs_indented = my_function( - foo="test, this is a sample value", - bar=some_long_value_name_foo_bar_baz - if some_boolean_variable - else some_fallback_value_foo_bar_baz, - baz="hello, this is a another value", -) - -imploding_kwargs = my_function( - foo="test, this is a sample value", - bar=a - if foo - else b, - baz="hello, this is a another value", -) - -imploding_line = ( - 1 - if 1 + 1 == 2 - else 0 -) - -exploding_line = "hello this is a slightly long string" if some_long_value_name_foo_bar_baz else "this one is a little shorter" - -positional_argument_test(some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz) - -def weird_default_argument(x=some_long_value_name_foo_bar_baz - if SOME_CONSTANT - else some_fallback_value_foo_bar_baz): - pass - -nested = "hello this is a slightly long string" if (some_long_value_name_foo_bar_baz if - nesting_test_expressions else some_fallback_value_foo_bar_baz) \ - else "this one is a little shorter" - -generator_expression = ( - some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz for some_boolean_variable in some_iterable -) - - -def limit_offset_sql(self, low_mark, high_mark): - """Return LIMIT/OFFSET SQL clause.""" - limit, offset = self._get_limit_offset_params(low_mark, high_mark) - return " ".join( - sql - for sql in ( - "LIMIT %d" % limit if limit else None, - ("OFFSET %d" % offset) if offset else None, - ) - if sql - ) - - -def something(): - clone._iterable_class = ( - NamedValuesListIterable - if named - else FlatValuesListIterable - if flat - else ValuesListIterable - ) - -# output - -long_kwargs_single_line = my_function( - foo="test, this is a sample value", - bar=( - some_long_value_name_foo_bar_baz - if some_boolean_variable - else some_fallback_value_foo_bar_baz - ), - baz="hello, this is a another value", -) - -multiline_kwargs_indented = my_function( - foo="test, this is a sample value", - bar=( - some_long_value_name_foo_bar_baz - if some_boolean_variable - else some_fallback_value_foo_bar_baz - ), - baz="hello, this is a another value", -) - -imploding_kwargs = my_function( - foo="test, this is a sample value", - bar=a if foo else b, - baz="hello, this is a another value", -) - -imploding_line = 1 if 1 + 1 == 2 else 0 - -exploding_line = ( - "hello this is a slightly long string" - if some_long_value_name_foo_bar_baz - else "this one is a little shorter" -) - -positional_argument_test( - some_long_value_name_foo_bar_baz - if some_boolean_variable - else some_fallback_value_foo_bar_baz -) - - -def weird_default_argument( - x=( - some_long_value_name_foo_bar_baz - if SOME_CONSTANT - else some_fallback_value_foo_bar_baz - ), -): - pass - - -nested = ( - "hello this is a slightly long string" - if ( - some_long_value_name_foo_bar_baz - if nesting_test_expressions - else some_fallback_value_foo_bar_baz - ) - else "this one is a little shorter" -) - -generator_expression = ( - ( - some_long_value_name_foo_bar_baz - if some_boolean_variable - else some_fallback_value_foo_bar_baz - ) - for some_boolean_variable in some_iterable -) - - -def limit_offset_sql(self, low_mark, high_mark): - """Return LIMIT/OFFSET SQL clause.""" - limit, offset = self._get_limit_offset_params(low_mark, high_mark) - return " ".join( - sql - for sql in ( - "LIMIT %d" % limit if limit else None, - ("OFFSET %d" % offset) if offset else None, - ) - if sql - ) - - -def something(): - clone._iterable_class = ( - NamedValuesListIterable - if named - else FlatValuesListIterable if flat else ValuesListIterable - ) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/empty_pyproject.toml b/crates/ruff_fmt/resources/test/fixtures/black/empty_pyproject.toml deleted file mode 100644 index 8c5274d900b065..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/empty_pyproject.toml +++ /dev/null @@ -1,2 +0,0 @@ -# Empty pyproject.toml to use with some tests that depend on Python 3.6 autodiscovery -# and so on. diff --git a/crates/ruff_fmt/resources/test/fixtures/black/fast/pep_572_do_not_remove_parens.py b/crates/ruff_fmt/resources/test/fixtures/black/fast/pep_572_do_not_remove_parens.py deleted file mode 100644 index 05619ddcc2b033..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/fast/pep_572_do_not_remove_parens.py +++ /dev/null @@ -1,25 +0,0 @@ -# Most of the following examples are really dumb, some of them aren't even accepted by Python, -# we're fixing them only so fuzzers (which follow the grammar which actually allows these -# examples matter of fact!) don't yell at us :p - -del (a := [1]) - -try: - pass -except (a := 1) as (b := why_does_this_exist): - pass - -for (z := 124) in (x := -124): - pass - -with (y := [3, 2, 1]) as (funfunfun := indeed): - pass - - -@(please := stop) -def sigh(): - pass - - -for (x := 3, y := 4) in y: - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/.gitignore deleted file mode 100644 index 2987e7bb646d5d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/.gitignore +++ /dev/null @@ -1 +0,0 @@ -a.py diff --git a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/a.py b/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/b.py b/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir1/b.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/a.py b/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/b.py b/crates/ruff_fmt/resources/test/fixtures/black/gitignore_used_on_multiple_sources/dir2/b.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/a.py b/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/.gitignore deleted file mode 100644 index 150f68c80f5295..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*/* diff --git a/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/b.py b/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/b.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/subdir/c.py b/crates/ruff_fmt/resources/test/fixtures/black/ignore_subfolders_gitignore_tests/subdir/subdir/c.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/.gitignore deleted file mode 100644 index 91f34560522c0b..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -dont_exclude/ diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pie b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pie deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.py b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pyi b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/.definitely_exclude/a.pyi deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pie b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pie deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.py b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pyi b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/dont_exclude/a.pyi deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pie b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pie deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.py b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pyi b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/b/exclude/a.pyi deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/pyproject.toml b/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/pyproject.toml deleted file mode 100644 index 9ba7ec26980a9d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/include_exclude_tests/pyproject.toml +++ /dev/null @@ -1,3 +0,0 @@ -[build-system] -requires = ["setuptools>=41.0", "setuptools-scm", "wheel"] -build-backend = "setuptools.build_meta" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/.gitignore deleted file mode 100644 index cdf4cb4feba5fc..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -! diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/a.py b/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/pyproject.toml b/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/pyproject.toml deleted file mode 100644 index 3908e457a9ec11..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/invalid_gitignore_tests/pyproject.toml +++ /dev/null @@ -1 +0,0 @@ -# Empty configuration file; used in tests to avoid interference from Black's own config. diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a.py b/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/.gitignore deleted file mode 100644 index cdf4cb4feba5fc..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -! diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/a.py b/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/a/a.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/pyproject.toml b/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/pyproject.toml deleted file mode 100644 index 3908e457a9ec11..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/invalid_nested_gitignore_tests/pyproject.toml +++ /dev/null @@ -1 +0,0 @@ -# Empty configuration file; used in tests to avoid interference from Black's own config. diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/non_python_notebook.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/non_python_notebook.ipynb deleted file mode 100644 index ee5453973b7ab3..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/non_python_notebook.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "metadata": { - "kernelspec": { - "name": "ir", - "display_name": "R", - "language": "R" - }, - "language_info": { - "name": "R", - "codemirror_mode": "r", - "pygments_lexer": "r", - "mimetype": "text/x-r-source", - "file_extension": ".r", - "version": "4.0.5" - } - }, - "nbformat_minor": 4, - "nbformat": 4, - "cells": [ - { - "cell_type": "code", - "source": "library(tidyverse) ", - "metadata": { - "_uuid": "051d70d956493feee0c6d64651c6a088724dca2a", - "_execution_state": "idle" - }, - "execution_count": null, - "outputs": [] - } - ] -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_empty_metadata.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_empty_metadata.ipynb deleted file mode 100644 index 7dc1f805cd67c6..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_empty_metadata.ipynb +++ /dev/null @@ -1,27 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%time\n", - "\n", - "print('foo')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_no_trailing_newline.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_no_trailing_newline.ipynb deleted file mode 100644 index 4f82869312d52c..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_no_trailing_newline.ipynb +++ /dev/null @@ -1,39 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%time\n", - "\n", - "print('foo')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "interpreter": { - "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8" - }, - "kernelspec": { - "display_name": "Python 3.8.10 64-bit ('black': venv)", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_trailing_newline.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_trailing_newline.ipynb deleted file mode 100644 index 4f82869312d52c..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_trailing_newline.ipynb +++ /dev/null @@ -1,39 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%time\n", - "\n", - "print('foo')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "interpreter": { - "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8" - }, - "kernelspec": { - "display_name": "Python 3.8.10 64-bit ('black': venv)", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_which_cant_be_parsed.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_which_cant_be_parsed.ipynb deleted file mode 100644 index 257cc5642cb1a0..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_which_cant_be_parsed.ipynb +++ /dev/null @@ -1 +0,0 @@ -foo diff --git a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_without_changes.ipynb b/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_without_changes.ipynb deleted file mode 100644 index 9eec9263aa3ed0..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/jupyter/notebook_without_changes.ipynb +++ /dev/null @@ -1,46 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%time\n", - "\n", - "print(\"foo\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This notebook should not be reformatted" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "interpreter": { - "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8" - }, - "kernelspec": { - "display_name": "Python 3.8.10 64-bit ('black': venv)", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/async_as_identifier.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/async_as_identifier.py deleted file mode 100644 index c36a5e54b0e332..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/async_as_identifier.py +++ /dev/null @@ -1,49 +0,0 @@ -def async(): - pass - - -def await(): - pass - - -await = lambda: None -async = lambda: None -async() -await() - - -def sync_fn(): - await = lambda: None - async = lambda: None - async() - await() - - -async def async_fn(): - await async_fn() - - -# output -def async(): - pass - - -def await(): - pass - - -await = lambda: None -async = lambda: None -async() -await() - - -def sync_fn(): - await = lambda: None - async = lambda: None - async() - await() - - -async def async_fn(): - await async_fn() diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.diff b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.diff deleted file mode 100644 index 6226858a157b4d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.diff +++ /dev/null @@ -1,13 +0,0 @@ ---- [Deterministic header] -+++ [Deterministic header] -@@ -1,6 +1,5 @@ --def abc (): -- return ["hello", "world", -- "!"] -+def abc(): -+ return ["hello", "world", "!"] - --print( "Incorrect formatting" --) -+ -+print("Incorrect formatting") diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.py deleted file mode 100644 index c5278325db3fc0..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/blackd_diff.py +++ /dev/null @@ -1,6 +0,0 @@ -def abc (): - return ["hello", "world", - "!"] - -print( "Incorrect formatting" -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.out b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.out deleted file mode 100644 index fa60010d421da5..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.out +++ /dev/null @@ -1,810 +0,0 @@ -file_input - decorated - decorator - AT - '@' - NAME - 'dataclass' - NEWLINE - '\n' - /decorator - classdef - NAME - 'class' - NAME - ' ' - 'DebugVisitor' - LPAR - '(' - power - NAME - 'Visitor' - trailer - LSQB - '[' - NAME - 'T' - RSQB - ']' - /trailer - /power - RPAR - ')' - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - expr_stmt - NAME - ' ' - 'tree_depth' - annassign - COLON - ':' - NAME - ' ' - 'int' - EQUAL - ' ' - '=' - NUMBER - ' ' - '0' - /annassign - /expr_stmt - NEWLINE - '\n' - /simple_stmt - funcdef - NAME - '\n ' - 'def' - NAME - ' ' - 'visit_default' - parameters - LPAR - '(' - typedargslist - NAME - 'self' - COMMA - ',' - tname - NAME - ' ' - 'node' - COLON - ':' - NAME - ' ' - 'LN' - /tname - /typedargslist - RPAR - ')' - /parameters - RARROW - ' ' - '->' - power - NAME - ' ' - 'Iterator' - trailer - LSQB - '[' - NAME - 'T' - RSQB - ']' - /trailer - /power - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - expr_stmt - NAME - ' ' - 'indent' - EQUAL - ' ' - '=' - term - STRING - ' ' - "' '" - STAR - ' ' - '*' - atom - LPAR - ' ' - '(' - term - NUMBER - '2' - STAR - ' ' - '*' - power - NAME - ' ' - 'self' - trailer - DOT - '.' - NAME - 'tree_depth' - /trailer - /power - /term - RPAR - ')' - /atom - /term - /expr_stmt - NEWLINE - '\n' - /simple_stmt - if_stmt - NAME - ' ' - 'if' - power - NAME - ' ' - 'isinstance' - trailer - LPAR - '(' - arglist - NAME - 'node' - COMMA - ',' - NAME - ' ' - 'Node' - /arglist - RPAR - ')' - /trailer - /power - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - expr_stmt - NAME - ' ' - '_type' - EQUAL - ' ' - '=' - power - NAME - ' ' - 'type_repr' - trailer - LPAR - '(' - power - NAME - 'node' - trailer - DOT - '.' - NAME - 'type' - /trailer - /power - RPAR - ')' - /trailer - /power - /expr_stmt - NEWLINE - '\n' - /simple_stmt - simple_stmt - power - NAME - ' ' - 'out' - trailer - LPAR - '(' - arglist - STRING - "f'{indent}{_type}'" - COMMA - ',' - argument - NAME - ' ' - 'fg' - EQUAL - '=' - STRING - "'yellow'" - /argument - /arglist - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - simple_stmt - expr_stmt - power - NAME - ' ' - 'self' - trailer - DOT - '.' - NAME - 'tree_depth' - /trailer - /power - PLUSEQUAL - ' ' - '+=' - NUMBER - ' ' - '1' - /expr_stmt - NEWLINE - '\n' - /simple_stmt - for_stmt - NAME - ' ' - 'for' - NAME - ' ' - 'child' - NAME - ' ' - 'in' - power - NAME - ' ' - 'node' - trailer - DOT - '.' - NAME - 'children' - /trailer - /power - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - yield_expr - NAME - ' ' - 'yield' - yield_arg - NAME - ' ' - 'from' - power - NAME - ' ' - 'self' - trailer - DOT - '.' - NAME - 'visit' - /trailer - trailer - LPAR - '(' - NAME - 'child' - RPAR - ')' - /trailer - /power - /yield_arg - /yield_expr - NEWLINE - '\n' - /simple_stmt - DEDENT - '' - /suite - /for_stmt - simple_stmt - expr_stmt - power - NAME - '\n ' - 'self' - trailer - DOT - '.' - NAME - 'tree_depth' - /trailer - /power - MINEQUAL - ' ' - '-=' - NUMBER - ' ' - '1' - /expr_stmt - NEWLINE - '\n' - /simple_stmt - simple_stmt - power - NAME - ' ' - 'out' - trailer - LPAR - '(' - arglist - STRING - "f'{indent}/{_type}'" - COMMA - ',' - argument - NAME - ' ' - 'fg' - EQUAL - '=' - STRING - "'yellow'" - /argument - COMMA - ',' - argument - NAME - ' ' - 'bold' - EQUAL - '=' - NAME - 'False' - /argument - /arglist - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - DEDENT - '' - /suite - NAME - ' ' - 'else' - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - expr_stmt - NAME - ' ' - '_type' - EQUAL - ' ' - '=' - power - NAME - ' ' - 'token' - trailer - DOT - '.' - NAME - 'tok_name' - /trailer - trailer - DOT - '.' - NAME - 'get' - /trailer - trailer - LPAR - '(' - arglist - power - NAME - 'node' - trailer - DOT - '.' - NAME - 'type' - /trailer - /power - COMMA - ',' - power - NAME - ' ' - 'str' - trailer - LPAR - '(' - power - NAME - 'node' - trailer - DOT - '.' - NAME - 'type' - /trailer - /power - RPAR - ')' - /trailer - /power - /arglist - RPAR - ')' - /trailer - /power - /expr_stmt - NEWLINE - '\n' - /simple_stmt - simple_stmt - power - NAME - ' ' - 'out' - trailer - LPAR - '(' - arglist - STRING - "f'{indent}{_type}'" - COMMA - ',' - argument - NAME - ' ' - 'fg' - EQUAL - '=' - STRING - "'blue'" - /argument - COMMA - ',' - argument - NAME - ' ' - 'nl' - EQUAL - '=' - NAME - 'False' - /argument - /arglist - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - if_stmt - NAME - ' ' - 'if' - power - NAME - ' ' - 'node' - trailer - DOT - '.' - NAME - 'prefix' - /trailer - /power - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - power - NAME - " # We don't have to handle prefixes for `Node` objects since\n # that delegates to the first child anyway.\n " - 'out' - trailer - LPAR - '(' - arglist - STRING - "f' {node.prefix!r}'" - COMMA - ',' - argument - NAME - ' ' - 'fg' - EQUAL - '=' - STRING - "'green'" - /argument - COMMA - ',' - argument - NAME - ' ' - 'bold' - EQUAL - '=' - NAME - 'False' - /argument - COMMA - ',' - argument - NAME - ' ' - 'nl' - EQUAL - '=' - NAME - 'False' - /argument - /arglist - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - DEDENT - '' - /suite - /if_stmt - simple_stmt - power - NAME - ' ' - 'out' - trailer - LPAR - '(' - arglist - STRING - "f' {node.value!r}'" - COMMA - ',' - argument - NAME - ' ' - 'fg' - EQUAL - '=' - STRING - "'blue'" - /argument - COMMA - ',' - argument - NAME - ' ' - 'bold' - EQUAL - '=' - NAME - 'False' - /argument - /arglist - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - DEDENT - '' - /suite - /if_stmt - DEDENT - '' - /suite - /funcdef - decorated - decorator - AT - '\n ' - '@' - NAME - 'classmethod' - NEWLINE - '\n' - /decorator - funcdef - NAME - ' ' - 'def' - NAME - ' ' - 'show' - parameters - LPAR - '(' - typedargslist - NAME - 'cls' - COMMA - ',' - tname - NAME - ' ' - 'code' - COLON - ':' - NAME - ' ' - 'str' - /tname - /typedargslist - RPAR - ')' - /parameters - RARROW - ' ' - '->' - NAME - ' ' - 'None' - COLON - ':' - suite - NEWLINE - '\n' - INDENT - '' - simple_stmt - STRING - ' ' - '"""Pretty-prints a given string of `code`.\n\n Convenience method for debugging.\n """' - NEWLINE - '\n' - /simple_stmt - simple_stmt - expr_stmt - NAME - ' ' - 'v' - annassign - COLON - ':' - power - NAME - ' ' - 'DebugVisitor' - trailer - LSQB - '[' - NAME - 'None' - RSQB - ']' - /trailer - /power - EQUAL - ' ' - '=' - power - NAME - ' ' - 'DebugVisitor' - trailer - LPAR - '(' - RPAR - ')' - /trailer - /power - /annassign - /expr_stmt - NEWLINE - '\n' - /simple_stmt - simple_stmt - power - NAME - ' ' - 'list' - trailer - LPAR - '(' - power - NAME - 'v' - trailer - DOT - '.' - NAME - 'visit' - /trailer - trailer - LPAR - '(' - power - NAME - 'lib2to3_parse' - trailer - LPAR - '(' - NAME - 'code' - RPAR - ')' - /trailer - /power - RPAR - ')' - /trailer - /power - RPAR - ')' - /trailer - /power - NEWLINE - '\n' - /simple_stmt - DEDENT - '' - /suite - /funcdef - /decorated - DEDENT - '' - /suite - /classdef - /decorated - ENDMARKER - '' -/file_input diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.py deleted file mode 100644 index d1d1ba12165148..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/debug_visitor.py +++ /dev/null @@ -1,32 +0,0 @@ -@dataclass -class DebugVisitor(Visitor[T]): - tree_depth: int = 0 - - def visit_default(self, node: LN) -> Iterator[T]: - indent = ' ' * (2 * self.tree_depth) - if isinstance(node, Node): - _type = type_repr(node.type) - out(f'{indent}{_type}', fg='yellow') - self.tree_depth += 1 - for child in node.children: - yield from self.visit(child) - - self.tree_depth -= 1 - out(f'{indent}/{_type}', fg='yellow', bold=False) - else: - _type = token.tok_name.get(node.type, str(node.type)) - out(f'{indent}{_type}', fg='blue', nl=False) - if node.prefix: - # We don't have to handle prefixes for `Node` objects since - # that delegates to the first child anyway. - out(f' {node.prefix!r}', fg='green', bold=False, nl=False) - out(f' {node.value!r}', fg='blue', bold=False) - - @classmethod - def show(cls, code: str) -> None: - """Pretty-prints a given string of `code`. - - Convenience method for debugging. - """ - v: DebugVisitor[None] = DebugVisitor() - list(v.visit(lib2to3_parse(code))) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/decorators.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/decorators.py deleted file mode 100644 index a0f38ca7b9d411..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/decorators.py +++ /dev/null @@ -1,182 +0,0 @@ -# This file doesn't use the standard decomposition. -# Decorator syntax test cases are separated by double # comments. -# Those before the 'output' comment are valid under the old syntax. -# Those after the 'ouput' comment require PEP614 relaxed syntax. -# Do not remove the double # separator before the first test case, it allows -# the comment before the test case to be ignored. - -## - -@decorator -def f(): - ... - -## - -@decorator() -def f(): - ... - -## - -@decorator(arg) -def f(): - ... - -## - -@decorator(kwarg=0) -def f(): - ... - -## - -@decorator(*args) -def f(): - ... - -## - -@decorator(**kwargs) -def f(): - ... - -## - -@decorator(*args, **kwargs) -def f(): - ... - -## - -@decorator(*args, **kwargs,) -def f(): - ... - -## - -@dotted.decorator -def f(): - ... - -## - -@dotted.decorator(arg) -def f(): - ... - -## - -@dotted.decorator(kwarg=0) -def f(): - ... - -## - -@dotted.decorator(*args) -def f(): - ... - -## - -@dotted.decorator(**kwargs) -def f(): - ... - -## - -@dotted.decorator(*args, **kwargs) -def f(): - ... - -## - -@dotted.decorator(*args, **kwargs,) -def f(): - ... - -## - -@double.dotted.decorator -def f(): - ... - -## - -@double.dotted.decorator(arg) -def f(): - ... - -## - -@double.dotted.decorator(kwarg=0) -def f(): - ... - -## - -@double.dotted.decorator(*args) -def f(): - ... - -## - -@double.dotted.decorator(**kwargs) -def f(): - ... - -## - -@double.dotted.decorator(*args, **kwargs) -def f(): - ... - -## - -@double.dotted.decorator(*args, **kwargs,) -def f(): - ... - -## - -@_(sequence["decorator"]) -def f(): - ... - -## - -@eval("sequence['decorator']") -def f(): - ... - -# output - -## - -@decorator()() -def f(): - ... - -## - -@(decorator) -def f(): - ... - -## - -@sequence["decorator"] -def f(): - ... - -## - -@decorator[List[str]] -def f(): - ... - -## - -@var := decorator -def f(): - ... \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_no_string_normalization.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_no_string_normalization.py deleted file mode 100644 index a90b578f09afb7..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_no_string_normalization.py +++ /dev/null @@ -1,249 +0,0 @@ -class ALonelyClass: - ''' - A multiline class docstring. - ''' - def AnEquallyLonelyMethod(self): - ''' - A multiline method docstring''' - pass - - -def one_function(): - '''This is a docstring with a single line of text.''' - pass - - -def shockingly_the_quotes_are_normalized(): - '''This is a multiline docstring. - This is a multiline docstring. - This is a multiline docstring. - ''' - pass - - -def foo(): - """This is a docstring with - some lines of text here - """ - return - - -def baz(): - '''"This" is a string with some - embedded "quotes"''' - return - - -def poit(): - """ - Lorem ipsum dolor sit amet. - - Consectetur adipiscing elit: - - sed do eiusmod tempor incididunt ut labore - - dolore magna aliqua - - enim ad minim veniam - - quis nostrud exercitation ullamco laboris nisi - - aliquip ex ea commodo consequat - """ - pass - - -def under_indent(): - """ - These lines are indented in a way that does not -make sense. - """ - pass - - -def over_indent(): - """ - This has a shallow indent - - But some lines are deeper - - And the closing quote is too deep - """ - pass - - -def single_line(): - """But with a newline after it! - - """ - pass - - -def this(): - r""" - 'hey ho' - """ - - -def that(): - """ "hey yah" """ - - -def and_that(): - """ - "hey yah" """ - - -def and_this(): - ''' - "hey yah"''' - - -def believe_it_or_not_this_is_in_the_py_stdlib(): ''' -"hey yah"''' - - -def shockingly_the_quotes_are_normalized_v2(): - ''' - Docstring Docstring Docstring - ''' - pass - - -def backslash_space(): - '\ ' - - -def multiline_backslash_1(): - ''' - hey\there\ - \ ''' - - -def multiline_backslash_2(): - ''' - hey there \ ''' - - -def multiline_backslash_3(): - ''' - already escaped \\ ''' - -# output - -class ALonelyClass: - ''' - A multiline class docstring. - ''' - - def AnEquallyLonelyMethod(self): - ''' - A multiline method docstring''' - pass - - -def one_function(): - '''This is a docstring with a single line of text.''' - pass - - -def shockingly_the_quotes_are_normalized(): - '''This is a multiline docstring. - This is a multiline docstring. - This is a multiline docstring. - ''' - pass - - -def foo(): - """This is a docstring with - some lines of text here - """ - return - - -def baz(): - '''"This" is a string with some - embedded "quotes"''' - return - - -def poit(): - """ - Lorem ipsum dolor sit amet. - - Consectetur adipiscing elit: - - sed do eiusmod tempor incididunt ut labore - - dolore magna aliqua - - enim ad minim veniam - - quis nostrud exercitation ullamco laboris nisi - - aliquip ex ea commodo consequat - """ - pass - - -def under_indent(): - """ - These lines are indented in a way that does not - make sense. - """ - pass - - -def over_indent(): - """ - This has a shallow indent - - But some lines are deeper - - And the closing quote is too deep - """ - pass - - -def single_line(): - """But with a newline after it!""" - pass - - -def this(): - r""" - 'hey ho' - """ - - -def that(): - """ "hey yah" """ - - -def and_that(): - """ - "hey yah" """ - - -def and_this(): - ''' - "hey yah"''' - - -def believe_it_or_not_this_is_in_the_py_stdlib(): - ''' - "hey yah"''' - - -def shockingly_the_quotes_are_normalized_v2(): - ''' - Docstring Docstring Docstring - ''' - pass - - -def backslash_space(): - '\ ' - - -def multiline_backslash_1(): - ''' - hey\there\ - \ ''' - - -def multiline_backslash_2(): - ''' - hey there \ ''' - - -def multiline_backslash_3(): - ''' - already escaped \\''' diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_preview_no_string_normalization.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_preview_no_string_normalization.py deleted file mode 100644 index 338cc01d33e64d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/docstring_preview_no_string_normalization.py +++ /dev/null @@ -1,10 +0,0 @@ -def do_not_touch_this_prefix(): - R"""There was a bug where docstring prefixes would be normalized even with -S.""" - - -def do_not_touch_this_prefix2(): - FR'There was a bug where docstring prefixes would be normalized even with -S.' - - -def do_not_touch_this_prefix3(): - u'''There was a bug where docstring prefixes would be normalized even with -S.''' diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/expression_skip_magic_trailing_comma.diff b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/expression_skip_magic_trailing_comma.diff deleted file mode 100644 index eba3fd2da7dfeb..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/expression_skip_magic_trailing_comma.diff +++ /dev/null @@ -1,447 +0,0 @@ ---- [Deterministic header] -+++ [Deterministic header] -@@ -1,8 +1,8 @@ - ... --'some_string' --b'\\xa3' -+"some_string" -+b"\\xa3" - Name - None - True - False - 1 -@@ -21,99 +21,118 @@ - Name1 or (Name2 and Name3) or Name4 - Name1 or Name2 and Name3 or Name4 - v1 << 2 - 1 >> v2 - 1 % finished --1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8 --((1 + v2) - (v3 * 4)) ^ (((5 ** v6) / 7) // 8) -+1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8 -+((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8) - not great - ~great - +value - -1 - ~int and not v1 ^ 123 + v2 | True - (~int) and (not ((v1 ^ (123 + v2)) | True)) --+really ** -confusing ** ~operator ** -precedence --flags & ~ select.EPOLLIN and waiters.write_task is not None -++(really ** -(confusing ** ~(operator**-precedence))) -+flags & ~select.EPOLLIN and waiters.write_task is not None - lambda arg: None - lambda a=True: a - lambda a, b, c=True: a --lambda a, b, c=True, *, d=(1 << v2), e='str': a --lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b -+lambda a, b, c=True, *, d=(1 << v2), e="str": a -+lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b - manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() --foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id]) -+foo = lambda port_id, ignore_missing: { -+ "port1": port1_resource, -+ "port2": port2_resource, -+}[port_id] - 1 if True else 2 - str or None if True else str or bytes or None - (str or None) if True else (str or bytes or None) - str or None if (1 if True else 2) else str or bytes or None - (str or None) if (1 if True else 2) else (str or bytes or None) --((super_long_variable_name or None) if (1 if super_long_test_name else 2) else (str or bytes or None)) --{'2.7': dead, '3.7': (long_live or die_hard)} --{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} -+( -+ (super_long_variable_name or None) -+ if (1 if super_long_test_name else 2) -+ else (str or bytes or None) -+) -+{"2.7": dead, "3.7": (long_live or die_hard)} -+{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}} - {**a, **b, **c} --{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} --({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None -+{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")} -+({"a": "b"}, (True or False), (+value), "string", b"bytes") or None - () - (1,) - (1, 2) - (1, 2, 3) - [] - [1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] --[1, 2, 3,] -+[1, 2, 3] - [*a] - [*range(10)] --[*a, 4, 5,] --[4, *a, 5,] --[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more] -+[*a, 4, 5] -+[4, *a, 5] -+[ -+ this_is_a_very_long_variable_which_will_force_a_delimiter_split, -+ element, -+ another, -+ *more, -+] - {i for i in (1, 2, 3)} --{(i ** 2) for i in (1, 2, 3)} --{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} --{((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} -+{(i**2) for i in (1, 2, 3)} -+{(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))} -+{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} - [i for i in (1, 2, 3)] --[(i ** 2) for i in (1, 2, 3)] --[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] --[((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] -+[(i**2) for i in (1, 2, 3)] -+[(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))] -+[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] - {i: 0 for i in (1, 2, 3)} --{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} -+{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))} - {a: b * 2 for a, b in dictionary.items()} - {a: b * -2 for a, b in dictionary.items()} --{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} -+{ -+ k: v -+ for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension -+} - Python3 > Python2 > COBOL - Life is Life - call() - call(arg) --call(kwarg='hey') --call(arg, kwarg='hey') --call(arg, another, kwarg='hey', **kwargs) --call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6 -+call(kwarg="hey") -+call(arg, kwarg="hey") -+call(arg, another, kwarg="hey", **kwargs) -+call( -+ this_is_a_very_long_variable_which_will_force_a_delimiter_split, -+ arg, -+ another, -+ kwarg="hey", -+ **kwargs -+) # note: no trailing comma pre-3.6 - call(*gidgets[:2]) - call(a, *gidgets[:2]) - call(**self.screen_kwargs) - call(b, **self.screen_kwargs) - lukasz.langa.pl - call.me(maybe) --1 .real --1.0 .real -+(1).real -+(1.0).real - ....__class__ - list[str] - dict[str, int] - tuple[str, ...] --tuple[ -- str, int, float, dict[str, int] --] -+tuple[str, int, float, dict[str, int]] - tuple[str, int, float, dict[str, int],] - very_long_variable_name_filters: t.List[ - t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], - ] - xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - ) - xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - ) --xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[ -- ..., List[SomeClass] --] = classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore -+xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( -+ sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -+) # type: ignore - slice[0] - slice[0:1] - slice[0:1:2] - slice[:] - slice[:-1] -@@ -137,118 +156,197 @@ - numpy[-(c + 1) :, d] - numpy[:, l[-2]] - numpy[:, ::-1] - numpy[np.newaxis, :] - (str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) --{'2.7': dead, '3.7': long_live or die_hard} --{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} -+{"2.7": dead, "3.7": long_live or die_hard} -+{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"} - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] - (SomeName) - SomeName - (Good, Bad, Ugly) - (i for i in (1, 2, 3)) --((i ** 2) for i in (1, 2, 3)) --((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) --(((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) -+((i**2) for i in (1, 2, 3)) -+((i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))) -+(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) - (*starred,) --{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs} -+{ -+ "id": "1", -+ "type": "type", -+ "started_at": now(), -+ "ended_at": now() + timedelta(days=10), -+ "priority": 1, -+ "import_session_id": 1, -+ **kwargs, -+} - a = (1,) --b = 1, -+b = (1,) - c = 1 - d = (1,) + a + (2,) - e = (1,).count(1) - f = 1, *range(10) - g = 1, *"ten" --what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove) --what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove) --result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc()).all() --result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc(),).all() -+what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( -+ vars_to_remove -+) -+what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( -+ vars_to_remove -+) -+result = ( -+ session.query(models.Customer.id) -+ .filter( -+ models.Customer.account_id == account_id, models.Customer.email == email_address -+ ) -+ .order_by(models.Customer.id.asc()) -+ .all() -+) -+result = ( -+ session.query(models.Customer.id) -+ .filter( -+ models.Customer.account_id == account_id, models.Customer.email == email_address -+ ) -+ .order_by(models.Customer.id.asc()) -+ .all() -+) - Ø = set() - authors.łukasz.say_thanks() - mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), - } - -+ - def gen(): - yield from outside_of_generator -- a = (yield) -- b = ((yield)) -- c = (((yield))) -+ a = yield -+ b = yield -+ c = yield -+ - - async def f(): - await some.complicated[0].call(with_args=(True or (1 is not 1))) --print(* [] or [1]) -+ -+ -+print(*[] or [1]) - print(**{1: 3} if False else {x: x for x in range(3)}) --print(* lambda x: x) --assert(not Test),("Short message") --assert this is ComplexTest and not requirements.fit_in_a_single_line(force=False), "Short message" --assert(((parens is TooMany))) --for x, in (1,), (2,), (3,): ... --for y in (): ... --for z in (i for i in (1, 2, 3)): ... --for i in (call()): ... --for j in (1 + (2 + 3)): ... --while(this and that): ... --for addr_family, addr_type, addr_proto, addr_canonname, addr_sockaddr in socket.getaddrinfo('google.com', 'http'): -+print(*lambda x: x) -+assert not Test, "Short message" -+assert this is ComplexTest and not requirements.fit_in_a_single_line( -+ force=False -+), "Short message" -+assert parens is TooMany -+for (x,) in (1,), (2,), (3,): -+ ... -+for y in (): -+ ... -+for z in (i for i in (1, 2, 3)): -+ ... -+for i in call(): -+ ... -+for j in 1 + (2 + 3): -+ ... -+while this and that: -+ ... -+for ( -+ addr_family, -+ addr_type, -+ addr_proto, -+ addr_canonname, -+ addr_sockaddr, -+) in socket.getaddrinfo("google.com", "http"): - pass --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --if ( -- threading.current_thread() != threading.main_thread() and -- threading.current_thread() != threading.main_thread() or -- signal.getsignal(signal.SIGINT) != signal.default_int_handler --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa & -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa / -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- ~ aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l ** aaaa.m // aaaa.n --): -- return True --if ( -- ~ aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l ** aaaaaaaa.m // aaaaaaaa.n --): -- return True --if ( -- ~ aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k >> aaaaaaaaaaaaaaaa.l ** aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n --): -- return True --aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+if ( -+ threading.current_thread() != threading.main_thread() -+ and threading.current_thread() != threading.main_thread() -+ or signal.getsignal(signal.SIGINT) != signal.default_int_handler -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ ~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e -+ | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n -+): -+ return True -+if ( -+ ~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e -+ | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h -+ ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n -+): -+ return True -+if ( -+ ~aaaaaaaaaaaaaaaa.a -+ + aaaaaaaaaaaaaaaa.b -+ - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e -+ | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h -+ ^ aaaaaaaaaaaaaaaa.i -+ << aaaaaaaaaaaaaaaa.k -+ >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n -+): -+ return True -+( -+ aaaaaaaaaaaaaaaa -+ + aaaaaaaaaaaaaaaa -+ - aaaaaaaaaaaaaaaa -+ * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+ / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+) - aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa --aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+) - bbbb >> bbbb * bbbb --aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+) - last_call() - # standalone comment at ENDMARKER diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_py36.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_py36.py deleted file mode 100644 index cad935e525a460..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_py36.py +++ /dev/null @@ -1,16 +0,0 @@ -# The input source must not contain any Py36-specific syntax (e.g. argument type -# annotations, trailing comma after *rest) or this test becomes invalid. -def long_function_name(argument_one, argument_two, argument_three, argument_four, argument_five, argument_six, *rest): ... -# output -# The input source must not contain any Py36-specific syntax (e.g. argument type -# annotations, trailing comma after *rest) or this test becomes invalid. -def long_function_name( - argument_one, - argument_two, - argument_three, - argument_four, - argument_five, - argument_six, - *rest, -): - ... diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_pyi.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_pyi.py deleted file mode 100644 index 07ed93c6879363..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/force_pyi.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import Union - -@bird -def zoo(): ... - -class A: ... -@bar -class B: - def BMethod(self) -> None: ... - @overload - def BMethod(self, arg : List[str]) -> None: ... - -class C: ... -@hmm -class D: ... -class E: ... - -@baz -def foo() -> None: - ... - -class F (A , C): ... -def spam() -> None: ... - -@overload -def spam(arg: str) -> str: ... - -var : int = 1 - -def eggs() -> Union[str, int]: ... - -# output - -from typing import Union - -@bird -def zoo(): ... - -class A: ... - -@bar -class B: - def BMethod(self) -> None: ... - @overload - def BMethod(self, arg: List[str]) -> None: ... - -class C: ... - -@hmm -class D: ... - -class E: ... - -@baz -def foo() -> None: ... - -class F(A, C): ... - -def spam() -> None: ... -@overload -def spam(arg: str) -> str: ... - -var: int = 1 - -def eggs() -> Union[str, int]: ... diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/invalid_header.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/invalid_header.py deleted file mode 100644 index fb49e2f93e725e..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/invalid_header.py +++ /dev/null @@ -1,2 +0,0 @@ -This is not valid Python syntax -y = "This is valid syntax" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/linelength6.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/linelength6.py deleted file mode 100644 index 4fb342726f57ac..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/linelength6.py +++ /dev/null @@ -1,5 +0,0 @@ -# Regression test for #3427, which reproes only with line length <= 6 -def f(): - """ - x - """ diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/long_strings_flag_disabled.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/long_strings_flag_disabled.py deleted file mode 100644 index db3954e3abd7ea..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/long_strings_flag_disabled.py +++ /dev/null @@ -1,292 +0,0 @@ -x = "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - -x += "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - -y = "Short string" - -print( - "This is a really long string inside of a print statement with extra arguments attached at the end of it.", - x, - y, - z, -) - -print( - "This is a really long string inside of a print statement with no extra arguments attached at the end of it." -) - -D1 = { - "The First": "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", - "The Second": "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", -} - -D2 = { - 1.0: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", - 2.0: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", -} - -D3 = { - x: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", - y: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", -} - -D4 = { - "A long and ridiculous {}".format( - string_key - ): "This is a really really really long string that has to go i,side of a dictionary. It is soooo bad.", - some_func( - "calling", "some", "stuff" - ): "This is a really really really long string that has to go inside of a dictionary. It is {soooo} bad (#{x}).".format( - sooo="soooo", x=2 - ), - "A %s %s" - % ( - "formatted", - "string", - ): "This is a really really really long string that has to go inside of a dictionary. It is %s bad (#%d)." - % ("soooo", 2), -} - -func_with_keywords( - my_arg, - my_kwarg="Long keyword strings also need to be wrapped, but they will probably need to be handled a little bit differently.", -) - -bad_split1 = ( - "But what should happen when code has already been formatted but in the wrong way? Like" - " with a space at the end instead of the beginning. Or what about when it is split too soon?" -) - -bad_split2 = ( - "But what should happen when code has already " - "been formatted but in the wrong way? Like " - "with a space at the end instead of the " - "beginning. Or what about when it is split too " - "soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." -) - -bad_split3 = ( - "What if we have inline comments on " # First Comment - "each line of a bad split? In that " # Second Comment - "case, we should just leave it alone." # Third Comment -) - -bad_split_func1( - "But what should happen when code has already " - "been formatted but in the wrong way? Like " - "with a space at the end instead of the " - "beginning. Or what about when it is split too " - "soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split.", - xxx, - yyy, - zzz, -) - -bad_split_func2( - xxx, - yyy, - zzz, - long_string_kwarg="But what should happen when code has already been formatted but in the wrong way? Like " - "with a space at the end instead of the beginning. Or what about when it is split too " - "soon?", -) - -bad_split_func3( - ( - "But what should happen when code has already " - r"been formatted but in the wrong way? Like " - "with a space at the end instead of the " - r"beginning. Or what about when it is split too " - r"soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." - ), - xxx, - yyy, - zzz, -) - -raw_string = r"This is a long raw string. When re-formatting this string, black needs to make sure it prepends the 'r' onto the new string." - -fmt_string1 = "We also need to be sure to preserve any and all {} which may or may not be attached to the string in question.".format( - "method calls" -) - -fmt_string2 = "But what about when the string is {} but {}".format( - "short", - "the method call is really really really really really really really really long?", -) - -old_fmt_string1 = ( - "While we are on the topic of %s, we should also note that old-style formatting must also be preserved, since some %s still uses it." - % ("formatting", "code") -) - -old_fmt_string2 = "This is a %s %s %s %s" % ( - "really really really really really", - "old", - "way to format strings!", - "Use f-strings instead!", -) - -old_fmt_string3 = ( - "Whereas only the strings after the percent sign were long in the last example, this example uses a long initial string as well. This is another %s %s %s %s" - % ( - "really really really really really", - "old", - "way to format strings!", - "Use f-strings instead!", - ) -) - -fstring = f"f-strings definitely make things more {difficult} than they need to be for {{black}}. But boy they sure are handy. The problem is that some lines will need to have the 'f' whereas others do not. This {line}, for example, needs one." - -fstring_with_no_fexprs = f"Some regular string that needs to get split certainly but is NOT an fstring by any means whatsoever." - -comment_string = "Long lines with inline comments should have their comments appended to the reformatted string's enclosing right parentheses." # This comment gets thrown to the top. - -arg_comment_string = print( - "Long lines with inline comments which are apart of (and not the only member of) an argument list should have their comments appended to the reformatted string's enclosing left parentheses.", # This comment stays on the bottom. - "Arg #2", - "Arg #3", - "Arg #4", - "Arg #5", -) - -pragma_comment_string1 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa: E501 - -pragma_comment_string2 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa - -"""This is a really really really long triple quote string and it should not be touched.""" - -triple_quote_string = """This is a really really really long triple quote string assignment and it should not be touched.""" - -assert ( - some_type_of_boolean_expression -), "Followed by a really really really long string that is used to provide context to the AssertionError exception." - -assert ( - some_type_of_boolean_expression -), "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string {}.".format( - "formatting" -) - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string %s." - % "formatting" -) - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic %s %s." - % ("string", "formatting") -) - -some_function_call( - "With a reallly generic name and with a really really long string that is, at some point down the line, " - + added - + " to a variable and then added to another string." -) - -some_function_call( - "With a reallly generic name and with a really really long string that is, at some point down the line, " - + added - + " to a variable and then added to another string. But then what happens when the final string is also supppppperrrrr long?! Well then that second (realllllllly long) string should be split too.", - "and a second argument", - and_a_third, -) - -return "A really really really really really really really really really really really really really long {} {}".format( - "return", "value" -) - -func_with_bad_comma( - "This is a really long string argument to a function that has a trailing comma which should NOT be there.", -) - -func_with_bad_comma( - "This is a really long string argument to a function that has a trailing comma which should NOT be there.", # comment after comma -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), # comment after comma -) - -func_with_bad_parens_that_wont_fit_in_one_line( - ("short string that should have parens stripped"), x, y, z -) - -func_with_bad_parens_that_wont_fit_in_one_line( - x, y, ("short string that should have parens stripped"), z -) - -func_with_bad_parens( - ("short string that should have parens stripped"), - x, - y, - z, -) - -func_with_bad_parens( - x, - y, - ("short string that should have parens stripped"), - z, -) - -annotated_variable: Final = ( - "This is a large " - + STRING - + " that has been " - + CONCATENATED - + "using the '+' operator." -) -annotated_variable: Final = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." -annotated_variable: Literal[ - "fakse_literal" -] = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." - -backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\" -backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\\\" -backslashes = "This is a really 'long' string with \"embedded double quotes\" and 'single' quotes that also handles checking for an odd number of backslashes \\\", like this...\\\\\\" - -short_string = "Hi" " there." - -func_call(short_string=("Hi" " there.")) - -raw_strings = r"Don't" " get" r" merged" " unless they are all raw." - - -def foo(): - yield "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - - -x = f"This is a {{really}} long string that needs to be split without a doubt (i.e. most definitely). In short, this {string} that can't possibly be {{expected}} to fit all together on one line. In {fact} it may even take up three or more lines... like four or five... but probably just four." - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # type: ignore - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # noqa - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # pylint: disable=some-pylint-check - " of it." -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.diff b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.diff deleted file mode 100644 index 6d991c74f8f0ea..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.diff +++ /dev/null @@ -1,8 +0,0 @@ ---- [Deterministic header] -+++ [Deterministic header] -@@ -1,3 +1,3 @@ - # A comment-only file, with no final EOL character - # This triggers https://bugs.python.org/issue2142 --# This is the line without the EOL character -\ No newline at end of file -+# This is the line without the EOL character diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.py deleted file mode 100644 index 687e13675524da..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/missing_final_newline.py +++ /dev/null @@ -1,3 +0,0 @@ -# A comment-only file, with no final EOL character -# This triggers https://bugs.python.org/issue2142 -# This is the line without the EOL character \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/pattern_matching_invalid.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/pattern_matching_invalid.py deleted file mode 100644 index 22b5b94c0a46a7..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/pattern_matching_invalid.py +++ /dev/null @@ -1,18 +0,0 @@ -# First match, no errors -match something: - case bla(): - pass - -# Problem on line 10 -match invalid_case: - case valid_case: - pass - case a := b: - pass - case valid_case: - pass - -# No problems either -match something: - case bla(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/power_op_newline.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/power_op_newline.py deleted file mode 100644 index 85d434d63f6ea1..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/power_op_newline.py +++ /dev/null @@ -1,10 +0,0 @@ -importA;()<<0**0# - -# output - -importA -( - () - << 0 - ** 0 -) # diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/python2_detection.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/python2_detection.py deleted file mode 100644 index 8de2bb58adc8e8..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/python2_detection.py +++ /dev/null @@ -1,90 +0,0 @@ -# This uses a similar construction to the decorators.py test data file FYI. - -print "hello, world!" - -### - -exec "print('hello, world!')" - -### - -def set_position((x, y), value): - pass - -### - -try: - pass -except Exception, err: - pass - -### - -raise RuntimeError, "I feel like crashing today :p" - -### - -`wow_these_really_did_exist` - -### - -10L - -### - -10l - -### - -0123 - -# output - -print("hello python three!") - -### - -exec("I'm not sure if you can use exec like this but that's not important here!") - -### - -try: - pass -except make_exception(1, 2): - pass - -### - -try: - pass -except Exception as err: - pass - -### - -raise RuntimeError(make_msg(1, 2)) - -### - -raise RuntimeError("boom!",) - -### - -def set_position(x, y, value): - pass - -### - -10 - -### - -0 - -### - -000 - -### - -0o12 \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/string_quotes.py b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/string_quotes.py deleted file mode 100644 index 3384241f4adaf7..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/string_quotes.py +++ /dev/null @@ -1,112 +0,0 @@ -'''''' -'\'' -'"' -"'" -"\"" -"Hello" -"Don't do that" -'Here is a "' -'What\'s the deal here?' -"What's the deal \"here\"?" -"And \"here\"?" -"""Strings with "" in them""" -'''Strings with "" in them''' -'''Here's a "''' -'''Here's a " ''' -'''Just a normal triple -quote''' -f"just a normal {f} string" -f'''This is a triple-quoted {f}-string''' -f'MOAR {" ".join([])}' -f"MOAR {' '.join([])}" -r"raw string ftw" -r'Date d\'expiration:(.*)' -r'Tricky "quote' -r'Not-so-tricky \"quote' -rf'{yay}' -'\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the \'lazy\' dog.\n\ -' -re.compile(r'[\\"]') -"x = ''; y = \"\"" -"x = '''; y = \"\"" -"x = ''''; y = \"\"" -"x = '' ''; y = \"\"" -"x = ''; y = \"\"\"" -"x = '''; y = \"\"\"\"" -"x = ''''; y = \"\"\"\"\"" -"x = '' ''; y = \"\"\"\"\"" -'unnecessary \"\"escaping' -"unnecessary \'\'escaping" -'\\""' -"\\''" -'Lots of \\\\\\\\\'quotes\'' -f'{y * " "} \'{z}\'' -f'{{y * " "}} \'{z}\'' -f'\'{z}\' {y * " "}' -f'{y * x} \'{z}\'' -'\'{z}\' {y * " "}' -'{y * x} \'{z}\'' - -# We must bail out if changing the quotes would introduce backslashes in f-string -# expressions. xref: /~https://github.com/psf/black/issues/2348 -f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n" -f"\"{a}\"{'hello' * b}\"{c}\"" - -# output - -"""""" -"'" -'"' -"'" -'"' -"Hello" -"Don't do that" -'Here is a "' -"What's the deal here?" -'What\'s the deal "here"?' -'And "here"?' -"""Strings with "" in them""" -"""Strings with "" in them""" -'''Here's a "''' -"""Here's a " """ -"""Just a normal triple -quote""" -f"just a normal {f} string" -f"""This is a triple-quoted {f}-string""" -f'MOAR {" ".join([])}' -f"MOAR {' '.join([])}" -r"raw string ftw" -r"Date d\'expiration:(.*)" -r'Tricky "quote' -r"Not-so-tricky \"quote" -rf"{yay}" -"\nThe \"quick\"\nbrown fox\njumps over\nthe 'lazy' dog.\n" -re.compile(r'[\\"]') -"x = ''; y = \"\"" -"x = '''; y = \"\"" -"x = ''''; y = \"\"" -"x = '' ''; y = \"\"" -'x = \'\'; y = """' -'x = \'\'\'; y = """"' -'x = \'\'\'\'; y = """""' -'x = \'\' \'\'; y = """""' -'unnecessary ""escaping' -"unnecessary ''escaping" -'\\""' -"\\''" -"Lots of \\\\\\\\'quotes'" -f'{y * " "} \'{z}\'' -f"{{y * \" \"}} '{z}'" -f'\'{z}\' {y * " "}' -f"{y * x} '{z}'" -"'{z}' {y * \" \"}" -"{y * x} '{z}'" - -# We must bail out if changing the quotes would introduce backslashes in f-string -# expressions. xref: /~https://github.com/psf/black/issues/2348 -f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n" -f"\"{a}\"{'hello' * b}\"{c}\"" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/stub.pyi b/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/stub.pyi deleted file mode 100644 index af2cd2c2c026e6..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/miscellaneous/stub.pyi +++ /dev/null @@ -1,151 +0,0 @@ -X: int - -def f(): ... - - -class D: - ... - - -class C: - ... - -class B: - this_lack_of_newline_should_be_kept: int - def b(self) -> None: ... - - but_this_newline_should_also_be_kept: int - -class A: - attr: int - attr2: str - - def f(self) -> int: - ... - - def g(self) -> str: ... - - - -def g(): - ... - -def h(): ... - -if sys.version_info >= (3, 8): - class E: - def f(self): ... - class F: - - def f(self): ... - class G: ... - class H: ... -else: - class I: ... - class J: ... - def f(): ... - - class K: - def f(self): ... - def f(): ... - -class Nested: - class dirty: ... - class little: ... - class secret: - def who_has_to_know(self): ... - def verse(self): ... - -class Conditional: - def f(self): ... - if sys.version_info >= (3, 8): - def g(self): ... - else: - def g(self): ... - def h(self): ... - def i(self): ... - if sys.version_info >= (3, 8): - def j(self): ... - def k(self): ... - if sys.version_info >= (3, 8): - class A: ... - class B: ... - class C: - def l(self): ... - def m(self): ... - - -# output -X: int - -def f(): ... - -class D: ... -class C: ... - -class B: - this_lack_of_newline_should_be_kept: int - def b(self) -> None: ... - - but_this_newline_should_also_be_kept: int - -class A: - attr: int - attr2: str - - def f(self) -> int: ... - def g(self) -> str: ... - -def g(): ... -def h(): ... - -if sys.version_info >= (3, 8): - class E: - def f(self): ... - - class F: - def f(self): ... - - class G: ... - class H: ... - -else: - class I: ... - class J: ... - - def f(): ... - - class K: - def f(self): ... - - def f(): ... - -class Nested: - class dirty: ... - class little: ... - - class secret: - def who_has_to_know(self): ... - - def verse(self): ... - -class Conditional: - def f(self): ... - if sys.version_info >= (3, 8): - def g(self): ... - else: - def g(self): ... - - def h(self): ... - def i(self): ... - if sys.version_info >= (3, 8): - def j(self): ... - - def k(self): ... - if sys.version_info >= (3, 8): - class A: ... - class B: ... - - class C: - def l(self): ... - def m(self): ... diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/pyproject.toml b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/pyproject.toml deleted file mode 100644 index 9ba7ec26980a9d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/pyproject.toml +++ /dev/null @@ -1,3 +0,0 @@ -[build-system] -requires = ["setuptools>=41.0", "setuptools-scm", "wheel"] -build-backend = "setuptools.build_meta" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/.gitignore deleted file mode 100644 index 2987e7bb646d5d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/.gitignore +++ /dev/null @@ -1 +0,0 @@ -a.py diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/a.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/a.py deleted file mode 100644 index 7135cfd187cd4c..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/a.py +++ /dev/null @@ -1 +0,0 @@ -# should be excluded (root/.gitignore) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/b.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/b.py deleted file mode 100644 index bdeeca3c602855..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/b.py +++ /dev/null @@ -1 +0,0 @@ -# should be included diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/c.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/c.py deleted file mode 100644 index bdeeca3c602855..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/c.py +++ /dev/null @@ -1 +0,0 @@ -# should be included diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/.gitignore b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/.gitignore deleted file mode 100644 index 6df81dd798ef97..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/.gitignore +++ /dev/null @@ -1 +0,0 @@ -b.py diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/a.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/a.py deleted file mode 100644 index 7135cfd187cd4c..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/a.py +++ /dev/null @@ -1 +0,0 @@ -# should be excluded (root/.gitignore) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/b.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/b.py deleted file mode 100644 index c91d47946e6f38..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/b.py +++ /dev/null @@ -1 +0,0 @@ -# should be excluded (child/.gitignore) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/c.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/c.py deleted file mode 100644 index bdeeca3c602855..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/root/child/c.py +++ /dev/null @@ -1 +0,0 @@ -# should be included diff --git a/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/x.py b/crates/ruff_fmt/resources/test/fixtures/black/nested_gitignore_tests/x.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/cantfit.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/cantfit.py deleted file mode 100644 index cade382e30d8cf..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/cantfit.py +++ /dev/null @@ -1,111 +0,0 @@ -# long variable name -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 0 -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 1 # with a comment -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ - 1, 2, 3 -] -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function() -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( - arg1, arg2, arg3 -) -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( - [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 -) -# long function name -normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() -normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( - arg1, arg2, arg3 -) -normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( - [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 -) -# long arguments -normal_name = normal_function_name( - "but with super long string arguments that on their own exceed the line limit so there's no way it can ever fit", - "eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs", - this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, -) -string_variable_name = ( - "a string that is waaaaaaaayyyyyyyy too long, even in parens, there's nothing you can do" # noqa -) -for key in """ - hostname - port - username -""".split(): - if key in self.connect_kwargs: - raise ValueError(err.format(key)) -concatenated_strings = "some strings that are " "concatenated implicitly, so if you put them on separate " "lines it will fit" -del concatenated_strings, string_variable_name, normal_function_name, normal_name, need_more_to_make_the_line_long_enough - - -# output - - -# long variable name -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( - 0 -) -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( - 1 # with a comment -) -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ - 1, - 2, - 3, -] -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( - function() -) -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( - arg1, arg2, arg3 -) -this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( - [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 -) -# long function name -normal_name = ( - but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() -) -normal_name = ( - but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( - arg1, arg2, arg3 - ) -) -normal_name = ( - but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( - [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 - ) -) -# long arguments -normal_name = normal_function_name( - ( - "but with super long string arguments that on their own exceed the line limit" - " so there's no way it can ever fit" - ), - ( - "eggs with spam and eggs and spam with eggs with spam and eggs and spam with" - " eggs with spam and eggs and spam with eggs" - ), - this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, -) -string_variable_name = "a string that is waaaaaaaayyyyyyyy too long, even in parens, there's nothing you can do" # noqa -for key in """ - hostname - port - username -""".split(): - if key in self.connect_kwargs: - raise ValueError(err.format(key)) -concatenated_strings = ( - "some strings that are " - "concatenated implicitly, so if you put them on separate " - "lines it will fit" -) -del ( - concatenated_strings, - string_variable_name, - normal_function_name, - normal_name, - need_more_to_make_the_line_long_enough, -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments7.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/comments7.py deleted file mode 100644 index ec2dc501d8ef83..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments7.py +++ /dev/null @@ -1,285 +0,0 @@ -from .config import ( - Any, - Bool, - ConfigType, - ConfigTypeAttributes, - Int, - Path, - # String, - # resolve_to_config_type, - # DEFAULT_TYPE_ATTRIBUTES, -) - - -from .config import ( - Any, - Bool, - ConfigType, - ConfigTypeAttributes, - Int, - no_comma_here_yet - # and some comments, - # resolve_to_config_type, - # DEFAULT_TYPE_ATTRIBUTES, -) -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent # NOT DRY -) -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent as component # DRY -) - - -result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - -result = ( - 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -) - -result = ( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # aaa -) - -result = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # aaa - - -def func(): - c = call( - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0789, - a[-1], # type: ignore - ) - c = call( - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0789, - a[-1] # type: ignore - ) - c = call( - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0456, - 0.0789, - a[-1] # type: ignore - ) - - # The type: ignore exception only applies to line length, not - # other types of formatting. - c = call( - "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", # type: ignore - "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" - ) - - -class C: - @pytest.mark.parametrize( - ("post_data", "message"), - [ - # metadata_version errors. - ( - {}, - "None is an invalid value for Metadata-Version. Error: This field is" - " required. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ( - {"metadata_version": "-1"}, - "'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata" - " Version see" - " https://packaging.python.org/specifications/core-metadata" - ), - # name errors. - ( - {"metadata_version": "1.2"}, - "'' is an invalid value for Name. Error: This field is required. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ( - {"metadata_version": "1.2", "name": "foo-"}, - "'foo-' is an invalid value for Name. Error: Must start and end with a" - " letter or numeral and contain only ascii numeric and '.', '_' and" - " '-'. see https://packaging.python.org/specifications/core-metadata" - ), - # version errors. - ( - {"metadata_version": "1.2", "name": "example"}, - "'' is an invalid value for Version. Error: This field is required. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ( - {"metadata_version": "1.2", "name": "example", "version": "dog"}, - "'dog' is an invalid value for Version. Error: Must start and end with" - " a letter or numeral and contain only ascii numeric and '.', '_' and" - " '-'. see https://packaging.python.org/specifications/core-metadata" - ) - ] - ) - def test_fails_invalid_post_data( - self, pyramid_config, db_request, post_data, message - ): - ... - -square = Square(4) # type: Optional[Square] - -# output - -from .config import ( - Any, - Bool, - ConfigType, - ConfigTypeAttributes, - Int, - Path, - # String, - # resolve_to_config_type, - # DEFAULT_TYPE_ATTRIBUTES, -) - - -from .config import ( - Any, - Bool, - ConfigType, - ConfigTypeAttributes, - Int, - no_comma_here_yet, - # and some comments, - # resolve_to_config_type, - # DEFAULT_TYPE_ATTRIBUTES, -) -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent, # NOT DRY -) -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent as component, # DRY -) - - -result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - -result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - -result = ( # aaa - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) - -result = ( # aaa - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) - - -def func(): - c = call( - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0789, - a[-1], # type: ignore - ) - c = call(0.0123, 0.0456, 0.0789, 0.0123, 0.0789, a[-1]) # type: ignore - c = call( - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0456, - 0.0789, - 0.0123, - 0.0456, - 0.0789, - a[-1], # type: ignore - ) - - # The type: ignore exception only applies to line length, not - # other types of formatting. - c = call( - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", # type: ignore - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - "aaaaaaaa", - ) - - -class C: - @pytest.mark.parametrize( - ("post_data", "message"), - [ - # metadata_version errors. - ( - {}, - ( - "None is an invalid value for Metadata-Version. Error: This field" - " is required. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ), - ( - {"metadata_version": "-1"}, - ( - "'-1' is an invalid value for Metadata-Version. Error: Unknown" - " Metadata Version see" - " https://packaging.python.org/specifications/core-metadata" - ), - ), - # name errors. - ( - {"metadata_version": "1.2"}, - ( - "'' is an invalid value for Name. Error: This field is required." - " see https://packaging.python.org/specifications/core-metadata" - ), - ), - ( - {"metadata_version": "1.2", "name": "foo-"}, - ( - "'foo-' is an invalid value for Name. Error: Must start and end" - " with a letter or numeral and contain only ascii numeric and '.'," - " '_' and '-'. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ), - # version errors. - ( - {"metadata_version": "1.2", "name": "example"}, - ( - "'' is an invalid value for Version. Error: This field is required." - " see https://packaging.python.org/specifications/core-metadata" - ), - ), - ( - {"metadata_version": "1.2", "name": "example", "version": "dog"}, - ( - "'dog' is an invalid value for Version. Error: Must start and end" - " with a letter or numeral and contain only ascii numeric and '.'," - " '_' and '-'. see" - " https://packaging.python.org/specifications/core-metadata" - ), - ), - ], - ) - def test_fails_invalid_post_data( - self, pyramid_config, db_request, post_data, message - ): - ... - - -square = Square(4) # type: Optional[Square] diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments8.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/comments8.py deleted file mode 100644 index a2030c2a092628..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments8.py +++ /dev/null @@ -1,15 +0,0 @@ -# The percent-percent comments are Spyder IDE cells. -# Both `#%%`` and `# %%` are accepted, so `black` standardises -# to the latter. - -#%% -# %% - -# output - -# The percent-percent comments are Spyder IDE cells. -# Both `#%%`` and `# %%` are accepted, so `black` standardises -# to the latter. - -# %% -# %% diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments9.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/comments9.py deleted file mode 100644 index 77b25556e74aae..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/comments9.py +++ /dev/null @@ -1,305 +0,0 @@ -# Test for /~https://github.com/psf/black/issues/246. - -some = statement -# This comment should be split from the statement above by two lines. -def function(): - pass - - -some = statement -# This multiline comments section -# should be split from the statement -# above by two lines. -def function(): - pass - - -some = statement -# This comment should be split from the statement above by two lines. -async def async_function(): - pass - - -some = statement -# This comment should be split from the statement above by two lines. -class MyClass: - pass - - -some = statement -# This should be stick to the statement above - -# This should be split from the above by two lines -class MyClassWithComplexLeadingComments: - pass - - -class ClassWithDocstring: - """A docstring.""" -# Leading comment after a class with just a docstring -class MyClassAfterAnotherClassWithDocstring: - pass - - -some = statement -# leading 1 -@deco1 -# leading 2 -# leading 2 extra -@deco2(with_args=True) -# leading 3 -@deco3 -# leading 4 -def decorated(): - pass - - -some = statement -# leading 1 -@deco1 -# leading 2 -@deco2(with_args=True) - -# leading 3 that already has an empty line -@deco3 -# leading 4 -def decorated_with_split_leading_comments(): - pass - - -some = statement -# leading 1 -@deco1 -# leading 2 -@deco2(with_args=True) -# leading 3 -@deco3 - -# leading 4 that already has an empty line -def decorated_with_split_leading_comments(): - pass - - -def main(): - if a: - # Leading comment before inline function - def inline(): - pass - # Another leading comment - def another_inline(): - pass - else: - # More leading comments - def inline_after_else(): - pass - - -if a: - # Leading comment before "top-level inline" function - def top_level_quote_inline(): - pass - # Another leading comment - def another_top_level_quote_inline_inline(): - pass -else: - # More leading comments - def top_level_quote_inline_after_else(): - pass - - -class MyClass: - # First method has no empty lines between bare class def. - # More comments. - def first_method(self): - pass - - -# Regression test for /~https://github.com/psf/black/issues/3454. -def foo(): - pass - # Trailing comment that belongs to this function - - -@decorator1 -@decorator2 # fmt: skip -def bar(): - pass - - -# Regression test for /~https://github.com/psf/black/issues/3454. -def foo(): - pass - # Trailing comment that belongs to this function. - # NOTE this comment only has one empty line below, and the formatter - # should enforce two blank lines. - -@decorator1 -# A standalone comment -def bar(): - pass - - -# output - - -# Test for /~https://github.com/psf/black/issues/246. - -some = statement - - -# This comment should be split from the statement above by two lines. -def function(): - pass - - -some = statement - - -# This multiline comments section -# should be split from the statement -# above by two lines. -def function(): - pass - - -some = statement - - -# This comment should be split from the statement above by two lines. -async def async_function(): - pass - - -some = statement - - -# This comment should be split from the statement above by two lines. -class MyClass: - pass - - -some = statement -# This should be stick to the statement above - - -# This should be split from the above by two lines -class MyClassWithComplexLeadingComments: - pass - - -class ClassWithDocstring: - """A docstring.""" - - -# Leading comment after a class with just a docstring -class MyClassAfterAnotherClassWithDocstring: - pass - - -some = statement - - -# leading 1 -@deco1 -# leading 2 -# leading 2 extra -@deco2(with_args=True) -# leading 3 -@deco3 -# leading 4 -def decorated(): - pass - - -some = statement - - -# leading 1 -@deco1 -# leading 2 -@deco2(with_args=True) - -# leading 3 that already has an empty line -@deco3 -# leading 4 -def decorated_with_split_leading_comments(): - pass - - -some = statement - - -# leading 1 -@deco1 -# leading 2 -@deco2(with_args=True) -# leading 3 -@deco3 - -# leading 4 that already has an empty line -def decorated_with_split_leading_comments(): - pass - - -def main(): - if a: - # Leading comment before inline function - def inline(): - pass - - # Another leading comment - def another_inline(): - pass - - else: - # More leading comments - def inline_after_else(): - pass - - -if a: - # Leading comment before "top-level inline" function - def top_level_quote_inline(): - pass - - # Another leading comment - def another_top_level_quote_inline_inline(): - pass - -else: - # More leading comments - def top_level_quote_inline_after_else(): - pass - - -class MyClass: - # First method has no empty lines between bare class def. - # More comments. - def first_method(self): - pass - - -# Regression test for /~https://github.com/psf/black/issues/3454. -def foo(): - pass - # Trailing comment that belongs to this function - - -@decorator1 -@decorator2 # fmt: skip -def bar(): - pass - - -# Regression test for /~https://github.com/psf/black/issues/3454. -def foo(): - pass - # Trailing comment that belongs to this function. - # NOTE this comment only has one empty line below, and the formatter - # should enforce two blank lines. - - -@decorator1 -# A standalone comment -def bar(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/docstring_preview.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/docstring_preview.py deleted file mode 100644 index ff4819acb67a87..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/docstring_preview.py +++ /dev/null @@ -1,103 +0,0 @@ -def docstring_almost_at_line_limit(): - """long docstring................................................................. - """ - - -def docstring_almost_at_line_limit_with_prefix(): - f"""long docstring................................................................ - """ - - -def mulitline_docstring_almost_at_line_limit(): - """long docstring................................................................. - - .................................................................................. - """ - - -def mulitline_docstring_almost_at_line_limit_with_prefix(): - f"""long docstring................................................................ - - .................................................................................. - """ - - -def docstring_at_line_limit(): - """long docstring................................................................""" - - -def docstring_at_line_limit_with_prefix(): - f"""long docstring...............................................................""" - - -def multiline_docstring_at_line_limit(): - """first line----------------------------------------------------------------------- - - second line----------------------------------------------------------------------""" - - -def multiline_docstring_at_line_limit_with_prefix(): - f"""first line---------------------------------------------------------------------- - - second line----------------------------------------------------------------------""" - - -def single_quote_docstring_over_line_limit(): - "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." - - -def single_quote_docstring_over_line_limit2(): - 'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).' - - -# output - - -def docstring_almost_at_line_limit(): - """long docstring.................................................................""" - - -def docstring_almost_at_line_limit_with_prefix(): - f"""long docstring................................................................""" - - -def mulitline_docstring_almost_at_line_limit(): - """long docstring................................................................. - - .................................................................................. - """ - - -def mulitline_docstring_almost_at_line_limit_with_prefix(): - f"""long docstring................................................................ - - .................................................................................. - """ - - -def docstring_at_line_limit(): - """long docstring................................................................""" - - -def docstring_at_line_limit_with_prefix(): - f"""long docstring...............................................................""" - - -def multiline_docstring_at_line_limit(): - """first line----------------------------------------------------------------------- - - second line----------------------------------------------------------------------""" - - -def multiline_docstring_at_line_limit_with_prefix(): - f"""first line---------------------------------------------------------------------- - - second line----------------------------------------------------------------------""" - - -def single_quote_docstring_over_line_limit(): - "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." - - -def single_quote_docstring_over_line_limit2(): - "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_dict_values.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/long_dict_values.py deleted file mode 100644 index 4c515180028f13..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_dict_values.py +++ /dev/null @@ -1,90 +0,0 @@ -my_dict = { - "something_something": - r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t", -} - -my_dict = { - "a key in my dict": a_very_long_variable * and_a_very_long_function_call() / 100000.0 -} - -my_dict = { - "a key in my dict": a_very_long_variable * and_a_very_long_function_call() * and_another_long_func() / 100000.0 -} - -my_dict = { - "a key in my dict": MyClass.some_attribute.first_call().second_call().third_call(some_args="some value") -} - -{ - 'xxxxxx': - xxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxx( - xxxxxxxxxxxxxx={ - 'x': - xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - .xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - .xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx={ - 'x': x.xx, - 'x': x.x, - })))) - }), -} - - -# output - - -my_dict = { - "something_something": ( - r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t" - ), -} - -my_dict = { - "a key in my dict": ( - a_very_long_variable * and_a_very_long_function_call() / 100000.0 - ) -} - -my_dict = { - "a key in my dict": ( - a_very_long_variable - * and_a_very_long_function_call() - * and_another_long_func() - / 100000.0 - ) -} - -my_dict = { - "a key in my dict": ( - MyClass.some_attribute.first_call() - .second_call() - .third_call(some_args="some value") - ) -} - -{ - "xxxxxx": xxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxx( - xxxxxxxxxxxxxx={ - "x": xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx={ - "x": x.xx, - "x": x.x, - } - ) - ) - ) - ) - } - ), -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings.py deleted file mode 100644 index b7a0a42f82a69c..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings.py +++ /dev/null @@ -1,861 +0,0 @@ -x = "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - -x += "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - -y = ( - 'Short string' -) - -print('This is a really long string inside of a print statement with extra arguments attached at the end of it.', x, y, z) - -print("This is a really long string inside of a print statement with no extra arguments attached at the end of it.") - -D1 = {"The First": "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", "The Second": "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary."} - -D2 = {1.0: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", 2.0: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary."} - -D3 = {x: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", y: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary."} - -D4 = {"A long and ridiculous {}".format(string_key): "This is a really really really long string that has to go i,side of a dictionary. It is soooo bad.", some_func("calling", "some", "stuff"): "This is a really really really long string that has to go inside of a dictionary. It is {soooo} bad (#{x}).".format(sooo="soooo", x=2), "A %s %s" % ("formatted", "string"): "This is a really really really long string that has to go inside of a dictionary. It is %s bad (#%d)." % ("soooo", 2)} - -D5 = { # Test for /~https://github.com/psf/black/issues/3261 - ("This is a really long string that can't be expected to fit in one line and is used as a nested dict's key"): {"inner": "value"}, -} - -D6 = { # Test for /~https://github.com/psf/black/issues/3261 - ("This is a really long string that can't be expected to fit in one line and is used as a dict's key"): ["value1", "value2"], -} - -L1 = ["The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a list literal, so it's expected to be wrapped in parens when spliting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a list literal.", ("parens should be stripped for short string in list")] - -L2 = ["This is a really long string that can't be expected to fit in one line and is the only child of a list literal."] - -S1 = {"The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a set literal, so it's expected to be wrapped in parens when spliting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a set literal.", ("parens should be stripped for short string in set")} - -S2 = {"This is a really long string that can't be expected to fit in one line and is the only child of a set literal."} - -T1 = ("The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a tuple literal, so it's expected to be wrapped in parens when spliting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a tuple literal.", ("parens should be stripped for short string in list")) - -T2 = ("This is a really long string that can't be expected to fit in one line and is the only child of a tuple literal.",) - -func_with_keywords(my_arg, my_kwarg="Long keyword strings also need to be wrapped, but they will probably need to be handled a little bit differently.") - -bad_split1 = ( - 'But what should happen when code has already been formatted but in the wrong way? Like' - " with a space at the end instead of the beginning. Or what about when it is split too soon?" -) - -bad_split2 = "But what should happen when code has already " \ - "been formatted but in the wrong way? Like " \ - "with a space at the end instead of the " \ - "beginning. Or what about when it is split too " \ - "soon? In the case of a split that is too " \ - "short, black will try to honer the custom " \ - "split." - -bad_split3 = ( - "What if we have inline comments on " # First Comment - "each line of a bad split? In that " # Second Comment - "case, we should just leave it alone." # Third Comment -) - -bad_split_func1( - "But what should happen when code has already " - "been formatted but in the wrong way? Like " - "with a space at the end instead of the " - "beginning. Or what about when it is split too " - "soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split.", - xxx, yyy, zzz -) - -bad_split_func2( - xxx, yyy, zzz, - long_string_kwarg="But what should happen when code has already been formatted but in the wrong way? Like " - "with a space at the end instead of the beginning. Or what about when it is split too " - "soon?", -) - -bad_split_func3( - ( - "But what should happen when code has already " - r"been formatted but in the wrong way? Like " - "with a space at the end instead of the " - r"beginning. Or what about when it is split too " - r"soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." - ), - xxx, - yyy, - zzz, -) - -inline_comments_func1( - "if there are inline " - "comments in the middle " - # Here is the standard alone comment. - "of the implicitly concatenated " - "string, we should handle " - "them correctly", - xxx, -) - -inline_comments_func2( - "what if the string is very very very very very very very very very very long and this part does " - "not fit into a single line? " - # Here is the standard alone comment. - "then the string should still be properly handled by merging and splitting " - "it into parts that fit in line length.", - xxx, -) - -raw_string = r"This is a long raw string. When re-formatting this string, black needs to make sure it prepends the 'r' onto the new string." - -fmt_string1 = "We also need to be sure to preserve any and all {} which may or may not be attached to the string in question.".format("method calls") - -fmt_string2 = "But what about when the string is {} but {}".format("short", "the method call is really really really really really really really really long?") - -old_fmt_string1 = "While we are on the topic of %s, we should also note that old-style formatting must also be preserved, since some %s still uses it." % ("formatting", "code") - -old_fmt_string2 = "This is a %s %s %s %s" % ("really really really really really", "old", "way to format strings!", "Use f-strings instead!") - -old_fmt_string3 = "Whereas only the strings after the percent sign were long in the last example, this example uses a long initial string as well. This is another %s %s %s %s" % ("really really really really really", "old", "way to format strings!", "Use f-strings instead!") - -fstring = f"f-strings definitely make things more {difficult} than they need to be for {{black}}. But boy they sure are handy. The problem is that some lines will need to have the 'f' whereas others do not. This {line}, for example, needs one." - -fstring_with_no_fexprs = f"Some regular string that needs to get split certainly but is NOT an fstring by any means whatsoever." - -comment_string = "Long lines with inline comments should have their comments appended to the reformatted string's enclosing right parentheses." # This comment gets thrown to the top. - -arg_comment_string = print("Long lines with inline comments which are apart of (and not the only member of) an argument list should have their comments appended to the reformatted string's enclosing left parentheses.", # This comment gets thrown to the top. - "Arg #2", "Arg #3", "Arg #4", "Arg #5") - -pragma_comment_string1 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa: E501 - -pragma_comment_string2 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa - -"""This is a really really really long triple quote string and it should not be touched.""" - -triple_quote_string = """This is a really really really long triple quote string assignment and it should not be touched.""" - -assert some_type_of_boolean_expression, "Followed by a really really really long string that is used to provide context to the AssertionError exception." - -assert some_type_of_boolean_expression, "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string {}.".format("formatting") - -assert some_type_of_boolean_expression, "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string %s." % "formatting" - -assert some_type_of_boolean_expression, "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic %s %s." % ("string", "formatting") - -some_function_call("With a reallly generic name and with a really really long string that is, at some point down the line, " + added + " to a variable and then added to another string.") - -some_function_call("With a reallly generic name and with a really really long string that is, at some point down the line, " + added + " to a variable and then added to another string. But then what happens when the final string is also supppppperrrrr long?! Well then that second (realllllllly long) string should be split too.", "and a second argument", and_a_third) - -return "A really really really really really really really really really really really really really long {} {}".format("return", "value") - -func_with_bad_comma( - "This is a really long string argument to a function that has a trailing comma which should NOT be there.", -) - -func_with_bad_comma( - "This is a really long string argument to a function that has a trailing comma which should NOT be there.", # comment after comma -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), # comment after comma -) - -func_with_bad_parens_that_wont_fit_in_one_line( - ("short string that should have parens stripped"), - x, - y, - z -) - -func_with_bad_parens_that_wont_fit_in_one_line( - x, - y, - ("short string that should have parens stripped"), - z -) - -func_with_bad_parens( - ("short string that should have parens stripped"), - x, - y, - z, -) - -func_with_bad_parens( - x, - y, - ("short string that should have parens stripped"), - z, -) - -annotated_variable: Final = "This is a large " + STRING + " that has been " + CONCATENATED + "using the '+' operator." -annotated_variable: Final = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." -annotated_variable: Literal["fakse_literal"] = "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." - -backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\" -backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\\\" -backslashes = "This is a really 'long' string with \"embedded double quotes\" and 'single' quotes that also handles checking for an odd number of backslashes \\\", like this...\\\\\\" - -short_string = ( - "Hi" - " there." -) - -func_call( - short_string=( - "Hi" - " there." - ) -) - -raw_strings = r"Don't" " get" r" merged" " unless they are all raw." - -def foo(): - yield "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." - -x = f"This is a {{really}} long string that needs to be split without a doubt (i.e. most definitely). In short, this {string} that can't possibly be {{expected}} to fit all together on one line. In {fact} it may even take up three or more lines... like four or five... but probably just four." - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # type: ignore - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # noqa - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # pylint: disable=some-pylint-check - " of it." -) - -string_with_nameescape = ( - "........................................................................ \N{LAO KO LA}" -) - -string_with_nameescape = ( - "........................................................................... \N{LAO KO LA}" -) - -string_with_nameescape = ( - "............................................................................ \N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - "...................................................................... \\\N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - "......................................................................... \\\N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - ".......................................................................... \\\N{LAO KO LA}" -) - -string_with_escaped_nameescape = ( - "........................................................................ \\N{LAO KO LA}" -) - -string_with_escaped_nameescape = ( - "........................................................................... \\N{LAO KO LA}" -) - -msg = lambda x: f"this is a very very very long lambda value {x} that doesn't fit on a single line" - -dict_with_lambda_values = { - "join": lambda j: ( - f"{j.__class__.__name__}({some_function_call(j.left)}, " - f"{some_function_call(j.right)})" - ), -} - -# Complex string concatenations with a method call in the middle. -code = ( - (" return [\n") - + ( - ", \n".join( - " (%r, self.%s, visitor.%s)" - % (attrname, attrname, visit_name) - for attrname, visit_name in names - ) - ) - + ("\n ]\n") -) - - -# Test case of an outer string' parens enclose an inner string's parens. -call(body=("%s %s" % ((",".join(items)), suffix))) - - -# output - - -x = ( - "This is a really long string that can't possibly be expected to fit all together" - " on one line. In fact it may even take up three or more lines... like four or" - " five... but probably just three." -) - -x += ( - "This is a really long string that can't possibly be expected to fit all together" - " on one line. In fact it may even take up three or more lines... like four or" - " five... but probably just three." -) - -y = "Short string" - -print( - ( - "This is a really long string inside of a print statement with extra arguments" - " attached at the end of it." - ), - x, - y, - z, -) - -print( - "This is a really long string inside of a print statement with no extra arguments" - " attached at the end of it." -) - -D1 = { - "The First": ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a dictionary, so formatting is more" - " difficult." - ), - "The Second": ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a" - " dictionary." - ), -} - -D2 = { - 1.0: ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a dictionary, so formatting is more" - " difficult." - ), - 2.0: ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a" - " dictionary." - ), -} - -D3 = { - x: ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a dictionary, so formatting is more" - " difficult." - ), - y: ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a" - " dictionary." - ), -} - -D4 = { - "A long and ridiculous {}".format(string_key): ( - "This is a really really really long string that has to go i,side of a" - " dictionary. It is soooo bad." - ), - some_func("calling", "some", "stuff"): ( - "This is a really really really long string that has to go inside of a" - " dictionary. It is {soooo} bad (#{x}).".format(sooo="soooo", x=2) - ), - "A %s %s" - % ("formatted", "string"): ( - "This is a really really really long string that has to go inside of a" - " dictionary. It is %s bad (#%d)." % ("soooo", 2) - ), -} - -D5 = { # Test for /~https://github.com/psf/black/issues/3261 - "This is a really long string that can't be expected to fit in one line and is used as a nested dict's key": { - "inner": "value" - }, -} - -D6 = { # Test for /~https://github.com/psf/black/issues/3261 - "This is a really long string that can't be expected to fit in one line and is used as a dict's key": [ - "value1", - "value2", - ], -} - -L1 = [ - "The is a short string", - ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a list literal, so it's expected to" - " be wrapped in parens when spliting to avoid implicit str concatenation." - ), - short_call("arg", {"key": "value"}), - ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a list" - " literal." - ), - "parens should be stripped for short string in list", -] - -L2 = [ - "This is a really long string that can't be expected to fit in one line and is the" - " only child of a list literal." -] - -S1 = { - "The is a short string", - ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a set literal, so it's expected to be" - " wrapped in parens when spliting to avoid implicit str concatenation." - ), - short_call("arg", {"key": "value"}), - ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a set" - " literal." - ), - "parens should be stripped for short string in set", -} - -S2 = { - "This is a really long string that can't be expected to fit in one line and is the" - " only child of a set literal." -} - -T1 = ( - "The is a short string", - ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. Also it is inside a tuple literal, so it's expected to" - " be wrapped in parens when spliting to avoid implicit str concatenation." - ), - short_call("arg", {"key": "value"}), - ( - "This is another really really (not really) long string that also can't be" - " expected to fit on one line and is, like the other string, inside a tuple" - " literal." - ), - "parens should be stripped for short string in list", -) - -T2 = ( - ( - "This is a really long string that can't be expected to fit in one line and is" - " the only child of a tuple literal." - ), -) - -func_with_keywords( - my_arg, - my_kwarg=( - "Long keyword strings also need to be wrapped, but they will probably need to" - " be handled a little bit differently." - ), -) - -bad_split1 = ( - "But what should happen when code has already been formatted but in the wrong way?" - " Like with a space at the end instead of the beginning. Or what about when it is" - " split too soon?" -) - -bad_split2 = ( - "But what should happen when code has already " - "been formatted but in the wrong way? Like " - "with a space at the end instead of the " - "beginning. Or what about when it is split too " - "soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." -) - -bad_split3 = ( - "What if we have inline comments on " # First Comment - "each line of a bad split? In that " # Second Comment - "case, we should just leave it alone." # Third Comment -) - -bad_split_func1( - ( - "But what should happen when code has already " - "been formatted but in the wrong way? Like " - "with a space at the end instead of the " - "beginning. Or what about when it is split too " - "soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." - ), - xxx, - yyy, - zzz, -) - -bad_split_func2( - xxx, - yyy, - zzz, - long_string_kwarg=( - "But what should happen when code has already been formatted but in the wrong" - " way? Like with a space at the end instead of the beginning. Or what about" - " when it is split too soon?" - ), -) - -bad_split_func3( - ( - "But what should happen when code has already " - r"been formatted but in the wrong way? Like " - "with a space at the end instead of the " - r"beginning. Or what about when it is split too " - r"soon? In the case of a split that is too " - "short, black will try to honer the custom " - "split." - ), - xxx, - yyy, - zzz, -) - -inline_comments_func1( - "if there are inline comments in the middle " - # Here is the standard alone comment. - "of the implicitly concatenated string, we should handle them correctly", - xxx, -) - -inline_comments_func2( - "what if the string is very very very very very very very very very very long and" - " this part does not fit into a single line? " - # Here is the standard alone comment. - "then the string should still be properly handled by merging and splitting " - "it into parts that fit in line length.", - xxx, -) - -raw_string = ( - r"This is a long raw string. When re-formatting this string, black needs to make" - r" sure it prepends the 'r' onto the new string." -) - -fmt_string1 = ( - "We also need to be sure to preserve any and all {} which may or may not be" - " attached to the string in question.".format("method calls") -) - -fmt_string2 = "But what about when the string is {} but {}".format( - "short", - "the method call is really really really really really really really really long?", -) - -old_fmt_string1 = ( - "While we are on the topic of %s, we should also note that old-style formatting" - " must also be preserved, since some %s still uses it." % ("formatting", "code") -) - -old_fmt_string2 = "This is a %s %s %s %s" % ( - "really really really really really", - "old", - "way to format strings!", - "Use f-strings instead!", -) - -old_fmt_string3 = ( - "Whereas only the strings after the percent sign were long in the last example," - " this example uses a long initial string as well. This is another %s %s %s %s" - % ( - "really really really really really", - "old", - "way to format strings!", - "Use f-strings instead!", - ) -) - -fstring = ( - f"f-strings definitely make things more {difficult} than they need to be for" - " {black}. But boy they sure are handy. The problem is that some lines will need" - f" to have the 'f' whereas others do not. This {line}, for example, needs one." -) - -fstring_with_no_fexprs = ( - f"Some regular string that needs to get split certainly but is NOT an fstring by" - f" any means whatsoever." -) - -comment_string = ( # This comment gets thrown to the top. - "Long lines with inline comments should have their comments appended to the" - " reformatted string's enclosing right parentheses." -) - -arg_comment_string = print( - ( # This comment gets thrown to the top. - "Long lines with inline comments which are apart of (and not the only member" - " of) an argument list should have their comments appended to the reformatted" - " string's enclosing left parentheses." - ), - "Arg #2", - "Arg #3", - "Arg #4", - "Arg #5", -) - -pragma_comment_string1 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa: E501 - -pragma_comment_string2 = "Lines which end with an inline pragma comment of the form `# : <...>` should be left alone." # noqa - -"""This is a really really really long triple quote string and it should not be touched.""" - -triple_quote_string = """This is a really really really long triple quote string assignment and it should not be touched.""" - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to" - " the AssertionError exception." -) - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to" - " the AssertionError exception, which uses dynamic string {}.".format("formatting") -) - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to" - " the AssertionError exception, which uses dynamic string %s." % "formatting" -) - -assert some_type_of_boolean_expression, ( - "Followed by a really really really long string that is used to provide context to" - " the AssertionError exception, which uses dynamic %s %s." - % ("string", "formatting") -) - -some_function_call( - "With a reallly generic name and with a really really long string that is, at some" - " point down the line, " - + added - + " to a variable and then added to another string." -) - -some_function_call( - "With a reallly generic name and with a really really long string that is, at some" - " point down the line, " - + added - + " to a variable and then added to another string. But then what happens when the" - " final string is also supppppperrrrr long?! Well then that second (realllllllly" - " long) string should be split too.", - "and a second argument", - and_a_third, -) - -return ( - "A really really really really really really really really really really really" - " really really long {} {}".format("return", "value") -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_comma( - ( # comment after comma - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_comma( - ( - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_comma( - ( # comment after comma - "This is a really long string argument to a function that has a trailing comma" - " which should NOT be there." - ), -) - -func_with_bad_parens_that_wont_fit_in_one_line( - "short string that should have parens stripped", x, y, z -) - -func_with_bad_parens_that_wont_fit_in_one_line( - x, y, "short string that should have parens stripped", z -) - -func_with_bad_parens( - "short string that should have parens stripped", - x, - y, - z, -) - -func_with_bad_parens( - x, - y, - "short string that should have parens stripped", - z, -) - -annotated_variable: Final = ( - "This is a large " - + STRING - + " that has been " - + CONCATENATED - + "using the '+' operator." -) -annotated_variable: Final = ( - "This is a large string that has a type annotation attached to it. A type" - " annotation should NOT stop a long string from being wrapped." -) -annotated_variable: Literal["fakse_literal"] = ( - "This is a large string that has a type annotation attached to it. A type" - " annotation should NOT stop a long string from being wrapped." -) - -backslashes = ( - "This is a really long string with \"embedded\" double quotes and 'single' quotes" - " that also handles checking for an even number of backslashes \\" -) -backslashes = ( - "This is a really long string with \"embedded\" double quotes and 'single' quotes" - " that also handles checking for an even number of backslashes \\\\" -) -backslashes = ( - "This is a really 'long' string with \"embedded double quotes\" and 'single' quotes" - ' that also handles checking for an odd number of backslashes \\", like' - " this...\\\\\\" -) - -short_string = "Hi there." - -func_call(short_string="Hi there.") - -raw_strings = r"Don't" " get" r" merged" " unless they are all raw." - - -def foo(): - yield ( - "This is a really long string that can't possibly be expected to fit all" - " together on one line. In fact it may even take up three or more lines... like" - " four or five... but probably just three." - ) - - -x = ( - "This is a {really} long string that needs to be split without a doubt (i.e." - f" most definitely). In short, this {string} that can't possibly be {{expected}} to" - f" fit all together on one line. In {fact} it may even take up three or more" - " lines... like four or five... but probably just four." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # type: ignore - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # noqa - " of it." -) - -long_unmergable_string_with_pragma = ( - "This is a really long string that can't be merged because it has a likely pragma at the end" # pylint: disable=some-pylint-check - " of it." -) - -string_with_nameescape = ( - "........................................................................" - " \N{LAO KO LA}" -) - -string_with_nameescape = ( - "..........................................................................." - " \N{LAO KO LA}" -) - -string_with_nameescape = ( - "............................................................................" - " \N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - "......................................................................" - " \\\N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - "........................................................................." - " \\\N{LAO KO LA}" -) - -string_with_nameescape_and_escaped_backslash = ( - ".........................................................................." - " \\\N{LAO KO LA}" -) - -string_with_escaped_nameescape = ( - "........................................................................ \\N{LAO" - " KO LA}" -) - -string_with_escaped_nameescape = ( - "..........................................................................." - " \\N{LAO KO LA}" -) - -msg = ( - lambda x: ( - f"this is a very very very long lambda value {x} that doesn't fit on a single" - " line" - ) -) - -dict_with_lambda_values = { - "join": lambda j: ( - f"{j.__class__.__name__}({some_function_call(j.left)}, " - f"{some_function_call(j.right)})" - ), -} - -# Complex string concatenations with a method call in the middle. -code = ( - " return [\n" - + ", \n".join( - " (%r, self.%s, visitor.%s)" % (attrname, attrname, visit_name) - for attrname, visit_name in names - ) - + "\n ]\n" -) - - -# Test case of an outer string' parens enclose an inner string's parens. -call(body="%s %s" % (",".join(items), suffix)) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__edge_case.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__edge_case.py deleted file mode 100644 index 2bc0b6ed32885a..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__edge_case.py +++ /dev/null @@ -1,140 +0,0 @@ -some_variable = "This string is long but not so long that it needs to be split just yet" -some_variable = 'This string is long but not so long that it needs to be split just yet' -some_variable = "This string is long, just long enough that it needs to be split, u get?" -some_variable = 'This string is long, just long enough that it needs to be split, u get?' -some_variable = "This string is long, just long enough that it needs to be split, u get? So we stay" -some_variable = 'This string is long, just long enough that it needs to be split, u get? So we stay' -some_variable = "This string is long, just long enough that it needs to be split, u get? So we split" -some_variable = 'This string is long, just long enough that it needs to be split, u get? So we split' -some_variable = "This string is long but not so long that it needs hahahah toooooo be so greatttt {} that I just can't think of any more good words to say about it at alll".format("ha") -some_variable = "This string is long but not so long that it needs hahahah toooooo be so greatttt {} that I just can't think of any more good words to say about it at allll".format("ha") -some_variable = "This string is long but not so long that it needs hahahah toooooo be so greatttt {} that I just can't think of any more good words to say about it at alllllllllll".format("ha") -some_variable = "This string is long but not so long that it needs hahahah toooooo be so greatttt {} that I just can't think of any more good words to say about it at allllllllllll".format("ha") -some_variable = "This is a long string that will end with a method that is not calleddd".format -addition_inside_tuple = ( - some_string_inside_a_variable - + "Some string that is just long enough to cause a split to take place.............", - xyz, - "Some really long string that needs to get split eventually but I'm running out of things to say" + some_string_inside_a_variable -) -addition_inside_tuple = ( - some_string_inside_a_variable - + "Some string that is just long enough to cause a split to take place.............." -) -return "Hi there. This is areally really reallllly long string that needs to be split!!!" -ternary_expression = ( - "Short String" - if some_condition - else "This is a really long string that will eventually need to be split right here." -) -return f'{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaa' -return f'{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaaa' -assert str(result) == "This long string should be split at some point right close to or around hereeeeeee" -assert str(result) < "This long string should be split at some point right close to or around hereeeeee" -assert "A format string: %s" % "This long string should be split at some point right close to or around hereeeeeee" != result -msg += "This long string should be wrapped in parens at some point right around hereeeee" -msg += "This long string should be split at some point right close to or around hereeeeeeee" -msg += "This long string should not be split at any point ever since it is just righttt" - - -# output - - -some_variable = "This string is long but not so long that it needs to be split just yet" -some_variable = "This string is long but not so long that it needs to be split just yet" -some_variable = ( - "This string is long, just long enough that it needs to be split, u get?" -) -some_variable = ( - "This string is long, just long enough that it needs to be split, u get?" -) -some_variable = ( - "This string is long, just long enough that it needs to be split, u get? So we stay" -) -some_variable = ( - "This string is long, just long enough that it needs to be split, u get? So we stay" -) -some_variable = ( - "This string is long, just long enough that it needs to be split, u get? So we" - " split" -) -some_variable = ( - "This string is long, just long enough that it needs to be split, u get? So we" - " split" -) -some_variable = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" - " {} that I just can't think of any more good words to say about it at alll".format( - "ha" - ) -) -some_variable = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" - " {} that I just can't think of any more good words to say about it at allll" - .format("ha") -) -some_variable = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" - " {} that I just can't think of any more good words to say about it at alllllllllll" - .format("ha") -) -some_variable = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" - " {} that I just can't think of any more good words to say about it at" - " allllllllllll".format("ha") -) -some_variable = ( - "This is a long string that will end with a method that is not calleddd".format -) -addition_inside_tuple = ( - some_string_inside_a_variable - + "Some string that is just long enough to cause a split to take" - " place.............", - xyz, - "Some really long string that needs to get split eventually but I'm running out of" - " things to say" - + some_string_inside_a_variable, -) -addition_inside_tuple = ( - some_string_inside_a_variable - + "Some string that is just long enough to cause a split to take" - " place.............." -) -return ( - "Hi there. This is areally really reallllly long string that needs to be split!!!" -) -ternary_expression = ( - "Short String" - if some_condition - else ( - "This is a really long string that will eventually need to be split right here." - ) -) -return ( - f"{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaa" -) -return f"{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaaa" -assert ( - str(result) - == "This long string should be split at some point right close to or around" - " hereeeeeee" -) -assert ( - str(result) - < "This long string should be split at some point right close to or around" - " hereeeeee" -) -assert ( - "A format string: %s" - % "This long string should be split at some point right close to or around" - " hereeeeeee" - != result -) -msg += ( - "This long string should be wrapped in parens at some point right around hereeeee" -) -msg += ( - "This long string should be split at some point right close to or around" - " hereeeeeeee" -) -msg += "This long string should not be split at any point ever since it is just righttt" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__regression.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__regression.py deleted file mode 100644 index ef9007f4ce11b0..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__regression.py +++ /dev/null @@ -1,1237 +0,0 @@ -class A: - def foo(): - result = type(message)("") - - -# Don't merge multiline (e.g. triple-quoted) strings. -def foo(): - query = ( - """SELECT xxxxxxxxxxxxxxxxxxxx(xxx)""" - """ FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""") - -# There was a bug where tuples were being identified as long strings. -long_tuple = ('Apple', 'Berry', 'Cherry', 'Dill', 'Evergreen', 'Fig', - 'Grape', 'Harry', 'Iglu', 'Jaguar') - -stupid_format_method_bug = "Some really long string that just so happens to be the {} {} to force the 'format' method to hang over the line length boundary. This is pretty annoying.".format("perfect", "length") - -class A: - def foo(): - os.system("This is a regression test. xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxxx.".format("xxxxxxxxxx", "xxxxxx", "xxxxxxxxxx")) - - -class A: - def foo(): - XXXXXXXXXXXX.append( - ( - "xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})".format( - xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx - ), - my_var, - my_other_var, - ) - ) - -class A: - class B: - def foo(): - bar( - ( - "[{}]: xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx={}" - " xxxx_xxxx_xxxxxxxxxx={}, xxxx={})" - .format(xxxx._xxxxxxxxxxxxxx, xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx, xxxxxxx) - ), - varX, - varY, - varZ, - ) - -def foo(xxxx): - for (xxx_xxxx, _xxx_xxx, _xxx_xxxxx, xxx_xxxx) in xxxx: - for xxx in xxx_xxxx: - assert ("x" in xxx) or ( - xxx in xxx_xxx_xxxxx - ), "{0} xxxxxxx xx {1}, xxx {1} xx xxx xx xxxx xx xxx xxxx: xxx xxxx {2}".format( - xxx_xxxx, xxx, xxxxxx.xxxxxxx(xxx_xxx_xxxxx) - ) - -class A: - def disappearing_comment(): - return ( - ( # xx -x xxxxxxx xx xxx xxxxxxx. - '{{xxx_xxxxxxxxxx_xxxxxxxx}} xxx xxxx' - ' {} {{xxxx}} >&2' - .format( - "{xxxx} {xxxxxx}" - if xxxxx.xx_xxxxxxxxxx - else ( # Disappearing Comment - "--xxxxxxx --xxxxxx=x --xxxxxx-xxxxx=xxxxxx" - " --xxxxxx-xxxx=xxxxxxxxxxx.xxx" - ) - ) - ), - (x, y, z), - ) - -class A: - class B: - def foo(): - xxxxx_xxxx( - xx, "\t" - "@xxxxxx '{xxxx_xxx}\t' > {xxxxxx_xxxx}.xxxxxxx;" - "{xxxx_xxx} >> {xxxxxx_xxxx}.xxxxxxx 2>&1; xx=$$?;" - "xxxx $$xx" - .format(xxxx_xxx=xxxx_xxxxxxx, xxxxxx_xxxx=xxxxxxx + "/" + xxxx_xxx_xxxx, x=xxx_xxxxx_xxxxx_xxx), - x, - y, - z, - ) - -func_call_where_string_arg_has_method_call_and_bad_parens( - ( - "A long string with {}. This string is so long that it is ridiculous. It can't fit on one line at alllll.".format("formatting") - ), -) - -func_call_where_string_arg_has_old_fmt_and_bad_parens( - ( - "A long string with {}. This string is so long that it is ridiculous. It can't fit on one line at alllll." % "formatting" - ), -) - -func_call_where_string_arg_has_old_fmt_and_bad_parens( - ( - "A long string with {}. This {} is so long that it is ridiculous. It can't fit on one line at alllll." % ("formatting", "string") - ), -) - -class A: - def append(self): - if True: - xxxx.xxxxxxx.xxxxx( ('xxxxxxxxxx xxxx xx xxxxxx(%x) xx %x xxxx xx xxx %x.xx' - % (len(self) + 1, - xxxx.xxxxxxxxxx, - xxxx.xxxxxxxxxx)) - + (' %.3f (%s) to %.3f (%s).\n' - % (xxxx.xxxxxxxxx, - xxxx.xxxxxxxxxxxxxx(xxxx.xxxxxxxxx), - x, - xxxx.xxxxxxxxxxxxxx( xx) - ))) - -class A: - def foo(): - some_func_call( - 'xxxxxxxxxx', - ( - "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " - "\"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; " - "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " - ), - None, - ('xxxxxxxxxxx',), - ), - -class A: - def foo(): - some_func_call( - ( - "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " - "xxxx, ('xxxxxxx xxxxxx xxxx, xxxx') xxxxxx_xxxxx xxxxxx xxxx; " - "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " - ), - None, - ('xxxxxxxxxxx',), - ), - -xxxxxxx = { 'xx' : 'xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} \ --xx {1} -xx xxx=xxx_xxxx,xxx_xx,xxx_xxx,xxx_xxxx,xxx_xx,xxx_xxx |\ - xxxxxx -x xxxxxxxx -x xxxxxxxx -x', - 'xx' : 'xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} \ --xx {1} -xx xxx=xxx_xxxx_xxx_xxxx,xxx_xx_xxx_xxxx,xxx_xxxx_xxx_xxxx,\ -xxx_xx_xxxx_xxxx,xxx_xxx_xxxx,xxx_xxx_xxxx xxxx=xxx | xxxxxx -x xxxxxxxx -x xxxxxxxx -x' -} - -class A: - def foo(self): - if True: - xxxxx_xxxxxxxxxxxx('xxx xxxxxx xxx xxxxxxxxx.xx xx xxxxxxxx. xxx xxxxxxxxxxxxx.xx xxxxxxx ' - + 'xx xxxxxx xxxxxx xxxxxx xx xxxxxxx xxx xxx ${0} xx x xxxxxxxx xxxxx'.xxxxxx(xxxxxx_xxxxxx_xxx)) - -class A: - class B: - def foo(): - row = { - 'xxxxxxxxxxxxxxx' : xxxxxx_xxxxx_xxxx, - # 'xxxxxxxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxx' - 'xxxxxxxxxx' : xxxxx_xxxxx, - } - -class A: - def xxxx_xxx_xx_xxxxxxxxxx_xxxx_xxxxxxxxx(xxxx): - xxxxxxxx = [ - xxxxxxxxxxxxxxxx( - 'xxxx', - xxxxxxxxxxx={ - 'xxxx' : 1.0, - }, - xxxxxx={'xxxxxx 1' : xxxxxx(xxxx='xxxxxx 1', xxxxxx=600.0)}, - xxxxxxxx_xxxxxxx=0.0, - ), - xxxxxxxxxxxxxxxx( - 'xxxxxxx', - xxxxxxxxxxx={ - 'xxxx' : 1.0, - }, - xxxxxx={'xxxxxx 1' : xxxxxx(xxxx='xxxxxx 1', xxxxxx=200.0)}, - xxxxxxxx_xxxxxxx=0.0, - ), - xxxxxxxxxxxxxxxx( - 'xxxx', - ), - ] - -some_dictionary = { - 'xxxxx006': ['xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx== xxxxx000 xxxxxxxxxx\n', - 'xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx== xxxxx010 xxxxxxxxxx\n'], - 'xxxxx016': ['xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx== xxxxx000 xxxxxxxxxx\n', - 'xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx== xxxxx010 xxxxxxxxxx\n'] -} - -def foo(): - xxx_xxx = ( - 'xxxx xxx xxxxxxxx_xxxx xx "xxxxxxxxxx".' - '\n xxx: xxxxxx xxxxxxxx_xxxx=xxxxxxxxxx' - ) # xxxx xxxxxxxxxx xxxx xx xxxx xx xxx xxxxxxxx xxxxxx xxxxx. - -some_tuple = ("some string", "some string" " which should be joined") - -some_commented_string = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" # This comment gets thrown to the top. - " {} that I just can't think of any more good words to say about it at" - " allllllllllll".format("ha") # comments here are fine -) - -some_commented_string = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" # But these - " {} that I just can't think of any more good words to say about it at" # comments will stay - " allllllllllll".format("ha") # comments here are fine -) - -lpar_and_rpar_have_comments = func_call( # LPAR Comment - "Long really ridiculous type of string that shouldn't really even exist at all. I mean commmme onnn!!!", # Comma Comment -) # RPAR Comment - -cmd_fstring = ( - f"sudo -E deluge-console info --detailed --sort-reverse=time_added " - f"{'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" -) - -cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" - -cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {'{{}}' if ID is None else ID} | perl -nE 'print if /^{field}:/'" - -cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {{'' if ID is None else ID}} | perl -nE 'print if /^{field}:/'" - -fstring = f"This string really doesn't need to be an {{{{fstring}}}}, but this one most certainly, absolutely {does}." - -fstring = ( - f"We have to remember to escape {braces}." - " Like {these}." - f" But not {this}." -) - -class A: - class B: - def foo(): - st_error = STError( - f"This string ({string_leaf.value}) appears to be pointless (i.e. has" - " no parent)." - ) - -def foo(): - user_regex = _lazy_re_compile( - r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom - r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string - re.IGNORECASE) - -def foo(): - user_regex = _lazy_re_compile( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom - 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # quoted-string - xyz - ) - -def foo(): - user_regex = _lazy_re_compile( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom - 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # quoted-string - xyz - ) - -class A: - class B: - def foo(): - if not hasattr(module, name): - raise ValueError( - "Could not find object %s in %s.\n" - "Please note that you cannot serialize things like inner " - "classes. Please move the object into the main module " - "body to use migrations.\n" - "For more information, see " - "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" - % (name, module_name, get_docs_version())) - -class A: - class B: - def foo(): - if not hasattr(module, name): - raise ValueError( - "Could not find object %s in %s.\nPlease note that you cannot serialize things like inner classes. Please move the object into the main module body to use migrations.\nFor more information, see https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" - % (name, module_name, get_docs_version())) - -x = ( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) - -class Step(StepBase): - def who(self): - self.cmd = 'SR AAAA-CORRECT NAME IS {last_name} {first_name}{middle_name} {title}/P{passenger_association}'.format( - last_name=last_name, - first_name=first_name, - middle_name=middle_name, - title=title, - passenger_association=passenger_association, - ) - -xxxxxxx_xxxxxx_xxxxxxx = xxx( - [ - xxxxxxxxxxxx( - xxxxxx_xxxxxxx=( - '((x.aaaaaaaaa = "xxxxxx.xxxxxxxxxxxxxxxxxxxxx") || (x.xxxxxxxxx = "xxxxxxxxxxxx")) && ' - # xxxxx xxxxxxxxxxxx xxxx xxx (xxxxxxxxxxxxxxxx) xx x xxxxxxxxx xx xxxxxx. - "(x.bbbbbbbbbbbb.xxx != " - '"xxx:xxx:xxx::cccccccccccc:xxxxxxx-xxxx/xxxxxxxxxxx/xxxxxxxxxxxxxxxxx") && ' - ) - ) - ] -) - -if __name__ == "__main__": - for i in range(4, 8): - cmd = ( - r"for pid in $(ps aux | grep paster | grep -v grep | grep '\-%d' | awk '{print $2}'); do kill $pid; done" - % (i) - ) - -def A(): - def B(): - def C(): - def D(): - def E(): - def F(): - def G(): - assert ( - c_float(val[0][0] / val[0][1]).value - == c_float(value[0][0] / value[0][1]).value - ), "%s didn't roundtrip" % tag - -class xxxxxxxxxxxxxxxxxxxxx(xxxx.xxxxxxxxxxxxx): - def xxxxxxx_xxxxxx(xxxx): - assert xxxxxxx_xxxx in [ - x.xxxxx.xxxxxx.xxxxx.xxxxxx, - x.xxxxx.xxxxxx.xxxxx.xxxx, - ], ("xxxxxxxxxxx xxxxxxx xxxx (xxxxxx xxxx) %x xxx xxxxx" % xxxxxxx_xxxx) - -value.__dict__[ - key -] = "test" # set some Thrift field to non-None in the struct aa bb cc dd ee - -RE_ONE_BACKSLASH = { - "asdf_hjkl_jkl": re.compile( - r"(?>\n" -) - -assert str(suffix_arr) == ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) != ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) <= ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) >= ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) < ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) > ( - "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert str(suffix_arr) in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -assert str(suffix_arr) not in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -message = ( - f"1. Go to Google Developers Console and log in with your Google account." - "(https://console.developers.google.com/)" - "2. You should be prompted to create a new project (name does not matter)." - "3. Click on Enable APIs and Services at the top." - "4. In the list of APIs choose or search for YouTube Data API v3 and " - "click on it. Choose Enable." - "5. Click on Credentials on the left navigation bar." - "6. Click on Create Credential at the top." - '7. At the top click the link for "API key".' - "8. No application restrictions are needed. Click Create at the bottom." - "9. You now have a key to add to `{prefix}set api youtube api_key`" -) -message = ( - f"1. Go to Google Developers Console and log in with your Google account." - "(https://console.developers.google.com/)" - "2. You should be prompted to create a new project (name does not matter)." - f"3. Click on Enable APIs and Services at the top." - "4. In the list of APIs choose or search for YouTube Data API v3 and " - "click on it. Choose Enable." - f"5. Click on Credentials on the left navigation bar." - "6. Click on Create Credential at the top." - '7. At the top click the link for "API key".' - "8. No application restrictions are needed. Click Create at the bottom." - "9. You now have a key to add to `{prefix}set api youtube api_key`" -) -message = ( - f"1. Go to Google Developers Console and log in with your Google account." - "(https://console.developers.google.com/)" - "2. You should be prompted to create a new project (name does not matter)." - f"3. Click on Enable APIs and Services at the top." - "4. In the list of APIs choose or search for YouTube Data API v3 and " - "click on it. Choose Enable." - f"5. Click on Credentials on the left navigation bar." - "6. Click on Create Credential at the top." - '7. At the top click the link for "API key".' - "8. No application restrictions are needed. Click Create at the bottom." - f"9. You now have a key to add to `{prefix}set api youtube api_key`" -) - -# It shouldn't matter if the string prefixes are capitalized. -temp_msg = ( - F"{F'{humanize_number(pos)}.': <{pound_len+2}} " - F"{balance: <{bal_len + 5}} " - F"<<{author.display_name}>>\n" -) - -fstring = ( - F"We have to remember to escape {braces}." - " Like {these}." - F" But not {this}." -) - -welcome_to_programming = R"hello," R" world!" - -fstring = F"f-strings definitely make things more {difficult} than they need to be for {{black}}. But boy they sure are handy. The problem is that some lines will need to have the 'f' whereas others do not. This {line}, for example, needs one." - -x = F"This is a long string which contains an f-expr that should not split {{{[i for i in range(5)]}}}." - -x = ( - "\N{BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR}\N{VARIATION SELECTOR-16}" -) - -xxxxxx_xxx_xxxx_xx_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxx_xxxx_xxxxx = xxxx.xxxxxx.xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx( - xx_xxxxxx={ - "x3_xxxxxxxx": "xxx3_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxxxxxx_xxxxxx_xxxxxxx", - }, -) - -# Regression test for /~https://github.com/psf/black/issues/3117. -some_dict = { - "something_something": - r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t", -} - -# Regression test for /~https://github.com/psf/black/issues/3459. -xxxx( - empty_str_as_first_split='' - f'xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx ' - 'xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. ' - f'xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}', - empty_u_str_as_first_split=u'' - f'xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx ' - 'xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. ' - f'xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}', -) - -# Regression test for /~https://github.com/psf/black/issues/3455. -a_dict = { - "/this/is/a/very/very/very/very/very/very/very/very/very/very/long/key/without/spaces": - # And there is a comment before the value - ("item1", "item2", "item3"), -} - - -# output - - -class A: - def foo(): - result = type(message)("") - - -# Don't merge multiline (e.g. triple-quoted) strings. -def foo(): - query = ( - """SELECT xxxxxxxxxxxxxxxxxxxx(xxx)""" - """ FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""" - ) - - -# There was a bug where tuples were being identified as long strings. -long_tuple = ( - "Apple", - "Berry", - "Cherry", - "Dill", - "Evergreen", - "Fig", - "Grape", - "Harry", - "Iglu", - "Jaguar", -) - -stupid_format_method_bug = ( - "Some really long string that just so happens to be the {} {} to force the 'format'" - " method to hang over the line length boundary. This is pretty annoying.".format( - "perfect", "length" - ) -) - - -class A: - def foo(): - os.system( - "This is a regression test. xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx" - " xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx" - " xxxx.".format("xxxxxxxxxx", "xxxxxx", "xxxxxxxxxx") - ) - - -class A: - def foo(): - XXXXXXXXXXXX.append( - ( - "xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})" - .format(xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx), - my_var, - my_other_var, - ) - ) - - -class A: - class B: - def foo(): - bar( - "[{}]: xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx={}" - " xxxx_xxxx_xxxxxxxxxx={}, xxxx={})".format( - xxxx._xxxxxxxxxxxxxx, xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx, xxxxxxx - ), - varX, - varY, - varZ, - ) - - -def foo(xxxx): - for xxx_xxxx, _xxx_xxx, _xxx_xxxxx, xxx_xxxx in xxxx: - for xxx in xxx_xxxx: - assert ("x" in xxx) or (xxx in xxx_xxx_xxxxx), ( - "{0} xxxxxxx xx {1}, xxx {1} xx xxx xx xxxx xx xxx xxxx: xxx xxxx {2}" - .format(xxx_xxxx, xxx, xxxxxx.xxxxxxx(xxx_xxx_xxxxx)) - ) - - -class A: - def disappearing_comment(): - return ( - ( # xx -x xxxxxxx xx xxx xxxxxxx. - "{{xxx_xxxxxxxxxx_xxxxxxxx}} xxx xxxx {} {{xxxx}} >&2".format( - "{xxxx} {xxxxxx}" - if xxxxx.xx_xxxxxxxxxx - else ( # Disappearing Comment - "--xxxxxxx --xxxxxx=x --xxxxxx-xxxxx=xxxxxx" - " --xxxxxx-xxxx=xxxxxxxxxxx.xxx" - ) - ) - ), - (x, y, z), - ) - - -class A: - class B: - def foo(): - xxxxx_xxxx( - xx, - "\t" - "@xxxxxx '{xxxx_xxx}\t' > {xxxxxx_xxxx}.xxxxxxx;" - "{xxxx_xxx} >> {xxxxxx_xxxx}.xxxxxxx 2>&1; xx=$$?;" - "xxxx $$xx".format( - xxxx_xxx=xxxx_xxxxxxx, - xxxxxx_xxxx=xxxxxxx + "/" + xxxx_xxx_xxxx, - x=xxx_xxxxx_xxxxx_xxx, - ), - x, - y, - z, - ) - - -func_call_where_string_arg_has_method_call_and_bad_parens( - "A long string with {}. This string is so long that it is ridiculous. It can't fit" - " on one line at alllll.".format("formatting"), -) - -func_call_where_string_arg_has_old_fmt_and_bad_parens( - "A long string with {}. This string is so long that it is ridiculous. It can't fit" - " on one line at alllll." % "formatting", -) - -func_call_where_string_arg_has_old_fmt_and_bad_parens( - "A long string with {}. This {} is so long that it is ridiculous. It can't fit on" - " one line at alllll." % ("formatting", "string"), -) - - -class A: - def append(self): - if True: - xxxx.xxxxxxx.xxxxx( - "xxxxxxxxxx xxxx xx xxxxxx(%x) xx %x xxxx xx xxx %x.xx" - % (len(self) + 1, xxxx.xxxxxxxxxx, xxxx.xxxxxxxxxx) - + " %.3f (%s) to %.3f (%s).\n" - % ( - xxxx.xxxxxxxxx, - xxxx.xxxxxxxxxxxxxx(xxxx.xxxxxxxxx), - x, - xxxx.xxxxxxxxxxxxxx(xx), - ) - ) - - -class A: - def foo(): - some_func_call( - "xxxxxxxxxx", - ( - "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " - '"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; ' - "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " - ), - None, - ("xxxxxxxxxxx",), - ), - - -class A: - def foo(): - some_func_call( - ( - "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " - "xxxx, ('xxxxxxx xxxxxx xxxx, xxxx') xxxxxx_xxxxx xxxxxx xxxx; " - "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " - ), - None, - ("xxxxxxxxxxx",), - ), - - -xxxxxxx = { - "xx": ( - "xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} -xx {1} -xx" - " xxx=xxx_xxxx,xxx_xx,xxx_xxx,xxx_xxxx,xxx_xx,xxx_xxx | xxxxxx -x xxxxxxxx -x" - " xxxxxxxx -x" - ), - "xx": ( - "xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} -xx {1} -xx" - " xxx=xxx_xxxx_xxx_xxxx,xxx_xx_xxx_xxxx,xxx_xxxx_xxx_xxxx,xxx_xx_xxxx_xxxx,xxx_xxx_xxxx,xxx_xxx_xxxx" - " xxxx=xxx | xxxxxx -x xxxxxxxx -x xxxxxxxx -x" - ), -} - - -class A: - def foo(self): - if True: - xxxxx_xxxxxxxxxxxx( - "xxx xxxxxx xxx xxxxxxxxx.xx xx xxxxxxxx. xxx xxxxxxxxxxxxx.xx" - " xxxxxxx " - + "xx xxxxxx xxxxxx xxxxxx xx xxxxxxx xxx xxx ${0} xx x xxxxxxxx xxxxx" - .xxxxxx(xxxxxx_xxxxxx_xxx) - ) - - -class A: - class B: - def foo(): - row = { - "xxxxxxxxxxxxxxx": xxxxxx_xxxxx_xxxx, - # 'xxxxxxxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxxx' - # 'xxxxxxxxxxxxxxxxx' - "xxxxxxxxxx": xxxxx_xxxxx, - } - - -class A: - def xxxx_xxx_xx_xxxxxxxxxx_xxxx_xxxxxxxxx(xxxx): - xxxxxxxx = [ - xxxxxxxxxxxxxxxx( - "xxxx", - xxxxxxxxxxx={ - "xxxx": 1.0, - }, - xxxxxx={"xxxxxx 1": xxxxxx(xxxx="xxxxxx 1", xxxxxx=600.0)}, - xxxxxxxx_xxxxxxx=0.0, - ), - xxxxxxxxxxxxxxxx( - "xxxxxxx", - xxxxxxxxxxx={ - "xxxx": 1.0, - }, - xxxxxx={"xxxxxx 1": xxxxxx(xxxx="xxxxxx 1", xxxxxx=200.0)}, - xxxxxxxx_xxxxxxx=0.0, - ), - xxxxxxxxxxxxxxxx( - "xxxx", - ), - ] - - -some_dictionary = { - "xxxxx006": [ - ( - "xxx-xxx" - " xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx==" - " xxxxx000 xxxxxxxxxx\n" - ), - ( - "xxx-xxx" - " xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx==" - " xxxxx010 xxxxxxxxxx\n" - ), - ], - "xxxxx016": [ - ( - "xxx-xxx" - " xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx==" - " xxxxx000 xxxxxxxxxx\n" - ), - ( - "xxx-xxx" - " xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx==" - " xxxxx010 xxxxxxxxxx\n" - ), - ], -} - - -def foo(): - xxx_xxx = ( # xxxx xxxxxxxxxx xxxx xx xxxx xx xxx xxxxxxxx xxxxxx xxxxx. - 'xxxx xxx xxxxxxxx_xxxx xx "xxxxxxxxxx".\n xxx: xxxxxx xxxxxxxx_xxxx=xxxxxxxxxx' - ) - - -some_tuple = ("some string", "some string which should be joined") - -some_commented_string = ( # This comment gets thrown to the top. - "This string is long but not so long that it needs hahahah toooooo be so greatttt" - " {} that I just can't think of any more good words to say about it at" - " allllllllllll".format("ha") # comments here are fine -) - -some_commented_string = ( - "This string is long but not so long that it needs hahahah toooooo be so greatttt" # But these - " {} that I just can't think of any more good words to say about it at" # comments will stay - " allllllllllll".format("ha") # comments here are fine -) - -lpar_and_rpar_have_comments = func_call( # LPAR Comment - ( # Comma Comment - "Long really ridiculous type of string that shouldn't really even exist at all." - " I mean commmme onnn!!!" - ), -) # RPAR Comment - -cmd_fstring = ( - "sudo -E deluge-console info --detailed --sort-reverse=time_added " - f"{'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" -) - -cmd_fstring = ( - "sudo -E deluge-console info --detailed --sort-reverse=time_added" - f" {'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" -) - -cmd_fstring = ( - "sudo -E deluge-console info --detailed --sort-reverse=time_added" - f" {'{{}}' if ID is None else ID} | perl -nE 'print if /^{field}:/'" -) - -cmd_fstring = ( - "sudo -E deluge-console info --detailed --sort-reverse=time_added {'' if ID is" - f" None else ID}} | perl -nE 'print if /^{field}:/'" -) - -fstring = ( - "This string really doesn't need to be an {{fstring}}, but this one most" - f" certainly, absolutely {does}." -) - -fstring = f"We have to remember to escape {braces}. Like {{these}}. But not {this}." - - -class A: - class B: - def foo(): - st_error = STError( - f"This string ({string_leaf.value}) appears to be pointless (i.e. has" - " no parent)." - ) - - -def foo(): - user_regex = _lazy_re_compile( - r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom - r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string - re.IGNORECASE, - ) - - -def foo(): - user_regex = _lazy_re_compile( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # quoted-string - xyz, - ) - - -def foo(): - user_regex = _lazy_re_compile( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # quoted-string - xyz, - ) - - -class A: - class B: - def foo(): - if not hasattr(module, name): - raise ValueError( - "Could not find object %s in %s.\n" - "Please note that you cannot serialize things like inner " - "classes. Please move the object into the main module " - "body to use migrations.\n" - "For more information, see " - "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" - % (name, module_name, get_docs_version()) - ) - - -class A: - class B: - def foo(): - if not hasattr(module, name): - raise ValueError( - "Could not find object %s in %s.\nPlease note that you cannot" - " serialize things like inner classes. Please move the object into" - " the main module body to use migrations.\nFor more information," - " see https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" - % (name, module_name, get_docs_version()) - ) - - -x = ( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) - - -class Step(StepBase): - def who(self): - self.cmd = ( - "SR AAAA-CORRECT NAME IS {last_name} {first_name}{middle_name}" - " {title}/P{passenger_association}".format( - last_name=last_name, - first_name=first_name, - middle_name=middle_name, - title=title, - passenger_association=passenger_association, - ) - ) - - -xxxxxxx_xxxxxx_xxxxxxx = xxx( - [ - xxxxxxxxxxxx( - xxxxxx_xxxxxxx=( - '((x.aaaaaaaaa = "xxxxxx.xxxxxxxxxxxxxxxxxxxxx") || (x.xxxxxxxxx =' - ' "xxxxxxxxxxxx")) && ' - # xxxxx xxxxxxxxxxxx xxxx xxx (xxxxxxxxxxxxxxxx) xx x xxxxxxxxx xx xxxxxx. - "(x.bbbbbbbbbbbb.xxx != " - '"xxx:xxx:xxx::cccccccccccc:xxxxxxx-xxxx/xxxxxxxxxxx/xxxxxxxxxxxxxxxxx") && ' - ) - ) - ] -) - -if __name__ == "__main__": - for i in range(4, 8): - cmd = ( - r"for pid in $(ps aux | grep paster | grep -v grep | grep '\-%d' | awk" - r" '{print $2}'); do kill $pid; done" % (i) - ) - - -def A(): - def B(): - def C(): - def D(): - def E(): - def F(): - def G(): - assert ( - c_float(val[0][0] / val[0][1]).value - == c_float(value[0][0] / value[0][1]).value - ), "%s didn't roundtrip" % tag - - -class xxxxxxxxxxxxxxxxxxxxx(xxxx.xxxxxxxxxxxxx): - def xxxxxxx_xxxxxx(xxxx): - assert xxxxxxx_xxxx in [ - x.xxxxx.xxxxxx.xxxxx.xxxxxx, - x.xxxxx.xxxxxx.xxxxx.xxxx, - ], ( - "xxxxxxxxxxx xxxxxxx xxxx (xxxxxx xxxx) %x xxx xxxxx" % xxxxxxx_xxxx - ) - - -value.__dict__[key] = ( - "test" # set some Thrift field to non-None in the struct aa bb cc dd ee -) - -RE_ONE_BACKSLASH = { - "asdf_hjkl_jkl": re.compile( - r"(?>\n" -) - -assert ( - str(suffix_arr) - == "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - != "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - <= "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - >= "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - < "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - > "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " - "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " - "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" -) -assert ( - str(suffix_arr) - in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$'," - " 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$', 'rykangaroo$'," - " 'ykangaroo$']" -) -assert ( - str(suffix_arr) - not in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$'," - " 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$'," - " 'rykangaroo$', 'ykangaroo$']" -) -message = ( - f"1. Go to Google Developers Console and log in with your Google account." - f"(https://console.developers.google.com/)" - f"2. You should be prompted to create a new project (name does not matter)." - f"3. Click on Enable APIs and Services at the top." - f"4. In the list of APIs choose or search for YouTube Data API v3 and " - f"click on it. Choose Enable." - f"5. Click on Credentials on the left navigation bar." - f"6. Click on Create Credential at the top." - f'7. At the top click the link for "API key".' - f"8. No application restrictions are needed. Click Create at the bottom." - f"9. You now have a key to add to `{{prefix}}set api youtube api_key`" -) -message = ( - f"1. Go to Google Developers Console and log in with your Google account." - f"(https://console.developers.google.com/)" - f"2. You should be prompted to create a new project (name does not matter)." - f"3. Click on Enable APIs and Services at the top." - f"4. In the list of APIs choose or search for YouTube Data API v3 and " - f"click on it. Choose Enable." - f"5. Click on Credentials on the left navigation bar." - f"6. Click on Create Credential at the top." - f'7. At the top click the link for "API key".' - f"8. No application restrictions are needed. Click Create at the bottom." - f"9. You now have a key to add to `{{prefix}}set api youtube api_key`" -) -message = ( - "1. Go to Google Developers Console and log in with your Google account." - "(https://console.developers.google.com/)" - "2. You should be prompted to create a new project (name does not matter)." - "3. Click on Enable APIs and Services at the top." - "4. In the list of APIs choose or search for YouTube Data API v3 and " - "click on it. Choose Enable." - "5. Click on Credentials on the left navigation bar." - "6. Click on Create Credential at the top." - '7. At the top click the link for "API key".' - "8. No application restrictions are needed. Click Create at the bottom." - f"9. You now have a key to add to `{prefix}set api youtube api_key`" -) - -# It shouldn't matter if the string prefixes are capitalized. -temp_msg = ( - f"{F'{humanize_number(pos)}.': <{pound_len+2}} " - f"{balance: <{bal_len + 5}} " - f"<<{author.display_name}>>\n" -) - -fstring = f"We have to remember to escape {braces}. Like {{these}}. But not {this}." - -welcome_to_programming = R"hello," R" world!" - -fstring = ( - f"f-strings definitely make things more {difficult} than they need to be for" - " {black}. But boy they sure are handy. The problem is that some lines will need" - f" to have the 'f' whereas others do not. This {line}, for example, needs one." -) - -x = ( - "This is a long string which contains an f-expr that should not split" - f" {{{[i for i in range(5)]}}}." -) - -x = ( - "\N{BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR}\N{VARIATION SELECTOR-16}" -) - -xxxxxx_xxx_xxxx_xx_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxx_xxxx_xxxxx = xxxx.xxxxxx.xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx( - xx_xxxxxx={ - "x3_xxxxxxxx": ( - "xxx3_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxxxxxx_xxxxxx_xxxxxxx" - ), - }, -) - -# Regression test for /~https://github.com/psf/black/issues/3117. -some_dict = { - "something_something": ( - r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t" - r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t" - ), -} - -# Regression test for /~https://github.com/psf/black/issues/3459. -xxxx( - empty_str_as_first_split=( - "" - f"xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx " - "xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. " - f"xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}" - ), - empty_u_str_as_first_split=( - "" - f"xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx " - "xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. " - f"xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}" - ), -) - -# Regression test for /~https://github.com/psf/black/issues/3455. -a_dict = { - "/this/is/a/very/very/very/very/very/very/very/very/very/very/long/key/without/spaces": - # And there is a comment before the value - ("item1", "item2", "item3"), -} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__type_annotations.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__type_annotations.py deleted file mode 100644 index 41d7ee2b67b0cf..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/long_strings__type_annotations.py +++ /dev/null @@ -1,59 +0,0 @@ -def func( - arg1, - arg2, -) -> Set["this_is_a_very_long_module_name.AndAVeryLongClasName" - ".WithAVeryVeryVeryVeryVeryLongSubClassName"]: - pass - - -def func( - argument: ( - "VeryLongClassNameWithAwkwardGenericSubtype[int] |" - "VeryLongClassNameWithAwkwardGenericSubtype[str]" - ), -) -> ( - "VeryLongClassNameWithAwkwardGenericSubtype[int] |" - "VeryLongClassNameWithAwkwardGenericSubtype[str]" -): - pass - - -def func( - argument: ( - "int |" - "str" - ), -) -> Set["int |" - " str"]: - pass - - -# output - - -def func( - arg1, - arg2, -) -> Set[ - "this_is_a_very_long_module_name.AndAVeryLongClasName" - ".WithAVeryVeryVeryVeryVeryLongSubClassName" -]: - pass - - -def func( - argument: ( - "VeryLongClassNameWithAwkwardGenericSubtype[int] |" - "VeryLongClassNameWithAwkwardGenericSubtype[str]" - ), -) -> ( - "VeryLongClassNameWithAwkwardGenericSubtype[int] |" - "VeryLongClassNameWithAwkwardGenericSubtype[str]" -): - pass - - -def func( - argument: ("int |" "str"), -) -> Set["int |" " str"]: - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/one_element_subscript.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/one_element_subscript.py deleted file mode 100644 index 39205ba9f7aae2..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/one_element_subscript.py +++ /dev/null @@ -1,36 +0,0 @@ -# We should not treat the trailing comma -# in a single-element subscript. -a: tuple[int,] -b = tuple[int,] - -# The magic comma still applies to multi-element subscripts. -c: tuple[int, int,] -d = tuple[int, int,] - -# Magic commas still work as expected for non-subscripts. -small_list = [1,] -list_of_types = [tuple[int,],] - -# output -# We should not treat the trailing comma -# in a single-element subscript. -a: tuple[int,] -b = tuple[int,] - -# The magic comma still applies to multi-element subscripts. -c: tuple[ - int, - int, -] -d = tuple[ - int, - int, -] - -# Magic commas still work as expected for non-subscripts. -small_list = [ - 1, -] -list_of_types = [ - tuple[int,], -] diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/percent_precedence.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/percent_precedence.py deleted file mode 100644 index b895443fb46bbf..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/percent_precedence.py +++ /dev/null @@ -1,41 +0,0 @@ -("" % a) ** 2 -("" % a)[0] -("" % a)() -("" % a).b - -2 * ("" % a) -2 @ ("" % a) -2 / ("" % a) -2 // ("" % a) -2 % ("" % a) -+("" % a) -b + ("" % a) --("" % a) -b - ("" % a) -b + -("" % a) -~("" % a) -2 ** ("" % a) -await ("" % a) -b[("" % a)] -b(("" % a)) -# output -("" % a) ** 2 -("" % a)[0] -("" % a)() -("" % a).b - -2 * ("" % a) -2 @ ("" % a) -2 / ("" % a) -2 // ("" % a) -2 % ("" % a) -+("" % a) -b + "" % a --("" % a) -b - "" % a -b + -("" % a) -~("" % a) -2 ** ("" % a) -await ("" % a) -b[("" % a)] -b(("" % a)) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split.py deleted file mode 100644 index 2f3cf33db41c30..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split.py +++ /dev/null @@ -1,85 +0,0 @@ -first_item, second_item = ( - some_looooooooong_module.some_looooooooooooooong_function_name( - first_argument, second_argument, third_argument - ) -) - -some_dict["with_a_long_key"] = ( - some_looooooooong_module.some_looooooooooooooong_function_name( - first_argument, second_argument, third_argument - ) -) - -# Make sure it works when the RHS only has one pair of (optional) parens. -first_item, second_item = ( - some_looooooooong_module.SomeClass.some_looooooooooooooong_variable_name -) - -some_dict["with_a_long_key"] = ( - some_looooooooong_module.SomeClass.some_looooooooooooooong_variable_name -) - -# Make sure chaining assignments work. -first_item, second_item, third_item, forth_item = m["everything"] = ( - some_looooooooong_module.some_looooooooooooooong_function_name( - first_argument, second_argument, third_argument - ) -) - -# Make sure when the RHS's first split at the non-optional paren fits, -# we split there instead of the outer RHS optional paren. -first_item, second_item = some_looooooooong_module.some_loooooog_function_name( - first_argument, second_argument, third_argument -) - -( - first_item, - second_item, - third_item, - forth_item, - fifth_item, - last_item_very_loooooong, -) = some_looooooooong_module.some_looooooooooooooong_function_name( - first_argument, second_argument, third_argument -) - -( - first_item, - second_item, - third_item, - forth_item, - fifth_item, - last_item_very_loooooong, -) = everything = some_looooong_function_name( - first_argument, second_argument, third_argument -) - - -# Make sure unsplittable type ignore won't be moved. -some_kind_of_table[some_key] = util.some_function( # type: ignore # noqa: E501 - some_arg -).intersection(pk_cols) - -some_kind_of_table[ - some_key -] = lambda obj: obj.some_long_named_method() # type: ignore # noqa: E501 - -some_kind_of_table[ - some_key # type: ignore # noqa: E501 -] = lambda obj: obj.some_long_named_method() - - -# Make when when the left side of assignement plus the opening paren "... = (" is -# exactly line length limit + 1, it won't be split like that. -xxxxxxxxx_yyy_zzzzzzzz[ - xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1) -] = 1 - - -# Right side of assignment contains un-nested pairs of inner parens. -some_kind_of_instance.some_kind_of_map[a_key] = ( - isinstance(some_var, SomeClass) - and table.something_and_something != table.something_else -) or ( - isinstance(some_other_var, BaseClass) and table.something != table.some_other_thing -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split_reformatted.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split_reformatted.py deleted file mode 100644 index 781e75be0aa84d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/prefer_rhs_split_reformatted.py +++ /dev/null @@ -1,38 +0,0 @@ -# Test cases separate from `prefer_rhs_split.py` that contains unformatted source. - -# Left hand side fits in a single line but will still be exploded by the -# magic trailing comma. -first_value, (m1, m2,), third_value = xxxxxx_yyyyyy_zzzzzz_wwwwww_uuuuuuu_vvvvvvvvvvv( - arg1, - arg2, -) - -# Make when when the left side of assignement plus the opening paren "... = (" is -# exactly line length limit + 1, it won't be split like that. -xxxxxxxxx_yyy_zzzzzzzz[xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1)] = 1 - - -# output - - -# Test cases separate from `prefer_rhs_split.py` that contains unformatted source. - -# Left hand side fits in a single line but will still be exploded by the -# magic trailing comma. -( - first_value, - ( - m1, - m2, - ), - third_value, -) = xxxxxx_yyyyyy_zzzzzz_wwwwww_uuuuuuu_vvvvvvvvvvv( - arg1, - arg2, -) - -# Make when when the left side of assignement plus the opening paren "... = (" is -# exactly line length limit + 1, it won't be split like that. -xxxxxxxxx_yyy_zzzzzzzz[ - xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1) -] = 1 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_await_parens.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_await_parens.py deleted file mode 100644 index 571210a2d80c7e..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_await_parens.py +++ /dev/null @@ -1,169 +0,0 @@ -import asyncio - -# Control example -async def main(): - await asyncio.sleep(1) - -# Remove brackets for short coroutine/task -async def main(): - await (asyncio.sleep(1)) - -async def main(): - await ( - asyncio.sleep(1) - ) - -async def main(): - await (asyncio.sleep(1) - ) - -# Check comments -async def main(): - await ( # Hello - asyncio.sleep(1) - ) - -async def main(): - await ( - asyncio.sleep(1) # Hello - ) - -async def main(): - await ( - asyncio.sleep(1) - ) # Hello - -# Long lines -async def main(): - await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)) - -# Same as above but with magic trailing comma in function -async def main(): - await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),) - -# Cr@zY Br@ck3Tz -async def main(): - await ( - ((((((((((((( - ((( ((( - ((( ((( - ((( ((( - ((( ((( - ((black(1))) - ))) ))) - ))) ))) - ))) ))) - ))) ))) - ))))))))))))) - ) - -# Keep brackets around non power operations and nested awaits -async def main(): - await (set_of_tasks | other_set) - -async def main(): - await (await asyncio.sleep(1)) - -# It's awaits all the way down... -async def main(): - await (await x) - -async def main(): - await (yield x) - -async def main(): - await (await (asyncio.sleep(1))) - -async def main(): - await (await (await (await (await (asyncio.sleep(1)))))) - -# output -import asyncio - - -# Control example -async def main(): - await asyncio.sleep(1) - - -# Remove brackets for short coroutine/task -async def main(): - await asyncio.sleep(1) - - -async def main(): - await asyncio.sleep(1) - - -async def main(): - await asyncio.sleep(1) - - -# Check comments -async def main(): - await asyncio.sleep(1) # Hello - - -async def main(): - await asyncio.sleep(1) # Hello - - -async def main(): - await asyncio.sleep(1) # Hello - - -# Long lines -async def main(): - await asyncio.gather( - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - ) - - -# Same as above but with magic trailing comma in function -async def main(): - await asyncio.gather( - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - asyncio.sleep(1), - ) - - -# Cr@zY Br@ck3Tz -async def main(): - await black(1) - - -# Keep brackets around non power operations and nested awaits -async def main(): - await (set_of_tasks | other_set) - - -async def main(): - await (await asyncio.sleep(1)) - - -# It's awaits all the way down... -async def main(): - await (await x) - - -async def main(): - await (yield x) - - -async def main(): - await (await asyncio.sleep(1)) - - -async def main(): - await (await (await (await (await asyncio.sleep(1))))) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_except_parens.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_except_parens.py deleted file mode 100644 index 322c5b7a51b07e..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_except_parens.py +++ /dev/null @@ -1,79 +0,0 @@ -# These brackets are redundant, therefore remove. -try: - a.something -except (AttributeError) as err: - raise err - -# This is tuple of exceptions. -# Although this could be replaced with just the exception, -# we do not remove brackets to preserve AST. -try: - a.something -except (AttributeError,) as err: - raise err - -# This is a tuple of exceptions. Do not remove brackets. -try: - a.something -except (AttributeError, ValueError) as err: - raise err - -# Test long variants. -try: - a.something -except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err: - raise err - -try: - a.something -except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err: - raise err - -try: - a.something -except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err: - raise err - -# output -# These brackets are redundant, therefore remove. -try: - a.something -except AttributeError as err: - raise err - -# This is tuple of exceptions. -# Although this could be replaced with just the exception, -# we do not remove brackets to preserve AST. -try: - a.something -except (AttributeError,) as err: - raise err - -# This is a tuple of exceptions. Do not remove brackets. -try: - a.something -except (AttributeError, ValueError) as err: - raise err - -# Test long variants. -try: - a.something -except ( - some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error -) as err: - raise err - -try: - a.something -except ( - some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, -) as err: - raise err - -try: - a.something -except ( - some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, - some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, -) as err: - raise err diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_for_brackets.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_for_brackets.py deleted file mode 100644 index cd5340462da800..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_for_brackets.py +++ /dev/null @@ -1,48 +0,0 @@ -# Only remove tuple brackets after `for` -for (k, v) in d.items(): - print(k, v) - -# Don't touch tuple brackets after `in` -for module in (core, _unicodefun): - if hasattr(module, "_verify_python3_env"): - module._verify_python3_env = lambda: None - -# Brackets remain for long for loop lines -for (why_would_anyone_choose_to_name_a_loop_variable_with_a_name_this_long, i_dont_know_but_we_should_still_check_the_behaviour_if_they_do) in d.items(): - print(k, v) - -for (k, v) in dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items(): - print(k, v) - -# Test deeply nested brackets -for (((((k, v))))) in d.items(): - print(k, v) - -# output -# Only remove tuple brackets after `for` -for k, v in d.items(): - print(k, v) - -# Don't touch tuple brackets after `in` -for module in (core, _unicodefun): - if hasattr(module, "_verify_python3_env"): - module._verify_python3_env = lambda: None - -# Brackets remain for long for loop lines -for ( - why_would_anyone_choose_to_name_a_loop_variable_with_a_name_this_long, - i_dont_know_but_we_should_still_check_the_behaviour_if_they_do, -) in d.items(): - print(k, v) - -for ( - k, - v, -) in ( - dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items() -): - print(k, v) - -# Test deeply nested brackets -for k, v in d.items(): - print(k, v) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_newline_after_code_block_open.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_newline_after_code_block_open.py deleted file mode 100644 index ef2e5c2f6f53fb..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/remove_newline_after_code_block_open.py +++ /dev/null @@ -1,189 +0,0 @@ -import random - - -def foo1(): - - print("The newline above me should be deleted!") - - -def foo2(): - - - - print("All the newlines above me should be deleted!") - - -def foo3(): - - print("No newline above me!") - - print("There is a newline above me, and that's OK!") - - -def foo4(): - - # There is a comment here - - print("The newline above me should not be deleted!") - - -class Foo: - def bar(self): - - print("The newline above me should be deleted!") - - -for i in range(5): - - print(f"{i}) The line above me should be removed!") - - -for i in range(5): - - - - print(f"{i}) The lines above me should be removed!") - - -for i in range(5): - - for j in range(7): - - print(f"{i}) The lines above me should be removed!") - - -if random.randint(0, 3) == 0: - - print("The new line above me is about to be removed!") - - -if random.randint(0, 3) == 0: - - - - - print("The new lines above me is about to be removed!") - - -if random.randint(0, 3) == 0: - if random.uniform(0, 1) > 0.5: - print("Two lines above me are about to be removed!") - - -while True: - - print("The newline above me should be deleted!") - - -while True: - - - - print("The newlines above me should be deleted!") - - -while True: - - while False: - - print("The newlines above me should be deleted!") - - -with open("/path/to/file.txt", mode="w") as file: - - file.write("The new line above me is about to be removed!") - - -with open("/path/to/file.txt", mode="w") as file: - - - - file.write("The new lines above me is about to be removed!") - - -with open("/path/to/file.txt", mode="r") as read_file: - - with open("/path/to/output_file.txt", mode="w") as write_file: - - write_file.writelines(read_file.readlines()) - -# output - -import random - - -def foo1(): - print("The newline above me should be deleted!") - - -def foo2(): - print("All the newlines above me should be deleted!") - - -def foo3(): - print("No newline above me!") - - print("There is a newline above me, and that's OK!") - - -def foo4(): - # There is a comment here - - print("The newline above me should not be deleted!") - - -class Foo: - def bar(self): - print("The newline above me should be deleted!") - - -for i in range(5): - print(f"{i}) The line above me should be removed!") - - -for i in range(5): - print(f"{i}) The lines above me should be removed!") - - -for i in range(5): - for j in range(7): - print(f"{i}) The lines above me should be removed!") - - -if random.randint(0, 3) == 0: - print("The new line above me is about to be removed!") - - -if random.randint(0, 3) == 0: - print("The new lines above me is about to be removed!") - - -if random.randint(0, 3) == 0: - if random.uniform(0, 1) > 0.5: - print("Two lines above me are about to be removed!") - - -while True: - print("The newline above me should be deleted!") - - -while True: - print("The newlines above me should be deleted!") - - -while True: - while False: - print("The newlines above me should be deleted!") - - -with open("/path/to/file.txt", mode="w") as file: - file.write("The new line above me is about to be removed!") - - -with open("/path/to/file.txt", mode="w") as file: - file.write("The new lines above me is about to be removed!") - - -with open("/path/to/file.txt", mode="r") as read_file: - with open("/path/to/output_file.txt", mode="w") as write_file: - write_file.writelines(read_file.readlines()) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/return_annotation_brackets.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/return_annotation_brackets.py deleted file mode 100644 index 27760bd51d7579..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/return_annotation_brackets.py +++ /dev/null @@ -1,222 +0,0 @@ -# Control -def double(a: int) -> int: - return 2*a - -# Remove the brackets -def double(a: int) -> (int): - return 2*a - -# Some newline variations -def double(a: int) -> ( - int): - return 2*a - -def double(a: int) -> (int -): - return 2*a - -def double(a: int) -> ( - int -): - return 2*a - -# Don't lose the comments -def double(a: int) -> ( # Hello - int -): - return 2*a - -def double(a: int) -> ( - int # Hello -): - return 2*a - -# Really long annotations -def foo() -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - -def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: - return 2 - -def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: - return 2 - -def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: - return 2 - -def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: - return 2 - -# Split args but no need to split return -def foo(a: int, b: int, c: int,) -> int: - return 2 - -# Deeply nested brackets -# with *interesting* spacing -def double(a: int) -> (((((int))))): - return 2*a - -def double(a: int) -> ( - ( ( - ((int) - ) - ) - ) - ): - return 2*a - -def foo() -> ( - ( ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -) -)): - return 2 - -# Return type with commas -def foo() -> ( - tuple[int, int, int] -): - return 2 - -def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]: - return 2 - -# Magic trailing comma example -def foo() -> tuple[int, int, int,]: - return 2 - -# Long string example -def frobnicate() -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnreasonablyExtremelyLongClassName]": - pass - -# output -# Control -def double(a: int) -> int: - return 2 * a - - -# Remove the brackets -def double(a: int) -> int: - return 2 * a - - -# Some newline variations -def double(a: int) -> int: - return 2 * a - - -def double(a: int) -> int: - return 2 * a - - -def double(a: int) -> int: - return 2 * a - - -# Don't lose the comments -def double(a: int) -> int: # Hello - return 2 * a - - -def double(a: int) -> int: # Hello - return 2 * a - - -# Really long annotations -def foo() -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - - -def foo() -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - - -def foo() -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds - | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - - -def foo( - a: int, - b: int, - c: int, -) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: - return 2 - - -def foo( - a: int, - b: int, - c: int, -) -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds - | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - - -# Split args but no need to split return -def foo( - a: int, - b: int, - c: int, -) -> int: - return 2 - - -# Deeply nested brackets -# with *interesting* spacing -def double(a: int) -> int: - return 2 * a - - -def double(a: int) -> int: - return 2 * a - - -def foo() -> ( - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds -): - return 2 - - -# Return type with commas -def foo() -> tuple[int, int, int]: - return 2 - - -def foo() -> ( - tuple[ - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - ] -): - return 2 - - -# Magic trailing comma example -def foo() -> ( - tuple[ - int, - int, - int, - ] -): - return 2 - - -# Long string example -def frobnicate() -> ( - "ThisIsTrulyUnreasonablyExtremelyLongClassName |" - " list[ThisIsTrulyUnreasonablyExtremelyLongClassName]" -): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/skip_magic_trailing_comma.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/skip_magic_trailing_comma.py deleted file mode 100644 index c020db798649a7..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/skip_magic_trailing_comma.py +++ /dev/null @@ -1,74 +0,0 @@ -# We should not remove the trailing comma in a single-element subscript. -a: tuple[int,] -b = tuple[int,] - -# But commas in multiple element subscripts should be removed. -c: tuple[int, int,] -d = tuple[int, int,] - -# Remove commas for non-subscripts. -small_list = [1,] -list_of_types = [tuple[int,],] -small_set = {1,} -set_of_types = {tuple[int,],} - -# Except single element tuples -small_tuple = (1,) - -# Trailing commas in multiple chained non-nested parens. -zero( - one, -).two( - three, -).four( - five, -) - -func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) - -( - a, - b, - c, - d, -) = func1( - arg1 -) and func2(arg2) - -func( - argument1, - ( - one, - two, - ), - argument4, - argument5, - argument6, -) - -# output -# We should not remove the trailing comma in a single-element subscript. -a: tuple[int,] -b = tuple[int,] - -# But commas in multiple element subscripts should be removed. -c: tuple[int, int] -d = tuple[int, int] - -# Remove commas for non-subscripts. -small_list = [1] -list_of_types = [tuple[int,]] -small_set = {1} -set_of_types = {tuple[int,]} - -# Except single element tuples -small_tuple = (1,) - -# Trailing commas in multiple chained non-nested parens. -zero(one).two(three).four(five) - -func1(arg1).func2(arg2).func3(arg3).func4(arg4).func5(arg5) - -(a, b, c, d) = func1(arg1) and func2(arg2) - -func(argument1, (one, two), argument4, argument5, argument6) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/trailing_commas_in_leading_parts.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/trailing_commas_in_leading_parts.py deleted file mode 100644 index 99d82a677f8359..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/trailing_commas_in_leading_parts.py +++ /dev/null @@ -1,88 +0,0 @@ -zero(one,).two(three,).four(five,) - -func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) - -# Inner one-element tuple shouldn't explode -func1(arg1).func2(arg1, (one_tuple,)).func3(arg3) - -(a, b, c, d,) = func1(arg1) and func2(arg2) - - -# Example from /~https://github.com/psf/black/issues/3229 -def refresh_token(self, device_family, refresh_token, api_key): - return self.orchestration.refresh_token( - data={ - "refreshToken": refresh_token, - }, - api_key=api_key, - )["extensions"]["sdk"]["token"] - - -# Edge case where a bug in a working-in-progress version of -# /~https://github.com/psf/black/pull/3370 causes an infinite recursion. -assert ( - long_module.long_class.long_func().another_func() - == long_module.long_class.long_func()["some_key"].another_func(arg1) -) - -# Regression test for /~https://github.com/psf/black/issues/3414. -assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx( - xxxxxxxxx -).xxxxxxxxxxxxxxxxxx(), ( - "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) - - -# output - - -zero( - one, -).two( - three, -).four( - five, -) - -func1(arg1).func2( - arg2, -).func3(arg3).func4( - arg4, -).func5(arg5) - -# Inner one-element tuple shouldn't explode -func1(arg1).func2(arg1, (one_tuple,)).func3(arg3) - -( - a, - b, - c, - d, -) = func1( - arg1 -) and func2(arg2) - - -# Example from /~https://github.com/psf/black/issues/3229 -def refresh_token(self, device_family, refresh_token, api_key): - return self.orchestration.refresh_token( - data={ - "refreshToken": refresh_token, - }, - api_key=api_key, - )["extensions"]["sdk"]["token"] - - -# Edge case where a bug in a working-in-progress version of -# /~https://github.com/psf/black/pull/3370 causes an infinite recursion. -assert ( - long_module.long_class.long_func().another_func() - == long_module.long_class.long_func()["some_key"].another_func(arg1) -) - -# Regression test for /~https://github.com/psf/black/issues/3414. -assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx( - xxxxxxxxx -).xxxxxxxxxxxxxxxxxx(), ( - "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview/whitespace.py b/crates/ruff_fmt/resources/test/fixtures/black/preview/whitespace.py deleted file mode 100644 index a319c0117b19e2..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview/whitespace.py +++ /dev/null @@ -1,6 +0,0 @@ - - - - - -# output diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_310/remove_newline_after_match.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_310/remove_newline_after_match.py deleted file mode 100644 index f7bcfbf27a232a..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_310/remove_newline_after_match.py +++ /dev/null @@ -1,34 +0,0 @@ -def http_status(status): - - match status: - - case 400: - - return "Bad request" - - case 401: - - return "Unauthorized" - - case 403: - - return "Forbidden" - - case 404: - - return "Not found" - -# output -def http_status(status): - match status: - case 400: - return "Bad request" - - case 401: - return "Unauthorized" - - case 403: - return "Forbidden" - - case 404: - return "Not found" \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_39/remove_with_brackets.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_39/remove_with_brackets.py deleted file mode 100644 index ea58ab93a16f60..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_39/remove_with_brackets.py +++ /dev/null @@ -1,119 +0,0 @@ -with (open("bla.txt")): - pass - -with (open("bla.txt")), (open("bla.txt")): - pass - -with (open("bla.txt") as f): - pass - -# Remove brackets within alias expression -with (open("bla.txt")) as f: - pass - -# Remove brackets around one-line context managers -with (open("bla.txt") as f, (open("x"))): - pass - -with ((open("bla.txt")) as f, open("x")): - pass - -with (CtxManager1() as example1, CtxManager2() as example2): - ... - -# Brackets remain when using magic comma -with (CtxManager1() as example1, CtxManager2() as example2,): - ... - -# Brackets remain for multi-line context managers -with (CtxManager1() as example1, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2): - ... - -# Don't touch assignment expressions -with (y := open("./test.py")) as f: - pass - -# Deeply nested examples -# N.B. Multiple brackets are only possible -# around the context manager itself. -# Only one brackets is allowed around the -# alias expression or comma-delimited context managers. -with (((open("bla.txt")))): - pass - -with (((open("bla.txt")))), (((open("bla.txt")))): - pass - -with (((open("bla.txt")))) as f: - pass - -with ((((open("bla.txt")))) as f): - pass - -with ((((CtxManager1()))) as example1, (((CtxManager2()))) as example2): - ... - -# output -with open("bla.txt"): - pass - -with open("bla.txt"), open("bla.txt"): - pass - -with open("bla.txt") as f: - pass - -# Remove brackets within alias expression -with open("bla.txt") as f: - pass - -# Remove brackets around one-line context managers -with open("bla.txt") as f, open("x"): - pass - -with open("bla.txt") as f, open("x"): - pass - -with CtxManager1() as example1, CtxManager2() as example2: - ... - -# Brackets remain when using magic comma -with ( - CtxManager1() as example1, - CtxManager2() as example2, -): - ... - -# Brackets remain for multi-line context managers -with ( - CtxManager1() as example1, - CtxManager2() as example2, - CtxManager2() as example2, - CtxManager2() as example2, - CtxManager2() as example2, -): - ... - -# Don't touch assignment expressions -with (y := open("./test.py")) as f: - pass - -# Deeply nested examples -# N.B. Multiple brackets are only possible -# around the context manager itself. -# Only one brackets is allowed around the -# alias expression or comma-delimited context managers. -with open("bla.txt"): - pass - -with open("bla.txt"), open("bla.txt"): - pass - -with open("bla.txt") as f: - pass - -with open("bla.txt") as f: - pass - -with CtxManager1() as example1, CtxManager2() as example2: - ... diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_10.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_10.py deleted file mode 100644 index 1458df1cb41819..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_10.py +++ /dev/null @@ -1,35 +0,0 @@ -# This file uses pattern matching introduced in Python 3.10. - - -match http_code: - case 404: - print("Not found") - - -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -# output - - -# This file uses pattern matching introduced in Python 3.10. - - -match http_code: - case 404: - print("Not found") - - -with ( - make_context_manager1() as cm1, - make_context_manager2() as cm2, - make_context_manager3() as cm3, - make_context_manager4() as cm4, -): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_11.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_11.py deleted file mode 100644 index f83c5330ab3bde..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_11.py +++ /dev/null @@ -1,37 +0,0 @@ -# This file uses except* clause in Python 3.11. - - -try: - some_call() -except* Error as e: - pass - - -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -# output - - -# This file uses except* clause in Python 3.11. - - -try: - some_call() -except* Error as e: - pass - - -with ( - make_context_manager1() as cm1, - make_context_manager2() as cm2, - make_context_manager3() as cm3, - make_context_manager4() as cm4, -): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_8.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_8.py deleted file mode 100644 index e05094e142197a..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_8.py +++ /dev/null @@ -1,30 +0,0 @@ -# This file doesn't use any Python 3.9+ only grammars. - - -# Make sure parens around a single context manager don't get autodetected as -# Python 3.9+. -with (a): - pass - - -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -# output -# This file doesn't use any Python 3.9+ only grammars. - - -# Make sure parens around a single context manager don't get autodetected as -# Python 3.9+. -with a: - pass - - -with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4: - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_9.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_9.py deleted file mode 100644 index 0d28f9931081ba..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/auto_detect/features_3_9.py +++ /dev/null @@ -1,34 +0,0 @@ -# This file uses parenthesized context managers introduced in Python 3.9. - - -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -with ( - new_new_new1() as cm1, - new_new_new2() -): - pass - - -# output -# This file uses parenthesized context managers introduced in Python 3.9. - - -with ( - make_context_manager1() as cm1, - make_context_manager2() as cm2, - make_context_manager3() as cm3, - make_context_manager4() as cm4, -): - pass - - -with new_new_new1() as cm1, new_new_new2(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py38.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py38.py deleted file mode 100644 index 6ec4684e441b8d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py38.py +++ /dev/null @@ -1,38 +0,0 @@ -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -with \ - make_context_manager1() as cm1, \ - make_context_manager2(), \ - make_context_manager3() as cm3, \ - make_context_manager4() \ -: - pass - - -with \ - new_new_new1() as cm1, \ - new_new_new2() \ -: - pass - - -# output - - -with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4: - pass - - -with make_context_manager1() as cm1, make_context_manager2(), make_context_manager3() as cm3, make_context_manager4(): - pass - - -with new_new_new1() as cm1, new_new_new2(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py39.py b/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py39.py deleted file mode 100644 index 5cb8763040a2e4..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/preview_context_managers/targeting_py39.py +++ /dev/null @@ -1,104 +0,0 @@ -with \ - make_context_manager1() as cm1, \ - make_context_manager2() as cm2, \ - make_context_manager3() as cm3, \ - make_context_manager4() as cm4 \ -: - pass - - -# Leading comment -with \ - make_context_manager1() as cm1, \ - make_context_manager2(), \ - make_context_manager3() as cm3, \ - make_context_manager4() \ -: - pass - - -with \ - new_new_new1() as cm1, \ - new_new_new2() \ -: - pass - - -with ( - new_new_new1() as cm1, - new_new_new2() -): - pass - - -# Leading comment. -with ( - # First comment. - new_new_new1() as cm1, - # Second comment. - new_new_new2() - # Last comment. -): - pass - - -with \ - this_is_a_very_long_call(looong_arg1=looong_value1, looong_arg2=looong_value2) as cm1, \ - this_is_a_very_long_call(looong_arg1=looong_value1, looong_arg2=looong_value2, looong_arg3=looong_value3, looong_arg4=looong_value4) as cm2 \ -: - pass - - -# output - - -with ( - make_context_manager1() as cm1, - make_context_manager2() as cm2, - make_context_manager3() as cm3, - make_context_manager4() as cm4, -): - pass - - -# Leading comment -with ( - make_context_manager1() as cm1, - make_context_manager2(), - make_context_manager3() as cm3, - make_context_manager4(), -): - pass - - -with new_new_new1() as cm1, new_new_new2(): - pass - - -with new_new_new1() as cm1, new_new_new2(): - pass - - -# Leading comment. -with ( - # First comment. - new_new_new1() as cm1, - # Second comment. - new_new_new2() - # Last comment. -): - pass - - -with ( - this_is_a_very_long_call( - looong_arg1=looong_value1, looong_arg2=looong_value2 - ) as cm1, - this_is_a_very_long_call( - looong_arg1=looong_value1, - looong_arg2=looong_value2, - looong_arg3=looong_value3, - looong_arg4=looong_value4, - ) as cm2, -): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/parenthesized_context_managers.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/parenthesized_context_managers.py deleted file mode 100644 index ccf1f94883e04d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/parenthesized_context_managers.py +++ /dev/null @@ -1,21 +0,0 @@ -with (CtxManager() as example): - ... - -with (CtxManager1(), CtxManager2()): - ... - -with (CtxManager1() as example, CtxManager2()): - ... - -with (CtxManager1(), CtxManager2() as example): - ... - -with (CtxManager1() as example1, CtxManager2() as example2): - ... - -with ( - CtxManager1() as example1, - CtxManager2() as example2, - CtxManager3() as example3, -): - ... diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_complex.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_complex.py deleted file mode 100644 index 97ee194fd39e2d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_complex.py +++ /dev/null @@ -1,144 +0,0 @@ -# Cases sampled from Lib/test/test_patma.py - -# case black_test_patma_098 -match x: - case -0j: - y = 0 -# case black_test_patma_142 -match x: - case bytes(z): - y = 0 -# case black_test_patma_073 -match x: - case 0 if 0: - y = 0 - case 0 if 1: - y = 1 -# case black_test_patma_006 -match 3: - case 0 | 1 | 2 | 3: - x = True -# case black_test_patma_049 -match x: - case [0, 1] | [1, 0]: - y = 0 -# case black_check_sequence_then_mapping -match x: - case [*_]: - return "seq" - case {}: - return "map" -# case black_test_patma_035 -match x: - case {0: [1, 2, {}]}: - y = 0 - case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | "X" | {}: - y = 1 - case []: - y = 2 -# case black_test_patma_107 -match x: - case 0.25 + 1.75j: - y = 0 -# case black_test_patma_097 -match x: - case -0j: - y = 0 -# case black_test_patma_007 -match 4: - case 0 | 1 | 2 | 3: - x = True -# case black_test_patma_154 -match x: - case 0 if x: - y = 0 -# case black_test_patma_134 -match x: - case {1: 0}: - y = 0 - case {0: 0}: - y = 1 - case {**z}: - y = 2 -# case black_test_patma_185 -match Seq(): - case [*_]: - y = 0 -# case black_test_patma_063 -match x: - case 1: - y = 0 - case 1: - y = 1 -# case black_test_patma_248 -match x: - case {"foo": bar}: - y = bar -# case black_test_patma_019 -match (0, 1, 2): - case [0, 1, *x, 2]: - y = 0 -# case black_test_patma_052 -match x: - case [0]: - y = 0 - case [1, 0] if (x := x[:0]): - y = 1 - case [1, 0]: - y = 2 -# case black_test_patma_191 -match w: - case [x, y, *_]: - z = 0 -# case black_test_patma_110 -match x: - case -0.25 - 1.75j: - y = 0 -# case black_test_patma_151 -match (x,): - case [y]: - z = 0 -# case black_test_patma_114 -match x: - case A.B.C.D: - y = 0 -# case black_test_patma_232 -match x: - case None: - y = 0 -# case black_test_patma_058 -match x: - case 0: - y = 0 -# case black_test_patma_233 -match x: - case False: - y = 0 -# case black_test_patma_078 -match x: - case []: - y = 0 - case [""]: - y = 1 - case "": - y = 2 -# case black_test_patma_156 -match x: - case z: - y = 0 -# case black_test_patma_189 -match w: - case [x, y, *rest]: - z = 0 -# case black_test_patma_042 -match x: - case (0 as z) | (1 as z) | (2 as z) if z == x % 2: - y = 0 -# case black_test_patma_034 -match x: - case {0: [1, 2, {}]}: - y = 0 - case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | "X" | {}: - y = 1 - case []: - y = 2 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_extras.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_extras.py deleted file mode 100644 index 0242d264e5b631..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_extras.py +++ /dev/null @@ -1,119 +0,0 @@ -import match - -match something: - case [a as b]: - print(b) - case [a as b, c, d, e as f]: - print(f) - case Point(a as b): - print(b) - case Point(int() as x, int() as y): - print(x, y) - - -match = 1 -case: int = re.match(something) - -match re.match(case): - case type("match", match): - pass - case match: - pass - - -def func(match: case, case: match) -> case: - match Something(): - case func(match, case): - ... - case another: - ... - - -match maybe, multiple: - case perhaps, 5: - pass - case perhaps, 6,: - pass - - -match more := (than, one), indeed,: - case _, (5, 6): - pass - case [[5], (6)], [7],: - pass - case _: - pass - - -match a, *b, c: - case [*_]: - assert "seq" == _ - case {}: - assert "map" == b - - -match match( - case, - match( - match, case, match, looooooooooooooooooooooooooooooooooooong, match, case, match - ), - case, -): - case case( - match=case, - case=re.match( - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong - ), - ): - pass - - case [a as match]: - pass - - case case: - pass - - -match match: - case case: - pass - - -match a, *b(), c: - case d, *f, g: - pass - - -match something: - case { - "key": key as key_1, - "password": PASS.ONE | PASS.TWO | PASS.THREE as password, - }: - pass - case {"maybe": something(complicated as this) as that}: - pass - - -match something: - case 1 as a: - pass - - case 2 as b, 3 as c: - pass - - case 4 as d, (5 as e), (6 | 7 as g), *h: - pass - - -match bar1: - case Foo(aa=Callable() as aa, bb=int()): - print(bar1.aa, bar1.bb) - case _: - print("no match", "\n") - - -match bar1: - case Foo( - normal=x, perhaps=[list, {"x": d, "y": 1.0}] as y, otherwise=something, q=t as u - ): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_generic.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_generic.py deleted file mode 100644 index 00a0e4a677dcf2..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_generic.py +++ /dev/null @@ -1,107 +0,0 @@ -re.match() -match = a -with match() as match: - match = f"{match}" - -re.match() -match = a -with match() as match: - match = f"{match}" - - -def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: - if not target_versions: - # No target_version specified, so try all grammars. - return [ - # Python 3.7+ - pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords, - # Python 3.0-3.6 - pygram.python_grammar_no_print_statement_no_exec_statement, - # Python 2.7 with future print_function import - pygram.python_grammar_no_print_statement, - # Python 2.7 - pygram.python_grammar, - ] - - match match: - case case: - match match: - case case: - pass - - if all(version.is_python2() for version in target_versions): - # Python 2-only code, so try Python 2 grammars. - return [ - # Python 2.7 with future print_function import - pygram.python_grammar_no_print_statement, - # Python 2.7 - pygram.python_grammar, - ] - - re.match() - match = a - with match() as match: - match = f"{match}" - - def test_patma_139(self): - x = False - match x: - case bool(z): - y = 0 - self.assertIs(x, False) - self.assertEqual(y, 0) - self.assertIs(z, x) - - # Python 3-compatible code, so only try Python 3 grammar. - grammars = [] - if supports_feature(target_versions, Feature.PATTERN_MATCHING): - # Python 3.10+ - grammars.append(pygram.python_grammar_soft_keywords) - # If we have to parse both, try to parse async as a keyword first - if not supports_feature( - target_versions, Feature.ASYNC_IDENTIFIERS - ) and not supports_feature(target_versions, Feature.PATTERN_MATCHING): - # Python 3.7-3.9 - grammars.append( - pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords - ) - if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS): - # Python 3.0-3.6 - grammars.append(pygram.python_grammar_no_print_statement_no_exec_statement) - - def test_patma_155(self): - x = 0 - y = None - match x: - case 1e1000: - y = 0 - self.assertEqual(x, 0) - self.assertIs(y, None) - - x = range(3) - match x: - case [y, case as x, z]: - w = 0 - - # At least one of the above branches must have been taken, because every Python - # version has exactly one of the two 'ASYNC_*' flags - return grammars - - -def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node: - """Given a string with source, return the lib2to3 Node.""" - if not src_txt.endswith("\n"): - src_txt += "\n" - - grammars = get_grammars(set(target_versions)) - - -re.match() -match = a -with match() as match: - match = f"{match}" - -re.match() -match = a -with match() as match: - match = f"{match}" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_simple.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_simple.py deleted file mode 100644 index 5ed62415a4b5d1..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_simple.py +++ /dev/null @@ -1,92 +0,0 @@ -# Cases sampled from PEP 636 examples - -match command.split(): - case [action, obj]: - ... # interpret action, obj - -match command.split(): - case [action]: - ... # interpret single-verb action - case [action, obj]: - ... # interpret action, obj - -match command.split(): - case ["quit"]: - print("Goodbye!") - quit_game() - case ["look"]: - current_room.describe() - case ["get", obj]: - character.get(obj, current_room) - case ["go", direction]: - current_room = current_room.neighbor(direction) - # The rest of your commands go here - -match command.split(): - case ["drop", *objects]: - for obj in objects: - character.drop(obj, current_room) - # The rest of your commands go here - -match command.split(): - case ["quit"]: - pass - case ["go", direction]: - print("Going:", direction) - case ["drop", *objects]: - print("Dropping: ", *objects) - case _: - print(f"Sorry, I couldn't understand {command!r}") - -match command.split(): - case ["north"] | ["go", "north"]: - current_room = current_room.neighbor("north") - case ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]: - ... # Code for picking up the given object - -match command.split(): - case ["go", ("north" | "south" | "east" | "west")]: - current_room = current_room.neighbor(...) - # how do I know which direction to go? - -match command.split(): - case ["go", ("north" | "south" | "east" | "west") as direction]: - current_room = current_room.neighbor(direction) - -match command.split(): - case ["go", direction] if direction in current_room.exits: - current_room = current_room.neighbor(direction) - case ["go", _]: - print("Sorry, you can't go that way") - -match event.get(): - case Click(position=(x, y)): - handle_click_at(x, y) - case KeyPress(key_name="Q") | Quit(): - game.quit() - case KeyPress(key_name="up arrow"): - game.go_north() - case KeyPress(): - pass # Ignore other keystrokes - case other_event: - raise ValueError(f"Unrecognized event: {other_event}") - -match event.get(): - case Click((x, y), button=Button.LEFT): # This is a left click - handle_click_at(x, y) - case Click(): - pass # ignore other clicks - - -def where_is(point): - match point: - case Point(x=0, y=0): - print("Origin") - case Point(x=0, y=y): - print(f"Y={y}") - case Point(x=x, y=0): - print(f"X={x}") - case Point(): - print("Somewhere else") - case _: - print("Not a point") diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_style.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_style.py deleted file mode 100644 index 8e18ce2ada6dda..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pattern_matching_style.py +++ /dev/null @@ -1,91 +0,0 @@ -match something: - case b(): print(1+1) - case c( - very_complex=True, - perhaps_even_loooooooooooooooooooooooooooooooooooooong=- 1 - ): print(1) - case c( - very_complex=True, - perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1, - ): print(2) - case a: pass - -match( - arg # comment -) - -match( -) - -match( - - -) - -case( - arg # comment -) - -case( -) - -case( - - -) - - -re.match( - something # fast -) -re.match( - - - -) -match match( - - -): - case case( - arg, # comment - ): - pass - -# output - -match something: - case b(): - print(1 + 1) - case c( - very_complex=True, perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1 - ): - print(1) - case c( - very_complex=True, - perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1, - ): - print(2) - case a: - pass - -match(arg) # comment - -match() - -match() - -case(arg) # comment - -case() - -case() - - -re.match(something) # fast -re.match() -match match(): - case case( - arg, # comment - ): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pep_572_py310.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/pep_572_py310.py deleted file mode 100644 index cb82b2d23f8a49..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/pep_572_py310.py +++ /dev/null @@ -1,15 +0,0 @@ -# Unparenthesized walruses are now allowed in indices since Python 3.10. -x[a:=0] -x[a:=0, b:=1] -x[5, b:=0] - -# Walruses are allowed inside generator expressions on function calls since 3.10. -if any(match := pattern_error.match(s) for s in buffer): - if match.group(2) == data_not_available: - # Error OK to ignore. - pass - -f(a := b + c for c in range(10)) -f((a := b + c for c in range(10)), x) -f(y=(a := b + c for c in range(10))) -f(x, (a := b + c for c in range(10)), y=z, **q) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_310/starred_for_target.py b/crates/ruff_fmt/resources/test/fixtures/black/py_310/starred_for_target.py deleted file mode 100644 index 8fc8e059ed3734..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_310/starred_for_target.py +++ /dev/null @@ -1,27 +0,0 @@ -for x in *a, *b: - print(x) - -for x in a, b, *c: - print(x) - -for x in *a, b, c: - print(x) - -for x in *a, b, *c: - print(x) - -async for x in *a, *b: - print(x) - -async for x in *a, b, *c: - print(x) - -async for x in a, b, *c: - print(x) - -async for x in ( - *loooooooooooooooooooooong, - very, - *loooooooooooooooooooooooooooooooooooooooooooooooong, -): - print(x) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_646.py b/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_646.py deleted file mode 100644 index e843ecf39d89f4..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_646.py +++ /dev/null @@ -1,194 +0,0 @@ -A[*b] -A[*b] = 1 -A -del A[*b] -A -A[*b, *b] -A[*b, *b] = 1 -A -del A[*b, *b] -A -A[b, *b] -A[b, *b] = 1 -A -del A[b, *b] -A -A[*b, b] -A[*b, b] = 1 -A -del A[*b, b] -A -A[b, b, *b] -A[b, b, *b] = 1 -A -del A[b, b, *b] -A -A[*b, b, b] -A[*b, b, b] = 1 -A -del A[*b, b, b] -A -A[b, *b, b] -A[b, *b, b] = 1 -A -del A[b, *b, b] -A -A[b, b, *b, b] -A[b, b, *b, b] = 1 -A -del A[b, b, *b, b] -A -A[b, *b, b, b] -A[b, *b, b, b] = 1 -A -del A[b, *b, b, b] -A -A[A[b, *b, b]] -A[A[b, *b, b]] = 1 -A -del A[A[b, *b, b]] -A -A[*A[b, *b, b]] -A[*A[b, *b, b]] = 1 -A -del A[*A[b, *b, b]] -A -A[b, ...] -A[b, ...] = 1 -A -del A[b, ...] -A -A[*A[b, ...]] -A[*A[b, ...]] = 1 -A -del A[*A[b, ...]] -A -l = [1, 2, 3] -A[*l] -A[*l] = 1 -A -del A[*l] -A -A[*l, 4] -A[*l, 4] = 1 -A -del A[*l, 4] -A -A[0, *l] -A[0, *l] = 1 -A -del A[0, *l] -A -A[1:2, *l] -A[1:2, *l] = 1 -A -del A[1:2, *l] -A -repr(A[1:2, *l]) == repr(A[1:2, 1, 2, 3]) -t = (1, 2, 3) -A[*t] -A[*t] = 1 -A -del A[*t] -A -A[*t, 4] -A[*t, 4] = 1 -A -del A[*t, 4] -A -A[0, *t] -A[0, *t] = 1 -A -del A[0, *t] -A -A[1:2, *t] -A[1:2, *t] = 1 -A -del A[1:2, *t] -A -repr(A[1:2, *t]) == repr(A[1:2, 1, 2, 3]) - - -def returns_list(): - return [1, 2, 3] - - -A[returns_list()] -A[returns_list()] = 1 -A -del A[returns_list()] -A -A[returns_list(), 4] -A[returns_list(), 4] = 1 -A -del A[returns_list(), 4] -A -A[*returns_list()] -A[*returns_list()] = 1 -A -del A[*returns_list()] -A -A[*returns_list(), 4] -A[*returns_list(), 4] = 1 -A -del A[*returns_list(), 4] -A -A[0, *returns_list()] -A[0, *returns_list()] = 1 -A -del A[0, *returns_list()] -A -A[*returns_list(), *returns_list()] -A[*returns_list(), *returns_list()] = 1 -A -del A[*returns_list(), *returns_list()] -A -A[1:2, *b] -A[*b, 1:2] -A[1:2, *b, 1:2] -A[*b, 1:2, *b] -A[1:, *b] -A[*b, 1:] -A[1:, *b, 1:] -A[*b, 1:, *b] -A[:1, *b] -A[*b, :1] -A[:1, *b, :1] -A[*b, :1, *b] -A[:, *b] -A[*b, :] -A[:, *b, :] -A[*b, :, *b] -A[a * b()] -A[a * b(), *c, *d(), e * f(g * h)] -A[a * b(), :] -A[a * b(), *c, *d(), e * f(g * h) :] -A[[b] * len(c), :] - - -def f1(*args: *b): - pass - - -f1.__annotations__ - - -def f2(*args: *b, arg1): - pass - - -f2.__annotations__ - - -def f3(*args: *b, arg1: int): - pass - - -f3.__annotations__ - - -def f4(*args: *b, arg1: int = 2): - pass - - -f4.__annotations__ diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654.py b/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654.py deleted file mode 100644 index 387c0816f4b824..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654.py +++ /dev/null @@ -1,53 +0,0 @@ -try: - raise OSError("blah") -except* ExceptionGroup as e: - pass - - -try: - async with trio.open_nursery() as nursery: - # Make two concurrent calls to child() - nursery.start_soon(child) - nursery.start_soon(child) -except* ValueError: - pass - -try: - try: - raise ValueError(42) - except: - try: - raise TypeError(int) - except* Exception: - pass - 1 / 0 -except Exception as e: - exc = e - -try: - try: - raise FalsyEG("eg", [TypeError(1), ValueError(2)]) - except* TypeError as e: - tes = e - raise - except* ValueError as e: - ves = e - pass -except Exception as e: - exc = e - -try: - try: - raise orig - except* (TypeError, ValueError) as e: - raise SyntaxError(3) from e -except BaseException as e: - exc = e - -try: - try: - raise orig - except* OSError as e: - raise TypeError(3) from e -except ExceptionGroup as e: - exc = e diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654_style.py b/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654_style.py deleted file mode 100644 index 568e5e3efa40a0..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_311/pep_654_style.py +++ /dev/null @@ -1,111 +0,0 @@ -try: - raise OSError("blah") -except * ExceptionGroup as e: - pass - - -try: - async with trio.open_nursery() as nursery: - # Make two concurrent calls to child() - nursery.start_soon(child) - nursery.start_soon(child) -except *ValueError: - pass - -try: - try: - raise ValueError(42) - except: - try: - raise TypeError(int) - except *(Exception): - pass - 1 / 0 -except Exception as e: - exc = e - -try: - try: - raise FalsyEG("eg", [TypeError(1), ValueError(2)]) - except \ - *TypeError as e: - tes = e - raise - except * ValueError as e: - ves = e - pass -except Exception as e: - exc = e - -try: - try: - raise orig - except *(TypeError, ValueError, *OTHER_EXCEPTIONS) as e: - raise SyntaxError(3) from e -except BaseException as e: - exc = e - -try: - try: - raise orig - except\ - * OSError as e: - raise TypeError(3) from e -except ExceptionGroup as e: - exc = e - -# output - -try: - raise OSError("blah") -except* ExceptionGroup as e: - pass - - -try: - async with trio.open_nursery() as nursery: - # Make two concurrent calls to child() - nursery.start_soon(child) - nursery.start_soon(child) -except* ValueError: - pass - -try: - try: - raise ValueError(42) - except: - try: - raise TypeError(int) - except* (Exception): - pass - 1 / 0 -except Exception as e: - exc = e - -try: - try: - raise FalsyEG("eg", [TypeError(1), ValueError(2)]) - except* TypeError as e: - tes = e - raise - except* ValueError as e: - ves = e - pass -except Exception as e: - exc = e - -try: - try: - raise orig - except* (TypeError, ValueError, *OTHER_EXCEPTIONS) as e: - raise SyntaxError(3) from e -except BaseException as e: - exc = e - -try: - try: - raise orig - except* OSError as e: - raise TypeError(3) from e -except ExceptionGroup as e: - exc = e diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals.py b/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals.py deleted file mode 100644 index 254da68d3308bf..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3.6 - -x = 123456789 -x = 123456 -x = .1 -x = 1. -x = 1E+1 -x = 1E-1 -x = 1.000_000_01 -x = 123456789.123456789 -x = 123456789.123456789E123456789 -x = 123456789E123456789 -x = 123456789J -x = 123456789.123456789J -x = 0XB1ACC -x = 0B1011 -x = 0O777 -x = 0.000000006 -x = 10000 -x = 133333 - -# output - - -#!/usr/bin/env python3.6 - -x = 123456789 -x = 123456 -x = 0.1 -x = 1.0 -x = 1e1 -x = 1e-1 -x = 1.000_000_01 -x = 123456789.123456789 -x = 123456789.123456789e123456789 -x = 123456789e123456789 -x = 123456789j -x = 123456789.123456789j -x = 0xB1ACC -x = 0b1011 -x = 0o777 -x = 0.000000006 -x = 10000 -x = 133333 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals_skip_underscores.py b/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals_skip_underscores.py deleted file mode 100644 index e345bb90276c70..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_36/numeric_literals_skip_underscores.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3.6 - -x = 123456789 -x = 1_2_3_4_5_6_7 -x = 1E+1 -x = 0xb1acc -x = 0.00_00_006 -x = 12_34_567J -x = .1_2 -x = 1_2. - -# output - -#!/usr/bin/env python3.6 - -x = 123456789 -x = 1_2_3_4_5_6_7 -x = 1e1 -x = 0xB1ACC -x = 0.00_00_006 -x = 12_34_567j -x = 0.1_2 -x = 1_2.0 \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_37/python37.py b/crates/ruff_fmt/resources/test/fixtures/black/py_37/python37.py deleted file mode 100644 index dab8b404a739c5..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_37/python37.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3.7 - - -def f(): - return (i * 2 async for i in arange(42)) - - -def g(): - return ( - something_long * something_long - async for something_long in async_generator(with_an_argument) - ) - - -async def func(): - if test: - out_batched = [ - i - async for i in aitertools._async_map( - self.async_inc, arange(8), batch_size=3 - ) - ] - - -def awaited_generator_value(n): - return (await awaitable for awaitable in awaitable_list) - - -def make_arange(n): - return (i * 2 for i in range(n) if await wrap(i)) - - -# output - - -#!/usr/bin/env python3.7 - - -def f(): - return (i * 2 async for i in arange(42)) - - -def g(): - return ( - something_long * something_long - async for something_long in async_generator(with_an_argument) - ) - - -async def func(): - if test: - out_batched = [ - i - async for i in aitertools._async_map( - self.async_inc, arange(8), batch_size=3 - ) - ] - - -def awaited_generator_value(n): - return (await awaitable for awaitable in awaitable_list) - - -def make_arange(n): - return (i * 2 for i in range(n) if await wrap(i)) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_570.py b/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_570.py deleted file mode 100644 index ca8f7ab1d95d08..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_570.py +++ /dev/null @@ -1,44 +0,0 @@ -def positional_only_arg(a, /): - pass - - -def all_markers(a, b, /, c, d, *, e, f): - pass - - -def all_markers_with_args_and_kwargs( - a_long_one, - b_long_one, - /, - c_long_one, - d_long_one, - *args, - e_long_one, - f_long_one, - **kwargs, -): - pass - - -def all_markers_with_defaults(a, b=1, /, c=2, d=3, *, e=4, f=5): - pass - - -def long_one_with_long_parameter_names( - but_all_of_them, - are_positional_only, - arguments_mmmmkay, - so_this_is_only_valid_after, - three_point_eight, - /, -): - pass - - -lambda a, /: a - -lambda a, b, /, c, d, *, e, f: a - -lambda a, b, /, c, d, *args, e, f, **kwargs: args - -lambda a, b=1, /, c=2, d=3, *, e=4, f=5: 1 diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572.py b/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572.py deleted file mode 100644 index d41805f1cb16d9..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572.py +++ /dev/null @@ -1,47 +0,0 @@ -(a := 1) -(a := a) -if (match := pattern.search(data)) is None: - pass -if match := pattern.search(data): - pass -[y := f(x), y**2, y**3] -filtered_data = [y for x in data if (y := f(x)) is None] -(y := f(x)) -y0 = (y1 := f(x)) -foo(x=(y := f(x))) - - -def foo(answer=(p := 42)): - pass - - -def foo(answer: (p := 42) = 5): - pass - - -lambda: (x := 1) -(x := lambda: 1) -(x := lambda: (y := 1)) -lambda line: (m := re.match(pattern, line)) and m.group(1) -x = (y := 0) -(z := (y := (x := 0))) -(info := (name, phone, *rest)) -(x := 1, 2) -(total := total + tax) -len(lines := f.readlines()) -foo(x := 3, cat="vector") -foo(cat=(category := "vector")) -if any(len(longline := l) >= 100 for l in lines): - print(longline) -if env_base := os.environ.get("PYTHONUSERBASE", None): - return env_base -if self._is_special and (ans := self._check_nans(context=context)): - return ans -foo(b := 2, a=1) -foo((b := 2), a=1) -foo(c=(b := 2), a=1) - -while x := f(x): - pass -while x := f(x): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572_remove_parens.py b/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572_remove_parens.py deleted file mode 100644 index 4e95fb07f3af5b..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_38/pep_572_remove_parens.py +++ /dev/null @@ -1,145 +0,0 @@ -if (foo := 0): - pass - -if (foo := 1): - pass - -if (y := 5 + 5): - pass - -y = (x := 0) - -y += (x := 0) - -(y := 5 + 5) - -test: int = (test2 := 2) - -a, b = (test := (1, 2)) - -# see also /~https://github.com/psf/black/issues/2139 -assert (foo := 42 - 12) - -foo(x=(y := f(x))) - - -def foo(answer=(p := 42)): - ... - - -def foo2(answer: (p := 42) = 5): - ... - - -lambda: (x := 1) - -a[(x := 12)] -a[:(x := 13)] - -# we don't touch expressions in f-strings but if we do one day, don't break 'em -f'{(x:=10)}' - - -def a(): - return (x := 3) - await (b := 1) - yield (a := 2) - raise (c := 3) - -def this_is_so_dumb() -> (please := no): - pass - -async def await_the_walrus(): - with (x := y): - pass - - with (x := y) as z, (a := b) as c: - pass - - with (x := await y): - pass - - with (x := await a, y := await b): - pass - - # Ideally we should remove one set of parentheses - with ((x := await a, y := await b)): - pass - - with (x := await a), (y := await b): - pass - - -# output -if foo := 0: - pass - -if foo := 1: - pass - -if y := 5 + 5: - pass - -y = (x := 0) - -y += (x := 0) - -(y := 5 + 5) - -test: int = (test2 := 2) - -a, b = (test := (1, 2)) - -# see also /~https://github.com/psf/black/issues/2139 -assert (foo := 42 - 12) - -foo(x=(y := f(x))) - - -def foo(answer=(p := 42)): - ... - - -def foo2(answer: (p := 42) = 5): - ... - - -lambda: (x := 1) - -a[(x := 12)] -a[:(x := 13)] - -# we don't touch expressions in f-strings but if we do one day, don't break 'em -f"{(x:=10)}" - - -def a(): - return (x := 3) - await (b := 1) - yield (a := 2) - raise (c := 3) - - -def this_is_so_dumb() -> (please := no): - pass - - -async def await_the_walrus(): - with (x := y): - pass - - with (x := y) as z, (a := b) as c: - pass - - with (x := await y): - pass - - with (x := await a, y := await b): - pass - - # Ideally we should remove one set of parentheses - with ((x := await a, y := await b)): - pass - - with (x := await a), (y := await b): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_38/python38.py b/crates/ruff_fmt/resources/test/fixtures/black/py_38/python38.py deleted file mode 100644 index 63b0588bc27a1a..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_38/python38.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3.8 - - -def starred_return(): - my_list = ["value2", "value3"] - return "value1", *my_list - - -def starred_yield(): - my_list = ["value2", "value3"] - yield "value1", *my_list - - -# all right hand side expressions allowed in regular assignments are now also allowed in -# annotated assignments -a : Tuple[ str, int] = "1", 2 -a: Tuple[int , ... ] = b, *c, d -def t(): - a : str = yield "a" - - -# output - - -#!/usr/bin/env python3.8 - - -def starred_return(): - my_list = ["value2", "value3"] - return "value1", *my_list - - -def starred_yield(): - my_list = ["value2", "value3"] - yield "value1", *my_list - - -# all right hand side expressions allowed in regular assignments are now also allowed in -# annotated assignments -a: Tuple[str, int] = "1", 2 -a: Tuple[int, ...] = b, *c, d - - -def t(): - a: str = yield "a" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_39/pep_572_py39.py b/crates/ruff_fmt/resources/test/fixtures/black/py_39/pep_572_py39.py deleted file mode 100644 index b8b081b8c4574d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_39/pep_572_py39.py +++ /dev/null @@ -1,7 +0,0 @@ -# Unparenthesized walruses are now allowed in set literals & set comprehensions -# since Python 3.9 -{x := 1, 2, 3} -{x4 := x**5 for x in range(7)} -# We better not remove the parentheses here (since it's a 3.10 feature) -x[(a := 1)] -x[(a := 1), (b := 3)] diff --git a/crates/ruff_fmt/resources/test/fixtures/black/py_39/python39.py b/crates/ruff_fmt/resources/test/fixtures/black/py_39/python39.py deleted file mode 100644 index ae67c2257ebba5..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/py_39/python39.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python3.9 - -@relaxed_decorator[0] -def f(): - ... - -@relaxed_decorator[extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length] -def f(): - ... - -@extremely_long_variable_name_that_doesnt_fit := complex.expression(with_long="arguments_value_that_wont_fit_at_the_end_of_the_line") -def f(): - ... - -# output - - -#!/usr/bin/env python3.9 - - -@relaxed_decorator[0] -def f(): - ... - - -@relaxed_decorator[ - extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length -] -def f(): - ... - - -@extremely_long_variable_name_that_doesnt_fit := complex.expression( - with_long="arguments_value_that_wont_fit_at_the_end_of_the_line" -) -def f(): - ... \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/attribute_access_on_number_literals.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/attribute_access_on_number_literals.py index c8d9e95fefc624..1507281ade6ed3 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/attribute_access_on_number_literals.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/attribute_access_on_number_literals.py @@ -20,28 +20,3 @@ y = 100[no] y = 100(no) - -# output - -x = (123456789).bit_count() -x = (123456).__abs__() -x = (0.1).is_integer() -x = (1.0).imag -x = (1e1).imag -x = (1e-1).real -x = (123456789.123456789).hex() -x = (123456789.123456789e123456789).real -x = (123456789e123456789).conjugate() -x = 123456789j.real -x = 123456789.123456789j.__add__(0b1011.bit_length()) -x = 0xB1ACC.conjugate() -x = 0b1011.conjugate() -x = 0o777.real -x = (0.000000006).hex() -x = -100.0000j - -if (10).real: - ... - -y = 100[no] -y = 100(no) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/beginning_backslash.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/beginning_backslash.bak deleted file mode 100644 index 66c347d99df7d6..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/beginning_backslash.bak +++ /dev/null @@ -1,12 +0,0 @@ -\ - - - - - -print("hello, world") - -# output - - -print("hello, world") diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/bracketmatch.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/bracketmatch.bak deleted file mode 100644 index 0aaa2d8e670262..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/bracketmatch.bak +++ /dev/null @@ -1,15 +0,0 @@ -for ((x in {}) or {})['a'] in x: - pass -pem_spam = lambda l, spam = { - "x": 3 -}: not spam.get(l.strip()) -lambda x=lambda y={1: 3}: y['x':lambda y: {1: 2}]: x - - -# output - - -for ((x in {}) or {})["a"] in x: - pass -pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip()) -lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_blank_parentheses.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_blank_parentheses.bak deleted file mode 100644 index 1a5721a288955d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_blank_parentheses.bak +++ /dev/null @@ -1,58 +0,0 @@ -class SimpleClassWithBlankParentheses(): - pass -class ClassWithSpaceParentheses ( ): - first_test_data = 90 - second_test_data = 100 - def test_func(self): - return None -class ClassWithEmptyFunc(object): - - def func_with_blank_parentheses(): - return 5 - - -def public_func_with_blank_parentheses(): - return None -def class_under_the_func_with_blank_parentheses(): - class InsideFunc(): - pass -class NormalClass ( -): - def func_for_testing(self, first, second): - sum = first + second - return sum - - -# output - - -class SimpleClassWithBlankParentheses: - pass - - -class ClassWithSpaceParentheses: - first_test_data = 90 - second_test_data = 100 - - def test_func(self): - return None - - -class ClassWithEmptyFunc(object): - def func_with_blank_parentheses(): - return 5 - - -def public_func_with_blank_parentheses(): - return None - - -def class_under_the_func_with_blank_parentheses(): - class InsideFunc: - pass - - -class NormalClass: - def func_for_testing(self, first, second): - sum = first + second - return sum diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_methods_new_line.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_methods_new_line.bak deleted file mode 100644 index 9a96ffe49d4695..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/class_methods_new_line.bak +++ /dev/null @@ -1,270 +0,0 @@ -class ClassSimplest: - pass -class ClassWithSingleField: - a = 1 -class ClassWithJustTheDocstring: - """Just a docstring.""" -class ClassWithInit: - def __init__(self): - pass -class ClassWithTheDocstringAndInit: - """Just a docstring.""" - def __init__(self): - pass -class ClassWithInitAndVars: - cls_var = 100 - def __init__(self): - pass -class ClassWithInitAndVarsAndDocstring: - """Test class""" - cls_var = 100 - def __init__(self): - pass -class ClassWithDecoInit: - @deco - def __init__(self): - pass -class ClassWithDecoInitAndVars: - cls_var = 100 - @deco - def __init__(self): - pass -class ClassWithDecoInitAndVarsAndDocstring: - """Test class""" - cls_var = 100 - @deco - def __init__(self): - pass -class ClassSimplestWithInner: - class Inner: - pass -class ClassSimplestWithInnerWithDocstring: - class Inner: - """Just a docstring.""" - def __init__(self): - pass -class ClassWithSingleFieldWithInner: - a = 1 - class Inner: - pass -class ClassWithJustTheDocstringWithInner: - """Just a docstring.""" - class Inner: - pass -class ClassWithInitWithInner: - class Inner: - pass - def __init__(self): - pass -class ClassWithInitAndVarsWithInner: - cls_var = 100 - class Inner: - pass - def __init__(self): - pass -class ClassWithInitAndVarsAndDocstringWithInner: - """Test class""" - cls_var = 100 - class Inner: - pass - def __init__(self): - pass -class ClassWithDecoInitWithInner: - class Inner: - pass - @deco - def __init__(self): - pass -class ClassWithDecoInitAndVarsWithInner: - cls_var = 100 - class Inner: - pass - @deco - def __init__(self): - pass -class ClassWithDecoInitAndVarsAndDocstringWithInner: - """Test class""" - cls_var = 100 - class Inner: - pass - @deco - def __init__(self): - pass -class ClassWithDecoInitAndVarsAndDocstringWithInner2: - """Test class""" - class Inner: - pass - cls_var = 100 - @deco - def __init__(self): - pass - - -# output - - -class ClassSimplest: - pass - - -class ClassWithSingleField: - a = 1 - - -class ClassWithJustTheDocstring: - """Just a docstring.""" - - -class ClassWithInit: - def __init__(self): - pass - - -class ClassWithTheDocstringAndInit: - """Just a docstring.""" - - def __init__(self): - pass - - -class ClassWithInitAndVars: - cls_var = 100 - - def __init__(self): - pass - - -class ClassWithInitAndVarsAndDocstring: - """Test class""" - - cls_var = 100 - - def __init__(self): - pass - - -class ClassWithDecoInit: - @deco - def __init__(self): - pass - - -class ClassWithDecoInitAndVars: - cls_var = 100 - - @deco - def __init__(self): - pass - - -class ClassWithDecoInitAndVarsAndDocstring: - """Test class""" - - cls_var = 100 - - @deco - def __init__(self): - pass - - -class ClassSimplestWithInner: - class Inner: - pass - - -class ClassSimplestWithInnerWithDocstring: - class Inner: - """Just a docstring.""" - - def __init__(self): - pass - - -class ClassWithSingleFieldWithInner: - a = 1 - - class Inner: - pass - - -class ClassWithJustTheDocstringWithInner: - """Just a docstring.""" - - class Inner: - pass - - -class ClassWithInitWithInner: - class Inner: - pass - - def __init__(self): - pass - - -class ClassWithInitAndVarsWithInner: - cls_var = 100 - - class Inner: - pass - - def __init__(self): - pass - - -class ClassWithInitAndVarsAndDocstringWithInner: - """Test class""" - - cls_var = 100 - - class Inner: - pass - - def __init__(self): - pass - - -class ClassWithDecoInitWithInner: - class Inner: - pass - - @deco - def __init__(self): - pass - - -class ClassWithDecoInitAndVarsWithInner: - cls_var = 100 - - class Inner: - pass - - @deco - def __init__(self): - pass - - -class ClassWithDecoInitAndVarsAndDocstringWithInner: - """Test class""" - - cls_var = 100 - - class Inner: - pass - - @deco - def __init__(self): - pass - - -class ClassWithDecoInitAndVarsAndDocstringWithInner2: - """Test class""" - - class Inner: - pass - - cls_var = 100 - - @deco - def __init__(self): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/collections.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/collections.bak deleted file mode 100644 index 684316652116fb..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/collections.bak +++ /dev/null @@ -1,174 +0,0 @@ -import core, time, a - -from . import A, B, C - -# keeps existing trailing comma -from foo import ( - bar, -) - -# also keeps existing structure -from foo import ( - baz, - qux, -) - -# `as` works as well -from foo import ( - xyzzy as magic, -) - -a = {1,2,3,} -b = { -1,2, - 3} -c = { - 1, - 2, - 3, -} -x = 1, -y = narf(), -nested = {(1,2,3),(4,5,6),} -nested_no_trailing_comma = {(1,2,3),(4,5,6)} -nested_long_lines = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccccccccccccccccccccc", (1, 2, 3), "dddddddddddddddddddddddddddddddddddddddd"] -{"oneple": (1,),} -{"oneple": (1,)} -['ls', 'lsoneple/%s' % (foo,)] -x = {"oneple": (1,)} -y = {"oneple": (1,),} -assert False, ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa wraps %s" % bar) - -# looping over a 1-tuple should also not get wrapped -for x in (1,): - pass -for (x,) in (1,), (2,), (3,): - pass - -[1, 2, 3,] - -division_result_tuple = (6/2,) -print("foo %r", (foo.bar,)) - -if True: - IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( - Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING - | {pylons.controllers.WSGIController} - ) - -if True: - ec2client.get_waiter('instance_stopped').wait( - InstanceIds=[instance.id], - WaiterConfig={ - 'Delay': 5, - }) - ec2client.get_waiter("instance_stopped").wait( - InstanceIds=[instance.id], - WaiterConfig={"Delay": 5,}, - ) - ec2client.get_waiter("instance_stopped").wait( - InstanceIds=[instance.id], WaiterConfig={"Delay": 5,}, - ) - -# output - - -import core, time, a - -from . import A, B, C - -# keeps existing trailing comma -from foo import ( - bar, -) - -# also keeps existing structure -from foo import ( - baz, - qux, -) - -# `as` works as well -from foo import ( - xyzzy as magic, -) - -a = { - 1, - 2, - 3, -} -b = {1, 2, 3} -c = { - 1, - 2, - 3, -} -x = (1,) -y = (narf(),) -nested = { - (1, 2, 3), - (4, 5, 6), -} -nested_no_trailing_comma = {(1, 2, 3), (4, 5, 6)} -nested_long_lines = [ - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "cccccccccccccccccccccccccccccccccccccccc", - (1, 2, 3), - "dddddddddddddddddddddddddddddddddddddddd", -] -{ - "oneple": (1,), -} -{"oneple": (1,)} -["ls", "lsoneple/%s" % (foo,)] -x = {"oneple": (1,)} -y = { - "oneple": (1,), -} -assert False, ( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa wraps %s" - % bar -) - -# looping over a 1-tuple should also not get wrapped -for x in (1,): - pass -for (x,) in (1,), (2,), (3,): - pass - -[ - 1, - 2, - 3, -] - -division_result_tuple = (6 / 2,) -print("foo %r", (foo.bar,)) - -if True: - IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( - Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING - | {pylons.controllers.WSGIController} - ) - -if True: - ec2client.get_waiter("instance_stopped").wait( - InstanceIds=[instance.id], - WaiterConfig={ - "Delay": 5, - }, - ) - ec2client.get_waiter("instance_stopped").wait( - InstanceIds=[instance.id], - WaiterConfig={ - "Delay": 5, - }, - ) - ec2client.get_waiter("instance_stopped").wait( - InstanceIds=[instance.id], - WaiterConfig={ - "Delay": 5, - }, - ) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comment_after_escaped_newline.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comment_after_escaped_newline.bak deleted file mode 100644 index 133f4898a4743f..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comment_after_escaped_newline.bak +++ /dev/null @@ -1,18 +0,0 @@ -def bob(): \ - # pylint: disable=W9016 - pass - - -def bobtwo(): \ - \ - # some comment here - pass - -# output - -def bob(): # pylint: disable=W9016 - pass - - -def bobtwo(): # some comment here - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments.bak deleted file mode 100644 index c34daaf6f0833d..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments.bak +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python3 -# fmt: on -# Some license here. -# -# Has many lines. Many, many lines. -# Many, many, many lines. -"""Module docstring. - -Possibly also many, many lines. -""" - -import os.path -import sys - -import a -from b.c import X # some noqa comment - -try: - import fast -except ImportError: - import slow as fast - - -# Some comment before a function. -y = 1 -( - # some strings - y # type: ignore -) - - -def function(default=None): - """Docstring comes first. - - Possibly many lines. - """ - # FIXME: Some comment about why this function is crap but still in production. - import inner_imports - - if inner_imports.are_evil(): - # Explains why we have this if. - # In great detail indeed. - x = X() - return x.method1() # type: ignore - - # This return is also commented for some reason. - return default - - -# Explains why we use global state. -GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)} - - -# Another comment! -# This time two lines. - - -class Foo: - """Docstring for class Foo. Example from Sphinx docs.""" - - #: Doc comment for class attribute Foo.bar. - #: It can have multiple lines. - bar = 1 - - flox = 1.5 #: Doc comment for Foo.flox. One line only. - - baz = 2 - """Docstring for class attribute Foo.baz.""" - - def __init__(self): - #: Doc comment for instance attribute qux. - self.qux = 3 - - self.spam = 4 - """Docstring for instance attribute spam.""" - - -#'

This is pweave!

- - -@fast(really=True) -async def wat(): - # This comment, for some reason \ - # contains a trailing backslash. - async with X.open_async() as x: # Some more comments - result = await x.method1() - # Comment after ending a block. - if result: - print("A OK", file=sys.stdout) - # Comment between things. - print() - - -# Some closing comments. -# Maybe Vim or Emacs directives for formatting. -# Who knows. diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments2.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments2.py index 4eea013151a1f2..d6a08c79f2c98d 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments2.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments2.py @@ -163,180 +163,3 @@ def _init_host(self, parsed) -> None: # END COMMENTS # MORE END COMMENTS - - -# output - - -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent, # NOT DRY -) -from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( - MyLovelyCompanyTeamProjectComponent as component, # DRY -) - -# Please keep __all__ alphabetized within each category. - -__all__ = [ - # Super-special typing primitives. - "Any", - "Callable", - "ClassVar", - # ABCs (from collections.abc). - "AbstractSet", # collections.abc.Set. - "ByteString", - "Container", - # Concrete collection types. - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "Set", - "FrozenSet", - "NamedTuple", # Not really a type. - "Generator", -] - -not_shareables = [ - # singletons - True, - False, - NotImplemented, - ..., - # builtin types and objects - type, - object, - object(), - Exception(), - 42, - 100.0, - "spam", - # user-defined types and objects - Cheese, - Cheese("Wensleydale"), - SubBytes(b"spam"), -] - -if "PYTHON" in os.environ: - add_compiler(compiler_from_env()) -else: - # for compiler in compilers.values(): - # add_compiler(compiler) - add_compiler(compilers[(7.0, 32)]) - # add_compiler(compilers[(7.1, 64)]) - -# Comment before function. -def inline_comments_in_brackets_ruin_everything(): - if typedargslist: - parameters.children = [children[0], body, children[-1]] # (1 # )1 - parameters.children = [ - children[0], - body, - children[-1], # type: ignore - ] - else: - parameters.children = [ - parameters.children[0], # (2 what if this was actually long - body, - parameters.children[-1], # )2 - ] - parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore - if ( - self._proc is not None - # has the child process finished? - and self._returncode is None - # the child process has finished, but the - # transport hasn't been notified yet? - and self._proc.poll() is None - ): - pass - # no newline before or after - short = [ - # one - 1, - # two - 2, - ] - - # no newline after - call( - arg1, - arg2, - """ -short -""", - arg3=True, - ) - - ############################################################################ - - call2( - # short - arg1, - # but - arg2, - # multiline - """ -short -""", - # yup - arg3=True, - ) - lcomp = [ - element for element in collection if element is not None # yup # yup # right - ] - lcomp2 = [ - # hello - element - # yup - for element in collection - # right - if element is not None - ] - lcomp3 = [ - # This one is actually too long to fit in a single line. - element.split("\n", 1)[0] - # yup - for element in collection.select_elements() - # right - if element is not None - ] - while True: - if False: - continue - - # and round and round we go - # and round and round we go - - # let's return - return Node( - syms.simple_stmt, - [Node(statement, result), Leaf(token.NEWLINE, "\n")], # FIXME: \r\n? - ) - - -CONFIG_FILES = ( - [ - CONFIG_FILE, - ] - + SHARED_CONFIG_FILES - + USER_CONFIG_FILES -) # type: Final - - -class Test: - def _init_host(self, parsed) -> None: - if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore - pass - - -####################### -### SECTION COMMENT ### -####################### - - -instruction() # comment with bad spacing - -# END COMMENTS -# MORE END COMMENTS diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments3.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments3.py index fbbef6dcc6bdcf..1bab9733b1e610 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments3.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments3.py @@ -44,4 +44,4 @@ def func(): ) -#%% \ No newline at end of file +#%% diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments_non_breaking_space.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments_non_breaking_space.py index e17c3f4ca3983d..d1d42f025969c2 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments_non_breaking_space.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/comments_non_breaking_space.py @@ -17,28 +17,3 @@ def function(a:int=42): #  There's a NBSP + 3 spaces before # And 4 spaces on the next line pass - -# output -from .config import ( - ConfigTypeAttributes, - Int, - Path, # String, - # DEFAULT_TYPE_ATTRIBUTES, -) - -result = 1 # A simple comment -result = (1,) # Another one - -result = 1 #  type: ignore -result = 1 # This comment is talking about type: ignore -square = Square(4) #  type: Optional[Square] - - -def function(a: int = 42): - """This docstring is already formatted - a - b - """ - # There's a NBSP + 3 spaces before - # And 4 spaces on the next line - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/composition_no_trailing_comma.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/composition_no_trailing_comma.py index f17b89dea8d6a3..7c77d1f5934cb4 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/composition_no_trailing_comma.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/composition_no_trailing_comma.py @@ -179,189 +179,3 @@ def tricky_asserts(self) -> None: key9: value9 } ) - - - -# output - -class C: - def test(self) -> None: - with patch("black.out", print): - self.assertEqual( - unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." - ) - self.assertEqual( - unstyle(str(report)), - "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", - ) - self.assertEqual( - unstyle(str(report)), - "2 files reformatted, 1 file left unchanged, 1 file failed to" - " reformat.", - ) - self.assertEqual( - unstyle(str(report)), - "2 files reformatted, 2 files left unchanged, 2 files failed to" - " reformat.", - ) - for i in (a,): - if ( - # Rule 1 - i % 2 == 0 - # Rule 2 - and i % 3 == 0 - ): - while ( - # Just a comment - call() - # Another - ): - print(i) - xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( - push_manager=context.request.resource_manager, - max_items_to_push=num_items, - batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE, - ).push( - # Only send the first n items. - items=items[:num_items] - ) - return ( - 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' - % (test.name, test.filename, lineno, lname, err) - ) - - def omitting_trailers(self) -> None: - get_collection( - hey_this_is_a_very_long_call, it_has_funny_attributes, really=True - )[OneLevelIndex] - get_collection( - hey_this_is_a_very_long_call, it_has_funny_attributes, really=True - )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] - d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ - 22 - ] - assignment = ( - some.rather.elaborate.rule() and another.rule.ending_with.index[123] - ) - - def easy_asserts(self) -> None: - assert { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - } == expected, "Not what we expected" - - assert expected == { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - }, "Not what we expected" - - assert expected == { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - } - - def tricky_asserts(self) -> None: - assert { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - } == expected( - value, is_going_to_be="too long to fit in a single line", srsly=True - ), "Not what we expected" - - assert { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - } == expected, ( - "Not what we expected and the message is too long to fit in one line" - ) - - assert expected( - value, is_going_to_be="too long to fit in a single line", srsly=True - ) == { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - }, "Not what we expected" - - assert expected == { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - }, ( - "Not what we expected and the message is too long to fit in one line" - " because it's too long" - ) - - dis_c_instance_method = """\ - %3d 0 LOAD_FAST 1 (x) - 2 LOAD_CONST 1 (1) - 4 COMPARE_OP 2 (==) - 6 LOAD_FAST 0 (self) - 8 STORE_ATTR 0 (x) - 10 LOAD_CONST 0 (None) - 12 RETURN_VALUE - """ % ( - _C.__init__.__code__.co_firstlineno + 1, - ) - - assert ( - expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect - == { - key1: value1, - key2: value2, - key3: value3, - key4: value4, - key5: value5, - key6: value6, - key7: value7, - key8: value8, - key9: value9, - } - ) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/docstring.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/docstring.py index c31d6a68783e3d..e1725f1f4fbfe0 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/docstring.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/docstring.py @@ -219,226 +219,3 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self): ''' - - -# output - -class MyClass: - """Multiline - class docstring - """ - - def method(self): - """Multiline - method docstring - """ - pass - - -def foo(): - """This is a docstring with - some lines of text here - """ - return - - -def bar(): - """This is another docstring - with more lines of text - """ - return - - -def baz(): - '''"This" is a string with some - embedded "quotes"''' - return - - -def troz(): - """Indentation with tabs - is just as OK - """ - return - - -def zort(): - """Another - multiline - docstring - """ - pass - - -def poit(): - """ - Lorem ipsum dolor sit amet. - - Consectetur adipiscing elit: - - sed do eiusmod tempor incididunt ut labore - - dolore magna aliqua - - enim ad minim veniam - - quis nostrud exercitation ullamco laboris nisi - - aliquip ex ea commodo consequat - """ - pass - - -def under_indent(): - """ - These lines are indented in a way that does not - make sense. - """ - pass - - -def over_indent(): - """ - This has a shallow indent - - But some lines are deeper - - And the closing quote is too deep - """ - pass - - -def single_line(): - """But with a newline after it!""" - pass - - -def this(): - r""" - 'hey ho' - """ - - -def that(): - """ "hey yah" """ - - -def and_that(): - """ - "hey yah" """ - - -def and_this(): - ''' - "hey yah"''' - - -def multiline_whitespace(): - """ """ - - -def oneline_whitespace(): - """ """ - - -def empty(): - """""" - - -def single_quotes(): - "testing" - - -def believe_it_or_not_this_is_in_the_py_stdlib(): - ''' - "hey yah"''' - - -def ignored_docstring(): - """a => \ -b""" - - -def single_line_docstring_with_whitespace(): - """This should be stripped""" - - -def docstring_with_inline_tabs_and_space_indentation(): - """hey - - tab separated value - tab at start of line and then a tab separated value - multiple tabs at the beginning and inline - mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. - - line ends with some tabs - """ - - -def docstring_with_inline_tabs_and_tab_indentation(): - """hey - - tab separated value - tab at start of line and then a tab separated value - multiple tabs at the beginning and inline - mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. - - line ends with some tabs - """ - pass - - -def backslash_space(): - """\ """ - - -def multiline_backslash_1(): - """ - hey\there\ - \ """ - - -def multiline_backslash_2(): - """ - hey there \ """ - - -# Regression test for #3425 -def multiline_backslash_really_long_dont_crash(): - """ - hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """ - - -def multiline_backslash_3(): - """ - already escaped \\""" - - -def my_god_its_full_of_stars_1(): - "I'm sorry Dave\u2001" - - -# the space below is actually a \u2001, removed in output -def my_god_its_full_of_stars_2(): - "I'm sorry Dave" - - -def docstring_almost_at_line_limit(): - """long docstring.................................................................""" - - -def docstring_almost_at_line_limit2(): - """long docstring................................................................. - - .................................................................................. - """ - - -def docstring_at_line_limit(): - """long docstring................................................................""" - - -def multiline_docstring_at_line_limit(): - """first line----------------------------------------------------------------------- - - second line----------------------------------------------------------------------""" - - -def stable_quote_normalization_with_immediate_inner_single_quote(self): - """' - - - """ diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/empty_lines.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/empty_lines.bak deleted file mode 100644 index 4c03e432383c17..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/empty_lines.bak +++ /dev/null @@ -1,187 +0,0 @@ -"""Docstring.""" - - -# leading comment -def f(): - NO = '' - SPACE = ' ' - DOUBLESPACE = ' ' - - t = leaf.type - p = leaf.parent # trailing comment - v = leaf.value - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: # another trailing comment - return DOUBLESPACE - - - assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" - - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - if not prevp or prevp.type in OPENING_BRACKETS: - - - return NO - - - if prevp.type == token.EQUAL: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - }: - return NO - - elif prevp.type == token.DOUBLESTAR: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.dictsetmaker, - }: - return NO - -############################################################################### -# SECTION BECAUSE SECTIONS -############################################################################### - -def g(): - NO = '' - SPACE = ' ' - DOUBLESPACE = ' ' - - t = leaf.type - p = leaf.parent - v = leaf.value - - # Comment because comments - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: - return DOUBLESPACE - - # Another comment because more comments - assert p is not None, f'INTERNAL ERROR: hand-made leaf without parent: {leaf!r}' - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - - if not prevp or prevp.type in OPENING_BRACKETS: - # Start of the line or a bracketed expression. - # More than one line for the comment. - return NO - - if prevp.type == token.EQUAL: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - }: - return NO - - -# output - - -"""Docstring.""" - - -# leading comment -def f(): - NO = "" - SPACE = " " - DOUBLESPACE = " " - - t = leaf.type - p = leaf.parent # trailing comment - v = leaf.value - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: # another trailing comment - return DOUBLESPACE - - assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - if not prevp or prevp.type in OPENING_BRACKETS: - - return NO - - if prevp.type == token.EQUAL: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - }: - return NO - - elif prevp.type == token.DOUBLESTAR: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.dictsetmaker, - }: - return NO - - -############################################################################### -# SECTION BECAUSE SECTIONS -############################################################################### - - -def g(): - NO = "" - SPACE = " " - DOUBLESPACE = " " - - t = leaf.type - p = leaf.parent - v = leaf.value - - # Comment because comments - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: - return DOUBLESPACE - - # Another comment because more comments - assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - - if not prevp or prevp.type in OPENING_BRACKETS: - # Start of the line or a bracketed expression. - # More than one line for the comment. - return NO - - if prevp.type == token.EQUAL: - if prevp.parent and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - }: - return NO diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.bak deleted file mode 100644 index 06096c589f1791..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.bak +++ /dev/null @@ -1,630 +0,0 @@ -... -'some_string' -b'\\xa3' -Name -None -True -False -1 -1.0 -1j -True or False -True or False or None -True and False -True and False and None -(Name1 and Name2) or Name3 -Name1 and Name2 or Name3 -Name1 or (Name2 and Name3) -Name1 or Name2 and Name3 -(Name1 and Name2) or (Name3 and Name4) -Name1 and Name2 or Name3 and Name4 -Name1 or (Name2 and Name3) or Name4 -Name1 or Name2 and Name3 or Name4 -v1 << 2 -1 >> v2 -1 % finished -1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8 -((1 + v2) - (v3 * 4)) ^ (((5 ** v6) / 7) // 8) -not great -~great -+value --1 -~int and not v1 ^ 123 + v2 | True -(~int) and (not ((v1 ^ (123 + v2)) | True)) -+really ** -confusing ** ~operator ** -precedence -flags & ~ select.EPOLLIN and waiters.write_task is not None -lambda arg: None -lambda a=True: a -lambda a, b, c=True: a -lambda a, b, c=True, *, d=(1 << v2), e='str': a -lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b -manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() -foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id]) -1 if True else 2 -str or None if True else str or bytes or None -(str or None) if True else (str or bytes or None) -str or None if (1 if True else 2) else str or bytes or None -(str or None) if (1 if True else 2) else (str or bytes or None) -((super_long_variable_name or None) if (1 if super_long_test_name else 2) else (str or bytes or None)) -{'2.7': dead, '3.7': (long_live or die_hard)} -{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} -{**a, **b, **c} -{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} -({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None -() -(1,) -(1, 2) -(1, 2, 3) -[] -[1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] -[1, 2, 3,] -[*a] -[*range(10)] -[*a, 4, 5,] -[4, *a, 5,] -[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more] -{i for i in (1, 2, 3)} -{(i ** 2) for i in (1, 2, 3)} -{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} -{((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} -[i for i in (1, 2, 3)] -[(i ** 2) for i in (1, 2, 3)] -[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] -[((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] -{i: 0 for i in (1, 2, 3)} -{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} -{a: b * 2 for a, b in dictionary.items()} -{a: b * -2 for a, b in dictionary.items()} -{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} -Python3 > Python2 > COBOL -Life is Life -call() -call(arg) -call(kwarg='hey') -call(arg, kwarg='hey') -call(arg, another, kwarg='hey', **kwargs) -call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6 -call(*gidgets[:2]) -call(a, *gidgets[:2]) -call(**self.screen_kwargs) -call(b, **self.screen_kwargs) -lukasz.langa.pl -call.me(maybe) -1 .real -1.0 .real -....__class__ -list[str] -dict[str, int] -tuple[str, ...] -tuple[ - str, int, float, dict[str, int] -] -tuple[str, int, float, dict[str, int],] -very_long_variable_name_filters: t.List[ - t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], -] -xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[ - ..., List[SomeClass] -] = classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore -slice[0] -slice[0:1] -slice[0:1:2] -slice[:] -slice[:-1] -slice[1:] -slice[::-1] -slice[d :: d + 1] -slice[:c, c - 1] -numpy[:, 0:1] -numpy[:, :-1] -numpy[0, :] -numpy[:, i] -numpy[0, :2] -numpy[:N, 0] -numpy[:2, :4] -numpy[2:4, 1:5] -numpy[4:, 2:] -numpy[:, (0, 1, 2, 5)] -numpy[0, [0]] -numpy[:, [i]] -numpy[1 : c + 1, c] -numpy[-(c + 1) :, d] -numpy[:, l[-2]] -numpy[:, ::-1] -numpy[np.newaxis, :] -(str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) -{'2.7': dead, '3.7': long_live or die_hard} -{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] -(SomeName) -SomeName -(Good, Bad, Ugly) -(i for i in (1, 2, 3)) -((i ** 2) for i in (1, 2, 3)) -((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) -(((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) -(*starred,) -{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs} -a = (1,) -b = 1, -c = 1 -d = (1,) + a + (2,) -e = (1,).count(1) -f = 1, *range(10) -g = 1, *"ten" -what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove) -what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove) -result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc()).all() -result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc(),).all() -Ø = set() -authors.łukasz.say_thanks() -mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), -} - -def gen(): - yield from outside_of_generator - a = (yield) - b = ((yield)) - c = (((yield))) - -async def f(): - await some.complicated[0].call(with_args=(True or (1 is not 1))) -print(* [] or [1]) -print(**{1: 3} if False else {x: x for x in range(3)}) -print(* lambda x: x) -assert(not Test),("Short message") -assert this is ComplexTest and not requirements.fit_in_a_single_line(force=False), "Short message" -assert(((parens is TooMany))) -for x, in (1,), (2,), (3,): ... -for y in (): ... -for z in (i for i in (1, 2, 3)): ... -for i in (call()): ... -for j in (1 + (2 + 3)): ... -while(this and that): ... -for addr_family, addr_type, addr_proto, addr_canonname, addr_sockaddr in socket.getaddrinfo('google.com', 'http'): - pass -a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -if ( - threading.current_thread() != threading.main_thread() and - threading.current_thread() != threading.main_thread() or - signal.getsignal(signal.SIGINT) != signal.default_int_handler -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa & - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa / - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - ~ aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l ** aaaa.m // aaaa.n -): - return True -if ( - ~ aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l ** aaaaaaaa.m // aaaaaaaa.n -): - return True -if ( - ~ aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k >> aaaaaaaaaaaaaaaa.l ** aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n -): - return True -aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -bbbb >> bbbb * bbbb -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -last_call() -# standalone comment at ENDMARKER - - -# output - - -... -"some_string" -b"\\xa3" -Name -None -True -False -1 -1.0 -1j -True or False -True or False or None -True and False -True and False and None -(Name1 and Name2) or Name3 -Name1 and Name2 or Name3 -Name1 or (Name2 and Name3) -Name1 or Name2 and Name3 -(Name1 and Name2) or (Name3 and Name4) -Name1 and Name2 or Name3 and Name4 -Name1 or (Name2 and Name3) or Name4 -Name1 or Name2 and Name3 or Name4 -v1 << 2 -1 >> v2 -1 % finished -1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8 -((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8) -not great -~great -+value --1 -~int and not v1 ^ 123 + v2 | True -(~int) and (not ((v1 ^ (123 + v2)) | True)) -+(really ** -(confusing ** ~(operator**-precedence))) -flags & ~select.EPOLLIN and waiters.write_task is not None -lambda arg: None -lambda a=True: a -lambda a, b, c=True: a -lambda a, b, c=True, *, d=(1 << v2), e="str": a -lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b -manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() -foo = lambda port_id, ignore_missing: { - "port1": port1_resource, - "port2": port2_resource, -}[port_id] -1 if True else 2 -str or None if True else str or bytes or None -(str or None) if True else (str or bytes or None) -str or None if (1 if True else 2) else str or bytes or None -(str or None) if (1 if True else 2) else (str or bytes or None) -( - (super_long_variable_name or None) - if (1 if super_long_test_name else 2) - else (str or bytes or None) -) -{"2.7": dead, "3.7": (long_live or die_hard)} -{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}} -{**a, **b, **c} -{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")} -({"a": "b"}, (True or False), (+value), "string", b"bytes") or None -() -(1,) -(1, 2) -(1, 2, 3) -[] -[1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] -[ - 1, - 2, - 3, -] -[*a] -[*range(10)] -[ - *a, - 4, - 5, -] -[ - 4, - *a, - 5, -] -[ - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - element, - another, - *more, -] -{i for i in (1, 2, 3)} -{(i**2) for i in (1, 2, 3)} -{(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))} -{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} -[i for i in (1, 2, 3)] -[(i**2) for i in (1, 2, 3)] -[(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))] -[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] -{i: 0 for i in (1, 2, 3)} -{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))} -{a: b * 2 for a, b in dictionary.items()} -{a: b * -2 for a, b in dictionary.items()} -{ - k: v - for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension -} -Python3 > Python2 > COBOL -Life is Life -call() -call(arg) -call(kwarg="hey") -call(arg, kwarg="hey") -call(arg, another, kwarg="hey", **kwargs) -call( - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - arg, - another, - kwarg="hey", - **kwargs -) # note: no trailing comma pre-3.6 -call(*gidgets[:2]) -call(a, *gidgets[:2]) -call(**self.screen_kwargs) -call(b, **self.screen_kwargs) -lukasz.langa.pl -call.me(maybe) -(1).real -(1.0).real -....__class__ -list[str] -dict[str, int] -tuple[str, ...] -tuple[str, int, float, dict[str, int]] -tuple[ - str, - int, - float, - dict[str, int], -] -very_long_variable_name_filters: t.List[ - t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], -] -xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) # type: ignore -slice[0] -slice[0:1] -slice[0:1:2] -slice[:] -slice[:-1] -slice[1:] -slice[::-1] -slice[d :: d + 1] -slice[:c, c - 1] -numpy[:, 0:1] -numpy[:, :-1] -numpy[0, :] -numpy[:, i] -numpy[0, :2] -numpy[:N, 0] -numpy[:2, :4] -numpy[2:4, 1:5] -numpy[4:, 2:] -numpy[:, (0, 1, 2, 5)] -numpy[0, [0]] -numpy[:, [i]] -numpy[1 : c + 1, c] -numpy[-(c + 1) :, d] -numpy[:, l[-2]] -numpy[:, ::-1] -numpy[np.newaxis, :] -(str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) -{"2.7": dead, "3.7": long_live or die_hard} -{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"} -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] -(SomeName) -SomeName -(Good, Bad, Ugly) -(i for i in (1, 2, 3)) -((i**2) for i in (1, 2, 3)) -((i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))) -(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) -(*starred,) -{ - "id": "1", - "type": "type", - "started_at": now(), - "ended_at": now() + timedelta(days=10), - "priority": 1, - "import_session_id": 1, - **kwargs, -} -a = (1,) -b = (1,) -c = 1 -d = (1,) + a + (2,) -e = (1,).count(1) -f = 1, *range(10) -g = 1, *"ten" -what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( - vars_to_remove -) -what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( - vars_to_remove -) -result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, models.Customer.email == email_address - ) - .order_by(models.Customer.id.asc()) - .all() -) -result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, models.Customer.email == email_address - ) - .order_by( - models.Customer.id.asc(), - ) - .all() -) -Ø = set() -authors.łukasz.say_thanks() -mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), -} - - -def gen(): - yield from outside_of_generator - a = yield - b = yield - c = yield - - -async def f(): - await some.complicated[0].call(with_args=(True or (1 is not 1))) - - -print(*[] or [1]) -print(**{1: 3} if False else {x: x for x in range(3)}) -print(*lambda x: x) -assert not Test, "Short message" -assert this is ComplexTest and not requirements.fit_in_a_single_line( - force=False -), "Short message" -assert parens is TooMany -for (x,) in (1,), (2,), (3,): - ... -for y in (): - ... -for z in (i for i in (1, 2, 3)): - ... -for i in call(): - ... -for j in 1 + (2 + 3): - ... -while this and that: - ... -for ( - addr_family, - addr_type, - addr_proto, - addr_canonname, - addr_sockaddr, -) in socket.getaddrinfo("google.com", "http"): - pass -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -if ( - threading.current_thread() != threading.main_thread() - and threading.current_thread() != threading.main_thread() - or signal.getsignal(signal.SIGINT) != signal.default_int_handler -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - ~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e - | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n -): - return True -if ( - ~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e - | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h - ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n -): - return True -if ( - ~aaaaaaaaaaaaaaaa.a - + aaaaaaaaaaaaaaaa.b - - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e - | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h - ^ aaaaaaaaaaaaaaaa.i - << aaaaaaaaaaaaaaaa.k - >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n -): - return True -( - aaaaaaaaaaaaaaaa - + aaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaa - * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) - / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -) -aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) -bbbb >> bbbb * bbbb -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) -last_call() -# standalone comment at ENDMARKER diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.diff b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.diff deleted file mode 100644 index 2eaaeb479f8c73..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/expression.diff +++ /dev/null @@ -1,466 +0,0 @@ ---- [Deterministic header] -+++ [Deterministic header] -@@ -1,8 +1,8 @@ - ... --'some_string' --b'\\xa3' -+"some_string" -+b"\\xa3" - Name - None - True - False - 1 -@@ -21,99 +21,135 @@ - Name1 or (Name2 and Name3) or Name4 - Name1 or Name2 and Name3 or Name4 - v1 << 2 - 1 >> v2 - 1 % finished --1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8 --((1 + v2) - (v3 * 4)) ^ (((5 ** v6) / 7) // 8) -+1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8 -+((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8) - not great - ~great - +value - -1 - ~int and not v1 ^ 123 + v2 | True - (~int) and (not ((v1 ^ (123 + v2)) | True)) --+really ** -confusing ** ~operator ** -precedence --flags & ~ select.EPOLLIN and waiters.write_task is not None -++(really ** -(confusing ** ~(operator**-precedence))) -+flags & ~select.EPOLLIN and waiters.write_task is not None - lambda arg: None - lambda a=True: a - lambda a, b, c=True: a --lambda a, b, c=True, *, d=(1 << v2), e='str': a --lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b -+lambda a, b, c=True, *, d=(1 << v2), e="str": a -+lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b - manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() --foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id]) -+foo = lambda port_id, ignore_missing: { -+ "port1": port1_resource, -+ "port2": port2_resource, -+}[port_id] - 1 if True else 2 - str or None if True else str or bytes or None - (str or None) if True else (str or bytes or None) - str or None if (1 if True else 2) else str or bytes or None - (str or None) if (1 if True else 2) else (str or bytes or None) --((super_long_variable_name or None) if (1 if super_long_test_name else 2) else (str or bytes or None)) --{'2.7': dead, '3.7': (long_live or die_hard)} --{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} -+( -+ (super_long_variable_name or None) -+ if (1 if super_long_test_name else 2) -+ else (str or bytes or None) -+) -+{"2.7": dead, "3.7": (long_live or die_hard)} -+{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}} - {**a, **b, **c} --{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} --({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None -+{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")} -+({"a": "b"}, (True or False), (+value), "string", b"bytes") or None - () - (1,) - (1, 2) - (1, 2, 3) - [] - [1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] --[1, 2, 3,] -+[ -+ 1, -+ 2, -+ 3, -+] - [*a] - [*range(10)] --[*a, 4, 5,] --[4, *a, 5,] --[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more] -+[ -+ *a, -+ 4, -+ 5, -+] -+[ -+ 4, -+ *a, -+ 5, -+] -+[ -+ this_is_a_very_long_variable_which_will_force_a_delimiter_split, -+ element, -+ another, -+ *more, -+] - {i for i in (1, 2, 3)} --{(i ** 2) for i in (1, 2, 3)} --{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} --{((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} -+{(i**2) for i in (1, 2, 3)} -+{(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))} -+{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} - [i for i in (1, 2, 3)] --[(i ** 2) for i in (1, 2, 3)] --[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] --[((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] -+[(i**2) for i in (1, 2, 3)] -+[(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))] -+[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] - {i: 0 for i in (1, 2, 3)} --{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} -+{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))} - {a: b * 2 for a, b in dictionary.items()} - {a: b * -2 for a, b in dictionary.items()} --{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} -+{ -+ k: v -+ for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension -+} - Python3 > Python2 > COBOL - Life is Life - call() - call(arg) --call(kwarg='hey') --call(arg, kwarg='hey') --call(arg, another, kwarg='hey', **kwargs) --call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6 -+call(kwarg="hey") -+call(arg, kwarg="hey") -+call(arg, another, kwarg="hey", **kwargs) -+call( -+ this_is_a_very_long_variable_which_will_force_a_delimiter_split, -+ arg, -+ another, -+ kwarg="hey", -+ **kwargs -+) # note: no trailing comma pre-3.6 - call(*gidgets[:2]) - call(a, *gidgets[:2]) - call(**self.screen_kwargs) - call(b, **self.screen_kwargs) - lukasz.langa.pl - call.me(maybe) --1 .real --1.0 .real -+(1).real -+(1.0).real - ....__class__ - list[str] - dict[str, int] - tuple[str, ...] -+tuple[str, int, float, dict[str, int]] - tuple[ -- str, int, float, dict[str, int] --] --tuple[str, int, float, dict[str, int],] -+ str, -+ int, -+ float, -+ dict[str, int], -+] - very_long_variable_name_filters: t.List[ - t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], - ] - xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - ) - xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - ) --xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[ -- ..., List[SomeClass] --] = classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore -+xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( -+ sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -+) # type: ignore - slice[0] - slice[0:1] - slice[0:1:2] - slice[:] - slice[:-1] -@@ -137,118 +173,199 @@ - numpy[-(c + 1) :, d] - numpy[:, l[-2]] - numpy[:, ::-1] - numpy[np.newaxis, :] - (str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) --{'2.7': dead, '3.7': long_live or die_hard} --{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} -+{"2.7": dead, "3.7": long_live or die_hard} -+{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"} - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] - (SomeName) - SomeName - (Good, Bad, Ugly) - (i for i in (1, 2, 3)) --((i ** 2) for i in (1, 2, 3)) --((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) --(((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) -+((i**2) for i in (1, 2, 3)) -+((i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))) -+(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) - (*starred,) --{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs} -+{ -+ "id": "1", -+ "type": "type", -+ "started_at": now(), -+ "ended_at": now() + timedelta(days=10), -+ "priority": 1, -+ "import_session_id": 1, -+ **kwargs, -+} - a = (1,) --b = 1, -+b = (1,) - c = 1 - d = (1,) + a + (2,) - e = (1,).count(1) - f = 1, *range(10) - g = 1, *"ten" --what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove) --what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove) --result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc()).all() --result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc(),).all() -+what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( -+ vars_to_remove -+) -+what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( -+ vars_to_remove -+) -+result = ( -+ session.query(models.Customer.id) -+ .filter( -+ models.Customer.account_id == account_id, models.Customer.email == email_address -+ ) -+ .order_by(models.Customer.id.asc()) -+ .all() -+) -+result = ( -+ session.query(models.Customer.id) -+ .filter( -+ models.Customer.account_id == account_id, models.Customer.email == email_address -+ ) -+ .order_by( -+ models.Customer.id.asc(), -+ ) -+ .all() -+) - Ø = set() - authors.łukasz.say_thanks() - mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), - } - -+ - def gen(): - yield from outside_of_generator -- a = (yield) -- b = ((yield)) -- c = (((yield))) -+ a = yield -+ b = yield -+ c = yield -+ - - async def f(): - await some.complicated[0].call(with_args=(True or (1 is not 1))) --print(* [] or [1]) -+ -+ -+print(*[] or [1]) - print(**{1: 3} if False else {x: x for x in range(3)}) --print(* lambda x: x) --assert(not Test),("Short message") --assert this is ComplexTest and not requirements.fit_in_a_single_line(force=False), "Short message" --assert(((parens is TooMany))) --for x, in (1,), (2,), (3,): ... --for y in (): ... --for z in (i for i in (1, 2, 3)): ... --for i in (call()): ... --for j in (1 + (2 + 3)): ... --while(this and that): ... --for addr_family, addr_type, addr_proto, addr_canonname, addr_sockaddr in socket.getaddrinfo('google.com', 'http'): -+print(*lambda x: x) -+assert not Test, "Short message" -+assert this is ComplexTest and not requirements.fit_in_a_single_line( -+ force=False -+), "Short message" -+assert parens is TooMany -+for (x,) in (1,), (2,), (3,): -+ ... -+for y in (): -+ ... -+for z in (i for i in (1, 2, 3)): -+ ... -+for i in call(): -+ ... -+for j in 1 + (2 + 3): -+ ... -+while this and that: -+ ... -+for ( -+ addr_family, -+ addr_type, -+ addr_proto, -+ addr_canonname, -+ addr_sockaddr, -+) in socket.getaddrinfo("google.com", "http"): - pass --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz --if ( -- threading.current_thread() != threading.main_thread() and -- threading.current_thread() != threading.main_thread() or -- signal.getsignal(signal.SIGINT) != signal.default_int_handler --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa & -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa / -- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --): -- return True --if ( -- ~ aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l ** aaaa.m // aaaa.n --): -- return True --if ( -- ~ aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l ** aaaaaaaa.m // aaaaaaaa.n --): -- return True --if ( -- ~ aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k >> aaaaaaaaaaaaaaaa.l ** aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n --): -- return True --aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+a = ( -+ aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp -+ is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -+) -+if ( -+ threading.current_thread() != threading.main_thread() -+ and threading.current_thread() != threading.main_thread() -+ or signal.getsignal(signal.SIGINT) != signal.default_int_handler -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+): -+ return True -+if ( -+ ~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e -+ | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n -+): -+ return True -+if ( -+ ~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e -+ | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h -+ ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n -+): -+ return True -+if ( -+ ~aaaaaaaaaaaaaaaa.a -+ + aaaaaaaaaaaaaaaa.b -+ - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e -+ | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h -+ ^ aaaaaaaaaaaaaaaa.i -+ << aaaaaaaaaaaaaaaa.k -+ >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n -+): -+ return True -+( -+ aaaaaaaaaaaaaaaa -+ + aaaaaaaaaaaaaaaa -+ - aaaaaaaaaaaaaaaa -+ * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+ / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -+) - aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa --aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+) - bbbb >> bbbb * bbbb --aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+( -+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+ ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -+) - last_call() - # standalone comment at ENDMARKER diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff.py index 5a50eb12ed32b2..0a46e0feb8f8ab 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff.py @@ -184,230 +184,3 @@ def single_literal_yapf_disable(): l=[1,2,3] d={'a':1, 'b':2} - -# output - - -#!/usr/bin/env python3 -import asyncio -import sys - -from third_party import X, Y, Z - -from library import some_connection, some_decorator - -# fmt: off -from third_party import (X, - Y, Z) -# fmt: on -f"trigger 3.6 mode" -# Comment 1 - -# Comment 2 - -# fmt: off -def func_no_args(): - a; b; c - if True: raise RuntimeError - if False: ... - for i in range(10): - print(i) - continue - exec('new-style exec', {}, {}) - return None -async def coroutine(arg, exec=False): - 'Single-line docstring. Multiline is harder to reformat.' - async with some_connection() as conn: - await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) - await asyncio.sleep(1) -@asyncio.coroutine -@some_decorator( -with_args=True, -many_args=[1,2,3] -) -def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str: - return text[number:-1] -# fmt: on -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(1, 2))) - assert task._cancel_stack[: len(old_stack)] == old_stack - - -def spaces_types( - a: int = 1, - b: tuple = (), - c: list = [], - d: dict = {}, - e: bool = True, - f: int = -1, - g: int = 1 if False else 2, - h: str = "", - i: str = r"", -): - ... - - -def spaces2(result=_core.Value(None)): - ... - - -something = { - # fmt: off - key: 'value', -} - - -def subscriptlist(): - atom[ - # fmt: off - 'some big and', - 'complex subscript', - # fmt: on - goes + here, - andhere, - ] - - -def import_as_names(): - # fmt: off - from hello import a, b - 'unformatted' - # fmt: on - - -def testlist_star_expr(): - # fmt: off - a , b = *hello - 'unformatted' - # fmt: on - - -def yield_expr(): - # fmt: off - yield hello - 'unformatted' - # fmt: on - "formatted" - # fmt: off - ( yield hello ) - 'unformatted' - # fmt: on - - -def example(session): - # fmt: off - result = session\ - .query(models.Customer.id)\ - .filter(models.Customer.account_id == account_id, - models.Customer.email == email_address)\ - .order_by(models.Customer.id.asc())\ - .all() - # fmt: on - - -def off_and_on_without_data(): - """All comments here are technically on the same prefix. - - The comments between will be formatted. This is a known limitation. - """ - # fmt: off - - # hey, that won't work - - # fmt: on - pass - - -def on_and_off_broken(): - """Another known limitation.""" - # fmt: on - # fmt: off - this=should.not_be.formatted() - and_=indeed . it is not formatted - because . the . handling . inside . generate_ignored_nodes() - now . considers . multiple . fmt . directives . within . one . prefix - # fmt: on - # fmt: off - # ...but comments still get reformatted even though they should not be - # fmt: on - - -def long_lines(): - if True: - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - ) - ) - # fmt: off - a = ( - unnecessary_bracket() - ) - # fmt: on - _type_comment_re = re.compile( - r""" - ^ - [\t ]* - \#[ ]type:[ ]* - (?P - [^#\t\n]+? - ) - (? to match - # a trailing space which is why we need the silliness below - (? - (?:\#[^\n]*)? - \n? - ) - $ - """, - # fmt: off - re.MULTILINE|re.VERBOSE - # fmt: on - ) - - -def single_literal_yapf_disable(): - """Black does not support this.""" - BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable - - -cfg.rule( - "Default", - "address", - xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"], - xxxxxx="xx_xxxxx", - xxxxxxx="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", - xxxxxxxxx_xxxx=True, - xxxxxxxx_xxxxxxxxxx=False, - xxxxxx_xxxxxx=2, - xxxxxx_xxxxx_xxxxxxxx=70, - xxxxxx_xxxxxx_xxxxx=True, - # fmt: off - xxxxxxx_xxxxxxxxxxxx={ - "xxxxxxxx": { - "xxxxxx": False, - "xxxxxxx": False, - "xxxx_xxxxxx": "xxxxx", - }, - "xxxxxxxx-xxxxx": { - "xxxxxx": False, - "xxxxxxx": True, - "xxxx_xxxxxx": "xxxxxx", - }, - }, - # fmt: on - xxxxxxxxxx_xxxxxxxxxxx_xxxxxxx_xxxxxxxxx=5, -) -# fmt: off -yield 'hello' -# No formatting to the end of the file -l=[1,2,3] -d={'a':1, - 'b':2} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff3.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff3.py index 4e3b024ed3c04c..a7a196669af8e2 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff3.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff3.py @@ -15,21 +15,3 @@ x = [ 1, 2, 3, 4 ] - -# output - -# fmt: off -x = [ - 1, 2, - 3, 4, -] -# fmt: on - -# fmt: off -x = [ - 1, 2, - 3, 4, -] -# fmt: on - -x = [1, 2, 3, 4] diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff4.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff4.py index 4ca707965ad17e..70dfb17324352f 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff4.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff4.py @@ -11,26 +11,3 @@ def f(): pass 3, 4, ]) def f(): pass - -# output - -# fmt: off -@test([ - 1, 2, - 3, 4, -]) -# fmt: on -def f(): - pass - - -@test( - [ - 1, - 2, - 3, - 4, - ] -) -def f(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff5.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff5.py index 181151b6bd6114..81e9be73c31161 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff5.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtonoff5.py @@ -82,95 +82,3 @@ def this_will_be_formatted ( self, **kwargs ) -> Named: ... elif unformatted: # fmt: on will_be_formatted () - - -# output - - -# Regression test for /~https://github.com/psf/black/issues/3129. -setup( - entry_points={ - # fmt: off - "console_scripts": [ - "foo-bar" - "=foo.bar.:main", - # fmt: on - ] # Includes an formatted indentation. - }, -) - - -# Regression test for /~https://github.com/psf/black/issues/2015. -run( - # fmt: off - [ - "ls", - "-la", - ] - # fmt: on - + path, - check=True, -) - - -# Regression test for /~https://github.com/psf/black/issues/3026. -def test_func(): - # yapf: disable - if unformatted( args ): - return True - # yapf: enable - elif b: - return True - - return False - - -# Regression test for /~https://github.com/psf/black/issues/2567. -if True: - # fmt: off - for _ in range( 1 ): - # fmt: on - print ( "This won't be formatted" ) - print ( "This won't be formatted either" ) -else: - print("This will be formatted") - - -# Regression test for /~https://github.com/psf/black/issues/3184. -class A: - async def call(param): - if param: - # fmt: off - if param[0:4] in ( - "ABCD", "EFGH" - ) : - # fmt: on - print ( "This won't be formatted" ) - - elif param[0:4] in ("ZZZZ",): - print ( "This won't be formatted either" ) - - print("This will be formatted") - - -# Regression test for /~https://github.com/psf/black/issues/2985. -class Named(t.Protocol): - # fmt: off - @property - def this_wont_be_formatted ( self ) -> str: ... - - -class Factory(t.Protocol): - def this_will_be_formatted(self, **kwargs) -> Named: - ... - - # fmt: on - - -# Regression test for /~https://github.com/psf/black/issues/3436. -if x: - return x -# fmt: off -elif unformatted: - # fmt: on - will_be_formatted() diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip2.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip2.py index e6248117aa9ac8..b4a792c16d9c3e 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip2.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip2.py @@ -1,17 +1,3 @@ l1 = ["This list should be broken up", "into multiple lines", "because it is way too long"] l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip l3 = ["I have", "trailing comma", "so I should be braked",] - -# output - -l1 = [ - "This list should be broken up", - "into multiple lines", - "because it is way too long", -] -l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip -l3 = [ - "I have", - "trailing comma", - "so I should be braked", -] \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip3.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip3.py index 6e166888e21926..bc0eca4ddb41da 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip3.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip3.py @@ -5,16 +5,3 @@ e = 5 # fmt: on f = ["This is a very long line that should be formatted into a clearer line ", "by rearranging."] - -# output - -a = 3 -# fmt: off -b, c = 1, 2 -d = 6 # fmt: skip -e = 5 -# fmt: on -f = [ - "This is a very long line that should be formatted into a clearer line ", - "by rearranging.", -] diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip4.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip4.py index aadd77d0e53d27..258d40b3639f1e 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip4.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip4.py @@ -1,13 +1,3 @@ a = 2 # fmt: skip l = [1, 2, 3,] - -# output - -a = 2 -# fmt: skip -l = [ - 1, - 2, - 3, -] \ No newline at end of file diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip5.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip5.py index d7b15e0ff41af3..873f0d6942bce8 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip5.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip5.py @@ -7,16 +7,3 @@ print("I'm good!") else: print("I'm bad") - - -# output - -a, b, c = 3, 4, 5 -if ( - a == 3 - and b != 9 # fmt: skip - and c is not None -): - print("I'm good!") -else: - print("I'm bad") diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip6.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip6.py index 0a779fcee00f47..cf829dbdb11016 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip6.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip6.py @@ -3,11 +3,3 @@ def f(self): for line in range(10): if True: pass # fmt: skip - -# output - -class A: - def f(self): - for line in range(10): - if True: - pass # fmt: skip diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip7.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip7.py index 15ac0ad7080eb8..5d7d9a4f31f633 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip7.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fmtskip7.py @@ -2,10 +2,3 @@ b = 5 #fmt:skip c = 9 #fmt: skip d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip - -# output - -a = "this is some code" -b = 5 # fmt:skip -c = 9 # fmt: skip -d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fstring.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fstring.py index 4b33231c01c087..b778ec2879798f 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fstring.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/fstring.py @@ -7,15 +7,3 @@ f"\"{f'{nested} inner'}\" outer" f"space between opening braces: { {a for a in (1, 2, 3)}}" f'Hello \'{tricky + "example"}\'' - -# output - -f"f-string without formatted values is just a string" -f"{{NOT a formatted value}}" -f'{{NOT \'a\' "formatted" "value"}}' -f"some f-string with {a} {few():.2f} {formatted.values!r}" -f'some f-string with {a} {few(""):.2f} {formatted.values!r}' -f"{f'''{'nested'} inner'''} outer" -f"\"{f'{nested} inner'}\" outer" -f"space between opening braces: { {a for a in (1, 2, 3)}}" -f'Hello \'{tricky + "example"}\'' diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function.bak deleted file mode 100644 index 2d642c8731b0ea..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function.bak +++ /dev/null @@ -1,247 +0,0 @@ -#!/usr/bin/env python3 -import asyncio -import sys - -from third_party import X, Y, Z - -from library import some_connection, \ - some_decorator -f'trigger 3.6 mode' -def func_no_args(): - a; b; c - if True: raise RuntimeError - if False: ... - for i in range(10): - print(i) - continue - exec("new-style exec", {}, {}) - return None -async def coroutine(arg, exec=False): - "Single-line docstring. Multiline is harder to reformat." - async with some_connection() as conn: - await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) - await asyncio.sleep(1) -@asyncio.coroutine -@some_decorator( -with_args=True, -many_args=[1,2,3] -) -def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str: - return text[number:-1] -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''): - offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000))) - assert task._cancel_stack[:len(old_stack)] == old_stack -def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ... -def spaces2(result= _core.Value(None)): - assert fut is self._read_fut, (fut, self._read_fut) - # EMPTY LINE WITH WHITESPACE (this comment will be removed) -def example(session): - result = session.query(models.Customer.id).filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, - ).order_by( - models.Customer.id.asc() - ).all() -def long_lines(): - if True: - typedargslist.extend( - gen_annotated_params(ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True) - ) - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True, - # trailing standalone comment - ) - ) - _type_comment_re = re.compile( - r""" - ^ - [\t ]* - \#[ ]type:[ ]* - (?P - [^#\t\n]+? - ) - (? to match - # a trailing space which is why we need the silliness below - (? - (?:\#[^\n]*)? - \n? - ) - $ - """, re.MULTILINE | re.VERBOSE - ) -def trailing_comma(): - mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), -} -def f( - a, - **kwargs, -) -> A: - return ( - yield from A( - very_long_argument_name1=very_long_value_for_the_argument, - very_long_argument_name2=very_long_value_for_the_argument, - **kwargs, - ) - ) -def __await__(): return (yield) - -# output - - -#!/usr/bin/env python3 -import asyncio -import sys - -from third_party import X, Y, Z - -from library import some_connection, some_decorator - -f"trigger 3.6 mode" - - -def func_no_args(): - a - b - c - if True: - raise RuntimeError - if False: - ... - for i in range(10): - print(i) - continue - exec("new-style exec", {}, {}) - return None - - -async def coroutine(arg, exec=False): - "Single-line docstring. Multiline is harder to reformat." - async with some_connection() as conn: - await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2) - await asyncio.sleep(1) - - -@asyncio.coroutine -@some_decorator(with_args=True, many_args=[1, 2, 3]) -def function_signature_stress_test( - number: int, - no_annotation=None, - text: str = "default", - *, - debug: bool = False, - **kwargs, -) -> str: - return text[number:-1] - - -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000))) - assert task._cancel_stack[: len(old_stack)] == old_stack - - -def spaces_types( - a: int = 1, - b: tuple = (), - c: list = [], - d: dict = {}, - e: bool = True, - f: int = -1, - g: int = 1 if False else 2, - h: str = "", - i: str = r"", -): - ... - - -def spaces2(result=_core.Value(None)): - assert fut is self._read_fut, (fut, self._read_fut) - - -def example(session): - result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, - ) - .order_by(models.Customer.id.asc()) - .all() - ) - - -def long_lines(): - if True: - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - ) - ) - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - # trailing standalone comment - ) - ) - _type_comment_re = re.compile( - r""" - ^ - [\t ]* - \#[ ]type:[ ]* - (?P - [^#\t\n]+? - ) - (? to match - # a trailing space which is why we need the silliness below - (? - (?:\#[^\n]*)? - \n? - ) - $ - """, - re.MULTILINE | re.VERBOSE, - ) - - -def trailing_comma(): - mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), - } - - -def f( - a, - **kwargs, -) -> A: - return ( - yield from A( - very_long_argument_name1=very_long_value_for_the_argument, - very_long_argument_name2=very_long_value_for_the_argument, - **kwargs, - ) - ) - - -def __await__(): - return (yield) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function2.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function2.bak deleted file mode 100644 index 5bb36c26318cbd..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function2.bak +++ /dev/null @@ -1,121 +0,0 @@ -def f( - a, - **kwargs, -) -> A: - with cache_dir(): - if something: - result = ( - CliRunner().invoke(black.main, [str(src1), str(src2), "--diff", "--check"]) - ) - limited.append(-limited.pop()) # negate top - return A( - very_long_argument_name1=very_long_value_for_the_argument, - very_long_argument_name2=-very.long.value.for_the_argument, - **kwargs, - ) -def g(): - "Docstring." - def inner(): - pass - print("Inner defs should breathe a little.") -def h(): - def inner(): - pass - print("Inner defs should breathe a little.") - - -if os.name == "posix": - import termios - def i_should_be_followed_by_only_one_newline(): - pass -elif os.name == "nt": - try: - import msvcrt - def i_should_be_followed_by_only_one_newline(): - pass - - except ImportError: - - def i_should_be_followed_by_only_one_newline(): - pass - -elif False: - - class IHopeYouAreHavingALovelyDay: - def __call__(self): - print("i_should_be_followed_by_only_one_newline") -else: - - def foo(): - pass - -with hmm_but_this_should_get_two_preceding_newlines(): - pass - -# output - -def f( - a, - **kwargs, -) -> A: - with cache_dir(): - if something: - result = CliRunner().invoke( - black.main, [str(src1), str(src2), "--diff", "--check"] - ) - limited.append(-limited.pop()) # negate top - return A( - very_long_argument_name1=very_long_value_for_the_argument, - very_long_argument_name2=-very.long.value.for_the_argument, - **kwargs, - ) - - -def g(): - "Docstring." - - def inner(): - pass - - print("Inner defs should breathe a little.") - - -def h(): - def inner(): - pass - - print("Inner defs should breathe a little.") - - -if os.name == "posix": - import termios - - def i_should_be_followed_by_only_one_newline(): - pass - -elif os.name == "nt": - try: - import msvcrt - - def i_should_be_followed_by_only_one_newline(): - pass - - except ImportError: - - def i_should_be_followed_by_only_one_newline(): - pass - -elif False: - - class IHopeYouAreHavingALovelyDay: - def __call__(self): - print("i_should_be_followed_by_only_one_newline") - -else: - - def foo(): - pass - - -with hmm_but_this_should_get_two_preceding_newlines(): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function_trailing_comma.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function_trailing_comma.bak deleted file mode 100644 index abe9617c0e9cbd..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/function_trailing_comma.bak +++ /dev/null @@ -1,182 +0,0 @@ -def f(a,): - d = {'key': 'value',} - tup = (1,) - -def f2(a,b,): - d = {'key': 'value', 'key2': 'value2',} - tup = (1,2,) - -def f(a:int=1,): - call(arg={'explode': 'this',}) - call2(arg=[1,2,3],) - x = { - "a": 1, - "b": 2, - }["a"] - if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]: - pass - -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - json = {"k": {"k2": {"k3": [1,]}}} - - - -# The type annotation shouldn't get a trailing comma since that would change its type. -# Relevant bug report: /~https://github.com/psf/black/issues/2381. -def some_function_with_a_really_long_name() -> ( - returning_a_deeply_nested_import_of_a_type_i_suppose -): - pass - - -def some_method_with_a_really_long_name(very_long_parameter_so_yeah: str, another_long_parameter: int) -> ( - another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not -): - pass - - -def func() -> ( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too) -): - pass - - -def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too - )) -): - pass - - -# Make sure inner one-element tuple won't explode -some_module.some_function( - argument1, (one_element_tuple,), argument4, argument5, argument6 -) - -# Inner trailing comma causes outer to explode -some_module.some_function( - argument1, (one, two,), argument4, argument5, argument6 -) - -# output - -def f( - a, -): - d = { - "key": "value", - } - tup = (1,) - - -def f2( - a, - b, -): - d = { - "key": "value", - "key2": "value2", - } - tup = ( - 1, - 2, - ) - - -def f( - a: int = 1, -): - call( - arg={ - "explode": "this", - } - ) - call2( - arg=[1, 2, 3], - ) - x = { - "a": 1, - "b": 2, - }["a"] - if ( - a - == { - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6, - "g": 7, - "h": 8, - }["a"] - ): - pass - - -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - json = { - "k": { - "k2": { - "k3": [ - 1, - ] - } - } - } - - -# The type annotation shouldn't get a trailing comma since that would change its type. -# Relevant bug report: /~https://github.com/psf/black/issues/2381. -def some_function_with_a_really_long_name() -> ( - returning_a_deeply_nested_import_of_a_type_i_suppose -): - pass - - -def some_method_with_a_really_long_name( - very_long_parameter_so_yeah: str, another_long_parameter: int -) -> ( - another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not -): - pass - - -def func() -> ( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too - ) -): - pass - - -def func() -> ( - ( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too - ) - ) -): - pass - - -# Make sure inner one-element tuple won't explode -some_module.some_function( - argument1, (one_element_tuple,), argument4, argument5, argument6 -) - -# Inner trailing comma causes outer to explode -some_module.some_function( - argument1, - ( - one, - two, - ), - argument4, - argument5, - argument6, -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/import_spacing.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/import_spacing.bak deleted file mode 100644 index 8e6e23cc348d0a..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/import_spacing.bak +++ /dev/null @@ -1,118 +0,0 @@ -"""The asyncio package, tracking PEP 3156.""" - -# flake8: noqa - -from logging import ( - WARNING -) -from logging import ( - ERROR, -) -import sys - -# This relies on each of the submodules having an __all__ variable. -from .base_events import * -from .coroutines import * -from .events import * # comment here - -from .futures import * -from .locks import * # comment here -from .protocols import * - -from ..runners import * # comment here -from ..queues import * -from ..streams import * - -from some_library import ( - Just, Enough, Libraries, To, Fit, In, This, Nice, Split, Which, We, No, Longer, Use -) -from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy -from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * - -from .a.b.c.subprocess import * -from . import (tasks) -from . import (A, B, C) -from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \ - SomeVeryLongNameAndAllOfItsAdditionalLetters2 - -__all__ = ( - base_events.__all__ - + coroutines.__all__ - + events.__all__ - + futures.__all__ - + locks.__all__ - + protocols.__all__ - + runners.__all__ - + queues.__all__ - + streams.__all__ - + tasks.__all__ -) - - -# output - - -"""The asyncio package, tracking PEP 3156.""" - -# flake8: noqa - -from logging import WARNING -from logging import ( - ERROR, -) -import sys - -# This relies on each of the submodules having an __all__ variable. -from .base_events import * -from .coroutines import * -from .events import * # comment here - -from .futures import * -from .locks import * # comment here -from .protocols import * - -from ..runners import * # comment here -from ..queues import * -from ..streams import * - -from some_library import ( - Just, - Enough, - Libraries, - To, - Fit, - In, - This, - Nice, - Split, - Which, - We, - No, - Longer, - Use, -) -from name_of_a_company.extremely_long_project_name.component.ttypes import ( - CuteLittleServiceHandlerFactoryyy, -) -from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * - -from .a.b.c.subprocess import * -from . import tasks -from . import A, B, C -from . import ( - SomeVeryLongNameAndAllOfItsAdditionalLetters1, - SomeVeryLongNameAndAllOfItsAdditionalLetters2, -) - -__all__ = ( - base_events.__all__ - + coroutines.__all__ - + events.__all__ - + futures.__all__ - + locks.__all__ - + protocols.__all__ - + runners.__all__ - + queues.__all__ - + streams.__all__ - + tasks.__all__ -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/power_op_spacing.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/power_op_spacing.bak deleted file mode 100644 index c95fa788fc3eba..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/power_op_spacing.bak +++ /dev/null @@ -1,131 +0,0 @@ -def function(**kwargs): - t = a**2 + b**3 - return t ** 2 - - -def function_replace_spaces(**kwargs): - t = a **2 + b** 3 + c ** 4 - - -def function_dont_replace_spaces(): - {**a, **b, **c} - - -a = 5**~4 -b = 5 ** f() -c = -(5**2) -d = 5 ** f["hi"] -e = lazy(lambda **kwargs: 5) -f = f() ** 5 -g = a.b**c.d -h = 5 ** funcs.f() -i = funcs.f() ** 5 -j = super().name ** 5 -k = [(2**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2**63], [1, 2**63])] -n = count <= 10**5 -o = settings(max_examples=10**6) -p = {(k, k**2): v**2 for k, v in pairs} -q = [10**i for i in range(6)] -r = x**y - -a = 5.0**~4.0 -b = 5.0 ** f() -c = -(5.0**2.0) -d = 5.0 ** f["hi"] -e = lazy(lambda **kwargs: 5) -f = f() ** 5.0 -g = a.b**c.d -h = 5.0 ** funcs.f() -i = funcs.f() ** 5.0 -j = super().name ** 5.0 -k = [(2.0**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2.0**63.0], [1.0, 2**63.0])] -n = count <= 10**5.0 -o = settings(max_examples=10**6.0) -p = {(k, k**2): v**2.0 for k, v in pairs} -q = [10.5**i for i in range(6)] - - -# WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (/~https://github.com/psf/black/issues/2873) -if hasattr(view, "sum_of_weights"): - return np.divide( # type: ignore[no-any-return] - view.variance, # type: ignore[union-attr] - view.sum_of_weights, # type: ignore[union-attr] - out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr] - where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr] - ) - -return np.divide( - where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore -) - - -# output - - -def function(**kwargs): - t = a**2 + b**3 - return t**2 - - -def function_replace_spaces(**kwargs): - t = a**2 + b**3 + c**4 - - -def function_dont_replace_spaces(): - {**a, **b, **c} - - -a = 5**~4 -b = 5 ** f() -c = -(5**2) -d = 5 ** f["hi"] -e = lazy(lambda **kwargs: 5) -f = f() ** 5 -g = a.b**c.d -h = 5 ** funcs.f() -i = funcs.f() ** 5 -j = super().name ** 5 -k = [(2**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2**63], [1, 2**63])] -n = count <= 10**5 -o = settings(max_examples=10**6) -p = {(k, k**2): v**2 for k, v in pairs} -q = [10**i for i in range(6)] -r = x**y - -a = 5.0**~4.0 -b = 5.0 ** f() -c = -(5.0**2.0) -d = 5.0 ** f["hi"] -e = lazy(lambda **kwargs: 5) -f = f() ** 5.0 -g = a.b**c.d -h = 5.0 ** funcs.f() -i = funcs.f() ** 5.0 -j = super().name ** 5.0 -k = [(2.0**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2.0**63.0], [1.0, 2**63.0])] -n = count <= 10**5.0 -o = settings(max_examples=10**6.0) -p = {(k, k**2): v**2.0 for k, v in pairs} -q = [10.5**i for i in range(6)] - - -# WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (/~https://github.com/psf/black/issues/2873) -if hasattr(view, "sum_of_weights"): - return np.divide( # type: ignore[no-any-return] - view.variance, # type: ignore[union-attr] - view.sum_of_weights, # type: ignore[union-attr] - out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr] - where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr] - ) - -return np.divide( - where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/string_prefixes.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/string_prefixes.py index f86da696e15664..80318fc6fb5bad 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/string_prefixes.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/string_prefixes.py @@ -10,31 +10,6 @@ (rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"") -def docstring_singleline(): - R"""2020 was one hell of a year. The good news is that we were able to""" - - -def docstring_multiline(): - R""" - clear out all of the issues opened in that time :p - """ - - -# output - - -#!/usr/bin/env python3 - -name = "Łukasz" -(f"hello {name}", f"hello {name}") -(b"", b"") -("", "") -(r"", R"") - -(rf"", rf"", Rf"", Rf"", rf"", rf"", Rf"", Rf"") -(rb"", rb"", Rb"", Rb"", rb"", rb"", Rb"", Rb"") - - def docstring_singleline(): R"""2020 was one hell of a year. The good news is that we were able to""" diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/torture.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/torture.py index 2a194759a821ec..42e4ef52cba0f0 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/torture.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/torture.py @@ -27,65 +27,3 @@ def test(self, othr): a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} ) - -# output - -importA -( - () - << 0 - ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 -) # - -assert sort_by_dependency( - { - "1": {"2", "3"}, - "2": {"2a", "2b"}, - "3": {"3a", "3b"}, - "2a": set(), - "2b": set(), - "3a": set(), - "3b": set(), - } -) == ["2a", "2b", "2", "3a", "3b", "3", "1"] - -importA -0 -0 ^ 0 # - - -class A: - def foo(self): - for _ in range(10): - aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( - xxxxxxxxxxxx - ) # pylint: disable=no-member - - -def test(self, othr): - return 1 == 2 and ( - name, - description, - self.default, - self.selected, - self.auto_generated, - self.parameters, - self.meta_data, - self.schedule, - ) == ( - name, - description, - othr.default, - othr.selected, - othr.auto_generated, - othr.parameters, - othr.meta_data, - othr.schedule, - ) - - -assert a_function( - very_long_arguments_that_surpass_the_limit, - which_is_eighty_eight_in_this_case_plus_a_bit_more, -) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} - diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens1.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens1.py index 85aa8badb26165..1951cc8d2a4494 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens1.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens1.py @@ -23,41 +23,3 @@ def b(self): 3, ) < self.connection.mysql_version < (10, 5, 2): pass - - -# output - -if e1234123412341234.winerror not in ( - _winapi.ERROR_SEM_TIMEOUT, - _winapi.ERROR_PIPE_BUSY, -) or _check_timeout(t): - pass - -if x: - if y: - new_id = ( - max( - Vegetable.objects.order_by("-id")[0].id, - Mineral.objects.order_by("-id")[0].id, - ) - + 1 - ) - - -class X: - def get_help_text(self): - return ngettext( - "Your password must contain at least %(min_length)d character.", - "Your password must contain at least %(min_length)d characters.", - self.min_length, - ) % {"min_length": self.min_length} - - -class A: - def b(self): - if self.connection.mysql_is_mariadb and ( - 10, - 4, - 3, - ) < self.connection.mysql_version < (10, 5, 2): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens2.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens2.py index 9541670e3945df..271371bd59addd 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens2.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens2.py @@ -1,12 +1,3 @@ if (e123456.get_tk_patchlevel() >= (8, 6, 0, 'final') or (8, 5, 8) <= get_tk_patchlevel() < (8, 6)): pass - -# output - -if e123456.get_tk_patchlevel() >= (8, 6, 0, "final") or ( - 8, - 5, - 8, -) <= get_tk_patchlevel() < (8, 6): - pass diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens3.py b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens3.py index c0ed699e6a61c2..e5b4b7c4dc5cb3 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens3.py +++ b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens3.py @@ -6,16 +6,3 @@ + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", ) % {"reported_username": reported_username, "report_reason": report_reason} - - -# output - - -if True: - if True: - if True: - return _( - "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas " - + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", - "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", - ) % {"reported_username": reported_username, "report_reason": report_reason} diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/tupleassign.bak b/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/tupleassign.bak deleted file mode 100644 index 3cb2a7c0983c06..00000000000000 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/tupleassign.bak +++ /dev/null @@ -1,23 +0,0 @@ -# This is a standalone comment. -sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 - -# This is as well. -this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890") - -(a,) = call() - -# output - - -# This is a standalone comment. -( - sdfjklsdfsjldkflkjsf, - sdfjsdfjlksdljkfsdlkf, - sdfsdjfklsdfjlksdljkf, - sdsfsdfjskdflsfsdf, -) = (1, 2, 3) - -# This is as well. -(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890") - -(a,) = call() diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__attribute_access_on_number_literals.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__attribute_access_on_number_literals.py.snap new file mode 100644 index 00000000000000..b4ae9ee6966373 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__attribute_access_on_number_literals.py.snap @@ -0,0 +1,28 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +x = (123456789).bit_count() +x = (123456).__abs__() +x = (0.1).is_integer() +x = (1.0).imag +x = (1e1).imag +x = (1e-1).real +x = (123456789.123456789).hex() +x = (123456789.123456789e123456789).real +x = (123456789e123456789).conjugate() +x = 123456789j.real +x = 123456789.123456789j.__add__(0b1011.bit_length()) +x = 0xB1ACC.conjugate() +x = 0b1011.conjugate() +x = 0o777.real +x = (0.000000006).hex() +x = -100.0000j + +if (10).real: + ... + +y = 100[no] +y = 100(no) + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comment_after_escaped_newline.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comment_after_escaped_newline.py.snap index e2d0719e53f2c1..18ac24ab78718d 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comment_after_escaped_newline.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comment_after_escaped_newline.py.snap @@ -3,10 +3,13 @@ source: src/source_code/mod.rs assertion_line: 0 expression: formatted --- -def bob(): # pylint: disable=W9016 +def bob(): \ + # pylint: disable=W9016 pass -def bobtwo(): # some comment here +def bobtwo(): \ + \ + # some comment here pass diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments2.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments2.py.snap new file mode 100644 index 00000000000000..323d64f7adbd71 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments2.py.snap @@ -0,0 +1,178 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( + MyLovelyCompanyTeamProjectComponent, # NOT DRY +) +from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( + MyLovelyCompanyTeamProjectComponent as component, # DRY +) + +# Please keep __all__ alphabetized within each category. + +__all__ = [ + # Super-special typing primitives. + "Any", + "Callable", + "ClassVar", + # ABCs (from collections.abc). + "AbstractSet", # collections.abc.Set. + "ByteString", + "Container", + # Concrete collection types. + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "Set", + "FrozenSet", + "NamedTuple", # Not really a type. + "Generator", +] + +not_shareables = [ + # singletons + True, + False, + NotImplemented, + ..., + # builtin types and objects + type, + object, + object(), + Exception(), + 42, + 100.0, + "spam", + # user-defined types and objects + Cheese, + Cheese("Wensleydale"), + SubBytes(b"spam"), +] + +if "PYTHON" in os.environ: + add_compiler(compiler_from_env()) +else: + # for compiler in compilers.values(): + # add_compiler(compiler) + add_compiler(compilers[(7.0, 32)]) + # add_compiler(compilers[(7.1, 64)]) + +# Comment before function. +def inline_comments_in_brackets_ruin_everything(): + if typedargslist: + parameters.children = [children[0], body, children[-1]] # (1 # )1 + parameters.children = [ + children[0], + body, + children[-1], # type: ignore + ] + else: + parameters.children = [ + parameters.children[0], # (2 what if this was actually long + body, + parameters.children[-1], # )2 + ] + parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore + if ( + self._proc is not None + # has the child process finished? + and self._returncode is None + # the child process has finished, but the + # transport hasn't been notified yet? + and self._proc.poll() is None + ): + pass + # no newline before or after + short = [ + # one + 1, + # two + 2, + ] + + # no newline after + call( + arg1, + arg2, + """ +short +""", + arg3=True, + ) + + ############################################################################ + + call2( + # short + arg1, + # but + arg2, + # multiline + """ +short +""", + # yup + arg3=True, + ) + lcomp = [ + element for element in collection if element is not None # yup # yup # right + ] + lcomp2 = [ + # hello + element + # yup + for element in collection + # right + if element is not None + ] + lcomp3 = [ + # This one is actually too long to fit in a single line. + element.split("\n", 1)[0] + # yup + for element in collection.select_elements() + # right + if element is not None + ] + while True: + if False: + continue + + # and round and round we go + # and round and round we go + + # let's return + return Node( + syms.simple_stmt, + [Node(statement, result), Leaf(token.NEWLINE, "\n")], # FIXME: \r\n? + ) + + +CONFIG_FILES = ( + [ + CONFIG_FILE, + ] + + SHARED_CONFIG_FILES + + USER_CONFIG_FILES +) # type: Final + + +class Test: + def _init_host(self, parsed) -> None: + if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore + pass + + +####################### +### SECTION COMMENT ### +####################### + + +instruction() # comment with bad spacing + +# END COMMENTS +# MORE END COMMENTS + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments3.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments3.py.snap new file mode 100644 index 00000000000000..8b37cc3fb0d765 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments3.py.snap @@ -0,0 +1,53 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# The percent-percent comments are Spyder IDE cells. + +#%% +def func(): + x = """ + a really long string + """ + lcomp3 = [ + # This one is actually too long to fit in a single line. + element.split("\n", 1)[0] + # yup + for element in collection.select_elements() + # right + if element is not None + ] + # Capture each of the exceptions in the MultiError along with each of their causes and contexts + if isinstance(exc_value, MultiError): + embedded = [] + for exc in exc_value.exceptions: + if exc not in _seen: + embedded.append( + # This should be left alone (before) + traceback.TracebackException.from_exception( + exc, + limit=limit, + lookup_lines=lookup_lines, + capture_locals=capture_locals, + # copy the set of _seen exceptions so that duplicates + # shared between sub-exceptions are not omitted + _seen=set(_seen), + ) + # This should be left alone (after) + ) + + # everything is fine if the expression isn't nested + traceback.TracebackException.from_exception( + exc, + limit=limit, + lookup_lines=lookup_lines, + capture_locals=capture_locals, + # copy the set of _seen exceptions so that duplicates + # shared between sub-exceptions are not omitted + _seen=set(_seen), + ) + + +#%% + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments4.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments4.py.snap new file mode 100644 index 00000000000000..ddb844f33c1577 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments4.py.snap @@ -0,0 +1,100 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( + MyLovelyCompanyTeamProjectComponent, # NOT DRY +) +from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( + MyLovelyCompanyTeamProjectComponent as component, # DRY +) + + +class C: + @pytest.mark.parametrize( + ("post_data", "message"), + [ + # metadata_version errors. + ( + {}, + "None is an invalid value for Metadata-Version. Error: This field is" + " required. see" + " https://packaging.python.org/specifications/core-metadata", + ), + ( + {"metadata_version": "-1"}, + "'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata" + " Version see" + " https://packaging.python.org/specifications/core-metadata", + ), + # name errors. + ( + {"metadata_version": "1.2"}, + "'' is an invalid value for Name. Error: This field is required. see" + " https://packaging.python.org/specifications/core-metadata", + ), + ( + {"metadata_version": "1.2", "name": "foo-"}, + "'foo-' is an invalid value for Name. Error: Must start and end with a" + " letter or numeral and contain only ascii numeric and '.', '_' and" + " '-'. see https://packaging.python.org/specifications/core-metadata", + ), + # version errors. + ( + {"metadata_version": "1.2", "name": "example"}, + "'' is an invalid value for Version. Error: This field is required. see" + " https://packaging.python.org/specifications/core-metadata", + ), + ( + {"metadata_version": "1.2", "name": "example", "version": "dog"}, + "'dog' is an invalid value for Version. Error: Must start and end with" + " a letter or numeral and contain only ascii numeric and '.', '_' and" + " '-'. see https://packaging.python.org/specifications/core-metadata", + ), + ], + ) + def test_fails_invalid_post_data( + self, pyramid_config, db_request, post_data, message + ): + pyramid_config.testing_securitypolicy(userid=1) + db_request.POST = MultiDict(post_data) + + +def foo(list_a, list_b): + results = ( + User.query.filter(User.foo == "bar") + .filter( # Because foo. + db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) + ) + .filter(User.xyz.is_(None)) + # Another comment about the filtering on is_quux goes here. + .filter(db.not_(User.is_pending.astext.cast(db.Boolean).is_(True))) + .order_by(User.created_at.desc()) + .with_for_update(key_share=True) + .all() + ) + return results + + +def foo2(list_a, list_b): + # Standalone comment reasonably placed. + return ( + User.query.filter(User.foo == "bar") + .filter( + db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) + ) + .filter(User.xyz.is_(None)) + ) + + +def foo3(list_a, list_b): + return ( + # Standlone comment but weirdly placed. + User.query.filter(User.foo == "bar") + .filter( + db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) + ) + .filter(User.xyz.is_(None)) + ) + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments5.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments5.py.snap new file mode 100644 index 00000000000000..4af52b1d1d4779 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments5.py.snap @@ -0,0 +1,77 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +while True: + if something.changed: + do.stuff() # trailing comment + # Comment belongs to the `if` block. + # This one belongs to the `while` block. + + # Should this one, too? I guess so. + +# This one is properly standalone now. + +for i in range(100): + # first we do this + if i % 33 == 0: + break + + # then we do this + print(i) + # and finally we loop around + +with open(some_temp_file) as f: + data = f.read() + +try: + with open(some_other_file) as w: + w.write(data) + +except OSError: + print("problems") + +import sys + + +# leading function comment +def wat(): + ... + # trailing function comment + + +# SECTION COMMENT + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading 3 +@deco3 +def decorated1(): + ... + + +# leading 1 +@deco1 +# leading 2 +@deco2(with_args=True) +# leading function comment +def decorated1(): + ... + + +# Note: this is fixed in +# Preview.empty_lines_before_class_or_def_with_leading_comments. +# In the current style, the user will have to split those lines by hand. +some_instruction +# This comment should be split from `some_instruction` by two lines but isn't. +def g(): + ... + + +if __name__ == "__main__": + main() + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments6.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments6.py.snap new file mode 100644 index 00000000000000..527609fa48c213 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments6.py.snap @@ -0,0 +1,124 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +from typing import Any, Tuple + + +def f( + a, # type: int +): + pass + + +# test type comments +def f(a, b, c, d, e, f, g, h, i): + # type: (int, int, int, int, int, int, int, int, int) -> None + pass + + +def f( + a, # type: int + b, # type: int + c, # type: int + d, # type: int + e, # type: int + f, # type: int + g, # type: int + h, # type: int + i, # type: int +): + # type: (...) -> None + pass + + +def f( + arg, # type: int + *args, # type: *Any + default=False, # type: bool + **kwargs, # type: **Any +): + # type: (...) -> None + pass + + +def f( + a, # type: int + b, # type: int + c, # type: int + d, # type: int +): + # type: (...) -> None + + element = 0 # type: int + another_element = 1 # type: float + another_element_with_long_name = 2 # type: int + another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style = ( + 3 + ) # type: int + an_element_with_a_long_value = calls() or more_calls() and more() # type: bool + + tup = ( + another_element, + another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style, + ) # type: Tuple[int, int] + + a = ( + element + + another_element + + another_element_with_long_name + + element + + another_element + + another_element_with_long_name + ) # type: int + + +def f( + x, # not a type comment + y, # type: int +): + # type: (...) -> None + pass + + +def f( + x, # not a type comment +): # type: (int) -> None + pass + + +def func( + a=some_list[0], # type: int +): # type: () -> int + c = call( + 0.0123, + 0.0456, + 0.0789, + 0.0123, + 0.0456, + 0.0789, + 0.0123, + 0.0456, + 0.0789, + a[-1], # type: ignore + ) + + c = call( + "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore + ) + + +result = ( # aaa + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +) + +AAAAAAAAAAAAA = [AAAAAAAAAAAAA] + SHARED_AAAAAAAAAAAAA + USER_AAAAAAAAAAAAA + AAAAAAAAAAAAA # type: ignore + +call_to_some_function_asdf( + foo, + [AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore +) + +aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments_non_breaking_space.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments_non_breaking_space.py.snap new file mode 100644 index 00000000000000..737aa0a47be0d1 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__comments_non_breaking_space.py.snap @@ -0,0 +1,29 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +from .config import ( + ConfigTypeAttributes, + Int, + Path, # String, + # DEFAULT_TYPE_ATTRIBUTES, +) + +result = 1 # A simple comment +result = (1,) # Another one + +result = 1 #  type: ignore +result = 1 # This comment is talking about type: ignore +square = Square(4) #  type: Optional[Square] + + +def function(a: int = 42): + """This docstring is already formatted + a + b + """ + # There's a NBSP + 3 spaces before + # And 4 spaces on the next line + pass + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition.py.snap new file mode 100644 index 00000000000000..4cc21eddcb6a8e --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition.py.snap @@ -0,0 +1,187 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +class C: + def test(self) -> None: + with patch("black.out", print): + self.assertEqual( + unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." + ) + self.assertEqual( + unstyle(str(report)), + "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", + ) + self.assertEqual( + unstyle(str(report)), + "2 files reformatted, 1 file left unchanged, 1 file failed to" + " reformat.", + ) + self.assertEqual( + unstyle(str(report)), + "2 files reformatted, 2 files left unchanged, 2 files failed to" + " reformat.", + ) + for i in (a,): + if ( + # Rule 1 + i % 2 == 0 + # Rule 2 + and i % 3 == 0 + ): + while ( + # Just a comment + call() + # Another + ): + print(i) + xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( + push_manager=context.request.resource_manager, + max_items_to_push=num_items, + batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE, + ).push( + # Only send the first n items. + items=items[:num_items] + ) + return ( + 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' + % (test.name, test.filename, lineno, lname, err) + ) + + def omitting_trailers(self) -> None: + get_collection( + hey_this_is_a_very_long_call, it_has_funny_attributes, really=True + )[OneLevelIndex] + get_collection( + hey_this_is_a_very_long_call, it_has_funny_attributes, really=True + )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] + d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ + 22 + ] + assignment = ( + some.rather.elaborate.rule() and another.rule.ending_with.index[123] + ) + + def easy_asserts(self) -> None: + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } + + def tricky_asserts(self) -> None: + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected( + value, is_going_to_be="too long to fit in a single line", srsly=True + ), "Not what we expected" + + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected, ( + "Not what we expected and the message is too long to fit in one line" + ) + + assert expected( + value, is_going_to_be="too long to fit in a single line", srsly=True + ) == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, ( + "Not what we expected and the message is too long to fit in one line" + " because it's too long" + ) + + dis_c_instance_method = """\ + %3d 0 LOAD_FAST 1 (x) + 2 LOAD_CONST 1 (1) + 4 COMPARE_OP 2 (==) + 6 LOAD_FAST 0 (self) + 8 STORE_ATTR 0 (x) + 10 LOAD_CONST 0 (None) + 12 RETURN_VALUE + """ % ( + _C.__init__.__code__.co_firstlineno + 1, + ) + + assert ( + expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect + == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } + ) + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition_no_trailing_comma.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition_no_trailing_comma.py.snap new file mode 100644 index 00000000000000..4cc21eddcb6a8e --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__composition_no_trailing_comma.py.snap @@ -0,0 +1,187 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +class C: + def test(self) -> None: + with patch("black.out", print): + self.assertEqual( + unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." + ) + self.assertEqual( + unstyle(str(report)), + "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", + ) + self.assertEqual( + unstyle(str(report)), + "2 files reformatted, 1 file left unchanged, 1 file failed to" + " reformat.", + ) + self.assertEqual( + unstyle(str(report)), + "2 files reformatted, 2 files left unchanged, 2 files failed to" + " reformat.", + ) + for i in (a,): + if ( + # Rule 1 + i % 2 == 0 + # Rule 2 + and i % 3 == 0 + ): + while ( + # Just a comment + call() + # Another + ): + print(i) + xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( + push_manager=context.request.resource_manager, + max_items_to_push=num_items, + batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE, + ).push( + # Only send the first n items. + items=items[:num_items] + ) + return ( + 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' + % (test.name, test.filename, lineno, lname, err) + ) + + def omitting_trailers(self) -> None: + get_collection( + hey_this_is_a_very_long_call, it_has_funny_attributes, really=True + )[OneLevelIndex] + get_collection( + hey_this_is_a_very_long_call, it_has_funny_attributes, really=True + )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] + d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ + 22 + ] + assignment = ( + some.rather.elaborate.rule() and another.rule.ending_with.index[123] + ) + + def easy_asserts(self) -> None: + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } + + def tricky_asserts(self) -> None: + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected( + value, is_going_to_be="too long to fit in a single line", srsly=True + ), "Not what we expected" + + assert { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } == expected, ( + "Not what we expected and the message is too long to fit in one line" + ) + + assert expected( + value, is_going_to_be="too long to fit in a single line", srsly=True + ) == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, "Not what we expected" + + assert expected == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + }, ( + "Not what we expected and the message is too long to fit in one line" + " because it's too long" + ) + + dis_c_instance_method = """\ + %3d 0 LOAD_FAST 1 (x) + 2 LOAD_CONST 1 (1) + 4 COMPARE_OP 2 (==) + 6 LOAD_FAST 0 (self) + 8 STORE_ATTR 0 (x) + 10 LOAD_CONST 0 (None) + 12 RETURN_VALUE + """ % ( + _C.__init__.__code__.co_firstlineno + 1, + ) + + assert ( + expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect + == { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + key5: value5, + key6: value6, + key7: value7, + key8: value8, + key9: value9, + } + ) + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring.py.snap new file mode 100644 index 00000000000000..b774287760b3a1 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring.py.snap @@ -0,0 +1,225 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +class MyClass: + """Multiline + class docstring + """ + + def method(self): + """Multiline + method docstring + """ + pass + + +def foo(): + """This is a docstring with + some lines of text here + """ + return + + +def bar(): + """This is another docstring + with more lines of text + """ + return + + +def baz(): + '''"This" is a string with some + embedded "quotes"''' + return + + +def troz(): + """Indentation with tabs + is just as OK + """ + return + + +def zort(): + """Another + multiline + docstring + """ + pass + + +def poit(): + """ + Lorem ipsum dolor sit amet. + + Consectetur adipiscing elit: + - sed do eiusmod tempor incididunt ut labore + - dolore magna aliqua + - enim ad minim veniam + - quis nostrud exercitation ullamco laboris nisi + - aliquip ex ea commodo consequat + """ + pass + + +def under_indent(): + """ + These lines are indented in a way that does not + make sense. + """ + pass + + +def over_indent(): + """ + This has a shallow indent + - But some lines are deeper + - And the closing quote is too deep + """ + pass + + +def single_line(): + """But with a newline after it!""" + pass + + +def this(): + r""" + 'hey ho' + """ + + +def that(): + """ "hey yah" """ + + +def and_that(): + """ + "hey yah" """ + + +def and_this(): + ''' + "hey yah"''' + + +def multiline_whitespace(): + """ """ + + +def oneline_whitespace(): + """ """ + + +def empty(): + """""" + + +def single_quotes(): + "testing" + + +def believe_it_or_not_this_is_in_the_py_stdlib(): + ''' + "hey yah"''' + + +def ignored_docstring(): + """a => \ +b""" + + +def single_line_docstring_with_whitespace(): + """This should be stripped""" + + +def docstring_with_inline_tabs_and_space_indentation(): + """hey + + tab separated value + tab at start of line and then a tab separated value + multiple tabs at the beginning and inline + mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. + + line ends with some tabs + """ + + +def docstring_with_inline_tabs_and_tab_indentation(): + """hey + + tab separated value + tab at start of line and then a tab separated value + multiple tabs at the beginning and inline + mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. + + line ends with some tabs + """ + pass + + +def backslash_space(): + """\ """ + + +def multiline_backslash_1(): + """ + hey\there\ + \ """ + + +def multiline_backslash_2(): + """ + hey there \ """ + + +# Regression test for #3425 +def multiline_backslash_really_long_dont_crash(): + """ + hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """ + + +def multiline_backslash_3(): + """ + already escaped \\""" + + +def my_god_its_full_of_stars_1(): + "I'm sorry Dave\u2001" + + +# the space below is actually a \u2001, removed in output +def my_god_its_full_of_stars_2(): + "I'm sorry Dave" + + +def docstring_almost_at_line_limit(): + """long docstring.................................................................""" + + +def docstring_almost_at_line_limit2(): + """long docstring................................................................. + + .................................................................................. + """ + + +def docstring_at_line_limit(): + """long docstring................................................................""" + + +def multiline_docstring_at_line_limit(): + """first line----------------------------------------------------------------------- + + second line----------------------------------------------------------------------""" + + +def stable_quote_normalization_with_immediate_inner_single_quote(self): + """' + + + """ + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring_no_extra_empty_line_before_eof.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring_no_extra_empty_line_before_eof.py.snap new file mode 100644 index 00000000000000..df6aa95f9afc0e --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__docstring_no_extra_empty_line_before_eof.py.snap @@ -0,0 +1,10 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# Make sure when the file ends with class's docstring, +# It doesn't add extra blank lines. +class ClassWithDocstring: + """A docstring.""" + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap index 093f36a39c287d..800921e04b4e1e 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap @@ -8,9 +8,9 @@ expression: formatted # leading comment def f(): - NO = "" - SPACE = " " - DOUBLESPACE = " " + NO = '' + SPACE = ' ' + DOUBLESPACE = ' ' t = leaf.type p = leaf.parent # trailing comment @@ -21,15 +21,19 @@ def f(): if t == token.COMMENT: # another trailing comment return DOUBLESPACE + assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" + prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: + return NO + if prevp.type == token.EQUAL: if prevp.parent and prevp.parent.type in { syms.typedargslist, @@ -50,16 +54,14 @@ def f(): }: return NO - ############################################################################### # SECTION BECAUSE SECTIONS ############################################################################### - def g(): - NO = "" - SPACE = " " - DOUBLESPACE = " " + NO = '' + SPACE = ' ' + DOUBLESPACE = ' ' t = leaf.type p = leaf.parent @@ -73,7 +75,7 @@ def g(): return DOUBLESPACE # Another comment because more comments - assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" + assert p is not None, f'INTERNAL ERROR: hand-made leaf without parent: {leaf!r}' prev = leaf.prev_sibling if not prev: diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap.new deleted file mode 100644 index 768fd9270ccaa9..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__empty_lines.py.snap.new +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 89 -expression: printed.as_code() ---- -"""Docstring.""" - - -# leading comment -def f(): - NO = '' - SPACE = ' ' - DOUBLESPACE = ' ' - - t = leaf.type - p = leaf.parent # trailing comment - v = leaf.value - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: - return DOUBLESPACE - - assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - if not prevp or prevp.type in OPENING_BRACKETS: - return NO - - if prevp.type == token.EQUAL: - if ( - prevp.parent - and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - } - ): - return NO - elif prevp.type == token.DOUBLESTAR: - if ( - prevp.parent - and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.dictsetmaker, - } - ): - return NO - - -############################################################################### -# SECTION BECAUSE SECTIONS -############################################################################### - -def g(): - NO = '' - SPACE = ' ' - DOUBLESPACE = ' ' - - t = leaf.type - p = leaf.parent - v = leaf.value - - # Comment because comments - - if t in ALWAYS_NO_SPACE: - pass - if t == token.COMMENT: - return DOUBLESPACE - - # Another comment because more comments - assert p is not None, f'INTERNAL ERROR: hand-made leaf without parent: {leaf!r}' - - prev = leaf.prev_sibling - if not prev: - prevp = preceding_leaf(p) - - if not prevp or prevp.type in OPENING_BRACKETS: - # Start of the line or a bracketed expression. - # More than one line for the comment. - return NO - - if prevp.type == token.EQUAL: - if ( - prevp.parent - and prevp.parent.type in { - syms.typedargslist, - syms.varargslist, - syms.parameters, - syms.arglist, - syms.argument, - } - ): - return NO - diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap index ff1b33cc9b4dac..fdc93bc7370d4d 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap @@ -4,8 +4,8 @@ assertion_line: 0 expression: formatted --- ... -"some_string" -b"\\xa3" +'some_string' +b'\\xa3' Name None True @@ -28,119 +28,83 @@ Name1 or Name2 and Name3 or Name4 v1 << 2 1 >> v2 1 % finished -1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8 -((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8) +1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8 +((1 + v2) - (v3 * 4)) ^ (((5 ** v6) / 7) // 8) not great ~great +value -1 ~int and not v1 ^ 123 + v2 | True (~int) and (not ((v1 ^ (123 + v2)) | True)) -+(really ** -(confusing ** ~(operator**-precedence))) -flags & ~select.EPOLLIN and waiters.write_task is not None ++really ** -confusing ** ~operator ** -precedence +flags & ~ select.EPOLLIN and waiters.write_task is not None lambda arg: None lambda a=True: a lambda a, b, c=True: a -lambda a, b, c=True, *, d=(1 << v2), e="str": a -lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b +lambda a, b, c=True, *, d=(1 << v2), e='str': a +lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() -foo = lambda port_id, ignore_missing: { - "port1": port1_resource, - "port2": port2_resource, -}[port_id] +foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id]) 1 if True else 2 str or None if True else str or bytes or None (str or None) if True else (str or bytes or None) str or None if (1 if True else 2) else str or bytes or None (str or None) if (1 if True else 2) else (str or bytes or None) -( - (super_long_variable_name or None) - if (1 if super_long_test_name else 2) - else (str or bytes or None) -) -{"2.7": dead, "3.7": (long_live or die_hard)} -{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}} +((super_long_variable_name or None) if (1 if super_long_test_name else 2) else (str or bytes or None)) +{'2.7': dead, '3.7': (long_live or die_hard)} +{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} {**a, **b, **c} -{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")} -({"a": "b"}, (True or False), (+value), "string", b"bytes") or None +{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} +({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None () (1,) (1, 2) (1, 2, 3) [] [1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] -[ - 1, - 2, - 3, -] +[1, 2, 3,] [*a] [*range(10)] -[ - *a, - 4, - 5, -] -[ - 4, - *a, - 5, -] -[ - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - element, - another, - *more, -] +[*a, 4, 5,] +[4, *a, 5,] +[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more] {i for i in (1, 2, 3)} -{(i**2) for i in (1, 2, 3)} -{(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))} -{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} +{(i ** 2) for i in (1, 2, 3)} +{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} +{((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} [i for i in (1, 2, 3)] -[(i**2) for i in (1, 2, 3)] -[(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))] -[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] +[(i ** 2) for i in (1, 2, 3)] +[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] +[((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] {i: 0 for i in (1, 2, 3)} -{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))} +{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} {a: b * 2 for a, b in dictionary.items()} {a: b * -2 for a, b in dictionary.items()} -{ - k: v - for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension -} +{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} Python3 > Python2 > COBOL Life is Life call() call(arg) -call(kwarg="hey") -call(arg, kwarg="hey") -call(arg, another, kwarg="hey", **kwargs) -call( - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - arg, - another, - kwarg="hey", - **kwargs -) # note: no trailing comma pre-3.6 +call(kwarg='hey') +call(arg, kwarg='hey') +call(arg, another, kwarg='hey', **kwargs) +call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6 call(*gidgets[:2]) call(a, *gidgets[:2]) call(**self.screen_kwargs) call(b, **self.screen_kwargs) lukasz.langa.pl call.me(maybe) -(1).real -(1.0).real +1 .real +1.0 .real ....__class__ list[str] dict[str, int] tuple[str, ...] -tuple[str, int, float, dict[str, int]] tuple[ - str, - int, - float, - dict[str, int], + str, int, float, dict[str, int] ] +tuple[str, int, float, dict[str, int],] very_long_variable_name_filters: t.List[ t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], ] @@ -150,9 +114,9 @@ xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: igno xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) ) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) -) # type: ignore +xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[ + ..., List[SomeClass] +] = classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore slice[0] slice[0:1] slice[0:1:2] @@ -180,57 +144,29 @@ numpy[:, l[-2]] numpy[:, ::-1] numpy[np.newaxis, :] (str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) -{"2.7": dead, "3.7": long_live or die_hard} -{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"} +{'2.7': dead, '3.7': long_live or die_hard} +{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] (SomeName) SomeName (Good, Bad, Ugly) (i for i in (1, 2, 3)) -((i**2) for i in (1, 2, 3)) -((i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))) -(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) +((i ** 2) for i in (1, 2, 3)) +((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) +(((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) (*starred,) -{ - "id": "1", - "type": "type", - "started_at": now(), - "ended_at": now() + timedelta(days=10), - "priority": 1, - "import_session_id": 1, - **kwargs, -} +{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs} a = (1,) -b = (1,) +b = 1, c = 1 d = (1,) + a + (2,) e = (1,).count(1) f = 1, *range(10) g = 1, *"ten" -what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( - vars_to_remove -) -what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( - vars_to_remove -) -result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, models.Customer.email == email_address - ) - .order_by(models.Customer.id.asc()) - .all() -) -result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, models.Customer.email == email_address - ) - .order_by( - models.Customer.id.asc(), - ) - .all() -) +what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove) +what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove) +result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc()).all() +result = session.query(models.Customer.id).filter(models.Customer.account_id == account_id, models.Customer.email == email_address).order_by(models.Customer.id.asc(),).all() Ø = set() authors.łukasz.say_thanks() mapping = { @@ -240,138 +176,85 @@ mapping = { D: 0.1 * (10.0 / 12), } - def gen(): yield from outside_of_generator - a = yield - b = yield - c = yield - + a = (yield) + b = ((yield)) + c = (((yield))) async def f(): await some.complicated[0].call(with_args=(True or (1 is not 1))) - - -print(*[] or [1]) +print(* [] or [1]) print(**{1: 3} if False else {x: x for x in range(3)}) -print(*lambda x: x) -assert not Test, "Short message" -assert this is ComplexTest and not requirements.fit_in_a_single_line( - force=False -), "Short message" -assert parens is TooMany -for (x,) in (1,), (2,), (3,): - ... -for y in (): - ... -for z in (i for i in (1, 2, 3)): - ... -for i in call(): - ... -for j in 1 + (2 + 3): - ... -while this and that: - ... -for ( - addr_family, - addr_type, - addr_proto, - addr_canonname, - addr_sockaddr, -) in socket.getaddrinfo("google.com", "http"): +print(* lambda x: x) +assert(not Test),("Short message") +assert this is ComplexTest and not requirements.fit_in_a_single_line(force=False), "Short message" +assert(((parens is TooMany))) +for x, in (1,), (2,), (3,): ... +for y in (): ... +for z in (i for i in (1, 2, 3)): ... +for i in (call()): ... +for j in (1 + (2 + 3)): ... +while(this and that): ... +for addr_family, addr_type, addr_proto, addr_canonname, addr_sockaddr in socket.getaddrinfo('google.com', 'http'): pass -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) +a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz +a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz +a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz +a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz if ( - threading.current_thread() != threading.main_thread() - and threading.current_thread() != threading.main_thread() - or signal.getsignal(signal.SIGINT) != signal.default_int_handler + threading.current_thread() != threading.main_thread() and + threading.current_thread() != threading.main_thread() or + signal.getsignal(signal.SIGINT) != signal.default_int_handler ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ): return True if ( - ~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e - | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n + ~ aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l ** aaaa.m // aaaa.n ): return True if ( - ~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e - | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h - ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n + ~ aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l ** aaaaaaaa.m // aaaaaaaa.n ): return True if ( - ~aaaaaaaaaaaaaaaa.a - + aaaaaaaaaaaaaaaa.b - - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e - | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h - ^ aaaaaaaaaaaaaaaa.i - << aaaaaaaaaaaaaaaa.k - >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n + ~ aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k >> aaaaaaaaaaaaaaaa.l ** aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n ): return True -( - aaaaaaaaaaaaaaaa - + aaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaa - * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) - / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -) +aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbb >> bbbb * bbbb -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa last_call() # standalone comment at ENDMARKER diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap.new deleted file mode 100644 index 8ab07a8fdcedde..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__expression.py.snap.new +++ /dev/null @@ -1,369 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 94 -expression: printed.as_code() ---- -... -'some_string' -b'\\xa3' -Name -None -True -False -1 -1.0 -1j -True or False -True or False or None -True and False -True and False and None -(Name1 and Name2) or Name3 -Name1 and Name2 or Name3 -Name1 or (Name2 and Name3) -Name1 or Name2 and Name3 -(Name1 and Name2) or (Name3 and Name4) -Name1 and Name2 or Name3 and Name4 -Name1 or (Name2 and Name3) or Name4 -Name1 or Name2 and Name3 or Name4 -v1 << 2 -1 >> v2 -1 % finished -1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8 -((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8) -not great -~great -+value --1 -~int and not v1 ^ 123 + v2 | True -(~int) and (not ((v1 ^ (123 + v2)) | True)) -+(really ** -(confusing ** ~(operator**-precedence))) -flags & ~select.EPOLLIN and waiters.write_task is not None -lambda arg: None -lambda a=True: a -lambda a, b, c=True: a -lambda a, b, c=True, *, d=(1 << v2), e='str': a -lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b -manylambdas = lambda x=lambda y=lambda z=1: z: y(): x() -foo = lambda port_id, -ignore_missing,: { - "port1": port1_resource, - "port2": port2_resource, -}[port_id] -1 if True else 2 -str or None if True else str or bytes or None -(str or None) if True else (str or bytes or None) -str or None if (1 if True else 2) else str or bytes or None -(str or None) if (1 if True else 2) else (str or bytes or None) -( - (super_long_variable_name or None) - if (1 if super_long_test_name else 2) - else (str or bytes or None) -) -{'2.7': dead, '3.7': (long_live or die_hard)} -{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}} -{**a, **b, **c} -{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')} -({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None -() -(1,) -(1, 2) -(1, 2, 3) -[] -[1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)] -[ - 1, - 2, - 3, -] -[*a] -[*range(10)] -[ - *a, - 4, - 5, -] -[ - 4, - *a, - 5, -] -[ - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - element, - another, - *more, -] -{i for i in (1, 2, 3)} -{(i**2) for i in (1, 2, 3)} -{(i**2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))} -{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)} -[i for i in (1, 2, 3)] -[(i**2) for i in (1, 2, 3)] -[(i**2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))] -[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)] -{i: 0 for i in (1, 2, 3)} -{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))} -{a: b * 2 for a, b in dictionary.items()} -{a: b * -2 for a, b in dictionary.items()} -{ - k: v - for k, - v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension -} -Python3 > Python2 > COBOL -Life is Life -call() -call(arg) -call(kwarg='hey') -call(arg, kwarg='hey') -call(arg, another, kwarg='hey', **kwargs) -call( - this_is_a_very_long_variable_which_will_force_a_delimiter_split, - arg, - another, - kwarg='hey', - **kwargs, -) # note: no trailing comma pre-3.6 -call(*gidgets[:2]) -call(a, *gidgets[:2]) -call(**self.screen_kwargs) -call(b, **self.screen_kwargs) -lukasz.langa.pl -call.me(maybe) -1.real -1.0.real -....__class__ -list[str] -dict[str, int] -tuple[str, ...] -tuple[str, int, float, dict[str, int]] -tuple[ - str, - int, - float, - dict[str, int], -] -very_long_variable_name_filters: t.List[ - t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]], -] -xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = ( - classmethod # type: ignore(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = ( - classmethod # type: ignore(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) -) -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = ( - classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) -) -slice[0] -slice[0:1] -slice[0:1:2] -slice[:] -slice[:-1] -slice[1:] -slice[::-1] -slice[d :: d + 1] -slice[:c, c - 1] -numpy[:, 0:1] -numpy[:, :-1] -numpy[0, :] -numpy[:, i] -numpy[0, :2] -numpy[:N, 0] -numpy[:2, :4] -numpy[2:4, 1:5] -numpy[4:, 2:] -numpy[:, (0, 1, 2, 5)] -numpy[0, [0]] -numpy[:, [i]] -numpy[1 : c + 1, c] -numpy[-(c + 1) :, d] -numpy[:, l[-2]] -numpy[:, ::-1] -numpy[np.newaxis, :] -(str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None) -{'2.7': dead, '3.7': long_live or die_hard} -{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'} -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C] -(SomeName) -SomeName -(Good, Bad, Ugly) -(i for i in (1, 2, 3)) -((i**2) for i in (1, 2, 3)) -((i**2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))) -(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)) -(*starred,) -{ - "id": "1", - "type": "type", - "started_at": now(), - "ended_at": now() + timedelta(days=10), - "priority": 1, - "import_session_id": 1, - **kwargs, -} -a = (1,) -b = (1,) -c = 1 -d = (1,) + a + (2,) -e = (1,).count(1) -f = 1, *range(10) -g = 1, *"ten" -what_is_up_with_those_new_coord_names = ( - (coord_names + set(vars_to_create)) - + set(vars_to_remove) -) -what_is_up_with_those_new_coord_names = ( - (coord_names | set(vars_to_create)) - - set(vars_to_remove) -) -result = session.query(models.Customer.id).filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, -).order_by(models.Customer.id.asc()).all() -result = session.query(models.Customer.id).filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, -).order_by( - models.Customer.id.asc(), -).all() -Ø = set() -authors.łukasz.say_thanks() -mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), -} - - -def gen(): - yield from outside_of_generator - a = yield - b = yield - c = yield - - -async def f(): - await some.complicated[0].call(with_args=(True or (1 is not 1))) - - -print(*[] or [1]) -print(**{1: 3} if False else {x: x for x in range(3)}) -print(*lambda x: x) -assert not Test, "Short message" -assert ( - this is ComplexTest - and not requirements.fit_in_a_single_line(force=False) -), "Short message" -assert parens is TooMany -for (x,) in (1,), (2,), (3,): - ... -for y in (): - ... -for z in (i for i in (1, 2, 3)): - ... -for i in call(): - ... -for j in 1 + (2 + 3): - ... -while this and that: - ... -for ( - addr_family, - addr_type, - addr_proto, - addr_canonname, - addr_sockaddr -) in socket.getaddrinfo('google.com', 'http'): - pass -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -a = ( - aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp - is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz -) -if ( - threading.current_thread() != threading.main_thread() - and threading.current_thread() != threading.main_thread() - or signal.getsignal(signal.SIGINT) != signal.default_int_handler -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - / aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -): - return True -if ( - ~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e - | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n -): - return True -if ( - ~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e - | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h - ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n -): - return True -if ( - ~aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e - | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h - ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k - >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n -): - return True -( - aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) - / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) -) -aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) -bbbb >> bbbb * bbbb -( - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -) -last_call()# standalone comment at ENDMARKER - diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff.py.snap new file mode 100644 index 00000000000000..f324c0856b477b --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff.py.snap @@ -0,0 +1,229 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +#!/usr/bin/env python3 +import asyncio +import sys + +from third_party import X, Y, Z + +from library import some_connection, some_decorator + +# fmt: off +from third_party import (X, + Y, Z) +# fmt: on +f"trigger 3.6 mode" +# Comment 1 + +# Comment 2 + +# fmt: off +def func_no_args(): + a; b; c + if True: raise RuntimeError + if False: ... + for i in range(10): + print(i) + continue + exec('new-style exec', {}, {}) + return None +async def coroutine(arg, exec=False): + 'Single-line docstring. Multiline is harder to reformat.' + async with some_connection() as conn: + await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) + await asyncio.sleep(1) +@asyncio.coroutine +@some_decorator( +with_args=True, +many_args=[1,2,3] +) +def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str: + return text[number:-1] +# fmt: on +def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): + offset = attr.ib(default=attr.Factory(lambda: _r.uniform(1, 2))) + assert task._cancel_stack[: len(old_stack)] == old_stack + + +def spaces_types( + a: int = 1, + b: tuple = (), + c: list = [], + d: dict = {}, + e: bool = True, + f: int = -1, + g: int = 1 if False else 2, + h: str = "", + i: str = r"", +): + ... + + +def spaces2(result=_core.Value(None)): + ... + + +something = { + # fmt: off + key: 'value', +} + + +def subscriptlist(): + atom[ + # fmt: off + 'some big and', + 'complex subscript', + # fmt: on + goes + here, + andhere, + ] + + +def import_as_names(): + # fmt: off + from hello import a, b + 'unformatted' + # fmt: on + + +def testlist_star_expr(): + # fmt: off + a , b = *hello + 'unformatted' + # fmt: on + + +def yield_expr(): + # fmt: off + yield hello + 'unformatted' + # fmt: on + "formatted" + # fmt: off + ( yield hello ) + 'unformatted' + # fmt: on + + +def example(session): + # fmt: off + result = session\ + .query(models.Customer.id)\ + .filter(models.Customer.account_id == account_id, + models.Customer.email == email_address)\ + .order_by(models.Customer.id.asc())\ + .all() + # fmt: on + + +def off_and_on_without_data(): + """All comments here are technically on the same prefix. + + The comments between will be formatted. This is a known limitation. + """ + # fmt: off + + # hey, that won't work + + # fmt: on + pass + + +def on_and_off_broken(): + """Another known limitation.""" + # fmt: on + # fmt: off + this=should.not_be.formatted() + and_=indeed . it is not formatted + because . the . handling . inside . generate_ignored_nodes() + now . considers . multiple . fmt . directives . within . one . prefix + # fmt: on + # fmt: off + # ...but comments still get reformatted even though they should not be + # fmt: on + + +def long_lines(): + if True: + typedargslist.extend( + gen_annotated_params( + ast_args.kwonlyargs, + ast_args.kw_defaults, + parameters, + implicit_default=True, + ) + ) + # fmt: off + a = ( + unnecessary_bracket() + ) + # fmt: on + _type_comment_re = re.compile( + r""" + ^ + [\t ]* + \#[ ]type:[ ]* + (?P + [^#\t\n]+? + ) + (? to match + # a trailing space which is why we need the silliness below + (? + (?:\#[^\n]*)? + \n? + ) + $ + """, + # fmt: off + re.MULTILINE|re.VERBOSE + # fmt: on + ) + + +def single_literal_yapf_disable(): + """Black does not support this.""" + BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable + + +cfg.rule( + "Default", + "address", + xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"], + xxxxxx="xx_xxxxx", + xxxxxxx="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + xxxxxxxxx_xxxx=True, + xxxxxxxx_xxxxxxxxxx=False, + xxxxxx_xxxxxx=2, + xxxxxx_xxxxx_xxxxxxxx=70, + xxxxxx_xxxxxx_xxxxx=True, + # fmt: off + xxxxxxx_xxxxxxxxxxxx={ + "xxxxxxxx": { + "xxxxxx": False, + "xxxxxxx": False, + "xxxx_xxxxxx": "xxxxx", + }, + "xxxxxxxx-xxxxx": { + "xxxxxx": False, + "xxxxxxx": True, + "xxxx_xxxxxx": "xxxxxx", + }, + }, + # fmt: on + xxxxxxxxxx_xxxxxxxxxxx_xxxxxxx_xxxxxxxxx=5, +) +# fmt: off +yield 'hello' +# No formatting to the end of the file +l=[1,2,3] +d={'a':1, + 'b':2} + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff2.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff2.py.snap new file mode 100644 index 00000000000000..2ab9cbe53670c9 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff2.py.snap @@ -0,0 +1,46 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +import pytest + +TmSt = 1 +TmEx = 2 + +# fmt: off + +# Test data: +# Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]] + +@pytest.mark.parametrize('test', [ + + # Test don't manage the volume + [ + ('stuff', 'in') + ], +]) +def test_fader(test): + pass + +def check_fader(test): + + pass + +def verify_fader(test): + # misaligned comment + pass + +def verify_fader(test): + """Hey, ho.""" + assert test.passed() + +def test_calculate_fades(): + calcs = [ + # one is zero/none + (0, 4, 0, 0, 10, 0, 0, 6, 10), + (None, 4, 0, 0, 10, 0, 0, 6, 10), + ] + +# fmt: on + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff3.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff3.py.snap new file mode 100644 index 00000000000000..c5b1e4506ec13c --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff3.py.snap @@ -0,0 +1,21 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# fmt: off +x = [ + 1, 2, + 3, 4, +] +# fmt: on + +# fmt: off +x = [ + 1, 2, + 3, 4, +] +# fmt: on + +x = [1, 2, 3, 4] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff4.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff4.py.snap new file mode 100644 index 00000000000000..b2f1528d5fe0c4 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff4.py.snap @@ -0,0 +1,26 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# fmt: off +@test([ + 1, 2, + 3, 4, +]) +# fmt: on +def f(): + pass + + +@test( + [ + 1, + 2, + 3, + 4, + ] +) +def f(): + pass + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff5.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff5.py.snap new file mode 100644 index 00000000000000..1d8c230ba2c363 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtonoff5.py.snap @@ -0,0 +1,93 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# Regression test for /~https://github.com/psf/black/issues/3129. +setup( + entry_points={ + # fmt: off + "console_scripts": [ + "foo-bar" + "=foo.bar.:main", + # fmt: on + ] # Includes an formatted indentation. + }, +) + + +# Regression test for /~https://github.com/psf/black/issues/2015. +run( + # fmt: off + [ + "ls", + "-la", + ] + # fmt: on + + path, + check=True, +) + + +# Regression test for /~https://github.com/psf/black/issues/3026. +def test_func(): + # yapf: disable + if unformatted( args ): + return True + # yapf: enable + elif b: + return True + + return False + + +# Regression test for /~https://github.com/psf/black/issues/2567. +if True: + # fmt: off + for _ in range( 1 ): + # fmt: on + print ( "This won't be formatted" ) + print ( "This won't be formatted either" ) +else: + print("This will be formatted") + + +# Regression test for /~https://github.com/psf/black/issues/3184. +class A: + async def call(param): + if param: + # fmt: off + if param[0:4] in ( + "ABCD", "EFGH" + ) : + # fmt: on + print ( "This won't be formatted" ) + + elif param[0:4] in ("ZZZZ",): + print ( "This won't be formatted either" ) + + print("This will be formatted") + + +# Regression test for /~https://github.com/psf/black/issues/2985. +class Named(t.Protocol): + # fmt: off + @property + def this_wont_be_formatted ( self ) -> str: ... + + +class Factory(t.Protocol): + def this_will_be_formatted(self, **kwargs) -> Named: + ... + + # fmt: on + + +# Regression test for /~https://github.com/psf/black/issues/3436. +if x: + return x +# fmt: off +elif unformatted: + # fmt: on + will_be_formatted() + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip.py.snap new file mode 100644 index 00000000000000..d618908662a8ed --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip.py.snap @@ -0,0 +1,9 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +a, b = 1, 2 +c = 6 # fmt: skip +d = 5 + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip2.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip2.py.snap new file mode 100644 index 00000000000000..2794958a2d2df0 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip2.py.snap @@ -0,0 +1,17 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +l1 = [ + "This list should be broken up", + "into multiple lines", + "because it is way too long", +] +l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip +l3 = [ + "I have", + "trailing comma", + "so I should be braked", +] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip3.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip3.py.snap new file mode 100644 index 00000000000000..a8b8fcc9464487 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip3.py.snap @@ -0,0 +1,16 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +a = 3 +# fmt: off +b, c = 1, 2 +d = 6 # fmt: skip +e = 5 +# fmt: on +f = [ + "This is a very long line that should be formatted into a clearer line ", + "by rearranging.", +] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip4.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip4.py.snap new file mode 100644 index 00000000000000..0c81a009b999c1 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip4.py.snap @@ -0,0 +1,13 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +a = 2 +# fmt: skip +l = [ + 1, + 2, + 3, +] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip5.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip5.py.snap new file mode 100644 index 00000000000000..4ad5157befce54 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip5.py.snap @@ -0,0 +1,15 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +a, b, c = 3, 4, 5 +if ( + a == 3 + and b != 9 # fmt: skip + and c is not None +): + print("I'm good!") +else: + print("I'm bad") + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip6.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip6.py.snap new file mode 100644 index 00000000000000..5690143bb87fac --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip6.py.snap @@ -0,0 +1,11 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +class A: + def f(self): + for line in range(10): + if True: + pass # fmt: skip + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip7.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip7.py.snap new file mode 100644 index 00000000000000..76dbf12310e4cd --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip7.py.snap @@ -0,0 +1,10 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +a = "this is some code" +b = 5 # fmt:skip +c = 9 # fmt: skip +d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip8.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip8.py.snap new file mode 100644 index 00000000000000..b249067ea9f3ae --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fmtskip8.py.snap @@ -0,0 +1,68 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +# Make sure a leading comment is not removed. +def some_func( unformatted, args ): # fmt: skip + print("I am some_func") + return 0 + # Make sure this comment is not removed. + + +# Make sure a leading comment is not removed. +async def some_async_func( unformatted, args): # fmt: skip + print("I am some_async_func") + await asyncio.sleep(1) + + +# Make sure a leading comment is not removed. +class SomeClass( Unformatted, SuperClasses ): # fmt: skip + def some_method( self, unformatted, args ): # fmt: skip + print("I am some_method") + return 0 + + async def some_async_method( self, unformatted, args ): # fmt: skip + print("I am some_async_method") + await asyncio.sleep(1) + + +# Make sure a leading comment is not removed. +if unformatted_call( args ): # fmt: skip + print("First branch") + # Make sure this is not removed. +elif another_unformatted_call( args ): # fmt: skip + print("Second branch") +else : # fmt: skip + print("Last branch") + + +while some_condition( unformatted, args ): # fmt: skip + print("Do something") + + +for i in some_iter( unformatted, args ): # fmt: skip + print("Do something") + + +async def test_async_for(): + async for i in some_async_iter( unformatted, args ): # fmt: skip + print("Do something") + + +try : # fmt: skip + some_call() +except UnformattedError as ex: # fmt: skip + handle_exception() +finally : # fmt: skip + finally_call() + + +with give_me_context( unformatted, args ): # fmt: skip + print("Do something") + + +async def test_async_with(): + async with give_me_async_context( unformatted, args ): # fmt: skip + print("Do something") + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fstring.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fstring.py.snap new file mode 100644 index 00000000000000..571a1683d4df5e --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__fstring.py.snap @@ -0,0 +1,15 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +f"f-string without formatted values is just a string" +f"{{NOT a formatted value}}" +f'{{NOT \'a\' "formatted" "value"}}' +f"some f-string with {a} {few():.2f} {formatted.values!r}" +f'some f-string with {a} {few(""):.2f} {formatted.values!r}' +f"{f'''{'nested'} inner'''} outer" +f"\"{f'{nested} inner'}\" outer" +f"space between opening braces: { {a for a in (1, 2, 3)}}" +f'Hello \'{tricky + "example"}\'' + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap index 20b3f4f84f1916..5809e6208169db 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap @@ -9,97 +9,52 @@ import sys from third_party import X, Y, Z -from library import some_connection, some_decorator - -f"trigger 3.6 mode" - - +from library import some_connection, \ + some_decorator +f'trigger 3.6 mode' def func_no_args(): - a - b - c - if True: - raise RuntimeError - if False: - ... - for i in range(10): - print(i) - continue - exec("new-style exec", {}, {}) - return None - - + a; b; c + if True: raise RuntimeError + if False: ... + for i in range(10): + print(i) + continue + exec("new-style exec", {}, {}) + return None async def coroutine(arg, exec=False): - "Single-line docstring. Multiline is harder to reformat." - async with some_connection() as conn: - await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2) - await asyncio.sleep(1) - - + "Single-line docstring. Multiline is harder to reformat." + async with some_connection() as conn: + await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) + await asyncio.sleep(1) @asyncio.coroutine -@some_decorator(with_args=True, many_args=[1, 2, 3]) -def function_signature_stress_test( - number: int, - no_annotation=None, - text: str = "default", - *, - debug: bool = False, - **kwargs, -) -> str: - return text[number:-1] - - -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000))) - assert task._cancel_stack[: len(old_stack)] == old_stack - - -def spaces_types( - a: int = 1, - b: tuple = (), - c: list = [], - d: dict = {}, - e: bool = True, - f: int = -1, - g: int = 1 if False else 2, - h: str = "", - i: str = r"", -): - ... - - -def spaces2(result=_core.Value(None)): - assert fut is self._read_fut, (fut, self._read_fut) - +@some_decorator( +with_args=True, +many_args=[1,2,3] +) +def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str: + return text[number:-1] +def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''): + offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000))) + assert task._cancel_stack[:len(old_stack)] == old_stack +def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ... +def spaces2(result= _core.Value(None)): + assert fut is self._read_fut, (fut, self._read_fut) def example(session): - result = ( - session.query(models.Customer.id) - .filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, - ) - .order_by(models.Customer.id.asc()) - .all() - ) - - + result = session.query(models.Customer.id).filter( + models.Customer.account_id == account_id, + models.Customer.email == email_address, + ).order_by( + models.Customer.id.asc() + ).all() def long_lines(): if True: typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - ) + gen_annotated_params(ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True) ) typedargslist.extend( gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, + ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True, # trailing standalone comment ) ) @@ -122,23 +77,18 @@ def long_lines(): \n? ) $ - """, - re.MULTILINE | re.VERBOSE, + """, re.MULTILINE | re.VERBOSE ) - - def trailing_comma(): mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), - } - - + A: 0.25 * (10.0 / 12), + B: 0.1 * (10.0 / 12), + C: 0.1 * (10.0 / 12), + D: 0.1 * (10.0 / 12), +} def f( - a, - **kwargs, + a, + **kwargs, ) -> A: return ( yield from A( @@ -147,8 +97,5 @@ def f( **kwargs, ) ) - - -def __await__(): - return (yield) +def __await__(): return (yield) diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap.new deleted file mode 100644 index c13a012fcf67ab..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function.py.snap.new +++ /dev/null @@ -1,148 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 95 -expression: adjust_quotes(formatted.print()?.as_code()) ---- -#!/usr/bin/env python3 -import asyncio -import sys - -from third_party import X, Y, Z - -from library import some_connection, some_decorator - -f"trigger 3.6 mode" - - -def func_no_args(): - a - b - c - if True: - raise RuntimeError - if False: - ... - for i in range(10): - print(i) - continue - exec("new-style exec", {}, {}) - return None - - -async def coroutine(arg, exec=False): - "Single-line docstring. Multiline is harder to reformat." - async with some_connection() as conn: - await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2) - await asyncio.sleep(1) - - -@asyncio.coroutine -@some_decorator(with_args=True, many_args=[1, 2, 3]) -def function_signature_stress_test( - number: int, - no_annotation=None, - text: str = "default", - *, - debug: bool = False, - **kwargs, -) -> str: - return text[number:-1] - - -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000))) - assert task._cancel_stack[: len(old_stack)] == old_stack - - -def spaces_types( - a: int = 1, - b: tuple = (), - c: list = [], - d: dict = {}, - e: bool = True, - f: int = -1, - g: int = 1 if False else 2, - h: str = "", - i: str = r"", -): - ... - - -def spaces2(result=_core.Value(None)): - assert fut is self._read_fut, fut, self._read_fut - - -def example(session): - result = session.query(models.Customer.id).filter( - models.Customer.account_id == account_id, - models.Customer.email == email_address, - ).order_by(models.Customer.id.asc()).all() - - -def long_lines(): - if True: - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - ) - ) - typedargslist.extend( - gen_annotated_params( - ast_args.kwonlyargs, - ast_args.kw_defaults, - parameters, - implicit_default=True, - # trailing standalone comment - ) - ) - _type_comment_re = re.compile( - r""" - ^ - [\t ]* - \#[ ]type:[ ]* - (?P - [^#\t\n]+? - ) - (? to match - # a trailing space which is why we need the silliness below - (? - (?:\#[^\n]*)? - \n? - ) - $ - """, - re.MULTILINE | re.VERBOSE, - ) - - -def trailing_comma(): - mapping = { - A: 0.25 * (10.0 / 12), - B: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12), - } - - -def f( - a, - **kwargs, -) -> A: - return - yield from A( - very_long_argument_name1=very_long_value_for_the_argument, - very_long_argument_name2=very_long_value_for_the_argument, - **kwargs, - ) - - -def __await__(): - return yield - diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function2.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function2.py.snap index c5249d27ba1665..55fe1f05fc1ffa 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function2.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function2.py.snap @@ -4,13 +4,13 @@ assertion_line: 0 expression: formatted --- def f( - a, - **kwargs, + a, + **kwargs, ) -> A: with cache_dir(): if something: - result = CliRunner().invoke( - black.main, [str(src1), str(src2), "--diff", "--check"] + result = ( + CliRunner().invoke(black.main, [str(src1), str(src2), "--diff", "--check"]) ) limited.append(-limited.pop()) # negate top return A( @@ -18,34 +18,24 @@ def f( very_long_argument_name2=-very.long.value.for_the_argument, **kwargs, ) - - def g(): "Docstring." - def inner(): pass - print("Inner defs should breathe a little.") - - def h(): def inner(): pass - print("Inner defs should breathe a little.") if os.name == "posix": import termios - def i_should_be_followed_by_only_one_newline(): pass - elif os.name == "nt": try: import msvcrt - def i_should_be_followed_by_only_one_newline(): pass @@ -59,13 +49,11 @@ elif False: class IHopeYouAreHavingALovelyDay: def __call__(self): print("i_should_be_followed_by_only_one_newline") - else: def foo(): pass - with hmm_but_this_should_get_two_preceding_newlines(): pass diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap index 762342e6819598..97403631df2d76 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap @@ -3,72 +3,29 @@ source: src/source_code/mod.rs assertion_line: 0 expression: formatted --- -def f( - a, -): - d = { - "key": "value", - } +def f(a,): + d = {'key': 'value',} tup = (1,) +def f2(a,b,): + d = {'key': 'value', 'key2': 'value2',} + tup = (1,2,) -def f2( - a, - b, -): - d = { - "key": "value", - "key2": "value2", - } - tup = ( - 1, - 2, - ) - - -def f( - a: int = 1, -): - call( - arg={ - "explode": "this", - } - ) - call2( - arg=[1, 2, 3], - ) +def f(a:int=1,): + call(arg={'explode': 'this',}) + call2(arg=[1,2,3],) x = { "a": 1, "b": 2, }["a"] - if ( - a - == { - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6, - "g": 7, - "h": 8, - }["a"] - ): + if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]: pass - def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ]: - json = { - "k": { - "k2": { - "k3": [ - 1, - ] - } - } - } + json = {"k": {"k2": {"k3": [1,]}}} + # The type annotation shouldn't get a trailing comma since that would change its type. @@ -79,28 +36,21 @@ def some_function_with_a_really_long_name() -> ( pass -def some_method_with_a_really_long_name( - very_long_parameter_so_yeah: str, another_long_parameter: int -) -> ( +def some_method_with_a_really_long_name(very_long_parameter_so_yeah: str, another_long_parameter: int) -> ( another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not ): pass def func() -> ( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too - ) + also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too) ): pass -def func() -> ( - ( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too - ) - ) +def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( + this_shouldn_t_get_a_trailing_comma_too + )) ): pass @@ -112,13 +62,6 @@ some_module.some_function( # Inner trailing comma causes outer to explode some_module.some_function( - argument1, - ( - one, - two, - ), - argument4, - argument5, - argument6, + argument1, (one, two,), argument4, argument5, argument6 ) diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap.new deleted file mode 100644 index da5a6cbec5d847..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__function_trailing_comma.py.snap.new +++ /dev/null @@ -1,118 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 95 -expression: adjust_quotes(formatted.print()?.as_code()) ---- -def f( - a, -): - d = { - "key": "value", - } - tup = (1,) - - -def f2( - a, - b, -): - d = { - "key": "value", - "key2": "value2", - } - tup = ( - 1, - 2, - ) - - -def f( - a: int = 1, -): - call( - arg={ - "explode": "this", - } - ) - call2( - arg=[1, 2, 3], - ) - x = { - "a": 1, - "b": 2, - }["a"] - if ( - a - == { - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6, - "g": 7, - "h": 8, - }["a"] - ): - pass - - -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -]: - json = { - "k": { - "k2": { - "k3": [ - 1, - ], - }, - }, - } - - -# The type annotation shouldn"t get a trailing comma since that would change its type. -# Relevant bug report: /~https://github.com/psf/black/issues/2381. -def some_function_with_a_really_long_name() -> returning_a_deeply_nested_import_of_a_type_i_suppose: - pass - - -def some_method_with_a_really_long_name( - very_long_parameter_so_yeah: str, - another_long_parameter: int, -) -> another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not: - pass - - -def func() -> also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too -): - pass - - -def func() -> also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - this_shouldn_t_get_a_trailing_comma_too -): - pass - - -# Make sure inner one-element tuple won"t explode -some_module.some_function( - argument1, - (one_element_tuple,), - argument4, - argument5, - argument6, -) - -# Inner trailing comma causes outer to explode -some_module.some_function( - argument1, - ( - one, - two, - ), - argument4, - argument5, - argument6, -) diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap index 7a8512a70cb507..0a16bc7b9f69ab 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap @@ -5,11 +5,11 @@ expression: formatted --- def function(**kwargs): t = a**2 + b**3 - return t**2 + return t ** 2 def function_replace_spaces(**kwargs): - t = a**2 + b**3 + c**4 + t = a **2 + b** 3 + c ** 4 def function_dont_replace_spaces(): diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap.new deleted file mode 100644 index acd53e17571864..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__power_op_spacing.py.snap.new +++ /dev/null @@ -1,68 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 112 -expression: formatted.print()?.as_code() ---- -def function(**kwargs): - t = a**2 + b**3 - return t**2 - - -def function_replace_spaces(**kwargs): - t = a**2 + b**3 + c**4 - - -def function_dont_replace_spaces(): - {**a, **b, **c} - - -a = 5**~4 -b = 5 ** f() -c = -(5**2) -d = 5 ** f["hi"] -e = lazy(lambda: 5) -f = f() ** 5 -g = a.b**c.d -h = 5 ** funcs.f() -i = funcs.f() ** 5 -j = super().name**5 -k = [(2**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2**63], [1, 2**63])] -n = count <= 10**5 -o = settings(max_examples=10**6) -p = {(k, k**2): v**2 for k, v in pairs} -q = [10**i for i in range(6)] -r = x**y - -a = 5.0**~4.0 -b = 5.0 ** f() -c = -(5.0**2.0) -d = 5.0 ** f["hi"] -e = lazy(lambda: 5) -f = f() ** 5.0 -g = a.b**c.d -h = 5.0 ** funcs.f() -i = funcs.f() ** 5.0 -j = super().name**5.0 -k = [(2.0**idx, value) for idx, value in pairs] -l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) -m = [([2.0**63.0], [1.0, 2**63.0])] -n = count <= 10**5.0 -o = settings(max_examples=10**6.0) -p = {(k, k**2): v**2.0 for k, v in pairs} -q = [10.5**i for i in range(6)] - - -# WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (/~https://github.com/psf/black/issues/2873) -if hasattr(view, "sum_of_weights"): - return np.divide # type: ignore[no-any-return]( - view.variance # type: ignore[union-attr], - view.sum_of_weights # type: ignore[union-attr], - out=np.full(view.sum_of_weights.shape, np.nan), - where=view.sum_of_weights**2 > view.sum_of_weights_squared, - ) - -return np.divide( - where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, -) diff --git a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/remove_parens.bak b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__remove_parens.py.snap similarity index 52% rename from crates/ruff_fmt/resources/test/fixtures/black/simple_cases/remove_parens.bak rename to crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__remove_parens.py.snap index abd5f71fcd0f46..171ab1dfe2abd0 100644 --- a/crates/ruff_fmt/resources/test/fixtures/black/simple_cases/remove_parens.bak +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__remove_parens.py.snap @@ -1,3 +1,8 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- x = (1) x = (1.2) @@ -54,89 +59,3 @@ def example7(): def example8(): return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) -# output -x = 1 -x = 1.2 - -data = ( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -).encode() - - -async def show_status(): - while True: - try: - if report_host: - data = ( - f"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ).encode() - except Exception as e: - pass - - -def example(): - return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - - -def example1(): - return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - - -def example1point5(): - return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - - -def example2(): - return ( - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - ) - - -def example3(): - return ( - 1111111111111111111111111111111111111111111111111111111111111111111111111111111 - ) - - -def example4(): - return True - - -def example5(): - return () - - -def example6(): - return {a: a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]} - - -def example7(): - return { - a: a - for a in [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20000000000000000000, - ] - } - - -def example8(): - return None diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__slices.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__slices.py.snap new file mode 100644 index 00000000000000..ee38b6941ccfc3 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__slices.py.snap @@ -0,0 +1,37 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +slice[a.b : c.d] +slice[d :: d + 1] +slice[d + 1 :: d] +slice[d::d] +slice[0] +slice[-1] +slice[:-1] +slice[::-1] +slice[:c, c - 1] +slice[c, c + 1, d::] +slice[ham[c::d] :: 1] +slice[ham[cheese**2 : -1] : 1 : 1, ham[1:2]] +slice[:-1:] +slice[lambda: None : lambda: None] +slice[lambda x, y, *args, really=2, **kwargs: None :, None::] +slice[1 or 2 : True and False] +slice[not so_simple : 1 < val <= 10] +slice[(1 for i in range(42)) : x] +slice[:: [i for i in range(42)]] + + +async def f(): + slice[await x : [i async for i in arange(42)] : 42] + + +# These are from PEP-8: +ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:] +ham[lower:upper], ham[lower:upper:], ham[lower::step] +# ham[lower+offset : upper+offset] +ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)] +ham[lower + offset : upper + offset] + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__string_prefixes.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__string_prefixes.py.snap new file mode 100644 index 00000000000000..96fe06ec845ccc --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__string_prefixes.py.snap @@ -0,0 +1,26 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +#!/usr/bin/env python3 + +name = "Łukasz" +(f"hello {name}", f"hello {name}") +(b"", b"") +("", "") +(r"", R"") + +(rf"", rf"", Rf"", Rf"", rf"", rf"", Rf"", Rf"") +(rb"", rb"", Rb"", Rb"", rb"", rb"", Rb"", Rb"") + + +def docstring_singleline(): + R"""2020 was one hell of a year. The good news is that we were able to""" + + +def docstring_multiline(): + R""" + clear out all of the issues opened in that time :p + """ + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__torture.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__torture.py.snap new file mode 100644 index 00000000000000..0bf010f59a7c89 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__torture.py.snap @@ -0,0 +1,64 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +importA +( + () + << 0 + ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 +) # + +assert sort_by_dependency( + { + "1": {"2", "3"}, + "2": {"2a", "2b"}, + "3": {"3a", "3b"}, + "2a": set(), + "2b": set(), + "3a": set(), + "3b": set(), + } +) == ["2a", "2b", "2", "3a", "3b", "3", "1"] + +importA +0 +0 ^ 0 # + + +class A: + def foo(self): + for _ in range(10): + aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( + xxxxxxxxxxxx + ) # pylint: disable=no-member + + +def test(self, othr): + return 1 == 2 and ( + name, + description, + self.default, + self.selected, + self.auto_generated, + self.parameters, + self.meta_data, + self.schedule, + ) == ( + name, + description, + othr.default, + othr.selected, + othr.auto_generated, + othr.parameters, + othr.meta_data, + othr.schedule, + ) + + +assert a_function( + very_long_arguments_that_surpass_the_limit, + which_is_eighty_eight_in_this_case_plus_a_bit_more, +) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens1.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens1.py.snap new file mode 100644 index 00000000000000..f76c0c61c4bd07 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens1.py.snap @@ -0,0 +1,40 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +if e1234123412341234.winerror not in ( + _winapi.ERROR_SEM_TIMEOUT, + _winapi.ERROR_PIPE_BUSY, +) or _check_timeout(t): + pass + +if x: + if y: + new_id = ( + max( + Vegetable.objects.order_by("-id")[0].id, + Mineral.objects.order_by("-id")[0].id, + ) + + 1 + ) + + +class X: + def get_help_text(self): + return ngettext( + "Your password must contain at least %(min_length)d character.", + "Your password must contain at least %(min_length)d characters.", + self.min_length, + ) % {"min_length": self.min_length} + + +class A: + def b(self): + if self.connection.mysql_is_mariadb and ( + 10, + 4, + 3, + ) < self.connection.mysql_version < (10, 5, 2): + pass + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens2.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens2.py.snap new file mode 100644 index 00000000000000..538fa6b013110b --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens2.py.snap @@ -0,0 +1,12 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +if e123456.get_tk_patchlevel() >= (8, 6, 0, "final") or ( + 8, + 5, + 8, +) <= get_tk_patchlevel() < (8, 6): + pass + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens3.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens3.py.snap new file mode 100644 index 00000000000000..c26109904a9608 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__trailing_comma_optional_parens3.py.snap @@ -0,0 +1,14 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +if True: + if True: + if True: + return _( + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas " + + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", + ) % {"reported_username": reported_username, "report_reason": report_reason} + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tricky_unicode_symbols.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tricky_unicode_symbols.py.snap new file mode 100644 index 00000000000000..127bddd4f5fcf0 --- /dev/null +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tricky_unicode_symbols.py.snap @@ -0,0 +1,15 @@ +--- +source: src/source_code/mod.rs +assertion_line: 0 +expression: formatted +--- +ä = 1 +µ = 2 +蟒 = 3 +x󠄀 = 4 +មុ = 1 +Q̇_per_meter = 4 + +A᧚ = 3 +A፩ = 8 + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap index a626cd1c38608a..b62974315a6ef9 100644 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap +++ b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap @@ -4,14 +4,10 @@ assertion_line: 0 expression: formatted --- # This is a standalone comment. -( - sdfjklsdfsjldkflkjsf, - sdfjsdfjlksdljkfsdlkf, - sdfsdjfklsdfjlksdljkf, - sdsfsdfjskdflsfsdf, -) = (1, 2, 3) +sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 # This is as well. -(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890") +this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890") (a,) = call() + diff --git a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap.new b/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap.new deleted file mode 100644 index dd71f95b5144f8..00000000000000 --- a/crates/ruff_fmt/src/snapshots/ruff_fmt__tests__simple_cases__tupleassign.py.snap.new +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: crates/ruff_fmt/src/lib.rs -assertion_line: 94 -expression: printed.as_code() ---- -# This is a standalone comment. -( - sdfjklsdfsjldkflkjsf, - sdfjsdfjlksdljkfsdlkf, - sdfsdjfklsdfjlksdljkf, - sdsfsdfjskdflsfsdf -) = 1, 2, 3 - -# This is as well. -(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890") - -(a,) = call()