Skip to content

Issue 810 - #1260

Merged
jackdewinter merged 3 commits into
mainfrom
issue-810
Nov 17, 2024
Merged

jackdewinter merged 3 commits into
mainfrom
issue-810

Conversation

@jackdewinter

@jackdewinter jackdewinter commented Nov 17, 2024 •

Copy link
Copy Markdown
Owner

closes #810
closes #1259

Summary by Sourcery

Enhance Rule Md012 to support automatic fixing of multiple consecutive blank lines and add comprehensive test coverage for various Markdown structures.

Bug Fixes:

  • Fix asserts and parsing issues related to container handling when blank lines remove all containers.

Enhancements:

  • Add support for fixing Rule Md012, which addresses multiple consecutive blank lines.

Tests:

  • Add extensive test cases for handling multiple consecutive blank lines in various Markdown structures, including lists and block quotes.

@sourcery-ai

sourcery-ai Bot commented Nov 17, 2024 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide by Sourcery

This pull request implements a fix for Rule MD012 (no-multiple-blanks) and fixes issues with container handling in blank lines. The changes primarily focus on improving the handling of consecutive blank lines in Markdown documents and fixing related container parsing issues.

Sequence diagram for handling excess blank lines

sequenceDiagram
    participant RuleMd012
    participant PluginScanContext
    participant MarkdownToken
    participant LeadingSpaceIndexTracker
    Note over RuleMd012: Start processing a new file
    RuleMd012->>RuleMd012: starting_new_file()
    Note over RuleMd012: Process each token
    RuleMd012->>MarkdownToken: next_token(context, token)
    alt token is blank line
        RuleMd012->>RuleMd012: __check_for_excess_blank_lines(context)
        RuleMd012->>RuleMd012: __captured_blank_line.append(token)
    else token is not blank line
        RuleMd012->>RuleMd012: __check_for_excess_blank_lines(context)
    end
    alt token is block quote or list end
        RuleMd012->>RuleMd012: __process_pending_container_end_fixes(context, token)
    end
    RuleMd012->>LeadingSpaceIndexTracker: track_since_last_non_end_token(token)
Loading

Class diagram for RuleMd012 and related classes

classDiagram
    class RuleMd012 {
        - int __blank_lines_maximum
        - int __blank_line_count
        - MarkdownToken __last_blank_line
        - List<MarkdownToken> __captured_blank_line
        - LeadingSpaceIndexTracker __leading_space_index_tracker
        - Dict<MarkdownToken, List<PendingContainerFixes>> __container_fix_map
        + void starting_new_file()
        + void __check_for_excess_blank_lines(PluginScanContext context)
        + void __process_pending_container_end_fixes(PluginScanContext context, MarkdownToken token)
        + void completed_file(PluginScanContext context)
        + void next_token(PluginScanContext context, MarkdownToken token)
    }
    class PendingContainerFixes {
        int leading_space_index
        int repeat_count
    }
    class LeadingSpaceIndexTracker {
        + void clear()
        + void open_container(MarkdownToken token)
        + void register_container_end(MarkdownToken token)
        + void track_since_last_non_end_token(MarkdownToken token)
        + int get_container_stack_size()
        + MarkdownToken get_container_stack_item(int index)
        + int get_tokens_block_quote_bleading_space_index(MarkdownToken token, int alternate_index)
        + int get_tokens_list_leading_space_index(MarkdownToken token, int alternate_index)
    }
    RuleMd012 --> LeadingSpaceIndexTracker
    RuleMd012 --> PendingContainerFixes
Loading

File-Level Changes

Change Details Files
Added fix functionality for Rule MD012 to handle multiple consecutive blank lines
  • Added fix support to Rule MD012 to reduce multiple consecutive blank lines to a single blank line
  • Updated Rule MD012 to handle blank lines within block quotes and lists
  • Added test cases for various blank line scenarios in different container contexts
  • Updated version number of MD012 from 0.6.0 to 0.7.0
pymarkdown/plugins/rule_md_012.py
test/rules/test_md012.py
Fixed container handling for blank lines and improved token management
  • Modified blank line handling in block quotes and lists to properly close containers
  • Fixed issues with leading space tracking in containers
  • Added support for container fix mapping to handle blank line removals
  • Updated token handling to properly manage container end tokens
pymarkdown/general/tokenized_markdown.py
pymarkdown/transform_markdown/transform_containers.py
pymarkdown/plugins/utils/leading_space_index_tracker.py
Enhanced test coverage and fixed test-related issues
  • Added extensive test cases for blank line handling in various container contexts
  • Updated existing tests to reflect new blank line handling behavior
  • Removed redundant test files and consolidated test cases
  • Fixed test assertions and debug flags
test/test_markdown_extra.py
test/nested_three/test_markdown_nested_three_block_unordered_block.py
test/nested_three/test_markdown_nested_three_block_unordered_unordered.py
test/nested_three/test_markdown_nested_three_ordered_block_unordered.py

Assessment against linked issues

Issue Objective Addressed Explanation
#810 Fix token changes in fix engine for MD012 rule ✅
#810 Consider other blanks and how they will compete ✅
#1259 Fix parsing issues with containers (block quotes, lists) being dropped back to zero containers when blank lines are present ✅
#1259 Add fix functionality for Rule MD012 (multiple consecutive blank lines) ✅

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @jackdewinter - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Please add more descriptive PR description explaining the changes made rather than just referencing issue numbers.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

self.__container_fix_map[key] = value_list
value_list.append(value)

def __fix_containers(self) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider extracting duplicate container handling logic into helper methods

The block quote and list handling branches share very similar structure. Consider extracting the common pattern into helper methods to reduce duplication and improve maintainability.

    def __fix_containers(self) -> None:
        self.__fix_block_quotes()
        self.__fix_lists()

    def __fix_block_quotes(self) -> None:
        outer_container_index = (
            self.__leading_space_index_tracker.get_container_stack_size() - 1

def __handle_block_quote_end_calc(
actual_tokens: List[MarkdownToken], search_index: int, current_token_index: int
) -> Tuple[bool, bool]:
) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider keeping tuple return type for better self-documentation

The change from returning a tuple to a single boolean loses semantic meaning. Consider keeping the tuple return type with named variables to better document the intent of the return value.

    ) -> Tuple[bool, bool]:  # type: ignore

md009 no-trailing-spaces True True 0.6.0 Yes
md010 no-hard-tabs True True 0.6.0 Yes
md011 no-reversed-links True True 0.5.0 No
md012 no-multiple-blanks True True 0.6.0 No

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Consider adding tests for new fixable rule functionality

The change indicates that rule md012 is now fixable (Yes) and has a version bump. Should there be additional tests added to verify the new fix functionality?

def test_md012_fix():
    """Test that md012 rule correctly fixes multiple blank lines."""
    input_text = "Line 1\n\n\n\nLine 2"
    expected = "Line 1\n\nLine 2"
    result = fix_multiple_blanks(input_text)
    assert result == expected

index -= adjust
return index

def __calculate_adjust(self, initial_index: int, container_index: int) -> int:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting the adjustment logic into a dedicated method with clear intent

The __calculate_adjust method introduces unnecessary complexity with nested conditions and unclear intent. Consider simplifying it to directly express the adjustment logic:

def __should_skip_adjustment(self, initial_index: int, container_index: int) -> bool:
    """Return True if we should skip the standard adjustment (returning 0 instead of 1)"""
    last_closed_info = self.get_closed_container_info(-1)
    return (
        initial_index >= 1 
        and not container_index 
        and last_closed_info.adjustment
    )

def get_tokens_list_leading_space_index(
    self, token: MarkdownToken, alternate_index: int = -1
) -> int:
    initial_index = self.get_container_stack_size() - 1
    container_index = alternate_index
    last_closed_info = self.get_closed_container_info(-1)

    assert not last_closed_info.adjustment

    # Determine if we need the standard +1 adjustment
    adjustment = 0 if self.__should_skip_adjustment(initial_index, container_index) else 1

    return (
        LeadingSpaceIndexTracker.calculate_token_line_number(token)
        - self.get_container_stack_item(initial_index).line_number
        - last_closed_info.adjustment 
        - adjustment
    )

This refactoring:

  1. Gives the adjustment logic a clear, descriptive name
  2. Removes the complex assertion in favor of more explicit logic
  3. Simplifies the index calculation by clearly separating the adjustment determination

@codecov

codecov Bot commented Nov 17, 2024 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (ab8a5de) to head (a8179a7).
Report is 29 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main     #1260      +/-   ##
===========================================
+ Coverage   99.98%   100.00%   +0.01%     
===========================================
  Files         191       191              
  Lines       21197     21304     +107     
  Branches     2716      2731      +15     
===========================================
+ Hits        21193     21304     +111     
+ Misses          1         0       -1     
+ Partials        3         0       -3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@jackdewinter
jackdewinter merged commit 5a8b409 into main Nov 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Double drop of containers back to zero containers not working properly. MD012: Add Fix

1 participant