Skip to content

Ensure uniform column widths#9

Merged
leynos merged 1 commit intomainfrom
codex/uniformly-pad-table-columns
Jun 13, 2025
Merged

Ensure uniform column widths#9
leynos merged 1 commit intomainfrom
codex/uniformly-pad-table-columns

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 13, 2025

Summary

  • pad table columns to equal width
  • test uniform width behaviour on sample tables
  • expose split_cells for doctests
  • fix doctest snippets
  • verify markdown outside of tables is unchanged
  • fix clippy errors in integration tests

Testing

  • cargo clippy -- -D warnings
  • cargo clippy --tests -- -D warnings
  • cargo test

https://chatgpt.com/codex/tasks/task_e_684c6cef66708322aba3799b34b2a8f8

Summary by Sourcery

Compute and apply uniform column widths when reflowing Markdown tables and ensure non-table lines remain unchanged

New Features:

  • Expose split_cells as a public API for doctests

Bug Fixes:

  • Fix doctest snippets to include necessary use statements
  • Resolve clippy errors in integration tests

Enhancements:

  • Pad each table cell to the maximum column width when reflowing tables

Documentation:

  • Update documentation examples with correct imports and add no_run annotation where appropriate

Tests:

  • Add integration tests verifying uniform column width behaviour on sample tables
  • Add tests to ensure non-table lines are left unchanged

Summary by CodeRabbit

  • Documentation
    • Updated the README with a brief description of the project.
  • New Features
    • Improved Markdown table reflow to ensure consistent column widths in the output.
  • Bug Fixes
    • Non-table lines in Markdown documents are now preserved without modification during processing.
  • Style
    • Updated test formatting to use modern Rust string interpolation.
  • Tests
    • Added new integration tests to verify table alignment and preservation of non-table content.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 13, 2025

Reviewer's Guide

This PR refactors table reflow logic to compute and apply uniform column widths, exposes internal helpers for doctests, updates examples accordingly, and adds integration tests to verify uniform padding and non-table line preservation.

File-Level Changes

Change Details Files
Refactor reflow_table to enforce uniform column widths
  • Iterate rows into a cleaned Vec instead of chaining map
  • Compute max width per column by scanning all rows
  • Pad each cell to its column width before joining
src/lib.rs
Make split_cells public and update doctest imports
  • Change split_cells to pub fn
  • Add use mdtablefix::split_cells in examples
  • Update other doctests to import reflow_table and process_stream
src/lib.rs
Add new integration tests for uniform width and non-table lines
  • Introduce test_uniform_example_one and test_uniform_example_two
  • Add test_non_table_lines_unchanged to verify untouched markdown
  • Use dynamic width assertions on reflow_table output
tests/integration.rs
Fix existing tests and clippy lints
  • Replace writeln!(f, "{}", line) with writeln!(f, "{line}")
  • Add no_run to doctest code blocks
  • Resolve clippy warnings in integration tests
tests/integration.rs
src/lib.rs

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. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the 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 exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 13, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 12 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 57c78e9 and 98e2209.

📒 Files selected for processing (1)
  • README.md (1 hunks)

Walkthrough

The updates introduce improved Markdown table formatting by refactoring the reflow_table function to ensure uniform column widths, make the split_cells function public, and enhance documentation and usage examples. Additional integration tests verify that table columns are consistently aligned and that non-table content remains unchanged.

Changes

File(s) Change Summary
README.md Added a descriptive line explaining the project's purpose below the project generation note.
src/lib.rs Made split_cells public; refactored reflow_table for consistent column widths; updated examples.
tests/integration.rs Updated a format string; added four new integration tests for table reflow and non-table content.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Library
    User->>Library: Call reflow_table(input)
    Library->>Library: Split rows into cells
    Library->>Library: Calculate max column widths
    Library->>Library: Pad each cell to column width
    Library->>User: Return reflowed table string
Loading

Possibly related PRs

Poem

A table reflows, neat and wide,
With columns now aligned with pride.
Cells are padded, lines are straight,
Markdown tables looking great!
Tests ensure it’s all just right—
The rabbit hops with pure delight.
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

  • The two-phase approach in reflow_table (first building cleaned, then computing widths) could be merged into a single pass to improve readability and avoid scanning the data twice.
  • Dropping all empty cell strings with row.retain(|c| !c.is_empty()) will remove intentionally blank columns—consider preserving empty strings and only padding missing cells instead.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The two-phase approach in reflow_table (first building `cleaned`, then computing `widths`) could be merged into a single pass to improve readability and avoid scanning the data twice.
- Dropping all empty cell strings with `row.retain(|c| !c.is_empty())` will remove intentionally blank columns—consider preserving empty strings and only padding missing cells instead.

## Individual Comments

### Comment 1
<location> `tests/integration.rs:209` </location>
<code_context>
+        "* bullet".to_string(),
+        String::new(),
+    ];
+    assert_eq!(output, expected);
+}
</code_context>

<issue_to_address>
Add a test case for `process_stream` with input containing no tables.

Add a test where the input contains only non-table Markdown elements to verify that `process_stream` returns the input unchanged.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    Command::cargo_bin("mdtablefix")
        .unwrap()
        .success()
        .stdout("| A | B |\n| 1 | 2 |\n| 3 | 4 |\n");
}

#[test]
fn test_uniform_example_one() {
=======
    Command::cargo_bin("mdtablefix")
        .unwrap()
        .success()
        .stdout("| A | B |\n| 1 | 2 |\n| 3 | 4 |\n");
}

#[test]
fn test_process_stream_no_tables() {
    let input = vec![
        "# Heading".to_string(),
        String::new(),
        "Some paragraph text.".to_string(),
        String::new(),
        "* List item 1".to_string(),
        "* List item 2".to_string(),
        String::new(),
        "> Blockquote".to_string(),
        String::new(),
        "1. Numbered list".to_string(),
        String::new(),
    ];
    let output = process_stream(input.clone());
    assert_eq!(output, input);
}

#[test]
fn test_uniform_example_one() {
>>>>>>> REPLACE

</suggested_fix>

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.

Comment thread tests/integration.rs
@leynos leynos force-pushed the codex/uniformly-pad-table-columns branch from 57c78e9 to 98e2209 Compare June 13, 2025 21:14
@leynos leynos merged commit 014e1e2 into main Jun 13, 2025
0 of 2 checks passed
@leynos leynos deleted the codex/uniformly-pad-table-columns branch June 13, 2025 21:14
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/lib.rs (1)

86-107: ⚠️ Potential issue

Empty-cell stripping corrupts table structure

row.retain(|c| !c.is_empty()) (and the earlier filter(|c| !c.is_empty())) silently drop legitimately empty cells.
For a row such as | Alice | | 42 |, the empty Age column disappears and the data shift one position to the left, producing an invalid table.

-        row.retain(|c| !c.is_empty());
-        while row.len() < max_cols {
-            row.push(String::new());
-        }
+        // Keep *all* cells – blank cells are meaningful.
+        if row.len() < max_cols {
+            row.extend(std::iter::repeat(String::new()).take(max_cols - row.len()));
+        }

You also need to compute max_cols from row.len() (not the non-empty count) and remove the corresponding filter(...).count() logic above.

Failing to fix this will yield data loss and wrong column alignment when blank cells are present.

🧹 Nitpick comments (4)
src/lib.rs (2)

58-60: Compile the sentinel regex once

Regex::new is executed every time reflow_table runs, incurring unnecessary recompilation overhead.
Move it into a lazy_static! / once_cell::sync::Lazy so it is compiled once and re-used.


108-124: Minor: tailor the separator row for nicer output

The current padding inserts spaces into the --- alignment row, e.g. | --- || --- |.
While valid CommonMark, visually it looks odd.
Consider detecting rows that consist solely of -, :, and spaces and extending them with '-' instead of spaces:

if row.iter().all(|c| c.trim_matches(':').chars().all(|ch| ch == '-')) {
    // rebuild with repeated '-' up to widths[i]
}

Purely cosmetic, feel free to skip.

README.md (1)

5-5: Tiny wording tweak

“A tool for reflowing Markdown tables …” reads a bit smoother than “A tool to reflow …”, but this is purely stylistic.

tests/integration.rs (1)

134-210: Width check includes leading spaces

The uniform-width tests measure str::len() on the raw split cells, which retain the leading space after the pipe.
Although the test passes today, trimming would make the intent clearer:

-            assert_eq!(col.len(), widths[i]);
+            assert_eq!(col.trim().len(), widths[i].saturating_sub(1));

Not mandatory, but avoids future confusion if the join delimiter changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 959117f and 57c78e9.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/lib.rs (5 hunks)
  • tests/integration.rs (2 hunks)
🔇 Additional comments (1)
tests/integration.rs (1)

124-125: Good use of the new {ident} formatting syntax

Switching to writeln!(f, "{line}") is concise and idiomatic. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant