From 431bd09e15247431056894bd6444dee7c22893f0 Mon Sep 17 00:00:00 2001 From: Ryan Siu Date: Sat, 9 Apr 2022 16:52:45 -0400 Subject: [PATCH] Correctly handle fmt: skip comments without internal spaces (#2970) Co-authored-by: Jelle Zijlstra --- CHANGES.md | 3 +++ src/black/comments.py | 7 +++++-- tests/data/fmtskip7.py | 11 +++++++++++ tests/test_format.py | 1 + 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 tests/data/fmtskip7.py diff --git a/CHANGES.md b/CHANGES.md index e168e24..b21c319 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,9 @@ +- Fix unstable formatting involving `# fmt: skip` comments without internal spaces + (#2970) + ### Preview style diff --git a/src/black/comments.py b/src/black/comments.py index 4553264..23bf87f 100644 --- a/src/black/comments.py +++ b/src/black/comments.py @@ -214,8 +214,11 @@ def generate_ignored_nodes( container: Optional[LN] = container_of(leaf) if comment.value in FMT_SKIP: prev_sibling = leaf.prev_sibling - if comment.value in leaf.prefix and prev_sibling is not None: - leaf.prefix = leaf.prefix.replace(comment.value, "") + # Need to properly format the leaf prefix to compare it to comment.value, + # which is also formatted + comments = list_comments(leaf.prefix, is_endmarker=False, preview=preview) + if comments and comment.value == comments[0].value and prev_sibling is not None: + leaf.prefix = "" siblings = [prev_sibling] while ( "\n" not in prev_sibling.prefix diff --git a/tests/data/fmtskip7.py b/tests/data/fmtskip7.py new file mode 100644 index 0000000..15ac0ad --- /dev/null +++ b/tests/data/fmtskip7.py @@ -0,0 +1,11 @@ +a = "this is some code" +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/tests/test_format.py b/tests/test_format.py index 51d8fb0..fd5f596 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -44,6 +44,7 @@ SIMPLE_CASES: List[str] = [ "fmtskip4", "fmtskip5", "fmtskip6", + "fmtskip7", "fstring", "function", "function2", -- 2.39.5