Skip to content

feat(fetcher): add code_loc for tracked-line counts per language - #167

Merged
unhappychoice merged 2 commits into
mainfrom
feat/code-loc
Apr 27, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/code-loc

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

New code_loc fetcher 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_loc checkbox on #62.

Kind Safety Shapes
cached Safe text, text_block, markdown_text_block, entries, bars, ratio, number_series, badge

Shapes

Shape What it carries
text "12,345 lines across 6 languages" summary
text_block aligned "Language count" rows
markdown_text_block - **Rust** 8,234 bullet list, for text_markdown
entries / bars per-language count, for table / chart
ratio primary language share (0..=1) + label + denominator, for gauge_*
number_series sorted-desc per-language counts, for chart_sparkline / chart_histogram
badge tier (toy / small / medium / large / huge) with Status mapping, for status_badge

Options

Option Type Required Default Description
limit integer no 10 Cap on rendered languages (TextBlock / MarkdownTextBlock / Entries / Bars / NumberSeries).
unit loc | kloc | percent (alias %) no loc Display format for counts. Percent falls back to loc for Text and kloc for Badge; Ratio / NumberSeries ignore 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 the animated_* post-process wrappers.

Implementation notes

  • Refactor: src/fetcher/code.rs → src/fetcher/code/{mod,scan,languages,todos,loc}.rs. The shared for_each_tracked_file walker now backs both code_todos and code_loc, so future code_* siblings (code_languages, code_largest_files) can ride on it.
  • Language map (src/fetcher/code/languages.rs) covers ~50 extensions plus bare-name detection (Dockerfile, Makefile, Rakefile, Gemfile). Reusable target for future code_language_logo (meta: fetcher roadmap - Local / System #62).
  • Unknown extensions bucket into "Other" so the total stays honest.

Exclusion hardening (benefits code_todos too)

  • New EXCLUDED_FILENAMES for 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 repo Cargo.lock alone is ~6k lines and would have dominated 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 now bounds real reads only — exclusion-skipped index entries no longer eat the budget.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test — 934 / 934 pass (28 new code_loc cases + 4 languages + 2 scan exclusion tests)
  • cargo run --bin splashboard -- catalog fetcher code_loc shows 8 shapes + 2 options + all compatible renderers
  • Smoke-tested locally with a multi-shape dashboard

🤖 Generated with Claude Code

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]>
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 39 minutes and 11 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: 60977d6c-9398-4342-a2eb-8432055d77e4

📥 Commits

Reviewing files that changed from the base of the PR and between 637c517 and b2362b8.

📒 Files selected for processing (1)
  • src/fetcher/code/loc.rs
📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
Language Classification
src/fetcher/code/languages.rs
New module providing file extension-to-language mapping with special filename recognition (Dockerfile, Makefile, etc.) and case-insensitive extension matching. Returns language label or None for unclassified/dotfiles. Includes unit tests for known extensions, special names, unknowns, and dotfiles.
Shared Scanning Logic
src/fetcher/code/scan.rs
New shared file scanner for git-tracked files with layered filtering: excludes directory segments and basenames from configured lists, enforces 1 MiB file size cap, detects binaries via NUL-byte heuristic, and limits scans to 100k files. Exposes for_each_tracked_file() helper and related utility functions. Includes validation tests for segment/basename matching and binary detection.
Code LOC Fetcher
src/fetcher/code/loc.rs
New fetcher implementation counting UTF-8 lines per language using languages::classify() for classification. Supports multiple render shapes (Text, TextBlock, Entries, Bars) with configurable language row limit (default 10). Implements cache key generation incorporating serialized options. Includes comprehensive tests for scanning, aggregation, rendering, comma formatting, and option parsing.
Module Organization
src/fetcher/code/mod.rs
New module entry point declaring submodules (languages, loc, scan, todos), re-exporting CodeLoc and CodeTodos, and exposing fetchers() function that returns boxed trait objects for shared ownership and dynamic dispatch.
CodeTodos Refactoring
src/fetcher/code/todos.rs
Refactored to use shared for_each_tracked_file() helper from scan.rs, removing duplicated file iteration, filtering logic, and fetchers() function. Test imports updated for new module structure.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • feat(fetcher): add code_todos #114: Refactors code fetchers (CodeTodos) to use the new shared for_each_tracked_file() scanning helper, exclusion lists, and filtering heuristics introduced alongside new CodeLoc and scan modules for unified repository file discovery across code metrics.

Poem

🐰 Hopping through commits with tests all in place,
Languages classified with elegance and grace,
Lines counted swiftly by lexicon's embrace,
A shared scanning pathway quickens the pace,
Code metrics refined in this architectural space! 📊

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.96% 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
Title check ✅ Passed The PR title clearly and concisely describes the main change: adding a new code_loc fetcher for tracking line counts per language in repositories.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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/code-loc

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

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

@codecov

codecov Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.70482% with 75 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.34%. Comparing base (a7f0445) to head (b2362b8).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/code/loc.rs 87.70% 67 Missing ⚠️
src/fetcher/code/scan.rs 90.14% 7 Missing ⚠️
src/fetcher/code/todos.rs 75.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/fetcher/code/languages.rs 100.00% <100.00%> (ø)
src/fetcher/code/mod.rs 100.00% <100.00%> (ø)
src/fetcher/code/todos.rs 84.91% <75.00%> (ø)
src/fetcher/code/scan.rs 90.14% <90.14%> (ø)
src/fetcher/code/loc.rs 87.70% <87.70%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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 (2)
src/fetcher/code/loc.rs (2)

220-231: Optional: consider num-format (or similar) for thousands separators.

format_with_commas is 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 char cast is safe because u64::to_string only 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: TextBlock rendering 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

📥 Commits

Reviewing files that changed from the base of the PR and between a7f0445 and 637c517.

📒 Files selected for processing (5)
  • src/fetcher/code/languages.rs
  • src/fetcher/code/loc.rs
  • src/fetcher/code/mod.rs
  • src/fetcher/code/scan.rs
  • src/fetcher/code/todos.rs

Comment thread src/fetcher/code/scan.rs
Comment on lines +93 to +110
// 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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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

1 participant