Repository navigation
feat(fetcher): add code_loc for tracked-line counts per language - #167
Conversation
Snapshot LOC over the discovered git repo's HEAD, classified by extension (plus Dockerfile / Makefile / Rakefile / Gemfile bare-name detection). Emits four shapes from one read: - Text: "12,345 lines across 6 languages" - TextBlock: aligned "Language count" rows - Entries: key/value rows for grid_table - Bars: label/value bars for chart_bar / chart_pie / list_ranking Refactor the index walker out of `code_todos` into a shared `code/scan.rs` helper (`for_each_tracked_file`) so both fetchers benefit from one set of exclusion rules. Tightens those rules: - Lockfile basenames (`Cargo.lock`, `package-lock.json`, `go.sum`, `flake.lock`, `Gemfile.lock`, …) skipped via new EXCLUDED_FILENAMES. Otherwise `Cargo.lock` alone (~6k lines) dominates the LOC summary. - EXCLUDED_DIRS extended with framework caches (`.next`, `.nuxt`, `.svelte-kit`, `.turbo`, `.cache`), generated outputs (`out`, `_build`, `_site`, `DerivedData`, `Pods`), coverage reports (`coverage`, `htmlcov`), and test/snapshot dirs (`__snapshots__`, `__pycache__`). - `MAX_FILES_SCANNED` budget now counts only files we actually read, so a committed `target/` or `node_modules/` no longer exhausts the cap before reaching real source. Tracks #164. Ticks the `code_loc` checkbox on #62. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Rate limit exceeded
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 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. 📝 WalkthroughWalkthroughThe PR introduces code metric fetchers including a shared file scanning utility for git-tracked files with language classification and line-of-code counting, while refactoring the existing CodeTodos module to reuse the shared scanning logic. Changes
Sequence DiagramsequenceDiagram
participant Ctx as FetchContext
participant CodeLoc as CodeLoc Fetcher
participant Scan as scan.rs
participant Repo as git Repository
participant Classify as languages.rs
participant Render as Renderer
Ctx->>CodeLoc: fetch(ctx)
CodeLoc->>Scan: for_each_tracked_file(repo, visitor)
Scan->>Repo: enumerate tracked files from index
loop for each tracked file
Scan->>Scan: apply exclusion filters<br/>(dir, filename, size, binary)
alt file passes filters
Scan->>Scan: read file bytes from disk
Scan->>CodeLoc: visit(path, bytes)
CodeLoc->>Classify: classify(path)
Classify-->>CodeLoc: language label or None
CodeLoc->>CodeLoc: aggregate line count<br/>per language bucket
end
end
CodeLoc->>CodeLoc: rank languages by<br/>descending line count
CodeLoc->>Render: render(shape, options)
Render-->>CodeLoc: formatted output
CodeLoc-->>Ctx: Payload with results
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #167 +/- ##
==========================================
+ Coverage 78.06% 78.34% +0.27%
==========================================
Files 124 128 +4
Lines 23783 24394 +611
==========================================
+ Hits 18567 19112 +545
- Misses 5216 5282 +66
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/fetcher/code/loc.rs (2)
220-231: Optional: considernum-format(or similar) for thousands separators.
format_with_commasis correct and well-tested, but a small dedicated crate (num-format,thousands) would handle locale and signed integers with no extra surface area. Not blocking — the current implementation is fine and the*b as charcast is safe becauseu64::to_stringonly emits ASCII digits.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/code/loc.rs` around lines 220 - 231, format_with_commas currently implements ASCII-only thousands separation manually; replace it with a small formatting crate (e.g., add and use num_format::ToFormattedString or thousands) to handle locale-aware separators and signed integers robustly. Update the function reference (format_with_commas) to call the chosen crate's formatting API (or provide a thin wrapper that calls ToFormattedString on the number) and adjust imports; ensure tests still cover existing behavior or update them to assert the crate-produced output.
79-102: Minor:TextBlockrendering doesn't align numbers, which contradicts the sample.The sample at Lines 82-87 shows right-aligned numbers in a fixed-width column (
"Rust 8,234","TOML 560"— both exactly 18 chars with the count right-aligned). However the actual rendering at Line 176 (format!("{:<14} {}", lang, format_with_commas(n))) only left-pads the language to 14 chars and appends the count without right-alignment, so real output ends up looking like:Rust 8,234 TypeScript 2,111 Markdown 820 TOML 560— numbers won't column-align across rows. Either fix the format string to right-align the count to a fixed width, or update the sample to reflect what users will actually see (so the catalog preview matches reality).
♻️ Proposed fix: right-align counts in TextBlock
Shape::TextBlock => Body::TextBlock(TextBlockData { lines: totals .by_language .into_iter() .take(limit) - .map(|(lang, n)| format!("{:<14} {}", lang, format_with_commas(n))) + .map(|(lang, n)| format!("{:<14} {:>10}", lang, format_with_commas(n))) .collect(), }),Also applies to: 169-204
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/code/loc.rs` around lines 79 - 102, The TextBlock sample in sample_body (Shape::TextBlock -> samples::text_block) shows right-aligned counts but the actual formatter uses format!("{:<14} {}", lang, format_with_commas(n)), which left-pads the language only and leaves counts unaligned; fix by changing that formatting to reserve a fixed width for the count and right-align it (e.g., adjust the format string so the count is formatted with a width like format!("{:<14} {:>4}", lang, format_with_commas(n)) or similar), or alternatively update the samples passed to samples::text_block to reflect the current output; locate and change the formatting expression used when building TextBlock rows or update the sample strings in sample_body accordingly.
🤖 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/fetcher/code/scan.rs`:
- Around line 93-110: The scanned counter is incremented too early (before
metadata/size/read/binary checks), so move the scanned += 1 increment to just
before the actual visitation call (i.e., immediately before visit(path_str,
&bytes)); keep all existing early-returns (std::fs::metadata, metadata.len() >
FILE_SIZE_CAP, std::fs::read, looks_binary) so they do not consume the scan
budget, and ensure the logic around workdir.join, FILE_SIZE_CAP, looks_binary,
and the visit(...) call remains otherwise unchanged.
---
Nitpick comments:
In `@src/fetcher/code/loc.rs`:
- Around line 220-231: format_with_commas currently implements ASCII-only
thousands separation manually; replace it with a small formatting crate (e.g.,
add and use num_format::ToFormattedString or thousands) to handle locale-aware
separators and signed integers robustly. Update the function reference
(format_with_commas) to call the chosen crate's formatting API (or provide a
thin wrapper that calls ToFormattedString on the number) and adjust imports;
ensure tests still cover existing behavior or update them to assert the
crate-produced output.
- Around line 79-102: The TextBlock sample in sample_body (Shape::TextBlock ->
samples::text_block) shows right-aligned counts but the actual formatter uses
format!("{:<14} {}", lang, format_with_commas(n)), which left-pads the language
only and leaves counts unaligned; fix by changing that formatting to reserve a
fixed width for the count and right-align it (e.g., adjust the format string so
the count is formatted with a width like format!("{:<14} {:>4}", lang,
format_with_commas(n)) or similar), or alternatively update the samples passed
to samples::text_block to reflect the current output; locate and change the
formatting expression used when building TextBlock rows or update the sample
strings in sample_body accordingly.
🪄 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: cf9b7400-70be-4cb4-82b2-66eea80bed60
📒 Files selected for processing (5)
src/fetcher/code/languages.rssrc/fetcher/code/loc.rssrc/fetcher/code/mod.rssrc/fetcher/code/scan.rssrc/fetcher/code/todos.rs
| // Count toward the I/O budget only here — we want the cap to bound real reads, not | ||
| // index entries skipped by the cheap exclusion checks. Otherwise a committed | ||
| // `target/` or `node_modules/` (5k+ entries each) can exhaust the budget before | ||
| // visiting any real source. | ||
| scanned += 1; | ||
| let abs = workdir.join(path_str); | ||
| let Ok(metadata) = std::fs::metadata(&abs) else { | ||
| continue; | ||
| }; | ||
| if !metadata.is_file() || metadata.len() > FILE_SIZE_CAP { | ||
| continue; | ||
| } | ||
| let Ok(bytes) = std::fs::read(&abs) else { | ||
| continue; | ||
| }; | ||
| if looks_binary(&bytes) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Minor: MAX_FILES_SCANNED counts files reaching the I/O step, not files that get visited.
scanned increments at Line 97 before the metadata / size-cap / read / looks_binary checks at Lines 99-110. That means oversized, binary, or metadata-failing files still consume the budget. The PR description says "MAX_FILES_SCANNED now counts only actually read files", but the code as written counts attempted reads (including ones that bail before/after the read).
The in-code comment (Lines 93-96) accurately describes the intent ("bound real reads, not index entries skipped by the cheap exclusion checks"), so this is mostly a description-vs-code wording mismatch. If you want the counter to literally bound visited files, move scanned += 1 to just before visit(path_str, &bytes). Otherwise the current placement is fine for capping I/O syscalls.
♻️ Optional: defer the increment to actual visit
- // Count toward the I/O budget only here — we want the cap to bound real reads, not
- // index entries skipped by the cheap exclusion checks. Otherwise a committed
- // `target/` or `node_modules/` (5k+ entries each) can exhaust the budget before
- // visiting any real source.
- scanned += 1;
let abs = workdir.join(path_str);
let Ok(metadata) = std::fs::metadata(&abs) else {
continue;
};
if !metadata.is_file() || metadata.len() > FILE_SIZE_CAP {
continue;
}
let Ok(bytes) = std::fs::read(&abs) else {
continue;
};
if looks_binary(&bytes) {
continue;
}
+ // Count only files actually handed to the visitor — the cap bounds visited
+ // sources, not index entries cheaply excluded or filtered by metadata/binary checks.
+ scanned += 1;
visit(path_str, &bytes);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/code/scan.rs` around lines 93 - 110, The scanned counter is
incremented too early (before metadata/size/read/binary checks), so move the
scanned += 1 increment to just before the actual visitation call (i.e.,
immediately before visit(path_str, &bytes)); keep all existing early-returns
(std::fs::metadata, metadata.len() > FILE_SIZE_CAP, std::fs::read, looks_binary)
so they do not consume the scan budget, and ensure the logic around
workdir.join, FILE_SIZE_CAP, looks_binary, and the visit(...) call remains
otherwise unchanged.
Adds the four shapes left on the table from the initial pass plus a display-format toggle, all from the same single HEAD-snapshot read: - `MarkdownTextBlock` — `- **Rust** 8,234` markdown list, for `text_markdown` consumers. - `Ratio` — primary language's share (0..=1) with the language name as label and total lines as denominator, for `gauge_*` renderers. - `NumberSeries` — sorted-desc per-language counts, for `chart_sparkline` / `chart_histogram` distribution sketches. - `Badge` — order-of-magnitude tier (`toy` <1k, `small` <10k, `medium` <100k, `large` <1M, `huge` ≥1M) with Status mapping (Ok / Warn / Error), for `status_badge`. New `unit` option toggles count formatting across the rendered shapes: unit = "loc" # default — "1,234" unit = "kloc" # "1.2k" unit = "percent" # "67.8%" (alias "%") Sensible fallbacks where percent doesn't apply: `Text` summary drops back to raw counts, `Badge` drops back to kloc, `Ratio` and `NumberSeries` ignore the option entirely (Ratio is always 0..=1; NumberSeries renderers normalise values visually). Brings `code_loc` from 4 → 8 shapes, lighting up `text_markdown`, `gauge_circle` / `gauge_battery` / `gauge_segment` / `gauge_thermometer`, `chart_sparkline` / `chart_histogram`, and `status_badge` as compatible renderers. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
New
code_locfetcher counts tracked source lines per language across the discovered git repo. Snapshot at HEAD, 8 shapes from one read.Tracks #164 (project_codebase preset). Ticks the
code_loccheckbox on #62.text,text_block,markdown_text_block,entries,bars,ratio,number_series,badgeShapes
text"12,345 lines across 6 languages"summarytext_block"Language count"rowsmarkdown_text_block- **Rust** 8,234bullet list, fortext_markdownentries/barsratiogauge_*number_serieschart_sparkline/chart_histogrambadgetoy/small/medium/large/huge) with Status mapping, forstatus_badgeOptions
limitTextBlock/MarkdownTextBlock/Entries/Bars/NumberSeries).unitloc|kloc|percent(alias%)loclocforTextandklocforBadge;Ratio/NumberSeriesignore it.Compatible renderers
Lights up
text_plain/text_ascii/list_plain/text_markdown/grid_table/chart_bar/chart_pie/chart_sparkline/chart_histogram/list_ranking/gauge_battery/gauge_circle/gauge_line/gauge_segment/gauge_thermometer/status_badge, plus theanimated_*post-process wrappers.Implementation notes
src/fetcher/code.rs→src/fetcher/code/{mod,scan,languages,todos,loc}.rs. The sharedfor_each_tracked_filewalker now backs bothcode_todosandcode_loc, so futurecode_*siblings (code_languages,code_largest_files) can ride on it.src/fetcher/code/languages.rs) covers ~50 extensions plus bare-name detection (Dockerfile,Makefile,Rakefile,Gemfile). Reusable target for futurecode_language_logo(meta: fetcher roadmap - Local / System #62)."Other"so the total stays honest.Exclusion hardening (benefits
code_todostoo)EXCLUDED_FILENAMESfor machine-written lock files:Cargo.lock,package-lock.json,yarn.lock,pnpm-lock.yaml,bun.lock(b),Gemfile.lock,composer.lock,poetry.lock,Pipfile.lock,uv.lock,go.sum,flake.lock,mix.lock,Podfile.lock. On this repoCargo.lockalone is ~6k lines and would have dominated the LOC summary.EXCLUDED_DIRSextended with framework caches (.next,.nuxt,.svelte-kit,.turbo,.cache), generated outputs (out,_build,_site,DerivedData,Pods), coverage reports (coverage,htmlcov), and test/snapshot dirs (__snapshots__,__pycache__).MAX_FILES_SCANNEDnow bounds real reads only — exclusion-skipped index entries no longer eat the budget.Test plan
cargo fmt --all -- --checkcargo clippy --all-targets -- -D warningscargo test— 934 / 934 pass (28 newcode_loccases + 4languages+ 2scanexclusion tests)cargo run --bin splashboard -- catalog fetcher code_locshows 8 shapes + 2 options + all compatible renderers🤖 Generated with Claude Code