@devries-cameron20 / t3code Mirror · read-only / commits / 49f849ecce
Fork 0

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 23, 16:45 UTC

refactor(source-control): GitManager reads provider resolvers, not host kinds (#17617)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 9, 2026 at 16:22 UTC 49f849ecce3667abab7ce9e6aaa42dfd2e3c45d7
11 files changed +190 -107
apps/server/src/git/GitManager.test.ts
+29 -6
@@ -44,6 +44,7 @@ import {
44 } from "@t3tools/contracts";
45 import * as DateTime from "effect/DateTime";
46 import { decodeGitHubPullRequestListJson } from "@t3tools/source-control-github/server/gitHubPullRequests";
47 +import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
48 import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
49 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
50 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
@@ -55,6 +56,7 @@ import * as VcsProjectConfig from "../vcs/VcsProjectConfig.ts";
56 import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
57 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
58 import * as GitWorkflowService from "./GitWorkflowService.ts";
59 +import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
60 import * as GitLabSourceControlProvider from "@t3tools/source-control-gitlab/server/GitLabSourceControlProvider";
61 import {
62 ForgejoPullRequestSchema,
@@ -545,6 +547,13 @@ function createGitHubProviderWithFakeGh(scenario: FakeGhScenario = {}): {
547 return {
548 service: {
549 kind: "github",
550 + // The GitHub provider's own lookup rule and template convention, which GitManager reads
551 + // instead of the kind.
552 + headBranchProbe: ({ headSelectors }) => ({
553 + headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
554 + limit: 100,
555 + }),
556 +
557 listChangeRequests: (input) =>
558 input.state === "open"
559 ? execute({
@@ -745,7 +754,18 @@ function makeManager(input?: {
754 );
755 const layerSourceControlRegistry = Layer.effect(
756 SourceControlProviderRegistry.SourceControlProviderRegistry,
748 - Effect.succeed(input?.sourceControlProvider ?? fakeGitHubProvider).pipe(
757 + Effect.gen(function* () {
758 + // GitHub reads its PR template with git, which the fake gh cannot answer; give the fake
759 + // the package's real reader over the test repository's git.
760 + const git = yield* GitVcsDriver.GitVcsDriver;
761 + return (
762 + input?.sourceControlProvider ?? {
763 + ...fakeGitHubProvider,
764 + readChangeRequestTemplate: ({ cwd, treeish }: { cwd: string; treeish: string }) =>
765 + GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
766 + }
767 + );
768 + }).pipe(
769 Effect.map((provider) =>
770 SourceControlProviderRegistry.SourceControlProviderRegistry.of({
771 resolveLink: (input) => provider.resolveLink?.(input),
@@ -769,9 +789,12 @@ function makeManager(input?: {
789 runForThread: () => Effect.succeed({ status: "no-script" as const }),
790 },
791 ),
772 - layerVcsDriver,
792 layerServerSettings,
774 - ).pipe(Layer.provideMerge(layerSourceControlRegistry), Layer.provideMerge(NodeServices.layer));
793 + ).pipe(
794 + Layer.provideMerge(layerSourceControlRegistry),
795 + Layer.provideMerge(layerVcsDriver),
796 + Layer.provideMerge(NodeServices.layer),
797 + );
798 // Built into the test's scope: the manager reads these stores after this returns.
799 const layerStores = Layer.merge(ProjectionStore.layer, ProjectStore.layer).pipe(
800 Layer.provideMerge(SqlitePersistence.layerMemory),
@@ -4232,7 +4255,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4255 };
4256 const repository = GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
4257 `https://forgejo.example/forgejo/${owner}/project.git`,
4235 - "forgejo",
4258 + { repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
4259 );
4260 expect(repository).toBe(`${owner}/project`);
4261 const context = {
@@ -4253,13 +4276,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4276 expect(
4277 GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
4278 "git@forgejo.example:maria/project.git",
4256 - "forgejo",
4279 + { repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
4280 ),
4281 ).toBe("maria/project");
4282 expect(
4283 GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
4284 "https://gitlab.example/group/maria/project.git",
4262 - "gitlab",
4285 + {},
4286 ),
4287 ).toBe("group/maria/project");
4288 }),
apps/server/src/git/GitManager.ts
+40 -52
@@ -35,7 +35,6 @@ import {
35 ModelSelection,
36 type ProjectId,
37 SourceControlProviderError,
38 - type SourceControlProviderKind,
38 type SourceControlWritingStyleSettings,
39 type ThreadId,
40 type ThreadPullRequestKey,
@@ -81,8 +80,8 @@ import { detachStackFrame } from "./detachStackFrame.ts";
80 import * as ServerSettings from "../serverSettings.ts";
81 import type { GitManagerServiceError } from "@t3tools/contracts";
82 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
83 +import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
84 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
85 -import { detectPrTemplate } from "../sourceControl/PrTemplateDetection.ts";
85 import type { ChangeRequest } from "@t3tools/contracts";
86
87 export interface GitActionProgressReporter {
@@ -314,27 +313,20 @@ function resolvePullRequestWorktreeLocalBranchName(
313 return `t3code/pr-${pullRequest.number}/${suffix}`;
314 }
315
316 +/** The repository's `owner/name` from a remote URL, as `provider` reads its remote paths. */
317 export function parseRepositoryNameWithOwnerFromRemoteUrl(
318 url: string | null,
319 - providerKind?: ChangeRequest["provider"],
319 + provider?: Pick<
320 + SourceControlProvider.SourceControlProvider["Service"],
321 + "repositoryNameFromRemoteUrl"
322 + >,
323 ): string | null {
324 const trimmed = url?.trim() ?? "";
322 - if (trimmed.length === 0) {
323 - return null;
324 - }
325 -
326 - const match =
327 - /^(?:[^@/\s]+@[^:/\s]+:|(?:ssh|https?|git):\/\/[^/]+\/)((?:[^/\s]+\/)+[^/\s]+?)(?:\.git)?\/?$/iu.exec(
328 - trimmed,
329 - );
330 - const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
331 - // Forgejo HTTP paths can include an installation mount; its API always names owner/repo.
332 - if (providerKind === "forgejo" && /^https?:\/\//iu.test(trimmed)) {
333 - return repositoryNameWithOwner.length > 0
334 - ? repositoryNameWithOwner.split("/").slice(-2).join("/")
335 - : null;
336 - }
337 - return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
325 + if (trimmed.length === 0) return null;
326 + return (
327 + provider?.repositoryNameFromRemoteUrl?.(trimmed) ??
328 + SourceControlProvider.repositoryPathFromRemoteUrl(trimmed)
329 + );
330 }
331
332 function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
@@ -625,24 +617,18 @@ function parseCustomCommitMessage(raw: string): { subject: string; body: string
617 };
618 }
619
628 -// Without the owner selector, a bare branch name also lists same-named
629 -// branches on other forks (`main`, `patch-1`), so GitHub probes ask for a full
630 -// page and let matchesBranchHeadContext pick the right head. gh fetches up to
631 -// 100 in one request, and GitHub prices a first:100 connection like first:1.
632 -const GITHUB_HEAD_BRANCH_PROBE_LIMIT = 100;
633 -
634 -// `gh pr list --head` filters on the head ref name alone and accepts anything, so an
635 -// `owner:branch` or `remote:branch` selector silently lists zero pull requests
636 -// while spending a GraphQL call. Git branch names cannot contain ":", and the
637 -// bare head branch is always among the selectors, so GitHub probes skip them and
638 -// leave the owner check to matchesBranchHeadContext.
639 -function probeableHeadSelectors(
640 - providerKind: SourceControlProviderKind,
620 +/** The selectors and page size `provider` asks about when looking up a branch's change requests. */
621 +function headBranchProbe(
622 + provider: SourceControlProvider.SourceControlProvider["Service"],
623 headSelectors: ReadonlyArray<string>,
642 -): ReadonlyArray<string> {
643 - return providerKind === "github"
644 - ? headSelectors.filter((selector) => !selector.includes(":"))
645 - : headSelectors;
624 + state: "open" | "all",
625 +) {
626 + return (
627 + provider.headBranchProbe?.({ headSelectors, state }) ?? {
628 + headSelectors,
629 + limit: state === "open" ? 1 : 20,
630 + }
631 + );
632 }
633
634 function appendUnique(values: string[], next: string | null | undefined): void {
@@ -1430,15 +1416,14 @@ export const make = Effect.gen(function* () {
1416 /^https?:\/\//iu.test(remoteUrl) &&
1417 (repositoryNameWithOwner?.split("/").length ?? 0) > 2
1418 ) {
1433 - const detected = detectSourceControlProviderFromGitRemoteUrl(remoteUrl);
1434 - const kind =
1435 - detected?.kind === "unknown"
1436 - ? yield* sourceControlProvider(cwd).pipe(
1437 - Effect.map((provider) => provider.kind),
1438 - Effect.orElseSucceed(() => undefined),
1439 - )
1440 - : detected?.kind;
1441 - repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, kind);
1419 + const kind = detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind;
1420 + const provider =
1421 + kind === undefined
1422 + ? undefined
1423 + : yield* (
1424 + kind === "unknown" ? sourceControlProvider(cwd) : sourceControlProviders.get(kind)
1425 + ).pipe(Effect.orElseSucceed(() => undefined));
1426 + repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, provider);
1427 }
1428 return {
1429 remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
@@ -1701,13 +1686,13 @@ export const make = Effect.gen(function* () {
1686 >,
1687 ) {
1688 const provider = yield* sourceControlProvider(cwd);
1704 - const headSelectors = probeableHeadSelectors(provider.kind, headContext.headSelectors);
1705 - for (const headSelector of headSelectors) {
1689 + const probe = headBranchProbe(provider, headContext.headSelectors, "open");
1690 + for (const headSelector of probe.headSelectors) {
1691 const pullRequests = yield* provider.listChangeRequests({
1692 cwd,
1693 headSelector,
1694 state: "open",
1710 - limit: provider.kind === "github" ? GITHUB_HEAD_BRANCH_PROBE_LIMIT : 1,
1695 + limit: probe.limit,
1696 });
1697 const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
1698
@@ -1733,12 +1718,13 @@ export const make = Effect.gen(function* () {
1718 const parsedByNumber = new Map<number, PullRequestInfo>();
1719
1720 const provider = yield* sourceControlProvider(cwd);
1736 - for (const headSelector of probeableHeadSelectors(provider.kind, headContext.headSelectors)) {
1721 + const probe = headBranchProbe(provider, headContext.headSelectors, "all");
1722 + for (const headSelector of probe.headSelectors) {
1723 const pullRequests = yield* provider.listChangeRequests({
1724 cwd,
1725 headSelector,
1726 state: "all",
1741 - limit: provider.kind === "github" ? GITHUB_HEAD_BRANCH_PROBE_LIMIT : 20,
1727 + limit: probe.limit,
1728 });
1729
1730 for (const pr of pullRequests.map(toPullRequestInfo)) {
@@ -2129,8 +2115,10 @@ export const make = Effect.gen(function* () {
2115 const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
2116 const policy = yield* resolveStylePolicy(cwd, settings);
2117 const changeRequestTemplate =
2132 - settings.style.followChangeRequestTemplates && provider.kind === "github"
2133 - ? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))
2118 + settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate
2119 + ? Option.getOrUndefined(
2120 + yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }),
2121 + )
2122 : undefined;
2123
2124 const generated = yield* textGeneration.generatePrContent({
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+1 -2
@@ -158,8 +158,7 @@ function bindProviderContext(
158 }
159
160 return SourceControlProvider.SourceControlProvider.of({
161 - kind: provider.kind,
162 - ...(provider.resolveLink ? { resolveLink: provider.resolveLink } : {}),
161 + ...provider,
162 listChangeRequests: (input) =>
163 provider.listChangeRequests({
164 ...input,
apps/server/src/sourceControl/gitHubChangeRequestTemplate.test.ts renamed
+2 -2
@@ -9,7 +9,7 @@ import * as Path from "effect/Path";
9 import * as ServerConfig from "../config.ts";
10 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
11 import * as VcsProcess from "../vcs/VcsProcess.ts";
12 -import { detectPrTemplate } from "./PrTemplateDetection.ts";
12 +import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
13 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
14
15 const SINGLE_TEMPLATE_PATHS = [
@@ -80,7 +80,7 @@ const commitTemplates = (cwd: string) =>
80 const detectTemplate = (cwd: string, treeish = "HEAD") =>
81 Effect.gen(function* () {
82 const git = yield* GitVcsDriver.GitVcsDriver;
83 - return yield* detectPrTemplate(cwd, treeish, git.execute);
83 + return yield* GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
84 });
85
86 it.effect.each(SINGLE_TEMPLATE_PATHS)("recognizes $0", (relativePath) =>
packages/source-control-core/src/server/SourceControlHost.ts
+2
@@ -83,6 +83,8 @@ export class SourceControlHost extends Context.Service<
83 readonly operation: string;
84 readonly cwd: string;
85 readonly args: ReadonlyArray<string>;
86 + readonly maxOutputBytes?: number;
87 + readonly appendTruncationMarker?: boolean;
88 }) => Effect.Effect<SourceControlGitOutput, GitCommandError>;
89 readonly resolveCommit: (input: {
90 readonly cwd: string;
packages/source-control-core/src/server/SourceControlProvider.ts
+39
@@ -1,5 +1,6 @@
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 +import type * as Option from "effect/Option";
4 import type {
5 ChangeRequest,
6 ChangeRequestState,
@@ -92,10 +93,48 @@ export function sourceControlRefFromInput(input: {
93 return input.source ?? parseSourceControlOwnerRef(input.headSelector);
94 }
95
96 +/** The repository path a remote URL names (`owner/name`, or deeper for nested groups). */
97 +export function repositoryPathFromRemoteUrl(url: string | null): string | null {
98 + const trimmed = url?.trim() ?? "";
99 + if (trimmed.length === 0) {
100 + return null;
101 + }
102 +
103 + const match =
104 + /^(?:[^@/\s]+@[^:/\s]+:|(?:ssh|https?|git):\/\/[^/]+\/)((?:[^/\s]+\/)+[^/\s]+?)(?:\.git)?\/?$/iu.exec(
105 + trimmed,
106 + );
107 + const path = match?.[1]?.trim() ?? "";
108 + return path.length > 0 ? path : null;
109 +}
110 +
111 export class SourceControlProvider extends Context.Service<
112 SourceControlProvider,
113 {
114 readonly kind: SourceControlProviderKind;
115 + /**
116 + * How to look up a branch's change requests: which head selectors to ask about, and how many
117 + * results to read per selector. The caller checks the owner against what comes back, so a
118 + * host that cannot search `owner:branch` can drop those selectors without losing anything.
119 + * Absent asks about every selector, reading 1 for the open lookup and 20 for any state.
120 + */
121 + readonly headBranchProbe?: (input: {
122 + readonly headSelectors: ReadonlyArray<string>;
123 + readonly state: "open" | "all";
124 + }) => { readonly headSelectors: ReadonlyArray<string>; readonly limit: number };
125 + /**
126 + * The repository's change request template at `treeish`, for change request content
127 + * generation to follow. Absent means the host has no template convention.
128 + */
129 + readonly readChangeRequestTemplate?: (input: {
130 + readonly cwd: string;
131 + readonly treeish: string;
132 + }) => Effect.Effect<Option.Option<string>>;
133 + /**
134 + * The repository's `owner/name` from a remote URL, for a host whose remote paths can carry
135 + * more than that (Forgejo's HTTP installation mount). Absent means the whole path.
136 + */
137 + readonly repositoryNameFromRemoteUrl?: (url: string) => string | null;
138 /** Optional capability for issue and change-request subjects. */
139 readonly resolveLink?: ResolveSourceControlLink;
140 readonly listChangeRequests: (input: {
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
+40 -40
@@ -1,13 +1,12 @@
1 import { assert, it } from "@effect/vitest";
2 import * as Effect from "effect/Effect";
3 -import type * as Context from "effect/Context";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import * as Schema from "effect/Schema";
7 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9 -import * as FetchHttpClient from "effect/http/FetchHttpClient";
8 import * as HttpClient from "effect/http/HttpClient";
9 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as HttpClientResponse from "effect/http/HttpClientResponse";
11 import { VcsProcessSpawnError } from "@t3tools/contracts";
12 import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
@@ -20,38 +19,45 @@ import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts
19 const processOutput = TestSourceControlHost.processOutput;
20
21 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22 +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
23 +
24 +/** The JSON body a request sends. Forgejo encodes bodies as UTF-8 text. */
25 +const requestJson = (request: HttpClientRequest.HttpClientRequest): unknown => {
26 + assert.strictEqual(request.body._tag, "Uint8Array");
27 + return request.body._tag === "Uint8Array"
28 + ? decodeJson(new TextDecoder().decode(request.body.body))
29 + : undefined;
30 +};
31 const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
32
33 it.effect("submits a Forgejo review without sending its summary in the preliminary GET", () => {
34 const methods: string[] = [];
27 - const fetchReview = async (
28 - ...[input, init]: Parameters<Context.Service.Shape<typeof FetchHttpClient.Fetch>>
29 - ) => {
30 - const request = new Request(input instanceof Request ? input.url : String(input), {
31 - ...(init?.method === undefined ? {} : { method: init.method }),
32 - ...(init?.headers === undefined ? {} : { headers: init.headers }),
33 - ...(init?.body === undefined ? {} : { body: init.body }),
34 - });
35 + const reviewClient = HttpClient.make((request) => {
36 methods.push(request.method);
37 if (request.method === "GET") {
38 assert.strictEqual(request.url, "https://forgejo.test/api/v1/repos/maria/project/pulls/42");
38 - return new Response(
39 - encodeJson({
40 - number: 42,
41 - title: "Review target",
42 - body: "",
43 - html_url: "https://forgejo.test/maria/project/pulls/42",
44 - user: { login: "maria" },
45 - state: "open",
46 - merged: false,
47 - head: { ref: "feature", sha: "head", repo: null },
48 - base: { ref: "main", sha: "base", repo: null },
49 - created_at: "2026-09-13T00:00:00Z",
50 - updated_at: "2026-09-13T00:00:00Z",
51 - closed_at: null,
52 - merged_at: null,
53 - labels: [],
54 - }),
39 + return Effect.succeed(
40 + HttpClientResponse.fromWeb(
41 + request,
42 + new Response(
43 + encodeJson({
44 + number: 42,
45 + title: "Review target",
46 + body: "",
47 + html_url: "https://forgejo.test/maria/project/pulls/42",
48 + user: { login: "maria" },
49 + state: "open",
50 + merged: false,
51 + head: { ref: "feature", sha: "head", repo: null },
52 + base: { ref: "main", sha: "base", repo: null },
53 + created_at: "2026-09-13T00:00:00Z",
54 + updated_at: "2026-09-13T00:00:00Z",
55 + closed_at: null,
56 + merged_at: null,
57 + labels: [],
58 + }),
59 + ),
60 + ),
61 );
62 }
63 assert.strictEqual(request.method, "POST");
@@ -59,14 +65,16 @@ it.effect("submits a Forgejo review without sending its summary in the prelimina
65 request.url,
66 "https://forgejo.test/api/v1/repos/maria/project/pulls/42/reviews",
67 );
62 - assert.deepStrictEqual(JSON.parse(await request.text()), {
68 + assert.deepStrictEqual(requestJson(request), {
69 event: "COMMENT",
70 body: "Review summary",
71 commit_id: "head",
72 comments: [],
73 });
68 - return new Response('{"id":1}', { status: 200 });
69 - };
74 + return Effect.succeed(
75 + HttpClientResponse.fromWeb(request, new Response('{"id":1}', { status: 200 })),
76 + );
77 + });
78 return Effect.gen(function* () {
79 const cli = yield* ForgejoCli.make;
80 const provider = yield* ForgejoPullRequestProvider.make.pipe(
@@ -83,11 +91,7 @@ it.effect("submits a Forgejo review without sending its summary in the prelimina
91 });
92 assert.deepStrictEqual(methods, ["GET", "POST"]);
93 }).pipe(
86 - Effect.provideService(
87 - FetchHttpClient.Fetch,
88 - Object.assign(fetchReview, { preconnect: () => undefined }),
89 - ),
90 - Effect.provide(FetchHttpClient.layer),
94 + Effect.provideService(HttpClient.HttpClient, reviewClient),
95 Effect.provideService(
96 FileSystem.FileSystem,
97 FileSystem.makeNoop({
@@ -837,11 +841,7 @@ it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
841 }
842 assert.strictEqual(request.method, "POST");
843 assert.strictEqual(request.headers.authorization, "token test-token");
840 - assert.strictEqual(request.body._tag, "Uint8Array");
841 - if (request.body._tag === "Uint8Array")
842 - assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(request.body.body)), {
843 - body: "verified through fj",
844 - });
844 + assert.deepStrictEqual(requestJson(request), { body: "verified through fj" });
845 return Effect.succeed(
846 HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
847 );
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts
+9
@@ -158,6 +158,14 @@ export const makeDiscovery = Effect.gen(function* () {
158 } satisfies SourceControlManagedCliDiscoverySpec;
159 });
160
161 +/** HTTP paths can include an installation mount; Forgejo's API always names owner/repo. */
162 +export function repositoryNameFromRemoteUrl(url: string): string | null {
163 + const path = SourceControlProvider.repositoryPathFromRemoteUrl(url);
164 + return path === null || !/^https?:\/\//iu.test(url.trim())
165 + ? path
166 + : path.split("/").slice(-2).join("/");
167 +}
168 +
169 const RepositorySchema = Schema.Struct({
170 full_name: Schema.String,
171 clone_url: Schema.String,
@@ -228,6 +236,7 @@ export const make = Effect.gen(function* () {
236 });
237 return SourceControlProvider.SourceControlProvider.of({
238 kind: "forgejo",
239 + repositoryNameFromRemoteUrl,
240 listChangeRequests: (input) =>
241 Effect.gen(function* () {
242 const repo = yield* cli.resolveRepository(input);
packages/source-control-github/package.json
+4
@@ -15,6 +15,10 @@
15 "types": "./src/server/gitHubAuthStatus.ts",
16 "import": "./src/server/gitHubAuthStatus.ts"
17 },
18 + "./server/gitHubChangeRequestTemplate": {
19 + "types": "./src/server/gitHubChangeRequestTemplate.ts",
20 + "import": "./src/server/gitHubChangeRequestTemplate.ts"
21 + },
22 "./server/gitHubConditionalChecks": {
23 "types": "./src/server/gitHubConditionalChecks.ts",
24 "import": "./src/server/gitHubConditionalChecks.ts"
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+13
@@ -23,6 +23,7 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson";
23 import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
24
25 import * as GitHubApi from "./GitHubApi.ts";
26 +import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
27 import {
28 decodeGitHubPullRequestEntries,
29 type NormalizedGitHubPullRequestRecord,
@@ -939,6 +940,18 @@ export const make = Effect.gen(function* () {
940
941 return SourceControlProvider.SourceControlProvider.of({
942 kind: "github",
943 + // `gh pr list --head` filters on the head ref name alone and accepts anything, so an
944 + // `owner:branch` or `remote:branch` selector silently lists zero pull requests while
945 + // spending a GraphQL call; the bare branch is always among the selectors. Without the owner,
946 + // a bare branch also lists same-named branches on other forks (`main`, `patch-1`), so read a
947 + // full page and let the owner check pick the right head. gh fetches up to 100 in one
948 + // request, and GitHub prices a first:100 connection like first:1.
949 + headBranchProbe: ({ headSelectors }) => ({
950 + headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
951 + limit: 100,
952 + }),
953 + readChangeRequestTemplate: ({ cwd, treeish }) =>
954 + GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
955 resolveLink: (input) => {
956 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
957 if (input.url.host !== "github.com") return undefined;
packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts renamed
+11 -5
@@ -1,8 +1,14 @@
1 +/**
2 + * GitHub's pull request template convention: the first single template found at a known path,
3 + * or the only Markdown file in a template directory, read from the committed base tree.
4 + *
5 + * @module source-control-github/server/gitHubChangeRequestTemplate
6 + */
7 import type { GitCommandError } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10
5 -import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
11 +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12
13 const TEMPLATE_MAX_BYTES = 8_000;
14 const TREE_LIST_MAX_BYTES = 100_000;
@@ -25,7 +31,7 @@ const TEMPLATE_DIRECTORIES = [
31
32 const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
33
28 -type ExecuteGit = GitVcsDriver.GitVcsDriver["Service"]["execute"];
34 +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"];
35
36 interface TemplateTreeEntry {
37 readonly objectId: string;
@@ -66,7 +72,7 @@ function readTemplateBlob(input: {
72 }): Effect.Effect<Option.Option<string>, GitCommandError> {
73 return input
74 .executeGit({
69 - operation: "PrTemplateDetection.readTemplateBlob",
75 + operation: "gitHubChangeRequestTemplate.readTemplateBlob",
76 cwd: input.cwd,
77 args: ["cat-file", "blob", input.entry.objectId],
78 maxOutputBytes: TEMPLATE_MAX_BYTES,
@@ -125,7 +131,7 @@ function readTemplateDirectory(input: {
131 });
132 }
133
128 -export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
134 +export const detect = Effect.fn("gitHubChangeRequestTemplate.detect")(function* (
135 cwd: string,
136 treeish: string,
137 executeGit: ExecuteGit,
@@ -134,7 +140,7 @@ export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
140 // Worktree paths can be replaced between validation and open. Read regular blobs from the
141 // committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
142 const result = yield* executeGit({
137 - operation: "PrTemplateDetection.listTemplates",
143 + operation: "gitHubChangeRequestTemplate.listTemplates",
144 cwd,
145 args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
146 maxOutputBytes: TREE_LIST_MAX_BYTES,