The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 22:00 UTC
feat(web): show how much of a PR is code vs tests, mocks, and generated files (#22189)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 20, 2026 at 01:01 UTC
92a6f6d731dd8c263434c645a6ec16001eb8a67b
23 files changed
+565
-23
apps/mobile/src/features/pull-requests/PullRequestFiles.tsx
+32
@@ -1,3 +1,4 @@
1
+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";
2
import { PullRequestSectionHeading } from "./PullRequestSectionHeading";
3
import { AnimatedLegendList } from "@legendapp/list/reanimated";
4
import Animated from "react-native-reanimated";
@@ -23,6 +24,33 @@ import {
24
import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
25
import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
26
27
+const BREAKDOWN_LABELS = {
28
+ code: "Code",
29
+ tests: "Tests",
30
+ mocks: "Mocks",
31
+ generated: "Generated",
32
+} satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;
33
+
34
+function PullRequestChangeBreakdownLine(props: {
35
+ readonly breakdown: NonNullable<PullRequestChangeBreakdown>;
36
+}) {
37
+ const parts = (Object.keys(BREAKDOWN_LABELS) as Array<keyof typeof BREAKDOWN_LABELS>).flatMap(
38
+ (kind) => {
39
+ const { additions, deletions } = props.breakdown[kind];
40
+ return additions === 0 && deletions === 0
41
+ ? []
42
+ : [
43
+ `${BREAKDOWN_LABELS[kind]} +${additions.toLocaleString()} −${deletions.toLocaleString()}`,
44
+ ];
45
+ },
46
+ );
47
+ return (
48
+ <Text className="text-2xs tabular-nums text-foreground-muted" numberOfLines={2}>
49
+ {parts.join(" · ")}
50
+ </Text>
51
+ );
52
+}
53
+
54
function fileDirectory(path: string) {
55
const separator = path.lastIndexOf("/");
56
return separator < 0 ? "" : path.slice(0, separator);
@@ -37,6 +65,9 @@ export function usePullRequestFilesContent(props: {
65
const result = usePullRequestDiff(props.params);
66
const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(props.params)));
67
const viewed = usePullRequestFilesViewed(props.params, props.params.commit ? null : detail.data);
68
+ const breakdown = useEnvironmentQuery(
69
+ props.params.commit ? null : composerPullRequests.changeBreakdown(requestTarget(props.params)),
70
+ ).data;
71
const filter = usePullRequestFileFilter(result.parsed);
72
const parsed = filter.parsed;
73
const loading = result.isPending && parsed.kind === "empty" && !result.error;
@@ -209,6 +240,7 @@ export function usePullRequestFilesContent(props: {
240
? `${filter.hiddenCount} test ${filter.hiddenCount === 1 ? "file" : "files"} hidden`
241
: "Test files included"}
242
</Text>
243
+ {breakdown ? <PullRequestChangeBreakdownLine breakdown={breakdown} /> : null}
244
</View>
245
<PullRequestDiffStats
246
additions={parsed.additions}
apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts
+4
-13
@@ -1,19 +1,10 @@
1
+import { classifyChangedFile } from "@t3tools/shared/changedFileKind";
2
import type { ReviewParsedDiff } from "../review/reviewModel";
3
4
+/** Test support such as fixtures and snapshots is hidden along with the tests. */
5
export function isPullRequestTestFile(path: string): boolean {
4
- const segments = path.replaceAll("\\", "/").split("/");
5
- const name = segments.at(-1) ?? "";
6
- return (
7
- segments
8
- .slice(0, -1)
9
- .some((segment) => /^(?:__tests__|__snapshots__|tests?|spec|e2e)$/i.test(segment)) ||
10
- /\.(?:test|spec)\./i.test(name) ||
11
- /\.snap$/i.test(name) ||
12
- /^(?:test_.+|.+_test)\.py$/i.test(name) ||
13
- /_test\.(?:go|rs|rb|c|cc|cpp|h|hpp)$/i.test(name) ||
14
- /(?:Test|Tests|Spec)\.(?:java|kt|kts|swift|cs)$/.test(name) ||
15
- /_spec\.rb$/i.test(name)
16
- );
6
+ const kind = classifyChangedFile(path);
7
+ return kind === "tests" || kind === "mocks";
8
}
9
10
export function filterPullRequestTestFiles(
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -133,6 +133,7 @@ export const RPC_REQUIRED_SCOPES = {
133
[WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,
134
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
135
[WS_METHODS.pullRequestsFilesViewed]: AuthOrchestrationReadScope,
136
+ [WS_METHODS.pullRequestsChangeBreakdown]: AuthOrchestrationReadScope,
137
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
138
[WS_METHODS.pullRequestsReportState]: AuthOrchestrationReadScope,
139
[WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -113,6 +113,7 @@ const RPC_AGGREGATES = {
113
[WS_METHODS.pullRequestsThreadComments]: "pull-requests",
114
[WS_METHODS.pullRequestsDiffFileContents]: "pull-requests",
115
[WS_METHODS.pullRequestsFilesViewed]: "pull-requests",
116
+ [WS_METHODS.pullRequestsChangeBreakdown]: "pull-requests",
117
[WS_METHODS.pullRequestsRunAction]: "pull-requests",
118
[WS_METHODS.pullRequestsUpdate]: "pull-requests",
119
[WS_METHODS.pullRequestsComment]: "pull-requests",
apps/server/src/pullRequest/PullRequestService.ts
+37
@@ -40,6 +40,7 @@ import {
40
type PullRequestDiffFileContentsResult,
41
type PullRequestDiffStat,
42
type PullRequestDiffInput,
43
+ type PullRequestChangeBreakdown,
44
type PullRequestFilesViewedResult,
45
type PullRequestDiffResult,
46
type PullRequestInvalidateInput,
@@ -95,6 +96,7 @@ import {
96
import * as PullRequestReadCache from "./PullRequestReadCache.ts";
97
import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts";
98
import * as ViewedFiles from "./pullRequestViewedFiles.ts";
99
+import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";
100
101
export interface PullRequestMergeEvent extends PullRequestRef {
102
readonly mergedAt: string;
@@ -230,6 +232,9 @@ export class PullRequestService extends Context.Service<
232
readonly setFilesViewed: (
233
input: PullRequestSetFilesViewedInput,
234
) => Effect.Effect<void, PullRequestError>;
235
+ readonly changeBreakdown: (
236
+ input: PullRequestRef,
237
+ ) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;
238
readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
239
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
240
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
@@ -535,6 +540,9 @@ function withRateLimitBackoff(
540
...(api.getFilesViewed === undefined
541
? {}
542
: { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }),
543
+ ...(api.getFileStats === undefined
544
+ ? {}
545
+ : { getFileStats: wrap("getFileStats", api.getFileStats) }),
546
...(api.setFilesViewed === undefined
547
? {}
548
: { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }),
@@ -2958,6 +2966,32 @@ export const make = Effect.gen(function* () {
2966
},
2967
);
2968
2969
+ const changeBreakdownCache = yield* Cache.makeWith(
2970
+ (key: string) => {
2971
+ const ref = refOfCacheKey(key);
2972
+ return requireProject(ref).pipe(
2973
+ Effect.flatMap((project) => {
2974
+ const read = project.api.getFileStats;
2975
+ if (read === undefined) return Effect.succeed(null);
2976
+ return read({
2977
+ cwd: project.project.workspaceRoot,
2978
+ repository: project.repository,
2979
+ host: project.host,
2980
+ number: ref.number,
2981
+ }).pipe(
2982
+ Effect.map(toChangeBreakdown),
2983
+ Effect.mapError(toPullRequestError("changeBreakdown")),
2984
+ );
2985
+ }),
2986
+ );
2987
+ },
2988
+ {
2989
+ capacity: DETAIL_CACHE_CAPACITY,
2990
+ timeToLive: (exit, key) =>
2991
+ Exit.isSuccess(exit) ? detailTimeToLive(lastGoodSummary.peek(key)?.state) : Duration.zero,
2992
+ },
2993
+ );
2994
+
2995
const previewCache = yield* Cache.makeWith(
2996
(key: string) => {
2997
return previewUncached(refOfCacheKey(key));
@@ -3366,6 +3400,9 @@ export const make = Effect.gen(function* () {
3400
diffFileContents,
3401
filesViewed: credentialCached(filesViewed),
3402
setFilesViewed,
3403
+ changeBreakdown: credentialCached((input) =>
3404
+ Cache.get(changeBreakdownCache, refCacheKey(input)),
3405
+ ),
3406
runAction: runActionAndInvalidate,
3407
update: invalidatedByMutation(update),
3408
comment: invalidatedByMutation(comment),
apps/server/src/pullRequest/pullRequestChangeBreakdown.test.ts
new
+33
@@ -0,0 +1,33 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";
4
+
5
+describe("toChangeBreakdown", () => {
6
+ it("sums line counts per kind", () => {
7
+ expect(
8
+ toChangeBreakdown({
9
+ truncated: false,
10
+ files: [
11
+ { path: "src/a.ts", additions: 10, deletions: 2 },
12
+ { path: "src/b.ts", additions: 5, deletions: 1 },
13
+ { path: "src/a.test.ts", additions: 40, deletions: 0 },
14
+ { path: "pnpm-lock.yaml", additions: 300, deletions: 120 },
15
+ ],
16
+ }),
17
+ ).toEqual({
18
+ code: { additions: 15, deletions: 3 },
19
+ tests: { additions: 40, deletions: 0 },
20
+ mocks: { additions: 0, deletions: 0 },
21
+ generated: { additions: 300, deletions: 120 },
22
+ });
23
+ });
24
+
25
+ it("gives no breakdown for a partial file list", () => {
26
+ expect(
27
+ toChangeBreakdown({
28
+ truncated: true,
29
+ files: [{ path: "src/a.ts", additions: 1, deletions: 0 }],
30
+ }),
31
+ ).toBeNull();
32
+ });
33
+});
apps/server/src/pullRequest/pullRequestChangeBreakdown.ts
new
+15
@@ -0,0 +1,15 @@
1
+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";
2
+import { classifyChangedFile } from "@t3tools/shared/changedFileKind";
3
+import type { ProviderFileStats } from "@t3tools/source-control-core/server/PullRequestProvider";
4
+
5
+export function toChangeBreakdown(stats: ProviderFileStats): PullRequestChangeBreakdown {
6
+ if (stats.truncated) return null;
7
+ const empty = () => ({ additions: 0, deletions: 0 });
8
+ const breakdown = { code: empty(), tests: empty(), mocks: empty(), generated: empty() };
9
+ for (const file of stats.files) {
10
+ const bucket = breakdown[classifyChangedFile(file.path)];
11
+ bucket.additions += file.additions;
12
+ bucket.deletions += file.deletions;
13
+ }
14
+ return breakdown;
15
+}
apps/server/src/ws.ts
+2
@@ -2489,6 +2489,8 @@ export const layerWsRpc = (
2489
withPullRequestViewer(input, pullRequests.diffFileContents(input)),
2490
[WS_METHODS.pullRequestsFilesViewed]: (input) =>
2491
withPullRequestViewer(input, pullRequests.filesViewed(input)),
2492
+ [WS_METHODS.pullRequestsChangeBreakdown]: (input) =>
2493
+ withPullRequestViewer(input, pullRequests.changeBreakdown(input)),
2494
[WS_METHODS.pullRequestsSetFilesViewed]: (input) =>
2495
withPullRequestViewer(input, pullRequests.setFilesViewed(input)),
2496
[WS_METHODS.pullRequestsRunAction]: (input) =>
apps/web/src/components/pullRequest/PullRequestChangeBreakdownStat.tsx
new
+100
@@ -0,0 +1,100 @@
1
+import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
2
+import type { EnvironmentId, PullRequestChangeBreakdown, PullRequestRef } from "@t3tools/contracts";
3
+import { useState } from "react";
4
+
5
+import { pullRequestEnvironment } from "~/state/pullRequests";
6
+import { useEnvironmentQuery } from "~/state/query";
7
+
8
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
9
+import { PullRequestDiffStat } from "./pullRequestPresentation";
10
+
11
+const KIND_LABELS = {
12
+ code: "Code",
13
+ tests: "Tests",
14
+ mocks: "Mocks",
15
+ generated: "Generated",
16
+} satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;
17
+
18
+/**
19
+ * The pull request's diff stat, with a hover split into code, tests, mocks, and generated files.
20
+ * The split is read on first pointer or focus intent, so a page nobody hovers costs the host
21
+ * nothing.
22
+ */
23
+export function PullRequestChangeBreakdownStat({
24
+ environmentId,
25
+ reference,
26
+ additions,
27
+ deletions,
28
+ className,
29
+}: {
30
+ environmentId: EnvironmentId;
31
+ reference: PullRequestRef;
32
+ additions: number;
33
+ deletions: number;
34
+ className: string;
35
+}) {
36
+ const [requested, setRequested] = useState(false);
37
+ const query = useEnvironmentQuery(
38
+ requested ? pullRequestEnvironment.changeBreakdown({ environmentId, input: reference }) : null,
39
+ );
40
+ const breakdown = query.data;
41
+ if (additions === 0 && deletions === 0) return null;
42
+ return (
43
+ <Tooltip>
44
+ <TooltipTrigger
45
+ onPointerEnter={() => setRequested(true)}
46
+ onFocus={() => setRequested(true)}
47
+ render={
48
+ <span className="inline-flex">
49
+ <PullRequestDiffStat
50
+ additions={additions}
51
+ deletions={deletions}
52
+ className={className}
53
+ />
54
+ </span>
55
+ }
56
+ />
57
+ {breakdown ? (
58
+ <TooltipPopup side="bottom">
59
+ <div className="grid grid-cols-[auto_auto_auto] gap-x-4 gap-y-1 py-0.5 font-mono tabular-nums">
60
+ {(Object.keys(KIND_LABELS) as Array<keyof typeof KIND_LABELS>).map((kind) => {
61
+ const { additions, deletions } = breakdown[kind];
62
+ return additions === 0 && deletions === 0 ? null : (
63
+ <BreakdownRow
64
+ key={kind}
65
+ label={KIND_LABELS[kind]}
66
+ additions={additions}
67
+ deletions={deletions}
68
+ />
69
+ );
70
+ })}
71
+ <div className="col-span-3 border-t border-border" />
72
+ <BreakdownRow label="Total" additions={additions} deletions={deletions} />
73
+ </div>
74
+ </TooltipPopup>
75
+ ) : query.isPending ? (
76
+ <TooltipPopup side="bottom">Loading breakdown</TooltipPopup>
77
+ ) : null}
78
+ </Tooltip>
79
+ );
80
+}
81
+
82
+function BreakdownRow({
83
+ label,
84
+ additions,
85
+ deletions,
86
+}: {
87
+ label: string;
88
+ additions: number;
89
+ deletions: number;
90
+}) {
91
+ return (
92
+ <>
93
+ <span className="font-sans">{label}</span>
94
+ <span className="text-right text-diff-addition-foreground">
95
+ +{formatDiffCount(additions)}
96
+ </span>
97
+ <span className="text-right text-diff-deletion">-{formatDiffCount(deletions)}</span>
98
+ </>
99
+ );
100
+}
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+7
-3
@@ -97,6 +97,7 @@ import {
97
} from "~/state/pullRequests";
98
import { useAtomCommand } from "~/state/use-atom-command";
99
import { PullRequestStackMenu } from "./PullRequestStackMenu";
100
+import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
101
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
102
import { PullRequestThreadLinks } from "./PullRequestThreadLinks";
103
import { vcsEnvironment } from "~/state/vcs";
@@ -182,7 +183,6 @@ import {
183
import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
184
import {
185
PullRequestActorLabel,
185
- PullRequestDiffStat,
186
PullRequestMetaLine,
187
PullRequestReviewOutcomeIcon,
188
pullRequestChecksState,
@@ -2430,7 +2430,9 @@ export function PullRequestDetailPanel({
2430
<FileDiffIcon aria-hidden className="size-3" />
2431
{detail.changedFiles.toLocaleString()}
2432
</span>
2433
- <PullRequestDiffStat
2433
+ <PullRequestChangeBreakdownStat
2434
+ environmentId={environmentId}
2435
+ reference={reference}
2436
additions={detail.additions}
2437
deletions={detail.deletions}
2438
className="shrink-0 font-mono text-2xs"
@@ -2604,7 +2606,9 @@ export function PullRequestDetailPanel({
2606
}
2607
files={`${detail.changedFiles.toLocaleString()} ${detail.changedFiles === 1 ? "file" : "files"}`}
2608
diffStat={
2607
- <PullRequestDiffStat
2609
+ <PullRequestChangeBreakdownStat
2610
+ environmentId={environmentId}
2611
+ reference={reference}
2612
additions={detail.additions}
2613
deletions={detail.deletions}
2614
className="shrink-0 font-mono text-xs"
packages/client-runtime/src/state/pullRequestRouting.ts
+1
@@ -41,6 +41,7 @@ const reads = new Set<string>([
41
WS_METHODS.pullRequestsThreadComments,
42
WS_METHODS.pullRequestsDiffFileContents,
43
WS_METHODS.pullRequestsFilesViewed,
44
+ WS_METHODS.pullRequestsChangeBreakdown,
45
WS_METHODS.pullRequestsReviewerCandidates,
46
WS_METHODS.pullRequestsLabelCandidates,
47
]);
packages/client-runtime/src/state/pullRequests.ts
+9
@@ -7,6 +7,7 @@ import {
7
PullRequestListResult,
8
PullRequestChecks,
9
PullRequestDiffResult,
10
+ PullRequestChangeBreakdown,
11
PullRequestFilesViewedResult,
12
PullRequestLinkedThreadsResult,
13
type EnvironmentId,
@@ -372,6 +373,14 @@ export function createPullRequestEnvironmentAtoms<R, E>(
373
execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),
374
staleTimeMs: 15_000,
375
}),
376
+ changeBreakdown: createEnvironmentRpcQueryAtomFamily(runtime, {
377
+ label: "environment-data:pull-requests:change-breakdown",
378
+ persistence: persistQuery(PullRequestChangeBreakdown),
379
+ tag: WS_METHODS.pullRequestsChangeBreakdown,
380
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsChangeBreakdown, input),
381
+ staleTimeMs: 60_000,
382
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
383
+ }),
384
/**
385
* One write in flight per change request: the host applies these in order, and a reader
386
* ticking down a file list faster than the round trip would otherwise race their own presses.
packages/contracts/src/pullRequest.ts
+20
@@ -682,6 +682,26 @@ export const PullRequestFilesViewedResult = Schema.Struct({
682
});
683
export type PullRequestFilesViewedResult = typeof PullRequestFilesViewedResult.Type;
684
685
+const PullRequestLineCount = Schema.Struct({
686
+ additions: NonNegativeInt,
687
+ deletions: NonNegativeInt,
688
+});
689
+
690
+/**
691
+ * A change's line counts split by what the changed files are, judged from their paths. Null when
692
+ * the host gives no per-file counts, or has more files than one read covers: a split of part of
693
+ * the change would not add up to the totals shown beside it.
694
+ */
695
+export const PullRequestChangeBreakdown = Schema.NullOr(
696
+ Schema.Struct({
697
+ code: PullRequestLineCount,
698
+ tests: PullRequestLineCount,
699
+ mocks: PullRequestLineCount,
700
+ generated: PullRequestLineCount,
701
+ }),
702
+);
703
+export type PullRequestChangeBreakdown = typeof PullRequestChangeBreakdown.Type;
704
+
705
const MAX_FILES_VIEWED_PRESSES = 500;
706
707
export const PullRequestSetFilesViewedInput = Schema.Struct({
packages/contracts/src/rpc.ts
+9
@@ -165,6 +165,7 @@ import { PullRequestReviewGuideResult } from "./pullRequestReviewGuide.ts";
165
import {
166
PullRequestActionInput,
167
PullRequestActivity,
168
+ PullRequestChangeBreakdown,
169
PullRequestCommentInput,
170
PullRequestCommentUpdateInput,
171
PullRequestDetail,
@@ -539,6 +540,7 @@ export const WS_METHODS = {
540
pullRequestsThreadComments: "pullRequests.threadComments",
541
pullRequestsDiffFileContents: "pullRequests.diffFileContents",
542
pullRequestsFilesViewed: "pullRequests.filesViewed",
543
+ pullRequestsChangeBreakdown: "pullRequests.changeBreakdown",
544
pullRequestsSetFilesViewed: "pullRequests.setFilesViewed",
545
pullRequestsRunAction: "pullRequests.runAction",
546
pullRequestsUpdate: "pullRequests.update",
@@ -1045,6 +1047,12 @@ const WsPullRequestsFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsFilesViewed
1047
error: PullRequestRpcError,
1048
});
1049
1050
+const WsPullRequestsChangeBreakdownRpc = Rpc.make(WS_METHODS.pullRequestsChangeBreakdown, {
1051
+ payload: PullRequestRef,
1052
+ success: PullRequestChangeBreakdown,
1053
+ error: PullRequestRpcError,
1054
+});
1055
+
1056
const WsPullRequestsSetFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsSetFilesViewed, {
1057
payload: PullRequestSetFilesViewedInput,
1058
success: Schema.Void,
@@ -1954,6 +1962,7 @@ export const WsRpcGroup = RpcGroup.make(
1962
WsPullRequestsThreadCommentsRpc,
1963
WsPullRequestsDiffFileContentsRpc,
1964
WsPullRequestsFilesViewedRpc,
1965
+ WsPullRequestsChangeBreakdownRpc,
1966
WsPullRequestsSetFilesViewedRpc,
1967
WsPullRequestsRunActionRpc,
1968
WsPullRequestsUpdateRpc,
packages/shared/package.json
+4
@@ -3,6 +3,10 @@
3
"private": true,
4
"type": "module",
5
"exports": {
6
+ "./changedFileKind": {
7
+ "types": "./src/changedFileKind.ts",
8
+ "import": "./src/changedFileKind.ts"
9
+ },
10
"./githubMarkdownLinks": {
11
"types": "./src/githubMarkdownLinks.ts",
12
"import": "./src/githubMarkdownLinks.ts"
packages/shared/src/changedFileKind.test.ts
new
+42
@@ -0,0 +1,42 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { classifyChangedFile } from "./changedFileKind.ts";
4
+
5
+describe("classifyChangedFile", () => {
6
+ it.each([
7
+ ["apps/server/src/ws.ts", "code"],
8
+ ["src/latest.ts", "code"],
9
+ ["src/Latest.java", "code"],
10
+ ["src/contest.py", "code"],
11
+ ["src/mockingbird.ts", "code"],
12
+ ["src/testimonials/List.tsx", "code"],
13
+ ["apps/web/src/foo.test.ts", "tests"],
14
+ ["apps/web/src/Foo.browser.test.tsx", "tests"],
15
+ ["src/foo.spec.js", "tests"],
16
+ ["pkg/server_test.go", "tests"],
17
+ ["tests/test_api.py", "tests"],
18
+ ["conftest.py", "tests"],
19
+ ["src/main/java/RequestTest.java", "tests"],
20
+ ["Sources/AppTests.swift", "tests"],
21
+ ["src/HTTPTest.java", "tests"],
22
+ ["Sources/URLTests.swift", "tests"],
23
+ ["spec/models/user_spec.rb", "tests"],
24
+ ["src/__tests__/helpers.ts", "tests"],
25
+ ["src/testUtils.ts", "code"],
26
+ ["src\\__tests__\\app.ts", "tests"],
27
+ ["src/__mocks__/fs.ts", "mocks"],
28
+ ["test/fixtures/pr.json", "mocks"],
29
+ ["src/__snapshots__/view.test.ts.snap", "mocks"],
30
+ ["src/api.mock.ts", "mocks"],
31
+ ["src/mockServer.ts", "mocks"],
32
+ ["pkg/testdata/input.txt", "mocks"],
33
+ ["pnpm-lock.yaml", "generated"],
34
+ ["apps/web/package-lock.json", "generated"],
35
+ ["go.sum", "generated"],
36
+ ["src/routeTree.gen.ts", "generated"],
37
+ ["src/__generated__/types.ts", "generated"],
38
+ ["dist/app.min.js", "generated"],
39
+ ] as const)("%s is %s", (path, kind) => {
40
+ expect(classifyChangedFile(path)).toBe(kind);
41
+ });
42
+});
packages/shared/src/changedFileKind.ts
new
+76
@@ -0,0 +1,76 @@
1
+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";
2
+
3
+export type ChangedFileKind = keyof NonNullable<PullRequestChangeBreakdown>;
4
+
5
+const GENERATED_FILES = new Set([
6
+ "bun.lock",
7
+ "bun.lockb",
8
+ "cargo.lock",
9
+ "composer.lock",
10
+ "deno.lock",
11
+ "flake.lock",
12
+ "gemfile.lock",
13
+ "go.sum",
14
+ "gradle.lockfile",
15
+ "mix.lock",
16
+ "npm-shrinkwrap.json",
17
+ "package-lock.json",
18
+ "packages.lock.json",
19
+ "pipfile.lock",
20
+ "pnpm-lock.yaml",
21
+ "podfile.lock",
22
+ "poetry.lock",
23
+ "pubspec.lock",
24
+ "uv.lock",
25
+ "yarn.lock",
26
+]);
27
+const GENERATED_NAME =
28
+ /(\.generated\.|\.gen\.|\.g\.dart$|\.pb\.go$|_pb2(_grpc)?\.py$|\.pb\.(cc|h)$|\.min\.(js|css)$|\.(js|css)\.map$)/;
29
+const GENERATED_DIRS = new Set(["__generated__", "generated"]);
30
+
31
+const MOCK_NAME =
32
+ /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$|^(mocks?|fixtures?|stubs?|fakes?)([-_.A-Z]|$))/;
33
+const MOCK_DIRS = new Set([
34
+ "__fixtures__",
35
+ "__mocks__",
36
+ "__snapshots__",
37
+ "fakes",
38
+ "fixture",
39
+ "fixtures",
40
+ "mock",
41
+ "mocks",
42
+ "stubs",
43
+ "testdata",
44
+]);
45
+
46
+const TEST_NAME =
47
+ /(\.(test|spec|e2e)\.[^.]+$|_(test|spec)\.[^.]+$|^test_.+\.py$|^conftest\.py$|^(vitest|jest)\.setup\.[^.]+$)/i;
48
+// Case-sensitive: `FooTest.java` is a test class, `Latest.java` is not.
49
+const CLASS_TEST_NAME = /(Tests?|Spec)\.(java|kt|kts|scala|groovy|cs|php|swift|m)$/;
50
+const TEST_DIRS = new Set([
51
+ "__tests__",
52
+ "__test__",
53
+ "cypress",
54
+ "e2e",
55
+ "spec",
56
+ "specs",
57
+ "test",
58
+ "tests",
59
+]);
60
+
61
+/**
62
+ * Sorts a changed file by its path alone, using common naming conventions. Lockfiles and build
63
+ * output count as generated, and test support (mocks, fixtures, snapshots) is kept apart from the
64
+ * tests themselves, so a reviewer can see how much of a change is logic.
65
+ */
66
+export function classifyChangedFile(path: string): ChangedFileKind {
67
+ const segments = path.replaceAll("\\", "/").split("/");
68
+ const name = segments.pop() ?? "";
69
+ const dirs = segments.map((segment) => segment.toLowerCase());
70
+ const inDir = (set: ReadonlySet<string>) => dirs.some((dir) => set.has(dir));
71
+ if (GENERATED_FILES.has(name.toLowerCase()) || GENERATED_NAME.test(name) || inDir(GENERATED_DIRS))
72
+ return "generated";
73
+ if (MOCK_NAME.test(name) || inDir(MOCK_DIRS)) return "mocks";
74
+ if (TEST_NAME.test(name) || CLASS_TEST_NAME.test(name) || inDir(TEST_DIRS)) return "tests";
75
+ return "code";
76
+}
packages/source-control-core/src/server/PullRequestProvider.ts
+15
@@ -226,6 +226,16 @@ export interface ProviderFilesViewed {
226
readonly truncated: boolean;
227
}
228
229
+export interface ProviderFileStats {
230
+ readonly files: ReadonlyArray<{
231
+ readonly path: string;
232
+ readonly additions: number;
233
+ readonly deletions: number;
234
+ }>;
235
+ /** The host has more files than were read. */
236
+ readonly truncated: boolean;
237
+}
238
+
239
/**
240
* Opaque strings, compared only against one another, where the empty string is the answer for a
241
* file the change request deletes rather than a gap. A path is absent only where the read could
@@ -408,6 +418,11 @@ export interface PullRequestProviderApi {
418
input: ProviderRepositoryRef & { readonly number: number },
419
) => Effect.Effect<ProviderFilesViewed, PullRequestProviderError>;
420
421
+ /** Line counts for every changed file. Optional: a host without one shows no breakdown. */
422
+ readonly getFileStats?: (
423
+ input: ProviderRepositoryRef & { readonly number: number },
424
+ ) => Effect.Effect<ProviderFileStats, PullRequestProviderError>;
425
+
426
/**
427
* A host with no bulk form is still owed one round trip for the batch rather than one per
428
* file, since the point of gathering presses is that the host is asked once.
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+42
@@ -59,6 +59,7 @@ import {
59
pullRequestChecksFromContexts,
60
decodeWorkflowRunsJson,
61
type GitHubPullRequestCore,
62
+ type GitHubPullRequestFileStat,
63
type GitHubPullRequestWatchFingerprint,
64
isSubjectOfPullRequest,
65
LenientPullRequestList,
@@ -71,6 +72,7 @@ import {
72
toPullRequestCheckContextsPage,
73
toPullRequestCore,
74
toPullRequestFilesViewedPage,
75
+ toPullRequestFileStatsPage,
76
toPullRequestHeads,
77
toPullRequestNodeId,
78
toPullRequestPreview,
@@ -412,6 +414,11 @@ export interface GitHubPullRequestFilesViewed {
414
readonly truncated: boolean;
415
}
416
417
+export interface GitHubPullRequestFileStats {
418
+ readonly files: ReadonlyArray<GitHubPullRequestFileStat>;
419
+ readonly truncated: boolean;
420
+}
421
+
422
export class GitHubPullRequestApi extends Context.Service<
423
GitHubPullRequestApi,
424
{
@@ -562,6 +569,13 @@ export class GitHubPullRequestApi extends Context.Service<
569
readonly number: number;
570
}) => Effect.Effect<GitHubPullRequestFilesViewed, GitHubPullRequestApiError>;
571
572
+ readonly getPullRequestFileStats: (input: {
573
+ readonly cwd: string;
574
+ readonly repository: string;
575
+ readonly host: string;
576
+ readonly number: number;
577
+ }) => Effect.Effect<GitHubPullRequestFileStats, GitHubPullRequestApiError>;
578
+
579
/**
580
* GitHub takes a single path per mutation, so a burst is batched with aliases into one
581
* document rather than one subprocess per press.
@@ -2666,6 +2680,34 @@ export const make = Effect.gen(function* () {
2680
);
2681
},
2682
2683
+ getPullRequestFileStats: (input) => {
2684
+ const { owner, name } = parseRepositorySelector(input.repository);
2685
+ const target = { ...input, operation: "getPullRequestFileStats" };
2686
+ return readPages(
2687
+ GraphQLClient.pages(client.PullRequestFileStats, {
2688
+ variables: { owner, name, number: input.number },
2689
+ connection: (result) => {
2690
+ const page = toPullRequestFileStatsPage(result);
2691
+ return {
2692
+ ...page,
2693
+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
2694
+ };
2695
+ },
2696
+ }),
2697
+ {
2698
+ ...target,
2699
+ maxPages: FILES_VIEWED_MAX_PAGES,
2700
+ hasNextPage: (page) => page.nextCursor !== null,
2701
+ },
2702
+ ).pipe(
2703
+ graphql(target),
2704
+ Effect.map(({ pages, truncated }) => ({
2705
+ files: pages.flatMap((page) => page.files),
2706
+ truncated,
2707
+ })),
2708
+ );
2709
+ },
2710
+
2711
setPullRequestFilesViewed: (input) => {
2712
if (input.files.length === 0) return Effect.void;
2713
const target = { ...input, operation: "setPullRequestFilesViewed" };
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+2
@@ -524,6 +524,8 @@ export const make = Effect.gen(function* () {
524
getFilesViewed: (input) =>
525
cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
526
527
+ getFileStats: (input) =>
528
+ cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
529
setFilesViewed: (input) =>
530
cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
531
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+24
@@ -56,6 +56,7 @@ import type {
56
PullRequestCheckContexts,
57
PullRequestCore,
58
PullRequestFilesViewed,
59
+ PullRequestFileStats,
60
PullRequestHeads,
61
PullRequestPreview as PullRequestPreviewQuery,
62
PullRequestSubject,
@@ -1806,6 +1807,29 @@ export function toPullRequestFilesViewedPage(
1807
};
1808
}
1809
1810
+export interface GitHubPullRequestFileStat {
1811
+ readonly path: string;
1812
+ readonly additions: number;
1813
+ readonly deletions: number;
1814
+}
1815
+
1816
+export interface GitHubPullRequestFileStatsPage {
1817
+ readonly files: ReadonlyArray<GitHubPullRequestFileStat>;
1818
+ readonly nextCursor: string | null;
1819
+}
1820
+
1821
+export function toPullRequestFileStatsPage(
1822
+ result: PullRequestFileStats.Result,
1823
+): GitHubPullRequestFileStatsPage {
1824
+ const files = result.repository?.pullRequest?.files;
1825
+ return {
1826
+ files: nodesOf(files).flatMap(({ path, additions, deletions }) =>
1827
+ path.length === 0 ? [] : [{ path, additions, deletions }],
1828
+ ),
1829
+ nextCursor: nextCursorOf(files?.pageInfo),
1830
+ };
1831
+}
1832
+
1833
const RawStackPullRequestSchema = Schema.Struct({
1834
title: Schema.optional(Schema.String),
1835
draft: Schema.optional(Schema.Boolean),
packages/source-control-github/src/server/pullRequestReads.graphql
+18
@@ -475,6 +475,24 @@ query PullRequestFilesViewed($owner: String!, $name: String!, $number: Int!, $af
475
}
476
}
477
478
+query PullRequestFileStats($owner: String!, $name: String!, $number: Int!, $after: String) {
479
+ repository(owner: $owner, name: $name) {
480
+ pullRequest(number: $number) {
481
+ files(first: 100, after: $after) {
482
+ pageInfo {
483
+ hasNextPage
484
+ endCursor
485
+ }
486
+ nodes {
487
+ path
488
+ additions
489
+ deletions
490
+ }
491
+ }
492
+ }
493
+ }
494
+}
495
+
496
# What a merge that rewrites its message reads first: GitHub's own message for the method, and
497
# whether a merge queue will choose its own instead.
498
query PullRequestMergeMessage(
packages/source-control-github/src/server/pullRequestReads.graphql.ts
+71
-7
@@ -1237,27 +1237,27 @@ export declare namespace LabelCandidates {
1237
}
1238
1239
/** A file changed in a pull request. */
1240
-export const PullRequestChangedFile = Schema.Struct({
1240
+export const PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({
1241
/** The path of the file. */
1242
path: Schema.String,
1243
/** The state of the file for the viewer. */
1244
viewerViewedState: GraphQL.enumLiterals(Shared.FileViewedState.literals)
1245
})
1246
-export interface PullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestChangedFile.fields> {}
1246
+export interface PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile.fields> {}
1247
1248
/** The connection type for PullRequestChangedFile. */
1249
-export const PullRequestChangedFileConnection = Schema.Struct({
1249
+export const PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
1250
/** Information to aid in pagination. */
1251
pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1252
/** A list of nodes. */
1253
- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestChangedFile)))
1253
+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile)))
1254
})
1255
-export interface PullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestChangedFileConnection.fields> {}
1255
+export interface PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection.fields> {}
1256
1257
/** A repository pull request. */
1258
export const PullRequestFilesViewedRepositoryPullRequestPullRequest = Schema.Struct({
1259
/** Lists the files changed within this pull request. */
1260
- files: Schema.NullOr(PullRequestChangedFileConnection)
1260
+ files: Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection)
1261
})
1262
export interface PullRequestFilesViewedRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestPullRequest.fields> {}
1263
@@ -1298,6 +1298,70 @@ export declare namespace PullRequestFilesViewed {
1298
export type Result = typeof PullRequestFilesViewed.result.Type
1299
}
1300
1301
+/** A file changed in a pull request. */
1302
+export const PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({
1303
+ /** The path of the file. */
1304
+ path: Schema.String,
1305
+ /** The number of additions to the file. */
1306
+ additions: Shared.Int,
1307
+ /** The number of deletions to the file. */
1308
+ deletions: Shared.Int
1309
+})
1310
+export interface PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile.fields> {}
1311
+
1312
+/** The connection type for PullRequestChangedFile. */
1313
+export const PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
1314
+ /** Information to aid in pagination. */
1315
+ pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1316
+ /** A list of nodes. */
1317
+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile)))
1318
+})
1319
+export interface PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection.fields> {}
1320
+
1321
+/** A repository pull request. */
1322
+export const PullRequestFileStatsRepositoryPullRequestPullRequest = Schema.Struct({
1323
+ /** Lists the files changed within this pull request. */
1324
+ files: Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection)
1325
+})
1326
+export interface PullRequestFileStatsRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestPullRequest.fields> {}
1327
+
1328
+/** A repository contains the content for a project. */
1329
+export const PullRequestFileStatsRepositoryRepository = Schema.Struct({
1330
+ /** Returns a single pull request from the current repository by number. */
1331
+ pullRequest: Schema.NullOr(PullRequestFileStatsRepositoryPullRequestPullRequest)
1332
+})
1333
+export interface PullRequestFileStatsRepositoryRepository extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryRepository.fields> {}
1334
+
1335
+/** `query PullRequestFileStats` */
1336
+export const PullRequestFileStats = GraphQL.query("PullRequestFileStats", {
1337
+ document: {
1338
+ variables: [
1339
+ { name: "owner", body: "String!" },
1340
+ { name: "name", body: "String!" },
1341
+ { name: "number", body: "Int!" },
1342
+ { name: "after", body: "String" }
1343
+ ],
1344
+ selections: [
1345
+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){files(first:100 after:$", "after", "){pageInfo{hasNextPage endCursor}nodes{path additions deletions}}}}"] }
1346
+ ],
1347
+ fragments: []
1348
+ },
1349
+ variables: {
1350
+ owner: Schema.String,
1351
+ name: Schema.String,
1352
+ number: Shared.Int,
1353
+ after: Schema.optional(Schema.NullOr(Schema.String))
1354
+ },
1355
+ result: Schema.Struct({
1356
+ /** Lookup a given repository by the owner and repository name. */
1357
+ repository: Schema.NullOr(PullRequestFileStatsRepositoryRepository)
1358
+ })
1359
+})
1360
+export declare namespace PullRequestFileStats {
1361
+ export type Variables = typeof PullRequestFileStats.variables.Type
1362
+ export type Result = typeof PullRequestFileStats.result.Type
1363
+}
1364
+
1365
/** A repository pull request. */
1366
export const PullRequestMergeMessageRepositoryPullRequestPullRequest = Schema.Struct({
1367
/** Indicates whether the pull request's base ref has a merge queue enabled. */
@@ -1523,4 +1587,4 @@ export declare namespace PullRequestSourceBranch {
1587
}
1588
1589
/** Every operation in pullRequestReads.graphql. */
1526
-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
1590
+export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)