Skip to content

Latest commit

 

History

History
274 lines (191 loc) · 22.5 KB

reports.md

File metadata and controls

274 lines (191 loc) · 22.5 KB

Read Counts, Coverage and Reports

Start with locmetry --root . --format headline at the intended project root. This compact JSON describes the measurement without loading all file records into your context. Use locmetry --schema report for exact fields and omission semantics. Retrieve a full report or a targeted explanation only when the headline leaves a concrete question.

Choose Content and Destination

Task Command
Source counts by language and folder locmetry --root . --format table --show-folders
Source tables with classification, scope and coverage notes locmetry --root . --format table --verbose
Production source only, with its comment density locmetry --root . --format table --table-purpose production
Compact JSON locmetry --root . --format headline
Full JSON on stdout locmetry --root . --format json
Full JSON with per-file decisions locmetry --root . --files --format json
Save a full baseline outside the root locmetry --root service --output before.json
Save a full baseline and print the table, from one scan locmetry --root service --output before.json --print table
Save Markdown and print full per-file JSON locmetry --root service --format markdown --output report.md --print json --files
Save Markdown locmetry --root service --format markdown --output report.md
Page a plain text report locmetry --root service --format table | less

Without explicit options, a terminal gets a table and a pipe gets a headline. Any --output defaults to full JSON; explicit --format wins. --output FILE writes only that file, with empty stdout, unless --print FORMAT adds a view of the same measurement there; --output - selects stdout. Extensions do not infer formats. Files are unstyled. --files requires at least one full JSON view, saved or printed, and affects each full JSON view. A simultaneous headline still omits file records. A headline is not comparison-ready, and cannot reconstruct the omitted baseline later. Aggregate comparison needs full reports, but not per-file records.

Default single-project tables show counted source by language, a reconciliation legend and the measurement date. When Rust production files contain #[cfg(test)] items, a legend line names that code, which counts as production because classification is per file; full JSON reports it as inline_tests. Language variants count within their family's row, such as TSX within TypeScript, and a Folded: line names each fold; --split-languages shows them as their own rows. JSON and breakdown keep the backend's language names, so a JSON language total can differ from a folded row. Add --show-folders for the folder table; workspace member rows remain visible by default. Default tables deliberately omit non-source totals and unrecognized-file counts, and do not prompt for classification. Use locmetry --format table --verbose to inspect notes such as “Unclaimed source” and “Not source code”, build inference and the largest files counted as Production only by a build layout, Git submodule hints and unused policy. To inspect or refine purpose classification, use locmetry --guide configure. locmetry --files --output - shows each file's rule. Markdown and JSON retain their existing detail. --verbose warns without changing the result in non-table measurement formats.

Real read/parse failures remain visible without --verbose: Not counted: summarizes only failures, workspace Unavailable counts: names affected members, and the backend warning, stderr path diagnostic and exit 2 remain. The report's parse-failure path list requires --verbose; unrecognized types use a separate neutral note there. Unclaimed source has been counted and does not itself make the report partial.

Protected export destinations must be outside the scan root (every member's root in workspace mode, which is the project for folders), and cannot overwrite configuration or workspace files. Shell redirection and tee bypass those checks. explain is different: JSON is always complete, with no headline or --output; use locmetry explain --help. Guides and schemas are standalone queries saved by shell redirection, without measurement flags.

For adaptive folder rows and saved tables, see Look inside large folders. --show-folders applies to saved table text and subfolder measurements, warns in non-table formats and is unavailable in workspace mode. --markdown-depth N limits only the Folder breakdown, not deeper review paths; see the depth and applicability contract. --show-categories adds a table view. Explicit ineffective depth/categories warn during measurement. These presentation options do not change counts. Human count tables expose total Lines before Code; Lines = Code + Comments + Blanks, while purpose columns split Code. Table and Markdown end with the measurement time in UTC, from JSON metadata.measured_at_unix_seconds; exported files retain this date independently of filesystem timestamps. Use locmetry --guide selection before changing the measurement root to explore a large folder.

Interpret the Numbers

all_counted includes source, data and documentation. source, purpose totals and language summaries describe source only. Purpose and content kind are separate: a documentation file with purpose other is not unclaimed source. review lists source left unclaimed; deliberate other entries keep their counts but leave that list. Use locmetry --guide configure before deciding how to classify anything.

Full-report breakdown rows describe each file's parent folder, split by kind/purpose/category/language. Sum rows whose folder equals a prefix or starts with that prefix plus / to obtain recursive totals; src must not also match src-old. Breakdown rows are additive, including embedded-language rows with zero files. Language summary file counts instead describe participation and can overlap. Do not sum language file counts to recover physical file counts, or average ratios to compute a total ratio.

Summary fields such as source and empty maps can be omitted where the schema permits that; an emitted count object includes zero-valued counters. Missing .files means per-file detail was not requested; it does not mean no files. Missing full-report sections in a headline are unavailable detail, not zero. Historical missing failure evidence also means “not recorded.” metadata.scope.subfolder, when present, means the summary measures that restriction, not the entire project. Workspace paths are member-prefixed, members have separate policy/coverage, and member sums reconcile with workspace totals. Inspect locmetry workspace --help and locmetry --schema workspace for workspace setup.

Unavailable Is Not Zero

A selected file can be counted, unrecognized, unreadable or a recorded parse failure. metadata.coverage records these distinctions. Recognized-but-unavailable counts set backend_inaccurate; the produced report is partial and exits 2. Exit 1 means an error without a promised usable document. Unrecognized files and unresolved classification do not themselves make counts partial. backend_inaccurate can also be true without identified failure paths, so empty failure lists alone do not establish completeness. Preserve status before parsing output; shell pipelines can otherwise hide it.

In a fresh temporary working directory:

mkdir demo
printf '' > demo/empty.py
printf '{}' > demo/broken.ipynb
locmetry --root demo --no-user-config --files --format json

This exits 2 and warns on stderr. The following checked projection retains coverage totals, each failure's path/reason and each counted file's path/code. An empty Python file is known zero; the invalid notebook contributes no file record, not an invented zero:

{
  "backend_inaccurate": true,
  "selected_files": 2,
  "counted_files": 1,
  "parse_failures": [{"path": "broken.ipynb", "reason": "invalid_notebook"}],
  "files": [{"path": "empty.py", "code": 0}]
}

For one path, use locmetry --guide selection. For historical evidence and partial comparisons, use locmetry --guide compare. JSON Schema validates structure; LOCmetry's reader also checks arithmetic and comparison eligibility. Schema validity alone does not make a headline a full baseline.

Common issues and useful queries

These queries use a small synthetic project named acme-orders, with a prototypes/ folder, run from the directory containing it. They require the optional external jq tool, not a LOCmetry runtime dependency. Personal defaults are disabled for the synthetic examples. These are interactive inspection pipelines; the CI recipe demonstrates preserving partial status.

Which files are unclaimed source?

The files were counted, but no rule, convention or module claimed their purpose. The full report's review list already contains every unclaimed source file, largest first; no --files is needed. List code lines, language and path for prototypes/, including descendants:

locmetry acme-orders --no-user-config --output - | jq -r '.review[] | select(.path | startswith("prototypes/")) | [.code, .language, .path] | @tsv'

Check the same folder's file count and code-line total, including the empty case:

locmetry acme-orders --no-user-config --output - | jq '[.review[] | select(.path | startswith("prototypes/"))] | {files: length, code: (map(.code) | add // 0)}'

For all counted source in web/src/, including production and tests, request file detail instead:

locmetry acme-orders --no-user-config --files --output - | jq -r '.files[] | select(.kind == "source" and (.path | startswith("web/src/"))) | [.counts.code, .purpose, .rule, .path] | @tsv'

Which files have unavailable counts?

locmetry acme-orders --no-user-config --output - | jq '.metadata.coverage'

Which files are not source code?

Content kind is separate from purpose: these files contribute to all_counted, but not source totals. Code embedded in them, such as fenced snippets in Markdown, stays documentation; the verbose note counts its code lines, and each file's languages splits them by language. List their kinds, physical line counts and paths:

locmetry acme-orders --no-user-config --files --output - | jq -r '.files[] | select(.kind != "source") | [.kind, .counts.lines, .path] | @tsv'

For field-level semantics use locmetry --schema report; an optional narrow query is locmetry --schema report | jq '."$defs".Coverage'. PRODUCT owns the contract, and measurement semantics records parser limits.

Look inside large folders

If the table requested with --show-folders concentrates most code in a container such as web or packages, request deeper detail without changing the scan root or classification context:

locmetry acme-orders --folder-rows 30

This enables the Folder table with adaptive detail, without requiring --show-folders as well. The first Language table stays as it is. Large folders expand into non-overlapping child rows, including direct files and scoped “other child folders” rows where needed. Every row still contributes once to the total. The budget counts Folder data rows, excluding its header, total and legends. It limits additional detail; existing top-level contributions are never merged away, so an initially wider table can exceed it. --sort name compares path components, keeping descendants before siblings such as src-old; the same comparison resolves code ties. Single-child chains collapse without using extra rows. Paths stay relative to the project root, including when combined with --subfolder.

--format table is an existing option that selects human-readable text. It is optional in a terminal, where table output is the default. Pipes normally select a JSON headline, and --output defaults to full JSON. Explicitly request table output when saving or paging this view:

locmetry acme-orders --folder-rows 30 --format table --output folders.txt

When the largest displayed row still has folder detail, a gray hint names the folder and suggests increasing --folder-rows. This also covers a largest “other child folders” remainder. Smaller expandable folders alone do not trigger it.

The option changes only the table view, not measurement counts, coverage or the Unclaimed source note requested with --verbose. It cannot accompany JSON output; save full JSON separately when needed. The verbose note uses its existing partition of unclaimed code and can therefore show different folder boundaries. Markdown retains its recursive --markdown-depth view; workspace mode rejects --folder-rows. Adaptive folder semantics defines selection, budgets and limits.

Measure several repositories together

locmetry workspace measures sibling repositories as one virtual monorepo. Each repository is measured with its own .locmetryrc, the repositories run in parallel, and the results merge into one report whose top-level folders are its members, one per repository:

locmetry workspace --root ../web --root ../api

Roots are relative to the current directory or absolute. To avoid repeating them, list them in a workspace file, where they are relative to the file itself or absolute, and name it with --workspace-file; locmetry --schema workspace describes the format:

version = 1
roots = ["web", "api", "/srv/shared/billing"]
locmetry workspace --workspace-file repos.toml
  • Each member keeps its policy: --config, --exclude, --hidden, and --respect-ignore-files are rejected, because each member's own configuration decides them, and options must follow workspace.
  • Paths name the member: every path is prefixed with its member's folder name, such as web/src/index.ts. Two members with the same folder name, a root given twice, or one root inside another fail before measuring.
  • Members as a dimension: summary.members holds each member's totals by purpose, category, kind, and language, equal to a regular run of that member. The table shows one row per member with its Test Code divided by Production Code and its share of the workspace, and the Markdown report adds grids of source categories and languages by member.
  • Findings stay with their member: metadata.members lists each member's root, configuration path, scope, coverage counts, unused entries, and unused exclusions; verbose table notes name the member, as in ghost (web), and list unclaimed source by member. Default and verbose tables name members with read/parse failures under Unavailable counts:; Markdown retains comprehensive member findings.
  • All or nothing, always the same: if one member fails, for example with an invalid configuration, the run fails and names it; the order of the roots never changes the report.

For the components of one repository, name folders of that project instead of roots. Each folder is then a member. Every folder is measured as --subfolder measures it, under the project's single .locmetryrc, so no member needs a configuration of its own:

version = 1
project = "."
folders = ["server", "web", "mobile"]

The members are named after the folders' last segments, and files outside every folder are not measured. The shared policy's unused entries and exclusions are those unused in every folder; they appear once in summary.unused_entries and summary.unused_exclusions and in verbose notes without a member name. summary.policy_entries counts the shared policy's entries once over all folders. Independent roots instead record their own entries as metadata.members[].policy_entries.

Query a Saved Report

Save full JSON outside the measured root. These queries require jq and use the synthetic acme-orders project of locmetry --guide reports --section common-issues-and-useful-queries, run from the directory containing it; a headline cannot supply the full breakdown and review sections.

locmetry acme-orders --no-user-config --output report.json

Sum test code by language across additive breakdown rows:

jq '[.breakdown[] | select(.kind == "source" and .purpose == "test")] | group_by(.language) | map({language: .[0].language, code: (map(.code) | add)})' report.json

Sum source code by purpose under web/, including descendants but not similarly named siblings:

jq '[.breakdown[] | select(.kind == "source" and (.folder == "web" or (.folder | startswith("web/"))))] | group_by(.purpose) | map({purpose: .[0].purpose, code: (map(.code) | add)})' report.json

Inspect files whose purpose remains unresolved; aggregate queries and this review list need no --files:

jq '.review[]' report.json

Continuous integration

Capture the measurement before applying a policy check, preserving LOCmetry's exit status. This script refuses partial reports, fails when more than 50 source lines remain unclaimed, and prints the test/production ratio only when production code is nonzero. jq -e fails when the policy expression is false:

set -eu
report=$(locmetry --format headline) || exit "$?"
printf '%s\n' "$report" | jq -e '([.summary.unclaimed_folders[].code] | add // 0) <= 50'
printf '%s\n' "$report" | jq -r '
  (.summary.source_purpose // {}) as $p |
  if ($p.production.code // 0) == 0 then
    "test/production: n/a (no production code)"
  else
    "test/production: \(($p.test.code // 0) * 100 / $p.production.code | floor)%"
  end'

To gate source file sizes by purpose, use the recipes in Gate file sizes.

CI executes these blocks and the comparison/explanation workflows against synthetic projects. The policy scenarios check stdout and stderr as well as status, so invalid configuration cannot masquerade as an unclaimed-code rejection. The Cargo tests separately guard its JSON and exit-code assumptions without requiring jq.

Command outcomes defines exit statuses for measurement, comparison and explanation, including backend inaccuracy without identified failure paths.

Gate file sizes

LOCmetry records what each file is for, so a gate can hold production code to a tighter limit than tests and leave generated code alone, without maintaining path patterns. LOCmetry itself enforces no limit: its exit status reports the measurement, and these scripts apply limits to the per-file records of --files, whose fields the report contract owns. This script fails on every production file over 1,000 code lines and every test file over 2,000, listing them on stderr. A purpose without a limit is not checked, so generated and unclaimed code in Other never fails the gate:

set -eu
report=$(locmetry --files --output -) || exit "$?"
printf '%s\n' "$report" | jq -e '
  {production: 1000, test: 2000} as $limit |
  [.files[] | select(.kind == "source" and $limit[.purpose] != null and .counts.code > $limit[.purpose])
   | "\(.path): \(.counts.code) code lines over the \(.purpose) limit of \($limit[.purpose])"] |
  if length == 0 then true else (join("\n") + "\n" | halt_error(1)) end'

Add .language == "Rust" to the selection to limit one language. A purpose without a limit is not checked; name other in $limit to check generated and unclaimed code too.

Warn before failing and freeze existing large files

A soft limit warns while a split is still cheap. A ceiling lets a file that predates the limits keep its current size, and fails as soon as it grows. Keep both in a policy file beside the script, for example file-size-limits.json:

{
  "limits": {
    "production": {"soft": 600, "hard": 1000},
    "test": {"soft": 1000, "hard": 2000}
  },
  "ceilings": {"src/legacy.rs": 2400}
}

The script prints warnings on stdout and fails with the errors on stderr:

set -eu
report=$(locmetry --files --output -) || exit "$?"
printf '%s\n' "$report" | jq -r --slurpfile policy file-size-limits.json '
  $policy[0] as $p |
  [.files[] | select(.kind == "source" and $p.limits[.purpose] != null)
   | $p.limits[.purpose] as $l | ($p.ceilings[.path] // $l.hard) as $max |
   if .counts.code > $max then {error: "\(.path): \(.counts.code) code lines over \($max)"}
   elif .counts.code > $l.soft and $p.ceilings[.path] == null
   then {warning: "\(.path): \(.counts.code) code lines over the \(.purpose) soft limit of \($l.soft)"}
   else empty end] as $findings |
  ($findings[] | .warning // empty),
  ([$findings[] | .error // empty] | if length == 0 then empty else join("\n") + "\n" | halt_error(1) end)'

Lower a ceiling in the same change that shrinks its file, and remove it once the file fits the hard limit; otherwise the file can grow back unnoticed.

Choose what to count

  • Code lines. counts.code excludes comments and blank lines, so explanatory comments never count against a file. Use counts.lines to limit physical length instead.
  • Nonblank lines. A limit in nonblank lines, such as awk 'NF' counts, has no exact equivalent: a blank line inside a comment or a multi-line string counts as a comment or code line, so counts.lines - counts.blanks can exceed a file's nonblank lines by those few lines, never fall below them.
  • Purpose, not paths. The project's classification policy (locmetry --guide configure) decides the purpose, so a file moved into a test folder or claimed by a rule changes its limit without editing the gate.
  • Embedded tests. Inline unit tests count with the file that contains them. Rust unit tests in src/ therefore count as production, and so does a tests.rs submodule there, because Cargo module inference claims every file under src/; add a project rule if such files should be tests.
  • Languages. Per-file records keep the backend's language names, so TSX files are TSX, not TypeScript as in folded tables.
  • Workspaces. locmetry workspace records paths prefixed by member name, so the same scripts gate several repositories at once.

CI executes these recipes against synthetic projects: within limits, over a limit, a larger test file under the test limit, a soft-limit warning, a ceiling that holds and one that is exceeded, and a partial measurement.

Analyze saved measurements

Full schema-3 measurements identify their document type and projection explicitly, so any JSON tool, such as jq, DuckDB or pandas, can read them. The breakdown rows add up to the summary, and --files adds one record per file. These are optional external workflows; LOCmetry has no analytics runtime dependency.