Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion repo-stats/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Generate a self-contained HTML dashboard of code statistics for any git repository.

* Lines of code over time, in total and by language, plus monthly churn.
* Lines of code over time, in total, by language and split into test and non-test code, plus monthly churn.
* Pull request (or merge request) volume per day, week and month.
* PR size: lines, files and commits.
* PR type, read from Conventional Commit titles.
Expand Down Expand Up @@ -229,6 +229,7 @@ The dashboard has a Methodology section that prints the rules it used. The defau
Lines of code::
Net lines added minus deleted along the first-parent history of the branch, for text files.
Lockfiles, vendored, build output and minified files are excluded.
Test lines are those in test paths (`tests/`, `spec/`, `test_*`, `*_test.*`, `*.spec.*` and similar); everything else is non-test.
Use `--exclude REGEX` to add paths, or `--no-default-excludes` to count everything.

PR type::
Expand Down
27 changes: 19 additions & 8 deletions repo-stats/repo_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
__version__ = "0.1.0"

# A first-parent commit summary from Scanner.scan: sha, parents, at, ct, author, subject, body, add, del,
# lines, files, code_lines, tests, sensitive, langs.
# lines, files, code_lines, tests, sensitive, langs, test_net, test_code_net.
Commit = Dict[str, Any]
# A raw PR/MR from the API or inferred from git, before build_records.
PR = Dict[str, Any]
Expand Down Expand Up @@ -447,9 +447,10 @@ def __init__(self, excludes: Iterable[str], sensitive_re: re.Pattern[str]) -> No
def summarize(self, numstat_lines: Iterable[str]) -> Commit:
"""Sum `git log --numstat` lines into size, file, language, test and sensitive-path stats.

langs maps language -> [added, deleted, kind].
langs maps language -> [added, deleted, kind]. test_net and test_code_net are the net lines (added minus
deleted) in test paths, for all languages and for code languages only.
"""
total_add = total_del = files = code_lines = 0
total_add = total_del = files = code_lines = test_net = test_code_net = 0
tests = sensitive = False
langs: dict[str, list[Any]] = {}
for line in numstat_lines:
Expand All @@ -472,12 +473,17 @@ def summarize(self, numstat_lines: Iterable[str]) -> Commit:
la[1] += d
is_test = bool(TEST_PATH.search(path))
tests = tests or is_test
if is_test:
test_net += a - d
if kind == "code":
test_code_net += a - d
if not is_test and not DOC_PATH.search(path) and kind == "code":
code_lines += a + d
if self.sensitive.search(path):
sensitive = True
return {"add": total_add, "del": total_del, "lines": total_add + total_del, "files": files,
"code_lines": code_lines, "tests": tests, "sensitive": sensitive, "langs": langs}
"code_lines": code_lines, "tests": tests, "sensitive": sensitive, "langs": langs,
"test_net": test_net, "test_code_net": test_code_net}

def scan(self, repo: str, branch: str) -> List[Commit]:
"""Return a chronologically ordered list of first-parent commit dicts.
Expand Down Expand Up @@ -548,32 +554,37 @@ def build_loc_series(first_parent: List[Commit]) -> Dict[str, Any]:
"""Return cumulative lines of code per UTC day, total and per language.

Returns:
{"days": [[day start, total, added, deleted], ...], "langs": language -> per-day lines,
"kinds": language -> kind}.
{"days": [[day start, total, added, deleted, test, test code], ...], "langs": language -> per-day lines,
"kinds": language -> kind}. test and test code are the cumulative lines in test paths, for all
languages and for code languages only.
"""
day = None
days: list[list[int]] = []
langs_cum: dict[str, int] = collections.defaultdict(int)
kinds: dict[str, str] = {}
snapshots: list[Any] = [] # per day: dict of cumulative lang -> lines
total = 0
total = test = test_code = 0
last_ct = 0
for c in first_parent:
ct = max(c["ct"], last_ct)
last_ct = ct
d = ct - ct % 86400
if d != day:
days.append([d, 0, 0, 0])
days.append([d, 0, 0, 0, 0, 0])
snapshots.append(None)
day = d
entry = days[-1]
entry[2] += c["add"]
entry[3] += c["del"]
total += c["add"] - c["del"]
test += c["test_net"]
test_code += c["test_code_net"]
for lang, (a, dl, kind) in c["langs"].items():
langs_cum[lang] += a - dl
kinds[lang] = kind
entry[1] = total
entry[4] = test
entry[5] = test_code
snapshots[-1] = dict(langs_cum)
peak: collections.Counter[str] = collections.Counter()
for snap in snapshots:
Expand Down
9 changes: 6 additions & 3 deletions repo-stats/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ <h1 id="title">Repository stats</h1>
kpi("Releases", fmtInt(deploys.length), deploys.length ? `${fmtNum(freq * 7)} per week` : "no release tags matched", deploys.length ? band("freq", freq) : null),
kpi("Change failure rate", fmtPct(cfr), `${fails} revert/hotfix PRs`, band("cfr", cfr)),
kpi("High or critical risk", fmtPct(hiRisk), "share of merged PRs"),
kpi("Lines of code", locEnd ? fmtCompact(locEnd[1]) : "–", locEnd ? "at end of range" : ""),
kpi("Lines of code", locEnd ? fmtCompact(locEnd[1]) : "–", locEnd ? `at end of range · ${fmtPct(locEnd[1] > 0 ? Math.max(0, locEnd[4]) / locEnd[1] : null)} test` : ""),
));
}

Expand All @@ -718,6 +718,9 @@ <h1 id="title">Repository stats</h1>
const total = idx.map((i) => mode.code ? sum(names.map((l) => langs[l][i])) : days[i][1]);
if (mode.view === "total") {
lineChart(c.body, { xs, series: [{ name: mode.code ? "Code lines" : "All text lines", color: css("--c1"), ys: total }], step: true, label: "Lines of code over time", table: c.table });
} else if (mode.view === "test") {
const test = idx.map((i) => Math.max(0, days[i][mode.code ? 5 : 4]));
lineChart(c.body, { xs, series: [{ name: "Non-test", color: css("--c1"), ys: total.map((t, k) => Math.max(0, t - test[k])) }, { name: "Test", color: css("--c2"), ys: test }], stacked: true, label: "Lines of code: test vs non-test", table: c.table });
} else {
const ranked = names.slice().sort((a, b) => Math.max(...langs[b]) - Math.max(...langs[a]));
const pal = SERIES();
Expand All @@ -727,7 +730,7 @@ <h1 id="title">Repository stats</h1>
lineChart(c.body, { xs, series: sers.reverse(), stacked: true, label: "Lines of code by language", table: c.table });
}
};
const seg = h("span", { class: "seg" }, [["total", "Total"], ["lang", "By language"]].map(([k, label]) =>
const seg = h("span", { class: "seg" }, [["total", "Total"], ["lang", "By language"], ["test", "Test vs non-test"]].map(([k, label]) =>
h("button", { type: "button", "aria-pressed": String(mode.view === k), onclick: (e) => { mode.view = k; seg.querySelectorAll("button").forEach((b) => b.setAttribute("aria-pressed", String(b === e.currentTarget))); draw(); } }, label)));
const codeBtn = h("button", { type: "button", "aria-pressed": "false", title: "Count only source code languages, not docs, data or config", onclick: (e) => { mode.code = !mode.code; e.currentTarget.setAttribute("aria-pressed", String(mode.code)); draw(); } }, "Code only");
ctl.append(seg, " ", codeBtn);
Expand Down Expand Up @@ -1050,7 +1053,7 @@ <h1 id="title">Repository stats</h1>
const src = card(grid, "Where the data comes from", { wide: true });
src.body.append(h("dl", { class: "method" },
h("dt", null, "PR data"), h("dd", null, META.mode === "api" ? `The ${META.provider} API. Open, review and merge times are exact.` : "Inferred from git history. A PR is a merge commit on the branch, or a squash commit whose subject ends in (#123) or whose body names a merge request. Open and review times do not exist in git."),
h("dt", null, "Lines of code"), h("dd", null, `Net lines added minus deleted along the first-parent history of ${META.branch}, text files only. Paths matching these patterns are ignored: `, META.excludes.length ? META.excludes.map((e) => h("code", { style: "display:block" }, e)) : "none"),
h("dt", null, "Lines of code"), h("dd", null, `Net lines added minus deleted along the first-parent history of ${META.branch}, text files only. Test lines are those in paths matching `, h("code", null, "/" + META.heuristics.test_path + "/"), `. Paths matching these patterns are ignored: `, META.excludes.length ? META.excludes.map((e) => h("code", { style: "display:block" }, e)) : "none"),
h("dt", null, "Direct commits"), h("dd", null, META.mode === "git" ? `${fmtInt(META.direct_commits)} commit(s) landed on the branch with no PR reference and are not counted as PRs.` : "Not applicable when PR data comes from the API."),
h("dt", null, "Statistics"), h("dd", null, "Percentiles use linear interpolation between ranks. Standard deviation is the sample deviation. Bins in distributions are log-spaced when values span more than one order of magnitude."),
h("dt", null, "Time zone"), h("dd", null, "Days, weeks (Monday start) and months are UTC.")));
Expand Down
12 changes: 12 additions & 0 deletions repo-stats/tests/test_repo_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,18 @@ def test_default_excludes_reduce_total(self) -> None:
self.assertEqual(full["loc"]["days"][-1][1], 610)
self.assertEqual(dflt["loc"]["days"][-1][1], 10)

def test_test_vs_non_test_split(self) -> None:
"""Each day carries cumulative test lines, for all languages and for code languages only."""
r = Repo()
r.commit("chore: init", {"src/a.py": lines(10), "tests/test_a.py": lines(4), "tests/data.json": lines(3)})
r.advance(DAY)
r.commit("test: more", {"tests/test_a.py": lines(6), "b_test.go": lines(5), "README.md": lines(2)})
r.advance(DAY)
r.git("rm", "-q", "tests/data.json")
r.commit("test: drop data", {"tests/test_a.py": lines(1)})
d = self._check(r.path)
self.assertEqual([day[4:] for day in d["loc"]["days"]], [[7, 4], [14, 11], [6, 6]])


class A8_Excludes(unittest.TestCase):
"""Path excludes for PR sizes and LOC."""
Expand Down
4 changes: 3 additions & 1 deletion repo-stats/tests/ui_runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,12 @@ async function applyStep(page, st) {
const issues = [];
const check = async (label) => { const t = await textIssues(page); if (t.length) issues.push({ label, t }); };
await check('initial');
for (const label of ['By language', 'Total']) { await page.click(`button:has-text("${label}")`).catch(() => {}); await check('loc ' + label); }
for (const label of ['By language', 'Test vs non-test', 'Total']) { await page.click(`button:has-text("${label}")`).catch(() => {}); await check('loc ' + label); }
await page.click('button:has-text("By language")').catch(() => {});
await page.click('button:has-text("Code only")').catch(() => {});
await check('loc lang + code only');
await page.click('button:has-text("Test vs non-test")').catch(() => {});
await check('loc test + code only');
await page.click('button:has-text("Total")').catch(() => {});
await check('loc total + code only');
const opts = await page.$$eval('select[aria-label="Duration metric"] option', (o) => o.map((x) => x.value)).catch(() => []);
Expand Down