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

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-09 16:22:36 -07:00
1 parent c85dc64268
commit 49f849ecce
11 files changed
+190 -107

No files matched your search

+29 -6
View File
@@ -44,6 +44,7 @@ import {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { decodeGitHubPullRequestListJson } from "@t3tools/source-control-github/server/gitHubPullRequests";
import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
@@ -55,6 +56,7 @@ import * as VcsProjectConfig from "../vcs/VcsProjectConfig.ts";
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as GitWorkflowService from "./GitWorkflowService.ts";
import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
import * as GitLabSourceControlProvider from "@t3tools/source-control-gitlab/server/GitLabSourceControlProvider";
import {
ForgejoPullRequestSchema,
@@ -545,6 +547,13 @@ function createGitHubProviderWithFakeGh(scenario: FakeGhScenario = {}): {
return {
service: {
kind: "github",
// The GitHub provider's own lookup rule and template convention, which GitManager reads
// instead of the kind.
headBranchProbe: ({ headSelectors }) => ({
headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
limit: 100,
}),
listChangeRequests: (input) =>
input.state === "open"
? execute({
@@ -745,7 +754,18 @@ function makeManager(input?: {
);
const layerSourceControlRegistry = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
Effect.succeed(input?.sourceControlProvider ?? fakeGitHubProvider).pipe(
Effect.gen(function* () {
// GitHub reads its PR template with git, which the fake gh cannot answer; give the fake
// the package's real reader over the test repository's git.
const git = yield* GitVcsDriver.GitVcsDriver;
return (
input?.sourceControlProvider ?? {
...fakeGitHubProvider,
readChangeRequestTemplate: ({ cwd, treeish }: { cwd: string; treeish: string }) =>
GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
}
);
}).pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
resolveLink: (input) => provider.resolveLink?.(input),
@@ -769,9 +789,12 @@ function makeManager(input?: {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
layerVcsDriver,
layerServerSettings,
).pipe(Layer.provideMerge(layerSourceControlRegistry), Layer.provideMerge(NodeServices.layer));
).pipe(
Layer.provideMerge(layerSourceControlRegistry),
Layer.provideMerge(layerVcsDriver),
Layer.provideMerge(NodeServices.layer),
);
// Built into the test's scope: the manager reads these stores after this returns.
const layerStores = Layer.merge(ProjectionStore.layer, ProjectStore.layer).pipe(
Layer.provideMerge(SqlitePersistence.layerMemory),
@@ -4232,7 +4255,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
};
const repository = GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
`https://forgejo.example/forgejo/${owner}/project.git`,
"forgejo",
{ repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
);
expect(repository).toBe(`${owner}/project`);
const context = {
@@ -4253,13 +4276,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
expect(
GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
"[email protected]:maria/project.git",
"forgejo",
{ repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
),
).toBe("maria/project");
expect(
GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
"https://gitlab.example/group/maria/project.git",
"gitlab",
{},
),
).toBe("group/maria/project");
}),
+40 -52
View File
@@ -35,7 +35,6 @@ import {
ModelSelection,
type ProjectId,
SourceControlProviderError,
type SourceControlProviderKind,
type SourceControlWritingStyleSettings,
type ThreadId,
type ThreadPullRequestKey,
@@ -81,8 +80,8 @@ import { detachStackFrame } from "./detachStackFrame.ts";
import * as ServerSettings from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import { detectPrTemplate } from "../sourceControl/PrTemplateDetection.ts";
import type { ChangeRequest } from "@t3tools/contracts";
export interface GitActionProgressReporter {
@@ -314,27 +313,20 @@ function resolvePullRequestWorktreeLocalBranchName(
return `t3code/pr-${pullRequest.number}/${suffix}`;
}
/** The repository's `owner/name` from a remote URL, as `provider` reads its remote paths. */
export function parseRepositoryNameWithOwnerFromRemoteUrl(
url: string | null,
providerKind?: ChangeRequest["provider"],
provider?: Pick<
SourceControlProvider.SourceControlProvider["Service"],
"repositoryNameFromRemoteUrl"
>,
): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const match =
/^(?:[^@/\s]+@[^:/\s]+:|(?:ssh|https?|git):\/\/[^/]+\/)((?:[^/\s]+\/)+[^/\s]+?)(?:\.git)?\/?$/iu.exec(
trimmed,
);
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
// Forgejo HTTP paths can include an installation mount; its API always names owner/repo.
if (providerKind === "forgejo" && /^https?:\/\//iu.test(trimmed)) {
return repositoryNameWithOwner.length > 0
? repositoryNameWithOwner.split("/").slice(-2).join("/")
: null;
}
return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
if (trimmed.length === 0) return null;
return (
provider?.repositoryNameFromRemoteUrl?.(trimmed) ??
SourceControlProvider.repositoryPathFromRemoteUrl(trimmed)
);
}
function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
@@ -625,24 +617,18 @@ function parseCustomCommitMessage(raw: string): { subject: string; body: string
};
}
// Without the owner selector, a bare branch name also lists same-named
// branches on other forks (`main`, `patch-1`), so GitHub probes ask for a full
// page and let matchesBranchHeadContext pick the right head. gh fetches up to
// 100 in one request, and GitHub prices a first:100 connection like first:1.
const GITHUB_HEAD_BRANCH_PROBE_LIMIT = 100;
// `gh pr list --head` filters on the head ref name alone and accepts anything, so an
// `owner:branch` or `remote:branch` selector silently lists zero pull requests
// while spending a GraphQL call. Git branch names cannot contain ":", and the
// bare head branch is always among the selectors, so GitHub probes skip them and
// leave the owner check to matchesBranchHeadContext.
function probeableHeadSelectors(
providerKind: SourceControlProviderKind,
/** The selectors and page size `provider` asks about when looking up a branch's change requests. */
function headBranchProbe(
provider: SourceControlProvider.SourceControlProvider["Service"],
headSelectors: ReadonlyArray<string>,
): ReadonlyArray<string> {
return providerKind === "github"
? headSelectors.filter((selector) => !selector.includes(":"))
: headSelectors;
state: "open" | "all",
) {
return (
provider.headBranchProbe?.({ headSelectors, state }) ?? {
headSelectors,
limit: state === "open" ? 1 : 20,
}
);
}
function appendUnique(values: string[], next: string | null | undefined): void {
@@ -1430,15 +1416,14 @@ export const make = Effect.gen(function* () {
/^https?:\/\//iu.test(remoteUrl) &&
(repositoryNameWithOwner?.split("/").length ?? 0) > 2
) {
const detected = detectSourceControlProviderFromGitRemoteUrl(remoteUrl);
const kind =
detected?.kind === "unknown"
? yield* sourceControlProvider(cwd).pipe(
Effect.map((provider) => provider.kind),
Effect.orElseSucceed(() => undefined),
)
: detected?.kind;
repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, kind);
const kind = detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind;
const provider =
kind === undefined
? undefined
: yield* (
kind === "unknown" ? sourceControlProvider(cwd) : sourceControlProviders.get(kind)
).pipe(Effect.orElseSucceed(() => undefined));
repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, provider);
}
return {
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
@@ -1701,13 +1686,13 @@ export const make = Effect.gen(function* () {
>,
) {
const provider = yield* sourceControlProvider(cwd);
const headSelectors = probeableHeadSelectors(provider.kind, headContext.headSelectors);
for (const headSelector of headSelectors) {
const probe = headBranchProbe(provider, headContext.headSelectors, "open");
for (const headSelector of probe.headSelectors) {
const pullRequests = yield* provider.listChangeRequests({
cwd,
headSelector,
state: "open",
limit: provider.kind === "github" ? GITHUB_HEAD_BRANCH_PROBE_LIMIT : 1,
limit: probe.limit,
});
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
@@ -1733,12 +1718,13 @@ export const make = Effect.gen(function* () {
const parsedByNumber = new Map<number, PullRequestInfo>();
const provider = yield* sourceControlProvider(cwd);
for (const headSelector of probeableHeadSelectors(provider.kind, headContext.headSelectors)) {
const probe = headBranchProbe(provider, headContext.headSelectors, "all");
for (const headSelector of probe.headSelectors) {
const pullRequests = yield* provider.listChangeRequests({
cwd,
headSelector,
state: "all",
limit: provider.kind === "github" ? GITHUB_HEAD_BRANCH_PROBE_LIMIT : 20,
limit: probe.limit,
});
for (const pr of pullRequests.map(toPullRequestInfo)) {
@@ -2129,8 +2115,10 @@ export const make = Effect.gen(function* () {
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
const policy = yield* resolveStylePolicy(cwd, settings);
const changeRequestTemplate =
settings.style.followChangeRequestTemplates && provider.kind === "github"
? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))
settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate
? Option.getOrUndefined(
yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }),
)
: undefined;
const generated = yield* textGeneration.generatePrContent({
@@ -1,177 +0,0 @@
import type { GitCommandError } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
const TEMPLATE_MAX_BYTES = 8_000;
const TREE_LIST_MAX_BYTES = 100_000;
const TRUNCATION_MARKER = "[truncated]";
const TEMPLATE_PATHS = [
".github/pull_request_template.md",
".github/PULL_REQUEST_TEMPLATE.md",
"pull_request_template.md",
"PULL_REQUEST_TEMPLATE.md",
"docs/pull_request_template.md",
"docs/PULL_REQUEST_TEMPLATE.md",
] as const;
const TEMPLATE_DIRECTORIES = [
".github/PULL_REQUEST_TEMPLATE",
"PULL_REQUEST_TEMPLATE",
"docs/PULL_REQUEST_TEMPLATE",
] as const;
const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
type ExecuteGit = GitVcsDriver.GitVcsDriver["Service"]["execute"];
interface TemplateTreeEntry {
readonly objectId: string;
readonly path: string;
}
function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
const entries: TemplateTreeEntry[] = [];
for (const record of output.split("\0")) {
if (record.length === 0) {
continue;
}
const separator = record.indexOf("\t");
if (separator < 0) {
continue;
}
const [mode, type, objectId] = record.slice(0, separator).split(" ");
if (
type !== "blob" ||
(mode !== "100644" && mode !== "100755") ||
!objectId ||
!/^[0-9a-f]{40,64}$/.test(objectId)
) {
continue;
}
entries.push({ objectId, path: record.slice(separator + 1) });
}
return entries;
}
function readTemplateBlob(input: {
readonly cwd: string;
readonly executeGit: ExecuteGit;
readonly entry: TemplateTreeEntry;
}): Effect.Effect<Option.Option<string>, GitCommandError> {
return input
.executeGit({
operation: "PrTemplateDetection.readTemplateBlob",
cwd: input.cwd,
args: ["cat-file", "blob", input.entry.objectId],
maxOutputBytes: TEMPLATE_MAX_BYTES,
appendTruncationMarker: true,
})
.pipe(
Effect.map((result) => {
const template = result.stdout.trim();
if (template.length === 0) {
return Option.none();
}
return Option.some(
result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
? `${template}\n\n${TRUNCATION_MARKER}`
: template,
);
}),
);
}
type DirectoryTemplateResult =
| { readonly _tag: "None" }
| { readonly _tag: "Ambiguous" }
| { readonly _tag: "Template"; readonly template: string };
function readTemplateDirectory(input: {
readonly cwd: string;
readonly executeGit: ExecuteGit;
readonly entries: ReadonlyArray<TemplateTreeEntry>;
readonly directory: string;
}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
return Effect.gen(function* () {
const prefix = `${input.directory}/`;
const candidates = input.entries.filter((entry) => {
if (!entry.path.startsWith(prefix)) {
return false;
}
const relativePath = entry.path.slice(prefix.length);
return !relativePath.includes("/") && relativePath.toLowerCase().endsWith(".md");
});
const templates: string[] = [];
for (const entry of candidates) {
const template = yield* readTemplateBlob({ ...input, entry });
if (Option.isSome(template)) {
templates.push(template.value);
if (templates.length > 1) {
return { _tag: "Ambiguous" } as const;
}
}
}
return templates[0]
? ({ _tag: "Template", template: templates[0] } as const)
: ({ _tag: "None" } as const);
});
}
export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
cwd: string,
treeish: string,
executeGit: ExecuteGit,
) {
return yield* Effect.gen(function* () {
// Worktree paths can be replaced between validation and open. Read regular blobs from the
// committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
const result = yield* executeGit({
operation: "PrTemplateDetection.listTemplates",
cwd,
args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
maxOutputBytes: TREE_LIST_MAX_BYTES,
appendTruncationMarker: true,
});
if (result.stdoutTruncated) {
return Option.none();
}
const entries = parseTemplateTreeEntries(result.stdout);
const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
for (const templatePath of TEMPLATE_PATHS) {
const entry = entriesByPath.get(templatePath);
if (!entry) {
continue;
}
const template = yield* readTemplateBlob({ cwd, executeGit, entry });
if (Option.isSome(template)) {
return template;
}
}
for (const directory of TEMPLATE_DIRECTORIES) {
const directoryTemplate = yield* readTemplateDirectory({
cwd,
executeGit,
entries,
directory,
});
if (directoryTemplate._tag === "Template") {
return Option.some(directoryTemplate.template);
}
if (directoryTemplate._tag === "Ambiguous") {
return Option.none();
}
}
return Option.none();
}).pipe(Effect.orElseSucceed(() => Option.none()));
});
@@ -158,8 +158,7 @@ function bindProviderContext(
}
return SourceControlProvider.SourceControlProvider.of({
kind: provider.kind,
...(provider.resolveLink ? { resolveLink: provider.resolveLink } : {}),
...provider,
listChangeRequests: (input) =>
provider.listChangeRequests({
...input,
@@ -9,7 +9,7 @@ import * as Path from "effect/Path";
import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { detectPrTemplate } from "./PrTemplateDetection.ts";
import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
const SINGLE_TEMPLATE_PATHS = [
@@ -80,7 +80,7 @@ const commitTemplates = (cwd: string) =>
const detectTemplate = (cwd: string, treeish = "HEAD") =>
Effect.gen(function* () {
const git = yield* GitVcsDriver.GitVcsDriver;
return yield* detectPrTemplate(cwd, treeish, git.execute);
return yield* GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
});
it.effect.each(SINGLE_TEMPLATE_PATHS)("recognizes $0", (relativePath) =>