Skip to content

feat(readFile): add lines range option#23

Merged
CoderSerio merged 2 commits into
mainfrom
feat/read-file-lines
May 4, 2026
Merged

feat(readFile): add lines range option#23
CoderSerio merged 2 commits into
mainfrom
feat/read-file-lines

Conversation

@CoderSerio

@CoderSerio CoderSerio commented May 4, 2026

Copy link
Copy Markdown
Collaborator

Summary

Closes #21 — adds support for reading specific line ranges via the readFile API.

API

await readFile('./test.ts', { lines: { from: 110, to: 120 } })
// reads lines 110–120 (1-based, inclusive)

Implementation

  • Added LineRange struct with from and to fields (1-based, inclusive)
  • Extended ReadFileOptions with optional lines field
  • apply_line_range helper handles slicing, clamping, and edge cases
  • Buffer mode (no encoding) ignores the lines option
  • TypeScript type definitions updated

Edge Cases Handled

Scenario Behavior
from < 1 Returns empty string
from > total lines Returns empty string
to > total lines Clamped to last line
from == to Returns single line
Buffer mode lines ignored, full buffer returned

Tests

5 new test cases, all passing:

  • ✅ Read lines 1–5
  • ✅ Start beyond file length → empty string
  • ✅ Single line (from == to)
  • ✅ Clamp range to file length
  • ✅ Buffer mode ignores lines option

Notes

Current implementation reads the full file then filters by line range. This is sufficient for most AI-coding scenarios. A streaming/seek-based optimization can be explored in a future PR for very large files.

Summary by CodeRabbit

  • New Features
    • Added optional lines parameter to readFile for reading specific line ranges from files. Configure from and to line numbers to extract only needed portions instead of reading entire file contents. Enables efficient processing of large files by limiting data transfers to requested line ranges.

@vercel

vercel Bot commented May 4, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rush-fs-docs Ready Ready Preview, Comment May 4, 2026 7:43am

@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

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

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a3b39ab3-5e99-45d7-a51d-37cd5af53d11

📥 Commits

Reviewing files that changed from the base of the PR and between 6afb469 and 8322803.

📒 Files selected for processing (4)
  • __test__/cp.spec.ts
  • __test__/read_file.spec.ts
  • index.d.ts
  • src/read_file.rs
📝 Walkthrough

Walkthrough

This PR implements a new lines option for readFile() that enables reading a specific range of lines from a file. The feature is declared in TypeScript types, implemented in Rust with line range parsing and slicing logic, and validated with comprehensive tests covering valid ranges, edge cases, and mode interactions.

Changes

Line Range Reading Feature

Layer / File(s) Summary
Type Declarations
index.d.ts, src/read_file.rs
New LineRange interface with from and to fields; ReadFileOptions extended with optional lines?: LineRange.
Core Implementation
src/read_file.rs
apply_line_range() function splits text by \n, validates 1-based inclusive bounds, and returns the selected line segment or empty string for invalid ranges. read_file_impl() applies line slicing when decoding produces text and lines option is present.
Tests & Validation
__test__/read_file.spec.ts
Multiline fixture and 5 test cases covering: specific range reads, out-of-range handling, single-line reads, range clamping, and verification that Buffer mode ignores the lines option.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A rabbit hops through files with glee,
"Just lines 10 to 20," said she,
No need for the rest, we slice with care,
Fewer tokens flying through the air! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(readFile): add lines range option' clearly describes the main change of adding a new lines range feature to the readFile function.
Linked Issues check ✅ Passed The PR implementation fully satisfies issue #21 by providing the requested API to read a specific line range with the exact signature specified: readFile with a lines option containing from and to properties.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the line range feature: TypeScript types, Rust implementation, and comprehensive test coverage with no extraneous modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/read-file-lines

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 11 minutes and 15 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
__test__/read_file.spec.ts (1)

69-113: ⚡ Quick win

Add a CRLF fixture for the new lines option.

All of the new cases use LF-only text, so they won't catch the carriage-return bug in apply_line_range. A Windows-style fixture will lock down the cross-platform behavior here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__test__/read_file.spec.ts` around lines 69 - 113, Existing tests only use
LF-only multilineFixture and won't detect CRLF handling in apply_line_range; add
a Windows-style CRLF fixture (e.g., multilineFixtureCRLF) and a small test that
uses readFile with lines option (use the same cases as one of the existing tests
like "should read a line range" and "should ignore line range in Buffer mode")
to assert that apply_line_range correctly handles '\r\n' line endings; reference
the readFile call in the tests and the apply_line_range function so you add the
CRLF fixture alongside multilineFixture and use it in one or two new test cases
mirroring the LF tests to lock down cross-platform behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/read_file.rs`:
- Around line 95-110: The current apply_line_range uses contents.split('\n')
which leaves CR characters on Windows and creates an extra empty line for
trailing newlines; replace the splitter with contents.lines() to get
newline-aware, cross-platform 1-based semantics. In apply_line_range, collect
lines with contents.lines().collect::<Vec<_>>(), use lines.len() (usize) for
total_lines, compute from as (range.from.saturating_sub(1)) as usize, compute to
as (range.to.min(total_lines as u32)) as usize (or convert range.to to usize
after min), and return lines[from..to].join("\n") so ranges map correctly for
both Unix and CRLF inputs (function: apply_line_range; type: LineRange).

---

Nitpick comments:
In `@__test__/read_file.spec.ts`:
- Around line 69-113: Existing tests only use LF-only multilineFixture and won't
detect CRLF handling in apply_line_range; add a Windows-style CRLF fixture
(e.g., multilineFixtureCRLF) and a small test that uses readFile with lines
option (use the same cases as one of the existing tests like "should read a line
range" and "should ignore line range in Buffer mode") to assert that
apply_line_range correctly handles '\r\n' line endings; reference the readFile
call in the tests and the apply_line_range function so you add the CRLF fixture
alongside multilineFixture and use it in one or two new test cases mirroring the
LF tests to lock down cross-platform behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d6f3edf6-4c5b-4d91-8959-fa3960c0d2ce

📥 Commits

Reviewing files that changed from the base of the PR and between 288401c and 6afb469.

📒 Files selected for processing (3)
  • __test__/read_file.spec.ts
  • index.d.ts
  • src/read_file.rs

Comment thread src/read_file.rs Outdated
Add support for reading specific line ranges via readFile API:
  await readFile('./test.ts', { lines: { from: 110, to: 120 } })

Implementation uses BufReader for streaming line-by-line reading,
avoiding loading the entire file into memory. This makes it suitable
for large files (GB-scale) — memory usage is O(target lines) instead
of O(file size).

Features:
- 1-based inclusive line range selection
- Streaming via BufReader (64KB buffer) — O(1) memory overhead
- Graceful handling of out-of-bounds ranges (empty string)
- Auto-clamping when 'to' exceeds total lines
- Buffer mode (no encoding) ignores lines option
- TypeScript type definitions updated

Edge Cases Handled:
| Scenario | Behavior |
|----------|----------|
| from < 1 | Returns empty string |
| from > total lines | Returns empty string |
| to > total lines | Clamped to last line |
| from == to | Returns single line |
| Buffer mode | lines ignored, full buffer returned |

Closes issue #21
@CoderSerio CoderSerio merged commit 2e21559 into main May 4, 2026
16 checks passed
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.

[Feature]: Read lines between a range

1 participant