TypeScript
fix(gitlab): merge requests show their line counts (#22374)
Antony444df6185081
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.tsindex 16326f57ffe..d4d8369f97f 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts@@ -1184,4 +1184,92 @@ layer("GitLabPullRequestCli.layer", (it) => {assert.strictEqual(mockedExecute.mock.calls.length, 3);}),);++ it.effect(+ "reads line counts a hundred at a time per project, keeping the reads that answered",+ () =>+ Effect.gen(function* () {+ const variablesOf = (stdin: string | undefined) =>+ (+ JSON.parse(stdin ?? "{}") as {+ readonly variables: {+ readonly fullPath: string;+ readonly iids: ReadonlyArray<string>;+ };+ }+ ).variables;+ mockedExecute.mockImplementation((request) => {+ const { fullPath, iids } = variablesOf(request.stdin);+ // GitLab answers only what it has (iid 3 is missing), and one project's read fails.+ const nodes = iids+ .filter((iid) => iid !== "3")+ .map((iid) => ({ iid, diffStatsSummary: { additions: Number(iid), deletions: 1 } }));+ return Effect.succeed(+ output(+ JSON.stringify(+ fullPath === "acme/api"+ ? { errors: [{ message: "Query timed out" }] }+ : { data: { project: { mergeRequests: { nodes } } } },+ ),+ ),+ );+ });+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const stats = yield* cli.listMergeRequestStats({+ cwd: "/w",+ changeRequests: [+ ...Array.from({ length: 150 }, (_, index) => ({+ repository: "acme/web",+ number: index + 1,+ })),+ { repository: "acme/api", number: 9 },+ ],+ });++ expect(stats).toHaveLength(149);+ expect(stats).toContainEqual({+ repository: "acme/web",+ number: 150,+ additions: 150,+ deletions: 1,+ });+ expect(stats.some((stat) => stat.number === 3 || stat.repository === "acme/api")).toBe(+ false,+ );+ expect(+ mockedExecute.mock.calls.map(([request]) => {+ const { fullPath, iids } = variablesOf(request.stdin);+ return [fullPath, iids.length];+ }),+ ).toEqual([+ ["acme/web", 100],+ ["acme/web", 50],+ ["acme/api", 1],+ ]);+ }),+ );+ it.effect.each([+ GitLabCli.GitLabCliUnavailableError,+ GitLabCli.GitLabCliAuthenticationError,+ GitLabCli.GitLabCliRateLimitError,+ ])("propagates unusable CLI and account failures from stats (%s)", (ErrorType) =>+ Effect.gen(function* () {+ const error = new ErrorType({+ operation: "execute",+ command: "glab",+ cwd: "/w",+ cause: null,+ });+ mockedExecute.mockReturnValueOnce(Effect.fail(error));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;+ const result = yield* Effect.result(+ cli.listMergeRequestStats({+ cwd: "/w",+ changeRequests: [{ repository: "acme/web", number: 7 }],+ }),+ );+ expect(result).toMatchObject({ _tag: "Failure", failure: error });+ }),+ );});diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex 0c1a74827bf..43f77e56c55 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -37,6 +37,8 @@ import {decodeMergeRequestDiffsJson,decodeMergeRequestChangesJson,decodeMergeRequestListJson,+ decodeMergeRequestFileStatsJson,+ decodeMergeRequestStatsJson,decodeNotesJson,decodeOwnAwardIdJson,decodeProjectMergeCapabilitiesJson,@@ -45,13 +47,18 @@ import {decodeRepositoryBlobsJson,decodeViewerJson,gitLabAwardName,+ MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,+ MERGE_REQUEST_STATS_GRAPHQL_QUERY,REPOSITORY_BLOBS_GRAPHQL_QUERY,type GitLabDiffRefs,type GitLabMergeRequestDetail,type GitLabMergeRequestListItem,type GitLabProjectUsers,} from "./gitLabMergeRequestJson.ts";-import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";+import type {+ ProviderFileStats,+ ProviderListCursor,+} from "@t3tools/source-control-core/server/PullRequestProvider";export class GitLabMergeRequestReadError extends Schema.TaggedError<GitLabMergeRequestReadError>()("GitLabMergeRequestReadError",@@ -237,6 +244,29 @@ export class GitLabPullRequestCli extends Context.Service<readonly number: number;}) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;+ /** Line counts for the given merge requests; one with no answer is left out. */+ readonly listMergeRequestStats: (input: {+ readonly cwd: string;+ readonly changeRequests: ReadonlyArray<{+ readonly repository: string;+ readonly number: number;+ }>;+ }) => Effect.Effect<+ ReadonlyArray<{+ readonly repository: string;+ readonly number: number;+ readonly additions: number;+ readonly deletions: number;+ }>,+ GitLabPullRequestCliError+ >;++ readonly getMergeRequestFileStats: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly number: number;+ }) => Effect.Effect<ProviderFileStats, GitLabPullRequestCliError>;+readonly listNotes: (input: {readonly cwd: string;readonly repository: string;@@ -1021,6 +1051,97 @@ export const make = Effect.gen(function* () {}),);+ /** The stats connection hands back one page, so a repository's rows are asked for 100 at a time. */+ const STAT_IIDS_PER_REQUEST = 100;++ const graphqlRead = <A>(input: {+ readonly cwd: string;+ readonly operation: string;+ readonly query: string;+ readonly variables: Record<string, unknown>;+ readonly decode: (raw: string) => Result.Result<A, unknown>;+ }) =>+ api({+ cwd: input.cwd,+ path: "graphql",+ method: "POST",+ stdin: JSON.stringify({ query: input.query, variables: input.variables }),+ }).pipe(+ Effect.flatMap((result) => {+ const decoded = input.decode(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: input.operation,+ cause: decoded.failure,+ }),+ );+ }),+ );++ const mergeRequestStats = (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly numbers: ReadonlyArray<number>;+ }) =>+ graphqlRead({+ cwd: input.cwd,+ operation: "listMergeRequestStats",+ query: MERGE_REQUEST_STATS_GRAPHQL_QUERY,+ variables: { fullPath: input.repository, iids: input.numbers.map(String) },+ decode: decodeMergeRequestStatsJson,+ });++ const STAT_REQUEST_CONCURRENCY = 4;++ const listMergeRequestStats: GitLabPullRequestCli["Service"]["listMergeRequestStats"] = (+ input,+ ) => {+ const byRepository = new Map<string, Set<number>>();+ for (const { repository, number } of input.changeRequests) {+ const numbers = byRepository.get(repository) ?? new Set<number>();+ numbers.add(number);+ byRepository.set(repository, numbers);+ }+ const reads: Array<{ readonly repository: string; readonly numbers: ReadonlyArray<number> }> =+ [];+ for (const [repository, numberSet] of byRepository) {+ const numbers = [...numberSet];+ for (let start = 0; start < numbers.length; start += STAT_IIDS_PER_REQUEST) {+ reads.push({ repository, numbers: numbers.slice(start, start + STAT_IIDS_PER_REQUEST) });+ }+ }+ return Effect.forEach(+ reads,+ (read) =>+ mergeRequestStats({ cwd: input.cwd, ...read }).pipe(+ Effect.map((stats) =>+ read.numbers.flatMap((number) => {+ const stat = stats.get(number);+ return stat === undefined ? [] : [{ repository: read.repository, number, ...stat }];+ }),+ ),+ // One read GitLab could not answer costs its own rows their counts, not every other+ // read's on the same page. An unusable CLI or account still reaches the caller.+ Effect.catchIf(+ (cause) =>+ cause._tag !== "GitLabCliUnavailableError" &&+ cause._tag !== "GitLabCliAuthenticationError" &&+ cause._tag !== "GitLabCliRateLimitError",+ (cause) =>+ Effect.logWarning("GitLab merge request line count read failed", {+ repository: read.repository,+ reason: cause._tag,+ }).pipe(Effect.as([])),+ ),+ ),+ { concurrency: STAT_REQUEST_CONCURRENCY },+ ).pipe(Effect.map((results) => results.flat()));+ };+// GitLab charges by path count and returns one connection page; respect both limits.const BLOB_PATHS_PER_REQUEST = 100;@@ -1125,6 +1246,18 @@ export const make = Effect.gen(function* () {getMergeRequestDetail: mergeRequestDetail,+ listMergeRequestStats,++ getMergeRequestFileStats: Effect.fn("GitLabPullRequestCli.getMergeRequestFileStats")((input) =>+ graphqlRead({+ cwd: input.cwd,+ operation: "getMergeRequestFileStats",+ query: MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,+ variables: { fullPath: input.repository, iid: String(input.number) },+ decode: decodeMergeRequestFileStatsJson,+ }),+ ),+listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) {return notesPage({ ...input, page: 1, collected: [] });}),diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.tsindex cc6bab6c53f..a00569a1b6b 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts@@ -74,6 +74,7 @@ describe("getChangeRequest base freshness", () => {Effect.provide(Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({getMergeRequestDetail: () => Effect.succeed(detail),+ listMergeRequestStats: () => Effect.succeed([]),}),),);@@ -85,7 +86,11 @@ describe("getChangeRequest base freshness", () => {}),);- const readWith = (divergence: { readonly divergedCommits?: number }) =>+ const readWith = (+ divergence: { readonly divergedCommits?: number },+ stats: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["listMergeRequestStats"] = () =>+ Effect.succeed([]),+ ) =>Effect.gen(function* () {const provider = yield* make;return yield* provider.getChangeRequest({@@ -100,6 +105,7 @@ describe("getChangeRequest base freshness", () => {getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),getProjectMergeCapabilities: () =>Effect.succeed({ merge: true, squash: true, rebase: true }),+ listMergeRequestStats: stats,}),),);@@ -121,6 +127,62 @@ describe("getChangeRequest base freshness", () => {expect(changeRequest.behindBy).toBeUndefined();}),);++ it.effect("fills in the line counts the REST detail leaves out", () =>+ Effect.gen(function* () {+ const changeRequest = yield* readWith({}, () =>+ Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),+ );++ expect(changeRequest.additions).toBe(40);+ expect(changeRequest.deletions).toBe(2);+ }),+ );++ it.effect("reports an unauthenticated line count read instead of a detail without counts", () =>+ Effect.gen(function* () {+ const result = yield* Effect.result(+ readWith({}, () =>+ Effect.fail(+ new GitLabCli.GitLabCliAuthenticationError({+ operation: "execute",+ command: "glab",+ cwd: "/w",+ cause: null,+ }),+ ),+ ),+ );++ expect(result).toMatchObject({+ _tag: "Failure",+ failure: { _tag: "PullRequestProviderError", reason: "unauthenticated" },+ });+ }),+ );++ it.effect("gives linked threads line counts without reading the merge settings", () =>+ Effect.gen(function* () {+ const summary = yield* Effect.gen(function* () {+ const provider = yield* make;+ const read = provider.getChangeRequestSummary;+ if (read === undefined) return yield* Effect.die("summary read missing");+ return yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 });+ }).pipe(+ Effect.provide(+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({+ getMergeRequestDetail: () => Effect.succeed(detail),+ getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),+ listMergeRequestStats: () =>+ Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),+ }),+ ),+ );++ expect(summary.additions).toBe(40);+ expect(summary.deletions).toBe(2);+ }),+ );});describe("merge request reads", () => {@@ -157,6 +219,7 @@ describe("merge request reads", () => {const provider = yield* make.pipe(Effect.provide(Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({+ listMergeRequestStats: () => Effect.succeed([]),getMergeRequestDetail: (input) =>Effect.sync(() => {calls.detail += 1;@@ -199,6 +262,11 @@ describe("merge request reads", () => {yield* checks(reference);expect(calls.detail).toBe(1);++ const summary = provider.getChangeRequestSummary;+ assert.isDefined(summary);+ yield* summary(reference);+ expect(calls.detail).toBe(2);}),);diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex 79c3d43c019..7184ebaa3ca 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -173,6 +173,25 @@ export const make = Effect.gen(function* () {}),);+ // REST omits line counts; the CLI recovers optional stats failures per batch.+ const mergeRequestWithStats = (+ input: {+ readonly cwd: string;+ readonly repository: string;+ readonly number: number;+ },+ detail = cli.getMergeRequestDetail(input),+ ) =>+ Effect.all([detail, cli.listMergeRequestStats({ cwd: input.cwd, changeRequests: [input] })], {+ concurrency: 2,+ }).pipe(+ Effect.map(([mergeRequest, [stat]]) =>+ stat === undefined+ ? mergeRequest+ : { ...mergeRequest, additions: stat.additions, deletions: stat.deletions },+ ),+ );+const provider: PullRequestProviderApi = {kind: SourceControlProviderKind.make("gitlab"),capabilities: CAPABILITIES,@@ -199,6 +218,14 @@ export const make = Effect.gen(function* () {Effect.map((batch) => ({ ...batch, continues: true })),),+ getFileStats: (input) =>+ cli.getMergeRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),++ listChangeRequestStats: (input) =>+ cli+ .listMergeRequestStats({ cwd: input.cwd, changeRequests: input.changeRequests })+ .pipe(Effect.mapError(fail("listChangeRequestStats"))),+getChangeRequestChecks: (input) =>mergeRequestDetail(input).pipe(Effect.map(({ state, checks }) => ({ state, checks })),@@ -210,12 +237,12 @@ export const make = Effect.gen(function* () {cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),getChangeRequestSummary: (input) =>- cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestSummary"))),+ mergeRequestWithStats(input).pipe(Effect.mapError(fail("getChangeRequestSummary"))),getChangeRequest: (input) =>Effect.all([- mergeRequestDetail(input),+ mergeRequestWithStats(input, mergeRequestDetail(input)),Cache.get(projectMergeCapabilities, JSON.stringify([input.cwd, input.repository])),],{ concurrency: 2 },diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.tsindex 92f9ed19fe4..890aa4b8dbe 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts@@ -8,6 +8,8 @@ import {decodeMergeRequestDetailJson,decodeMergeRequestDiffsJson,decodeMergeRequestListJson,+ decodeMergeRequestFileStatsJson,+ decodeMergeRequestStatsJson,decodeNotesJson,decodeOwnAwardIdJson,} from "./gitLabMergeRequestJson.ts";@@ -620,3 +622,59 @@ describe("decodeRepositoryBlobsJson", () => {).toEqual(new Map());});});++describe("decodeMergeRequestStatsJson", () => {+ it("keys the counts by merge request number", () => {+ const stats = expectSuccess(+ decodeMergeRequestStatsJson(+ JSON.stringify({+ data: {+ project: {+ mergeRequests: {+ nodes: [+ { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },+ { iid: "8", diffStatsSummary: null },+ ],+ },+ },+ },+ }),+ ),+ );++ // A merge request without a summary is left out rather than shown as zero lines changed.+ expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);+ });++ it("answers nothing for a project the token cannot see", () => {+ const stats = expectSuccess(+ decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),+ );++ expect(stats.size).toBe(0);+ });++ it("reports a file list shorter than the summary as truncated", () => {+ const read = (fileCount: number) =>+ expectSuccess(+ decodeMergeRequestFileStatsJson(+ JSON.stringify({+ data: {+ project: {+ mergeRequest: {+ diffStatsSummary: { fileCount },+ diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],+ },+ },+ },+ }),+ ),+ );++ expect(read(1)).toEqual({+ files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],+ truncated: false,+ });+ expect(read(2).truncated).toBe(true);+ });+});diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex 9c315669d02..af21a5ed9f7 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -946,3 +946,118 @@ export function decodeRepositoryBlobsJson(}return Result.succeed(blobs);}++/**+ * Line counts for merge requests of one project. The REST listing carries no line counts, and+ * reading each diff to count them would cost a request per row, so GraphQL's per-merge-request+ * summary is asked for in one read instead.+ */+export const MERGE_REQUEST_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {+ project(fullPath: $fullPath) {+ mergeRequests(iids: $iids, first: 100) {+ nodes { iid diffStatsSummary { additions deletions } }+ }+ }+}`;++const LineCountsSchema = Schema.Struct({ additions: Schema.Int, deletions: Schema.Int });++const RawMergeRequestStatsSchema = Schema.Struct({+ data: Schema.Struct({+ project: Schema.NullOr(+ Schema.Struct({+ mergeRequests: Schema.NullOr(+ Schema.Struct({+ nodes: Schema.Array(+ Schema.NullOr(+ Schema.Struct({+ iid: Schema.String,+ diffStatsSummary: Schema.NullOr(LineCountsSchema),+ }),+ ),+ ),+ }),+ ),+ }),+ ),+ }),+});++const decodeMergeRequestStats = decodeJsonResult(RawMergeRequestStatsSchema);++/**+ * The counts by merge request number. A merge request GitLab returned no summary for is left+ * out rather than counted as zero, so its row keeps whatever it already showed.+ */+export function decodeMergeRequestStatsJson(+ raw: string,+): Result.Result<+ ReadonlyMap<number, { readonly additions: number; readonly deletions: number }>,+ DecodeFailure+> {+ const decoded = decodeMergeRequestStats(raw);+ if (!Result.isSuccess(decoded)) {+ return Result.fail(decoded.failure);+ }+ const stats = new Map<number, { readonly additions: number; readonly deletions: number }>();+ for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) {+ const iid = Number(node?.iid);+ if (!Number.isSafeInteger(iid) || iid <= 0 || node?.diffStatsSummary == null) continue;+ stats.set(iid, node.diffStatsSummary);+ }+ return Result.succeed(stats);+}++/** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */+export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {+ project(fullPath: $fullPath) {+ mergeRequest(iid: $iid) {+ diffStatsSummary { fileCount }+ diffStats { path additions deletions }+ }+ }+}`;++const decodeMergeRequestFileStats = decodeJsonResult(+ Schema.Struct({+ data: Schema.Struct({+ project: Schema.NullOr(+ Schema.Struct({+ mergeRequest: Schema.NullOr(+ Schema.Struct({+ diffStatsSummary: Schema.NullOr(Schema.Struct({ fileCount: Schema.Int })),+ diffStats: Schema.NullOr(+ Schema.Array(Schema.Struct({ path: Schema.String, ...LineCountsSchema.fields })),+ ),+ }),+ ),+ }),+ ),+ }),+ }),+);++/**+ * GitLab stops listing files past its diff limits while the summary still counts them all, so a+ * shorter list is reported as truncated rather than as a breakdown that misses lines.+ */+export function decodeMergeRequestFileStatsJson(raw: string): Result.Result<+ {+ readonly files: ReadonlyArray<{+ readonly path: string;+ readonly additions: number;+ readonly deletions: number;+ }>;+ readonly truncated: boolean;+ },+ DecodeFailure+> {+ const decoded = decodeMergeRequestFileStats(raw);+ if (!Result.isSuccess(decoded)) {+ return Result.fail(decoded.failure);+ }+ const mergeRequest = decoded.success.data.project?.mergeRequest;+ const files = mergeRequest?.diffStats ?? [];+ const fileCount = mergeRequest?.diffStatsSummary?.fileCount;+ return Result.succeed({ files, truncated: fileCount === undefined || files.length < fileCount });+}