TypeScript
feat(web): show how much of a PR is code vs tests, mocks, and generated files (#22189)
Theo Browne92a6f6d731dd
diff --git a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsxindex f699e46d6fb..dc9c765bf50 100644--- a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx@@ -1,3 +1,4 @@+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";import { PullRequestSectionHeading } from "./PullRequestSectionHeading";import { AnimatedLegendList } from "@legendapp/list/reanimated";import Animated from "react-native-reanimated";@@ -23,6 +24,33 @@ import {import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";import { usePullRequestFileFilter } from "./usePullRequestFileFilter";+const BREAKDOWN_LABELS = {+ code: "Code",+ tests: "Tests",+ mocks: "Mocks",+ generated: "Generated",+} satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;++function PullRequestChangeBreakdownLine(props: {+ readonly breakdown: NonNullable<PullRequestChangeBreakdown>;+}) {+ const parts = (Object.keys(BREAKDOWN_LABELS) as Array<keyof typeof BREAKDOWN_LABELS>).flatMap(+ (kind) => {+ const { additions, deletions } = props.breakdown[kind];+ return additions === 0 && deletions === 0+ ? []+ : [+ `${BREAKDOWN_LABELS[kind]} +${additions.toLocaleString()} −${deletions.toLocaleString()}`,+ ];+ },+ );+ return (+ <Text className="text-2xs tabular-nums text-foreground-muted" numberOfLines={2}>+ {parts.join(" · ")}+ </Text>+ );+}+function fileDirectory(path: string) {const separator = path.lastIndexOf("/");return separator < 0 ? "" : path.slice(0, separator);@@ -37,6 +65,9 @@ export function usePullRequestFilesContent(props: {const result = usePullRequestDiff(props.params);const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(props.params)));const viewed = usePullRequestFilesViewed(props.params, props.params.commit ? null : detail.data);+ const breakdown = useEnvironmentQuery(+ props.params.commit ? null : composerPullRequests.changeBreakdown(requestTarget(props.params)),+ ).data;const filter = usePullRequestFileFilter(result.parsed);const parsed = filter.parsed;const loading = result.isPending && parsed.kind === "empty" && !result.error;@@ -209,6 +240,7 @@ export function usePullRequestFilesContent(props: {? `${filter.hiddenCount} test ${filter.hiddenCount === 1 ? "file" : "files"} hidden`: "Test files included"}</Text>+ {breakdown ? <PullRequestChangeBreakdownLine breakdown={breakdown} /> : null}</View><PullRequestDiffStatsadditions={parsed.additions}diff --git a/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts b/apps/mobile/src/features/pull-requests/pullRequestFileFilters.tsindex a8c9f0209e4..2d8e3a94fe4 100644--- a/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestFileFilters.ts@@ -1,19 +1,10 @@+import { classifyChangedFile } from "@t3tools/shared/changedFileKind";import type { ReviewParsedDiff } from "../review/reviewModel";+/** Test support such as fixtures and snapshots is hidden along with the tests. */export function isPullRequestTestFile(path: string): boolean {- const segments = path.replaceAll("\\", "/").split("/");- const name = segments.at(-1) ?? "";- return (- segments- .slice(0, -1)- .some((segment) => /^(?:__tests__|__snapshots__|tests?|spec|e2e)$/i.test(segment)) ||- /\.(?:test|spec)\./i.test(name) ||- /\.snap$/i.test(name) ||- /^(?:test_.+|.+_test)\.py$/i.test(name) ||- /_test\.(?:go|rs|rb|c|cc|cpp|h|hpp)$/i.test(name) ||- /(?:Test|Tests|Spec)\.(?:java|kt|kts|swift|cs)$/.test(name) ||- /_spec\.rb$/i.test(name)- );+ const kind = classifyChangedFile(path);+ return kind === "tests" || kind === "mocks";}export function filterPullRequestTestFiles(diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex dca29f707a1..18919cea55e 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -133,6 +133,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsFilesViewed]: AuthOrchestrationReadScope,+ [WS_METHODS.pullRequestsChangeBreakdown]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsReportState]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 4b3ea1f7410..3f3942e75d0 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -113,6 +113,7 @@ const RPC_AGGREGATES = {[WS_METHODS.pullRequestsThreadComments]: "pull-requests",[WS_METHODS.pullRequestsDiffFileContents]: "pull-requests",[WS_METHODS.pullRequestsFilesViewed]: "pull-requests",+ [WS_METHODS.pullRequestsChangeBreakdown]: "pull-requests",[WS_METHODS.pullRequestsRunAction]: "pull-requests",[WS_METHODS.pullRequestsUpdate]: "pull-requests",[WS_METHODS.pullRequestsComment]: "pull-requests",diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 4bac77b4ac0..f0c2b580064 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -40,6 +40,7 @@ import {type PullRequestDiffFileContentsResult,type PullRequestDiffStat,type PullRequestDiffInput,+ type PullRequestChangeBreakdown,type PullRequestFilesViewedResult,type PullRequestDiffResult,type PullRequestInvalidateInput,@@ -95,6 +96,7 @@ import {import * as PullRequestReadCache from "./PullRequestReadCache.ts";import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts";import * as ViewedFiles from "./pullRequestViewedFiles.ts";+import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";export interface PullRequestMergeEvent extends PullRequestRef {readonly mergedAt: string;@@ -230,6 +232,9 @@ export class PullRequestService extends Context.Service<readonly setFilesViewed: (input: PullRequestSetFilesViewedInput,) => Effect.Effect<void, PullRequestError>;+ readonly changeBreakdown: (+ input: PullRequestRef,+ ) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;@@ -535,6 +540,9 @@ function withRateLimitBackoff(...(api.getFilesViewed === undefined? {}: { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }),+ ...(api.getFileStats === undefined+ ? {}+ : { getFileStats: wrap("getFileStats", api.getFileStats) }),...(api.setFilesViewed === undefined? {}: { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }),@@ -2958,6 +2966,32 @@ export const make = Effect.gen(function* () {},);+ const changeBreakdownCache = yield* Cache.makeWith(+ (key: string) => {+ const ref = refOfCacheKey(key);+ return requireProject(ref).pipe(+ Effect.flatMap((project) => {+ const read = project.api.getFileStats;+ if (read === undefined) return Effect.succeed(null);+ return read({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ number: ref.number,+ }).pipe(+ Effect.map(toChangeBreakdown),+ Effect.mapError(toPullRequestError("changeBreakdown")),+ );+ }),+ );+ },+ {+ capacity: DETAIL_CACHE_CAPACITY,+ timeToLive: (exit, key) =>+ Exit.isSuccess(exit) ? detailTimeToLive(lastGoodSummary.peek(key)?.state) : Duration.zero,+ },+ );+const previewCache = yield* Cache.makeWith((key: string) => {return previewUncached(refOfCacheKey(key));@@ -3366,6 +3400,9 @@ export const make = Effect.gen(function* () {diffFileContents,filesViewed: credentialCached(filesViewed),setFilesViewed,+ changeBreakdown: credentialCached((input) =>+ Cache.get(changeBreakdownCache, refCacheKey(input)),+ ),runAction: runActionAndInvalidate,update: invalidatedByMutation(update),comment: invalidatedByMutation(comment),diff --git a/apps/server/src/pullRequest/pullRequestChangeBreakdown.test.ts b/apps/server/src/pullRequest/pullRequestChangeBreakdown.test.tsnew file mode 100644index 00000000000..68321f39eb2--- /dev/null+++ b/apps/server/src/pullRequest/pullRequestChangeBreakdown.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vite-plus/test";++import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";++describe("toChangeBreakdown", () => {+ it("sums line counts per kind", () => {+ expect(+ toChangeBreakdown({+ truncated: false,+ files: [+ { path: "src/a.ts", additions: 10, deletions: 2 },+ { path: "src/b.ts", additions: 5, deletions: 1 },+ { path: "src/a.test.ts", additions: 40, deletions: 0 },+ { path: "pnpm-lock.yaml", additions: 300, deletions: 120 },+ ],+ }),+ ).toEqual({+ code: { additions: 15, deletions: 3 },+ tests: { additions: 40, deletions: 0 },+ mocks: { additions: 0, deletions: 0 },+ generated: { additions: 300, deletions: 120 },+ });+ });++ it("gives no breakdown for a partial file list", () => {+ expect(+ toChangeBreakdown({+ truncated: true,+ files: [{ path: "src/a.ts", additions: 1, deletions: 0 }],+ }),+ ).toBeNull();+ });+});diff --git a/apps/server/src/pullRequest/pullRequestChangeBreakdown.ts b/apps/server/src/pullRequest/pullRequestChangeBreakdown.tsnew file mode 100644index 00000000000..77d8162e895--- /dev/null+++ b/apps/server/src/pullRequest/pullRequestChangeBreakdown.ts@@ -0,0 +1,15 @@+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";+import { classifyChangedFile } from "@t3tools/shared/changedFileKind";+import type { ProviderFileStats } from "@t3tools/source-control-core/server/PullRequestProvider";++export function toChangeBreakdown(stats: ProviderFileStats): PullRequestChangeBreakdown {+ if (stats.truncated) return null;+ const empty = () => ({ additions: 0, deletions: 0 });+ const breakdown = { code: empty(), tests: empty(), mocks: empty(), generated: empty() };+ for (const file of stats.files) {+ const bucket = breakdown[classifyChangedFile(file.path)];+ bucket.additions += file.additions;+ bucket.deletions += file.deletions;+ }+ return breakdown;+}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 7d63d72d861..7b88c268e7c 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -2489,6 +2489,8 @@ export const layerWsRpc = (withPullRequestViewer(input, pullRequests.diffFileContents(input)),[WS_METHODS.pullRequestsFilesViewed]: (input) =>withPullRequestViewer(input, pullRequests.filesViewed(input)),+ [WS_METHODS.pullRequestsChangeBreakdown]: (input) =>+ withPullRequestViewer(input, pullRequests.changeBreakdown(input)),[WS_METHODS.pullRequestsSetFilesViewed]: (input) =>withPullRequestViewer(input, pullRequests.setFilesViewed(input)),[WS_METHODS.pullRequestsRunAction]: (input) =>diff --git a/apps/web/src/components/pullRequest/PullRequestChangeBreakdownStat.tsx b/apps/web/src/components/pullRequest/PullRequestChangeBreakdownStat.tsxnew file mode 100644index 00000000000..cba047e2a41--- /dev/null+++ b/apps/web/src/components/pullRequest/PullRequestChangeBreakdownStat.tsx@@ -0,0 +1,100 @@+import { formatDiffCount } from "@t3tools/client-runtime/diff-count";+import type { EnvironmentId, PullRequestChangeBreakdown, PullRequestRef } from "@t3tools/contracts";+import { useState } from "react";++import { pullRequestEnvironment } from "~/state/pullRequests";+import { useEnvironmentQuery } from "~/state/query";++import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import { PullRequestDiffStat } from "./pullRequestPresentation";++const KIND_LABELS = {+ code: "Code",+ tests: "Tests",+ mocks: "Mocks",+ generated: "Generated",+} satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;++/**+ * The pull request's diff stat, with a hover split into code, tests, mocks, and generated files.+ * The split is read on first pointer or focus intent, so a page nobody hovers costs the host+ * nothing.+ */+export function PullRequestChangeBreakdownStat({+ environmentId,+ reference,+ additions,+ deletions,+ className,+}: {+ environmentId: EnvironmentId;+ reference: PullRequestRef;+ additions: number;+ deletions: number;+ className: string;+}) {+ const [requested, setRequested] = useState(false);+ const query = useEnvironmentQuery(+ requested ? pullRequestEnvironment.changeBreakdown({ environmentId, input: reference }) : null,+ );+ const breakdown = query.data;+ if (additions === 0 && deletions === 0) return null;+ return (+ <Tooltip>+ <TooltipTrigger+ onPointerEnter={() => setRequested(true)}+ onFocus={() => setRequested(true)}+ render={+ <span className="inline-flex">+ <PullRequestDiffStat+ additions={additions}+ deletions={deletions}+ className={className}+ />+ </span>+ }+ />+ {breakdown ? (+ <TooltipPopup side="bottom">+ <div className="grid grid-cols-[auto_auto_auto] gap-x-4 gap-y-1 py-0.5 font-mono tabular-nums">+ {(Object.keys(KIND_LABELS) as Array<keyof typeof KIND_LABELS>).map((kind) => {+ const { additions, deletions } = breakdown[kind];+ return additions === 0 && deletions === 0 ? null : (+ <BreakdownRow+ key={kind}+ label={KIND_LABELS[kind]}+ additions={additions}+ deletions={deletions}+ />+ );+ })}+ <div className="col-span-3 border-t border-border" />+ <BreakdownRow label="Total" additions={additions} deletions={deletions} />+ </div>+ </TooltipPopup>+ ) : query.isPending ? (+ <TooltipPopup side="bottom">Loading breakdown</TooltipPopup>+ ) : null}+ </Tooltip>+ );+}++function BreakdownRow({+ label,+ additions,+ deletions,+}: {+ label: string;+ additions: number;+ deletions: number;+}) {+ return (+ <>+ <span className="font-sans">{label}</span>+ <span className="text-right text-diff-addition-foreground">+ +{formatDiffCount(additions)}+ </span>+ <span className="text-right text-diff-deletion">-{formatDiffCount(deletions)}</span>+ </>+ );+}diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 071b77b39db..33c87722ff5 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -97,6 +97,7 @@ import {} from "~/state/pullRequests";import { useAtomCommand } from "~/state/use-atom-command";import { PullRequestStackMenu } from "./PullRequestStackMenu";+import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { PullRequestThreadLinks } from "./PullRequestThreadLinks";import { vcsEnvironment } from "~/state/vcs";@@ -182,7 +183,6 @@ import {import { PullRequestChecksPopover } from "./PullRequestChecksPopover";import {PullRequestActorLabel,- PullRequestDiffStat,PullRequestMetaLine,PullRequestReviewOutcomeIcon,pullRequestChecksState,@@ -2430,7 +2430,9 @@ export function PullRequestDetailPanel({<FileDiffIcon aria-hidden className="size-3" />{detail.changedFiles.toLocaleString()}</span>- <PullRequestDiffStat+ <PullRequestChangeBreakdownStat+ environmentId={environmentId}+ reference={reference}additions={detail.additions}deletions={detail.deletions}className="shrink-0 font-mono text-2xs"@@ -2604,7 +2606,9 @@ export function PullRequestDetailPanel({}files={`${detail.changedFiles.toLocaleString()} ${detail.changedFiles === 1 ? "file" : "files"}`}diffStat={- <PullRequestDiffStat+ <PullRequestChangeBreakdownStat+ environmentId={environmentId}+ reference={reference}additions={detail.additions}deletions={detail.deletions}className="shrink-0 font-mono text-xs"diff --git a/packages/client-runtime/src/state/pullRequestRouting.ts b/packages/client-runtime/src/state/pullRequestRouting.tsindex 8bdcb481c5f..73624f97b48 100644--- a/packages/client-runtime/src/state/pullRequestRouting.ts+++ b/packages/client-runtime/src/state/pullRequestRouting.ts@@ -41,6 +41,7 @@ const reads = new Set<string>([WS_METHODS.pullRequestsThreadComments,WS_METHODS.pullRequestsDiffFileContents,WS_METHODS.pullRequestsFilesViewed,+ WS_METHODS.pullRequestsChangeBreakdown,WS_METHODS.pullRequestsReviewerCandidates,WS_METHODS.pullRequestsLabelCandidates,]);diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 684c3d1999f..75703773447 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -7,6 +7,7 @@ import {PullRequestListResult,PullRequestChecks,PullRequestDiffResult,+ PullRequestChangeBreakdown,PullRequestFilesViewedResult,PullRequestLinkedThreadsResult,type EnvironmentId,@@ -372,6 +373,14 @@ export function createPullRequestEnvironmentAtoms<R, E>(execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),staleTimeMs: 15_000,}),+ changeBreakdown: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:pull-requests:change-breakdown",+ persistence: persistQuery(PullRequestChangeBreakdown),+ tag: WS_METHODS.pullRequestsChangeBreakdown,+ execute: (input) => routedRequest(WS_METHODS.pullRequestsChangeBreakdown, input),+ staleTimeMs: 60_000,+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),+ }),/*** One write in flight per change request: the host applies these in order, and a reader* ticking down a file list faster than the round trip would otherwise race their own presses.diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 1777dc6762f..1bdedef2475 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -682,6 +682,26 @@ export const PullRequestFilesViewedResult = Schema.Struct({});export type PullRequestFilesViewedResult = typeof PullRequestFilesViewedResult.Type;+const PullRequestLineCount = Schema.Struct({+ additions: NonNegativeInt,+ deletions: NonNegativeInt,+});++/**+ * A change's line counts split by what the changed files are, judged from their paths. Null when+ * the host gives no per-file counts, or has more files than one read covers: a split of part of+ * the change would not add up to the totals shown beside it.+ */+export const PullRequestChangeBreakdown = Schema.NullOr(+ Schema.Struct({+ code: PullRequestLineCount,+ tests: PullRequestLineCount,+ mocks: PullRequestLineCount,+ generated: PullRequestLineCount,+ }),+);+export type PullRequestChangeBreakdown = typeof PullRequestChangeBreakdown.Type;+const MAX_FILES_VIEWED_PRESSES = 500;export const PullRequestSetFilesViewedInput = Schema.Struct({diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex ea834d15caa..d7a11234c44 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -165,6 +165,7 @@ import { PullRequestReviewGuideResult } from "./pullRequestReviewGuide.ts";import {PullRequestActionInput,PullRequestActivity,+ PullRequestChangeBreakdown,PullRequestCommentInput,PullRequestCommentUpdateInput,PullRequestDetail,@@ -539,6 +540,7 @@ export const WS_METHODS = {pullRequestsThreadComments: "pullRequests.threadComments",pullRequestsDiffFileContents: "pullRequests.diffFileContents",pullRequestsFilesViewed: "pullRequests.filesViewed",+ pullRequestsChangeBreakdown: "pullRequests.changeBreakdown",pullRequestsSetFilesViewed: "pullRequests.setFilesViewed",pullRequestsRunAction: "pullRequests.runAction",pullRequestsUpdate: "pullRequests.update",@@ -1045,6 +1047,12 @@ const WsPullRequestsFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsFilesViewederror: PullRequestRpcError,});+const WsPullRequestsChangeBreakdownRpc = Rpc.make(WS_METHODS.pullRequestsChangeBreakdown, {+ payload: PullRequestRef,+ success: PullRequestChangeBreakdown,+ error: PullRequestRpcError,+});+const WsPullRequestsSetFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsSetFilesViewed, {payload: PullRequestSetFilesViewedInput,success: Schema.Void,@@ -1954,6 +1962,7 @@ export const WsRpcGroup = RpcGroup.make(WsPullRequestsThreadCommentsRpc,WsPullRequestsDiffFileContentsRpc,WsPullRequestsFilesViewedRpc,+ WsPullRequestsChangeBreakdownRpc,WsPullRequestsSetFilesViewedRpc,WsPullRequestsRunActionRpc,WsPullRequestsUpdateRpc,diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex cd9137885a5..31828017d81 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -3,6 +3,10 @@"private": true,"type": "module","exports": {+ "./changedFileKind": {+ "types": "./src/changedFileKind.ts",+ "import": "./src/changedFileKind.ts"+ },"./githubMarkdownLinks": {"types": "./src/githubMarkdownLinks.ts","import": "./src/githubMarkdownLinks.ts"diff --git a/packages/shared/src/changedFileKind.test.ts b/packages/shared/src/changedFileKind.test.tsnew file mode 100644index 00000000000..a3a8fd62fae--- /dev/null+++ b/packages/shared/src/changedFileKind.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vite-plus/test";++import { classifyChangedFile } from "./changedFileKind.ts";++describe("classifyChangedFile", () => {+ it.each([+ ["apps/server/src/ws.ts", "code"],+ ["src/latest.ts", "code"],+ ["src/Latest.java", "code"],+ ["src/contest.py", "code"],+ ["src/mockingbird.ts", "code"],+ ["src/testimonials/List.tsx", "code"],+ ["apps/web/src/foo.test.ts", "tests"],+ ["apps/web/src/Foo.browser.test.tsx", "tests"],+ ["src/foo.spec.js", "tests"],+ ["pkg/server_test.go", "tests"],+ ["tests/test_api.py", "tests"],+ ["conftest.py", "tests"],+ ["src/main/java/RequestTest.java", "tests"],+ ["Sources/AppTests.swift", "tests"],+ ["src/HTTPTest.java", "tests"],+ ["Sources/URLTests.swift", "tests"],+ ["spec/models/user_spec.rb", "tests"],+ ["src/__tests__/helpers.ts", "tests"],+ ["src/testUtils.ts", "code"],+ ["src\\__tests__\\app.ts", "tests"],+ ["src/__mocks__/fs.ts", "mocks"],+ ["test/fixtures/pr.json", "mocks"],+ ["src/__snapshots__/view.test.ts.snap", "mocks"],+ ["src/api.mock.ts", "mocks"],+ ["src/mockServer.ts", "mocks"],+ ["pkg/testdata/input.txt", "mocks"],+ ["pnpm-lock.yaml", "generated"],+ ["apps/web/package-lock.json", "generated"],+ ["go.sum", "generated"],+ ["src/routeTree.gen.ts", "generated"],+ ["src/__generated__/types.ts", "generated"],+ ["dist/app.min.js", "generated"],+ ] as const)("%s is %s", (path, kind) => {+ expect(classifyChangedFile(path)).toBe(kind);+ });+});diff --git a/packages/shared/src/changedFileKind.ts b/packages/shared/src/changedFileKind.tsnew file mode 100644index 00000000000..e2d6dcbe1d7--- /dev/null+++ b/packages/shared/src/changedFileKind.ts@@ -0,0 +1,76 @@+import type { PullRequestChangeBreakdown } from "@t3tools/contracts";++export type ChangedFileKind = keyof NonNullable<PullRequestChangeBreakdown>;++const GENERATED_FILES = new Set([+ "bun.lock",+ "bun.lockb",+ "cargo.lock",+ "composer.lock",+ "deno.lock",+ "flake.lock",+ "gemfile.lock",+ "go.sum",+ "gradle.lockfile",+ "mix.lock",+ "npm-shrinkwrap.json",+ "package-lock.json",+ "packages.lock.json",+ "pipfile.lock",+ "pnpm-lock.yaml",+ "podfile.lock",+ "poetry.lock",+ "pubspec.lock",+ "uv.lock",+ "yarn.lock",+]);+const GENERATED_NAME =+ /(\.generated\.|\.gen\.|\.g\.dart$|\.pb\.go$|_pb2(_grpc)?\.py$|\.pb\.(cc|h)$|\.min\.(js|css)$|\.(js|css)\.map$)/;+const GENERATED_DIRS = new Set(["__generated__", "generated"]);++const MOCK_NAME =+ /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$|^(mocks?|fixtures?|stubs?|fakes?)([-_.A-Z]|$))/;+const MOCK_DIRS = new Set([+ "__fixtures__",+ "__mocks__",+ "__snapshots__",+ "fakes",+ "fixture",+ "fixtures",+ "mock",+ "mocks",+ "stubs",+ "testdata",+]);++const TEST_NAME =+ /(\.(test|spec|e2e)\.[^.]+$|_(test|spec)\.[^.]+$|^test_.+\.py$|^conftest\.py$|^(vitest|jest)\.setup\.[^.]+$)/i;+// Case-sensitive: `FooTest.java` is a test class, `Latest.java` is not.+const CLASS_TEST_NAME = /(Tests?|Spec)\.(java|kt|kts|scala|groovy|cs|php|swift|m)$/;+const TEST_DIRS = new Set([+ "__tests__",+ "__test__",+ "cypress",+ "e2e",+ "spec",+ "specs",+ "test",+ "tests",+]);++/**+ * Sorts a changed file by its path alone, using common naming conventions. Lockfiles and build+ * output count as generated, and test support (mocks, fixtures, snapshots) is kept apart from the+ * tests themselves, so a reviewer can see how much of a change is logic.+ */+export function classifyChangedFile(path: string): ChangedFileKind {+ const segments = path.replaceAll("\\", "/").split("/");+ const name = segments.pop() ?? "";+ const dirs = segments.map((segment) => segment.toLowerCase());+ const inDir = (set: ReadonlySet<string>) => dirs.some((dir) => set.has(dir));+ if (GENERATED_FILES.has(name.toLowerCase()) || GENERATED_NAME.test(name) || inDir(GENERATED_DIRS))+ return "generated";+ if (MOCK_NAME.test(name) || inDir(MOCK_DIRS)) return "mocks";+ if (TEST_NAME.test(name) || CLASS_TEST_NAME.test(name) || inDir(TEST_DIRS)) return "tests";+ return "code";+}diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex 0aadb0bbc92..3bb7a757f77 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -226,6 +226,16 @@ export interface ProviderFilesViewed {readonly truncated: boolean;}+export interface ProviderFileStats {+ readonly files: ReadonlyArray<{+ readonly path: string;+ readonly additions: number;+ readonly deletions: number;+ }>;+ /** The host has more files than were read. */+ readonly truncated: boolean;+}+/*** Opaque strings, compared only against one another, where the empty string is the answer for a* 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 {input: ProviderRepositoryRef & { readonly number: number },) => Effect.Effect<ProviderFilesViewed, PullRequestProviderError>;+ /** Line counts for every changed file. Optional: a host without one shows no breakdown. */+ readonly getFileStats?: (+ input: ProviderRepositoryRef & { readonly number: number },+ ) => Effect.Effect<ProviderFileStats, PullRequestProviderError>;+/*** A host with no bulk form is still owed one round trip for the batch rather than one per* file, since the point of gathering presses is that the host is asked once.diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex 0833d2d4339..c25699714d1 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -59,6 +59,7 @@ import {pullRequestChecksFromContexts,decodeWorkflowRunsJson,type GitHubPullRequestCore,+ type GitHubPullRequestFileStat,type GitHubPullRequestWatchFingerprint,isSubjectOfPullRequest,LenientPullRequestList,@@ -71,6 +72,7 @@ import {toPullRequestCheckContextsPage,toPullRequestCore,toPullRequestFilesViewedPage,+ toPullRequestFileStatsPage,toPullRequestHeads,toPullRequestNodeId,toPullRequestPreview,@@ -412,6 +414,11 @@ export interface GitHubPullRequestFilesViewed {readonly truncated: boolean;}+export interface GitHubPullRequestFileStats {+ readonly files: ReadonlyArray<GitHubPullRequestFileStat>;+ readonly truncated: boolean;+}+export class GitHubPullRequestApi extends Context.Service<GitHubPullRequestApi,{@@ -562,6 +569,13 @@ export class GitHubPullRequestApi extends Context.Service<readonly number: number;}) => Effect.Effect<GitHubPullRequestFilesViewed, GitHubPullRequestApiError>;+ readonly getPullRequestFileStats: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly number: number;+ }) => Effect.Effect<GitHubPullRequestFileStats, GitHubPullRequestApiError>;+/*** GitHub takes a single path per mutation, so a burst is batched with aliases into one* document rather than one subprocess per press.@@ -2666,6 +2680,34 @@ export const make = Effect.gen(function* () {);},+ getPullRequestFileStats: (input) => {+ const { owner, name } = parseRepositorySelector(input.repository);+ const target = { ...input, operation: "getPullRequestFileStats" };+ return readPages(+ GraphQLClient.pages(client.PullRequestFileStats, {+ variables: { owner, name, number: input.number },+ connection: (result) => {+ const page = toPullRequestFileStatsPage(result);+ return {+ ...page,+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },+ };+ },+ }),+ {+ ...target,+ maxPages: FILES_VIEWED_MAX_PAGES,+ hasNextPage: (page) => page.nextCursor !== null,+ },+ ).pipe(+ graphql(target),+ Effect.map(({ pages, truncated }) => ({+ files: pages.flatMap((page) => page.files),+ truncated,+ })),+ );+ },+setPullRequestFilesViewed: (input) => {if (input.files.length === 0) return Effect.void;const target = { ...input, operation: "setPullRequestFilesViewed" };diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex ad1a8fa68d9..dd710dffcfd 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -524,6 +524,8 @@ export const make = Effect.gen(function* () {getFilesViewed: (input) =>cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),+ getFileStats: (input) =>+ cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),setFilesViewed: (input) =>cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.tsindex 90bf0f5be04..318ba41468c 100644--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts@@ -56,6 +56,7 @@ import type {PullRequestCheckContexts,PullRequestCore,PullRequestFilesViewed,+ PullRequestFileStats,PullRequestHeads,PullRequestPreview as PullRequestPreviewQuery,PullRequestSubject,@@ -1806,6 +1807,29 @@ export function toPullRequestFilesViewedPage(};}+export interface GitHubPullRequestFileStat {+ readonly path: string;+ readonly additions: number;+ readonly deletions: number;+}++export interface GitHubPullRequestFileStatsPage {+ readonly files: ReadonlyArray<GitHubPullRequestFileStat>;+ readonly nextCursor: string | null;+}++export function toPullRequestFileStatsPage(+ result: PullRequestFileStats.Result,+): GitHubPullRequestFileStatsPage {+ const files = result.repository?.pullRequest?.files;+ return {+ files: nodesOf(files).flatMap(({ path, additions, deletions }) =>+ path.length === 0 ? [] : [{ path, additions, deletions }],+ ),+ nextCursor: nextCursorOf(files?.pageInfo),+ };+}+const RawStackPullRequestSchema = Schema.Struct({title: Schema.optional(Schema.String),draft: Schema.optional(Schema.Boolean),diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphqlindex da3778d6af8..7281af8c898 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql+++ b/packages/source-control-github/src/server/pullRequestReads.graphql@@ -475,6 +475,24 @@ query PullRequestFilesViewed($owner: String!, $name: String!, $number: Int!, $af}}+query PullRequestFileStats($owner: String!, $name: String!, $number: Int!, $after: String) {+ repository(owner: $owner, name: $name) {+ pullRequest(number: $number) {+ files(first: 100, after: $after) {+ pageInfo {+ hasNextPage+ endCursor+ }+ nodes {+ path+ additions+ deletions+ }+ }+ }+ }+}+# What a merge that rewrites its message reads first: GitHub's own message for the method, and# whether a merge queue will choose its own instead.query PullRequestMergeMessage(diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.tsindex bbf591bb641..fd0fef547ea 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts@@ -1237,27 +1237,27 @@ export declare namespace LabelCandidates {}/** A file changed in a pull request. */-export const PullRequestChangedFile = Schema.Struct({+export const PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({/** The path of the file. */path: Schema.String,/** The state of the file for the viewer. */viewerViewedState: GraphQL.enumLiterals(Shared.FileViewedState.literals)})-export interface PullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestChangedFile.fields> {}+export interface PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile.fields> {}/** The connection type for PullRequestChangedFile. */-export const PullRequestChangedFileConnection = Schema.Struct({+export const PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({/** Information to aid in pagination. */pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,/** A list of nodes. */- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestChangedFile)))+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile)))})-export interface PullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestChangedFileConnection.fields> {}+export interface PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection.fields> {}/** A repository pull request. */export const PullRequestFilesViewedRepositoryPullRequestPullRequest = Schema.Struct({/** Lists the files changed within this pull request. */- files: Schema.NullOr(PullRequestChangedFileConnection)+ files: Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection)})export interface PullRequestFilesViewedRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestFilesViewedRepositoryPullRequestPullRequest.fields> {}@@ -1298,6 +1298,70 @@ export declare namespace PullRequestFilesViewed {export type Result = typeof PullRequestFilesViewed.result.Type}+/** A file changed in a pull request. */+export const PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({+ /** The path of the file. */+ path: Schema.String,+ /** The number of additions to the file. */+ additions: Shared.Int,+ /** The number of deletions to the file. */+ deletions: Shared.Int+})+export interface PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile.fields> {}++/** The connection type for PullRequestChangedFile. */+export const PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({+ /** Information to aid in pagination. */+ pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,+ /** A list of nodes. */+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile)))+})+export interface PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection.fields> {}++/** A repository pull request. */+export const PullRequestFileStatsRepositoryPullRequestPullRequest = Schema.Struct({+ /** Lists the files changed within this pull request. */+ files: Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection)+})+export interface PullRequestFileStatsRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryPullRequestPullRequest.fields> {}++/** A repository contains the content for a project. */+export const PullRequestFileStatsRepositoryRepository = Schema.Struct({+ /** Returns a single pull request from the current repository by number. */+ pullRequest: Schema.NullOr(PullRequestFileStatsRepositoryPullRequestPullRequest)+})+export interface PullRequestFileStatsRepositoryRepository extends Schema.Struct.Type<typeof PullRequestFileStatsRepositoryRepository.fields> {}++/** `query PullRequestFileStats` */+export const PullRequestFileStats = GraphQL.query("PullRequestFileStats", {+ document: {+ variables: [+ { name: "owner", body: "String!" },+ { name: "name", body: "String!" },+ { name: "number", body: "Int!" },+ { name: "after", body: "String" }+ ],+ selections: [+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){files(first:100 after:$", "after", "){pageInfo{hasNextPage endCursor}nodes{path additions deletions}}}}"] }+ ],+ fragments: []+ },+ variables: {+ owner: Schema.String,+ name: Schema.String,+ number: Shared.Int,+ after: Schema.optional(Schema.NullOr(Schema.String))+ },+ result: Schema.Struct({+ /** Lookup a given repository by the owner and repository name. */+ repository: Schema.NullOr(PullRequestFileStatsRepositoryRepository)+ })+})+export declare namespace PullRequestFileStats {+ export type Variables = typeof PullRequestFileStats.variables.Type+ export type Result = typeof PullRequestFileStats.result.Type+}+/** A repository pull request. */export const PullRequestMergeMessageRepositoryPullRequestPullRequest = Schema.Struct({/** Indicates whether the pull request's base ref has a merge queue enabled. */@@ -1523,4 +1587,4 @@ export declare namespace PullRequestSourceBranch {}/** Every operation in pullRequestReads.graphql. */-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)+export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)