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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions packages/source-control-gitlab/src/server/GitLabCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo
import {
decodeGitLabMergeRequestJson,
decodeGitLabMergeRequestListJson,
type NormalizedGitLabMergeRequestRecord,
withSourceProjectPath,
} from "./gitLabMergeRequests.ts";
import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";

Expand Down Expand Up @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect(
Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })),
);

const decodeGitLabProjectPath = Schema.decodeEffect(
Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })),
);

const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
Expand Down Expand Up @@ -559,13 +565,43 @@ export const make = Effect.gen(function* () {
),
);

// glab's MR JSON names a fork's source project only by `source_project_id`.
const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* (
cwd: string,
records: ReadonlyArray<NormalizedGitLabMergeRequestRecord>,
paths: Map<number, string | null>,
) {
const ids = new Set<number>();
for (const record of records) {
const id = record.unresolvedSourceProjectId;
if (id !== undefined && !paths.has(id)) ids.add(id);
}
yield* Effect.forEach(
ids,
(id) =>
execute({ cwd, args: ["api", `projects/${id}`] }).pipe(
Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())),
Effect.map((project) => project.path_with_namespace),
Effect.orElseSucceed(() => null),
Effect.map((path) => void paths.set(id, path)),
),
{ concurrency: 8, discard: true },
);
return records.map((record) =>
record.unresolvedSourceProjectId === undefined
? record
: withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null),
);
});

return GitLabCli.of({
execute,
listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) {
const limit = input.limit ?? 20;
let pageSize = limit;
let page = 1;
const items: GitLabMergeRequestSummary[] = [];
const sourceProjectPaths = input.source?.owner ? new Map<number, string | null>() : null;
while (items.length < limit) {
const result = yield* execute({
cwd: input.cwd,
Expand Down Expand Up @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () {
cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated",
});
}
items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt));
// Only a fork head can match a fork's merge request, so other lookups skip the API calls.
const records = sourceProjectPaths
? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths)
: decoded.success;
items.push(...records.map(toSummaryWithOptionalUpdatedAt));
// Count raw entries: the decoder drops invalid ones, which would end paging early.
const entries = decodeJsonArray(raw);
if (
Expand Down Expand Up @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () {
);
}

return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe(
Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)),
);
}),
),
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names
}),
);

// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its
// source project only by `source_project_id`, never by a `source_project` path.
it.effect("names a fork merge request's source project from real glab list output", () =>
Effect.gen(function* () {
const branch = "feature/fork-work";
const mergeRequest = (iid: number, sourceProjectId: number) => ({
id: 9000 + iid,
iid,
project_id: 100,
title: `Work ${iid}`,
state: "opened",
target_branch: "main",
source_branch: branch,
source_project_id: sourceProjectId,
target_project_id: 100,
draft: false,
sha: "0123456789abcdef0123456789abcdef01234567",
updated_at: "2026-04-07T15:00:00.000Z",
references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` },
web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`,
});
const output = JSON.stringify([
mergeRequest(1, 101),
mergeRequest(2, 101),
mergeRequest(3, 100),
mergeRequest(4, 102),
]);
const apiCalls: ReadonlyArray<string>[] = [];
const provider = yield* GitLabSourceControlProvider.make.pipe(
Effect.provide(
GitLabCli.layer.pipe(
Layer.provideMerge(
TestSourceControlHost.layer({
process: {
run: (input) =>
Effect.sync(() => {
if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output);
apiCalls.push(input.args);
return TestSourceControlHost.processOutput(
input.args[1] === "projects/101"
? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" })
: "not json",
);
}),
},
}),
),
Layer.provide(FileSystem.layerNoop({})),
),
),
);

const upstreamHead = yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: branch,
state: "open",
limit: 20,
});
expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner");
expect(apiCalls).toEqual([]);

const changeRequests = yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: `alice:${branch}`,
state: "open",
limit: 20,
});
// GitManager drops a cross-repository MR whose head project is unnamed.
expect(changeRequests).toMatchObject([
{
number: 1,
isCrossRepository: true,
headRepositoryNameWithOwner: "alice/upstream",
headRepositoryOwnerLogin: "alice",
},
{ number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" },
{ number: 3, isCrossRepository: false },
{ number: 4, isCrossRepository: true },
]);
expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner");
expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner");
expect(apiCalls).toHaveLength(2);
expect(apiCalls).toEqual(
expect.arrayContaining([
["api", "projects/101"],
["api", "projects/102"],
]),
);
}),
);

const withRepository = <A, E>(
test: (input: {
readonly git: (...args: string[]) => Effect.Effect<string, GitCommandError>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,13 @@ it.effect(
headSelectors: ["octocat:feature", "feature"],
state: "open",
}),
{ headSelectors: ["octocat:feature"], limit: 100 },
);
assert.deepStrictEqual(
provider.headBranchProbe?.({
headSelectors: ["feature", "octocat:feature"],
state: "open",
}),
{ headSelectors: ["feature"], limit: 100 },
);
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () {

return SourceControlProvider.SourceControlProvider.of({
kind: SourceControlProviderKind.make("gitlab"),
// GitLab lists fork merge requests by source branch with no owner filter, so read a full page.
headBranchProbe: ({ headSelectors }) => ({
headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
limit: 100,
}),
// GitLab lists fork merge requests by source branch with no owner filter, so read a full page
// once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork
// head, which tells the list to name fork source projects.
headBranchProbe: ({ headSelectors }) => {
const byBranch = new Map<string, string>();
for (const selector of headSelectors) {
const branch = SourceControlProvider.sourceBranch({ headSelector: selector });
if (!byBranch.has(branch)) byBranch.set(branch, selector);
}
return { headSelectors: [...byBranch.values()], limit: 100 };
},
readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")(
function ({ cwd, treeish }) {
return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute);
Expand Down
20 changes: 20 additions & 0 deletions packages/source-control-gitlab/src/server/gitLabMergeRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord {
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
/** Set when a cross-repository MR names its source project only by id. */
readonly unresolvedSourceProjectId?: number;
}

const GitLabProjectReferenceSchema = Schema.Struct({
Expand Down Expand Up @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord(
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
...(isCrossRepository === true &&
!sourceProjectPath &&
typeof raw.source_project_id === "number"
? { unresolvedSourceProjectId: raw.source_project_id }
: {}),
};
}

export function withSourceProjectPath(
record: NormalizedGitLabMergeRequestRecord,
sourceProjectPath: string | null,
): NormalizedGitLabMergeRequestRecord {
const { unresolvedSourceProjectId: _, ...resolved } = record;
const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);
return {
...resolved,
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}

Expand Down
Loading