Skip to content

Implement markdown table fixer#1

Merged
leynos merged 4 commits intomainfrom
codex/implement-rust-tool-to-reflow-markdown-tables
Jun 13, 2025
Merged

Implement markdown table fixer#1
leynos merged 4 commits intomainfrom
codex/implement-rust-tool-to-reflow-markdown-tables

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 13, 2025

Summary

  • implement table reflow logic in library crate
  • provide CLI for fixing markdown files
  • add tests with rstest

Testing

  • cargo clippy -- -D warnings
  • cargo test
  • npx markdownlint-cli2 '**/*.md' '#node_modules' (fails: 339 errors)
  • npx nixie '**/*.md' '#node_modules' (failed: Syntax error)

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

Summary by Sourcery

Implement a markdown table fixer by adding reflow logic in a library crate, wiring up a clap-based CLI for file or stdin processing, and covering behavior with comprehensive tests.

New Features:

  • Implement markdown table reflow functions in the library crate
  • Provide a CLI tool for fixing markdown tables with in-place editing and stdin/stdout support

Enhancements:

  • Skip code fence blocks when processing tables

Build:

  • Add dependencies: anyhow, clap (derive), regex; and dev-dependencies: rstest, assert_cmd, tempfile

Tests:

  • Add unit and integration tests for table reflow and CLI behavior using rstest

Summary by CodeRabbit

  • New Features

    • Introduced a tool to automatically fix and reformat broken markdown tables in documents.
    • Added command-line interface supporting file and standard input processing, with an option to rewrite files in place.
  • Bug Fixes

    • Ensured code blocks within markdown documents are not altered during table reformatting.
  • Tests

    • Added integration tests to verify table fixing, CLI behaviour, and handling of edge cases.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 13, 2025

Reviewer's Guide

Implements core markdown table reflow in a library, exposes a clap-based CLI (mdtablefix) with in-place and stdin modes, adds necessary dependencies, and covers functionality with integration tests.

Sequence Diagram: mdtablefix In-Place File Processing

sequenceDiagram
    actor User
    User->>+CLI (mdtablefix): Executes `mdtablefix --in-place file.md`
    CLI (mdtablefix)->>+rewrite (lib.rs): rewrite("file.md")
    rewrite (lib.rs)->>+FileSystem: read_to_string("file.md")
    FileSystem-->>-rewrite (lib.rs): file_content
    rewrite (lib.rs)->>+process_stream (lib.rs): process_stream(file_content)
    process_stream (lib.rs)-->>-rewrite (lib.rs): fixed_content
    rewrite (lib.rs)->>+FileSystem: write("file.md", fixed_content)
    FileSystem-->>-rewrite (lib.rs): success
    rewrite (lib.rs)-->>-CLI (mdtablefix): Ok
    CLI (mdtablefix)-->>-User: (File updated)
Loading

Sequence Diagram: mdtablefix Stdin Processing

sequenceDiagram
    actor User
    User->>+Stdin: Pipes content
    Stdin->>+CLI (mdtablefix): input_stream
    CLI (mdtablefix)->>+process_stream (lib.rs): process_stream(input_content)
    process_stream (lib.rs)-->>-CLI (mdtablefix): fixed_content
    CLI (mdtablefix)->>+Stdout: Prints fixed_content
    Stdout-->>-User: Displays output
Loading

File-Level Changes

Change Details Files
Add markdown table reflow logic in library crate
  • Implement split_cells to parse table rows
  • Add reflow_table to normalize broken tables
  • Implement process_stream to detect and fix tables while preserving code fences
  • Provide rewrite for in‐place file updates
src/lib.rs
Introduce CLI tool with in-place and stdin support
  • Use clap derive to parse --in-place flag and file arguments
  • Validate --in-place requires at least one file
  • Read from stdin when no files provided
  • Invoke process_stream or rewrite based on mode
src/main.rs
Update Cargo.toml with new dependencies and dev-dependencies
  • Add anyhow for error handling
  • Add clap with derive feature for CLI
  • Add regex for table and fence detection
  • Add dev-dependencies rstest, assert_cmd, and tempfile for testing
Cargo.toml
Add integration tests for table reflow and CLI behavior
  • Use rstest fixtures to test basic and malformed tables
  • Verify code fences are ignored in process_stream
  • Test CLI error on missing files with --in-place
  • Test file processing output via assert_cmd and tempfile
tests/integration.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 8 minutes and 36 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 24a583f and 5f82e59.

📒 Files selected for processing (3)
  • src/lib.rs (1 hunks)
  • src/main.rs (1 hunks)
  • tests/integration.rs (1 hunks)

Walkthrough

The changes introduce a Rust library and command-line tool for reflowing and fixing broken markdown tables. New dependencies are added, the main logic for table processing and file rewriting is implemented, and a CLI interface is created using clap. Integration tests are provided to validate core functionality and CLI behaviour.

Changes

File(s) Change Summary
Cargo.toml Added dependencies: anyhow, clap (with "derive"), regex; added dev-dependencies: rstest, assert_cmd, tempfile.
src/lib.rs Introduced core logic: functions to reflow markdown tables, process markdown streams, and rewrite files.
src/main.rs Rewrote main function to implement a CLI with clap, supporting in-place and standard output modes.
tests/integration.rs Added integration tests for table reflow, stream processing, and CLI behaviour using fixtures and temp files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI (main.rs)
    participant Library (lib.rs)
    participant FileSystem

    User->>CLI (main.rs): Run with [--in-place] [files]
    alt No files
        CLI (main.rs)->>User: Read from stdin
        CLI (main.rs)->>Library (lib.rs): process_stream(lines)
        Library (lib.rs)-->>CLI (main.rs): processed_lines
        CLI (main.rs)->>User: Output to stdout
    else With files and --in-place
        loop For each file
            CLI (main.rs)->>Library (lib.rs): rewrite(file_path)
            Library (lib.rs)->>FileSystem: Read & Write file
        end
    else With files, no --in-place
        loop For each file
            CLI (main.rs)->>FileSystem: Read file
            FileSystem-->>CLI (main.rs): file_content
            CLI (main.rs)->>Library (lib.rs): process_stream(lines)
            Library (lib.rs)-->>CLI (main.rs): processed_lines
            CLI (main.rs)->>User: Output to stdout
        end
    end
Loading

Poem

A table askew, a markdown despair,
Now fixed with regex and padding with care.
With clap at the helm, the CLI's spry,
In-place or streamed, your tables won't cry.
Integration tests hop in with glee,
🐇 Markdown mender, as neat as can be!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/main.rs:20` </location>
<code_context>
+fn main() -> anyhow::Result<()> {
+    let cli = Cli::parse();
+
+    if cli.in_place && cli.files.is_empty() {
+        anyhow::bail!("--in-place requires at least one file");
+    }
</code_context>

<issue_to_address>
Use clap's validation to enforce --in-place requires files

Consider using `.requires` on the `in_place` argument or an `ArgGroup` so clap enforces this constraint and provides consistent error messages.

Suggested implementation:

```rust
    /// Rewrite files in place
    #[arg(long = "in-place", requires = "files")]
    in_place: bool,

```

```rust

```
</issue_to_address>

### Comment 2
<location> `src/lib.rs:11` </location>
<code_context>
+
+/// Split a markdown table line into its cells.
+#[must_use]
+fn split_cells(line: &str) -> Vec<String> {
+    let mut s = line.trim();
+    if let Some(stripped) = s.strip_prefix('|') {
</code_context>

<issue_to_address>
split_cells may mis-handle escaped pipes

Consider using a parser or regex that correctly handles escaped pipes (\|) to avoid incorrect cell splitting.
</issue_to_address>

### Comment 3
<location> `src/lib.rs:27` </location>
<code_context>
+/// # Panics
+/// Panics if the internal regex fails to compile.
+#[must_use]
+pub fn reflow_table(lines: &[String]) -> Vec<String> {
+    let raw = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
+    let sentinel_re = Regex::new(r"\|\s*\|\s*").unwrap();
</code_context>

<issue_to_address>
Header separator rows are not preserved

Update the logic to identify and retain header separator rows (e.g., `|---|---|`) to maintain valid markdown formatting after reflow.
</issue_to_address>

### Comment 4
<location> `src/lib.rs:29` </location>
<code_context>
+#[must_use]
+pub fn reflow_table(lines: &[String]) -> Vec<String> {
+    let raw = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
+    let sentinel_re = Regex::new(r"\|\s*\|\s*").unwrap();
+    let chunks: Vec<&str> = sentinel_re.split(&raw).collect();
+    let mut cells = Vec::new();
</code_context>

<issue_to_address>
Avoid recompiling regex on every call

Compiling the regex on each function call is inefficient; use `lazy_static` or `once_cell` to compile it once and reuse it.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
#[must_use]
pub fn reflow_table(lines: &[String]) -> Vec<String> {
    let raw = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
    let sentinel_re = Regex::new(r"\|\s*\|\s*").unwrap();
    let chunks: Vec<&str> = sentinel_re.split(&raw).collect();
    let mut cells = Vec::new();
=======
use once_cell::sync::Lazy;
use regex::Regex;

static SENTINEL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\|\s*\|\s*").unwrap());

#[must_use]
pub fn reflow_table(lines: &[String]) -> Vec<String> {
    let raw = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
    let chunks: Vec<&str> = SENTINEL_RE.split(&raw).collect();
    let mut cells = Vec::new();
>>>>>>> REPLACE

</suggested_fix>

### Comment 5
<location> `src/lib.rs:28` </location>
<code_context>
+/// Panics if the internal regex fails to compile.
+#[must_use]
+pub fn reflow_table(lines: &[String]) -> Vec<String> {
+    let raw = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
+    let sentinel_re = Regex::new(r"\|\s*\|\s*").unwrap();
+    let chunks: Vec<&str> = sentinel_re.split(&raw).collect();
</code_context>

<issue_to_address>
Trimming lines drops indentation

`trim()` removes leading spaces, which may disrupt nested tables. Suggest preserving and restoring indentation.
</issue_to_address>

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 src/main.rs
Comment thread src/lib.rs
Comment thread src/lib.rs
Comment thread src/lib.rs
Comment thread src/lib.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 13, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 13, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 2

♻️ Duplicate comments (3)
src/main.rs (1)

10-14: Let clap enforce the --in-place → files relationship

Instead of the manual runtime check below, add .requires("files") to the in_place arg (or use an ArgGroup).
That way clap gives a consistent error message and the early-return logic can be removed.

-    /// Rewrite files in place
-    #[arg(long = "in-place")]
+    /// Rewrite files in place
+    #[arg(long = "in-place", requires = "files")]
     in_place: bool,
src/lib.rs (2)

29-31: Regex re-compiled on every call – use a static

Regex::new(..) inside reflow_table is executed per invocation.
Move it to a static via once_cell/lazy_static to avoid repeated compilation.


12-13: 🛠️ Refactor suggestion

trim() drops indentation

Calling trim() on every line removes leading spaces, so tables nested in lists lose their indent.
Preserve leading whitespace and restore it when formatting.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ed8dec and 24a583f.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • src/lib.rs (1 hunks)
  • src/main.rs (1 hunks)
  • tests/integration.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/main.rs (1)
src/lib.rs (3)
  • process_stream (85-141)
  • rewrite (147-152)
  • lines (28-28)
tests/integration.rs (1)
src/lib.rs (3)
  • process_stream (85-141)
  • reflow_table (27-78)
  • lines (28-28)
🔇 Additional comments (1)
Cargo.toml (1)

4-4: edition = "2024" requires nightly – verify tool-chain or downgrade to 2021

The 2024 edition is, at the moment, only available on nightly Rust.
Unless the project is intentionally targeting nightly, consider setting edition = "2021" to avoid breaking users who build with stable cargo.

Comment thread src/lib.rs
Comment thread tests/integration.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 13, 2025

@sourcery-ai review

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 and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `tests/integration.rs:33` </location>
<code_context>
+}
+
+#[rstest]
+fn test_process_stream_ignores_code_fences() {
+    let lines = vec![
+        "```".to_string(),
</code_context>

<issue_to_address>
Add a test case for tilde-based code fences (`~~~`) in `process_stream`.

Please add a test case using `~~~` as the code fence to verify this variant is handled correctly.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
#[rstest]
fn test_process_stream_ignores_code_fences() {
    let lines = vec![
        "```".to_string(),
        "| not | a | table |".to_string(),
        "```".to_string(),
    ];
    assert_eq!(process_stream(&lines), lines);
}
=======
#[rstest]
fn test_process_stream_ignores_code_fences() {
    let lines = vec![
        "```".to_string(),
        "| not | a | table |".to_string(),
        "```".to_string(),
    ];
    assert_eq!(process_stream(&lines), lines);

    // Test with tilde-based code fences
    let tilde_lines = vec![
        "~~~".to_string(),
        "| not | a | table |".to_string(),
        "~~~".to_string(),
    ];
    assert_eq!(process_stream(&tilde_lines), tilde_lines);
}
>>>>>>> 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 and others added 2 commits June 13, 2025 19:09
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…les`

Docstrings generation was requested by @leynos.

* #1 (comment)

The following files were modified:

* `src/lib.rs`
* `src/main.rs`
* `tests/integration.rs`
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 13, 2025

Note

Generated docstrings for this pull request at #6

…D5esj42rZYjTqgG31ObYBIhCLJhgeBqlKaS4WfMG5ng8LGP4nFu6yBeIf1

📝 Add docstrings to `codex/implement-rust-tool-to-reflow-markdown-tables`
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