feat(source-control): support Forgejo and Gitea with fj and tea (#11436)

This commit is contained in:
maria authored and GitHub committed 2026-09-13 00:02:42 -03:00
1 parent c29976458a
commit 6fd68f5c3e
66 files changed
+4545 -102

No files matched your search

@@ -1,9 +1,9 @@
import Svg, { Defs, LinearGradient, Path, Stop } from "react-native-svg";
import Svg, { Circle, Defs, G, LinearGradient, Path, Stop } from "react-native-svg";
import { withUniwind } from "uniwind";
const ThemedSvg = withUniwind(Svg);
export type SourceControlIconKind = "github" | "gitlab" | "bitbucket" | "azure-devops";
export type SourceControlIconKind = "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops";
export function SourceControlIcon(props: {
readonly kind: SourceControlIconKind;
@@ -14,6 +14,19 @@ export function SourceControlIcon(props: {
const size = props.size ?? 18;
switch (props.kind) {
case "forgejo":
// Official two-color mark from https://forgejo.org/favicon.svg.
return (
<Svg width={size} height={size} viewBox="0 0 212 212">
<G transform="translate(6 6)" fill="none">
<Path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" stroke="#ff6600" strokeWidth={25} />
<Path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" stroke="#d40000" strokeWidth={25} />
<Circle cx={142} cy={20} r={18} stroke="#ff6600" strokeWidth={15} />
<Circle cx={142} cy={88} r={18} stroke="#d40000" strokeWidth={15} />
<Circle cx={58} cy={180} r={18} stroke="#d40000" strokeWidth={15} />
</G>
</Svg>
);
case "github":
return (
<ThemedSvg
@@ -17,6 +17,7 @@ export function AddProjectRepositoryRoute({
const title =
source === "github" ||
source === "gitlab" ||
source === "forgejo" ||
source === "bitbucket" ||
source === "azure-devops"
? addProjectRemoteSourceLabel(source)
@@ -110,6 +110,7 @@ function sourceFromParam(value: string | string[] | undefined): AddProjectRemote
source === "url" ||
source === "github" ||
source === "gitlab" ||
source === "forgejo" ||
source === "bitbucket" ||
source === "azure-devops"
) {
+68
View File
@@ -37,6 +37,10 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as GitLabSourceControlProvider from "../sourceControl/GitLabSourceControlProvider.ts";
import {
ForgejoPullRequestSchema,
toForgejoChangeRequest,
} from "../sourceControl/forgejoPullRequests.ts";
import type { SourceControlProvider } from "../sourceControl/SourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as ServerConfig from "../config.ts";
@@ -46,6 +50,7 @@ import * as ServerSettings from "../serverSettings.ts";
import * as GitManager from "./GitManager.ts";
const encodeCliJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeForgejoPullRequest = Schema.decodeEffect(ForgejoPullRequestSchema);
interface FakeGhScenario {
prListSequence?: string[];
@@ -3851,6 +3856,69 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
20_000,
);
it.effect("matches mounted Forgejo heads without confusing forks sharing a branch", () =>
Effect.gen(function* () {
for (const owner of ["maria", "reviewer"]) {
const mapped = toForgejoChangeRequest(
yield* decodeForgejoPullRequest({
number: 42,
title: "Greeting",
html_url: "https://forgejo.example/forgejo/maria/project/pulls/42",
state: "open",
merged: false,
base: {
ref: "main",
sha: "base",
repo: { full_name: "maria/project", owner: { login: "maria" } },
},
head: {
ref: "greeting",
sha: "head",
repo: { full_name: `${owner}/project`, owner: { login: owner } },
},
}),
);
const pr = {
...mapped,
isDraft: mapped.isDraft ?? false,
closedAt: mapped.closedAt ?? null,
mergedAt: mapped.mergedAt ?? null,
};
const repository = GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
`https://forgejo.example/forgejo/${owner}/project.git`,
"forgejo",
);
expect(repository).toBe(`${owner}/project`);
const context = {
headBranch: "greeting",
headRepositoryNameWithOwner: repository,
headRepositoryOwnerLogin: repository?.split("/")[0] ?? null,
isCrossRepository: owner !== "maria",
};
expect(GitManager.matchesBranchHeadContext(pr, context)).toBe(true);
expect(
GitManager.matchesBranchHeadContext(pr, {
...context,
headRepositoryNameWithOwner: "other/project",
headRepositoryOwnerLogin: "other",
}),
).toBe(false);
}
expect(
GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
"[email protected]:maria/project.git",
"forgejo",
),
).toBe("maria/project");
expect(
GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
"https://gitlab.example/group/maria/project.git",
"gitlab",
),
).toBe("group/maria/project");
}),
);
it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>
Effect.sync(() => {
const headContext = {
+35 -3
View File
@@ -277,7 +277,10 @@ function resolvePullRequestWorktreeLocalBranchName(
return `t3code/pr-${pullRequest.number}/${suffix}`;
}
function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
export function parseRepositoryNameWithOwnerFromRemoteUrl(
url: string | null,
providerKind?: ChangeRequest["provider"],
): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return null;
@@ -288,6 +291,12 @@ function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string |
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;
}
@@ -1291,7 +1300,15 @@ export const make = Effect.gen(function* () {
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
const provider = remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
if (!remoteUrl || provider?.kind !== "unknown") return provider;
const handle = yield* sourceControlProviders
.resolveHandle({
cwd,
context: { provider, remoteName: preferredRemoteName, remoteUrl },
})
.pipe(Effect.orElseSucceed(() => null));
return handle?.context?.provider ?? provider;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
@@ -1307,7 +1324,22 @@ export const make = Effect.gen(function* () {
}
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
const repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
let repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
if (
remoteUrl !== null &&
/^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);
}
return {
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
repositoryNameWithOwner,
@@ -265,6 +265,40 @@ describe("pull request toolkit handlers", () => {
}),
);
it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
project: makeProject({
canonicalKey: "forge.example/git/owner/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "http://forge.example:3000/git/owner/repo.git",
},
provider: "forgejo",
displayName: "git/owner/repo",
}),
});
const result = yield* harness.call("link_pull_request", {
repository: "git/owner/repo",
number: 42,
});
expect(result).toEqual({
host: "forge.example:3000",
repository: "git/owner/repo",
number: 42,
url: "http://forge.example:3000/git/owner/repo/pulls/42",
alreadyLinked: false,
});
const other = yield* harness.call("link_pull_request", {
host: "other.example",
repository: "owner/repo",
number: 42,
});
expect(other.url).toBe("https://other.example/owner/repo/pull/42");
}),
);
it.effect("rejects a target that names neither a URL nor repository and number", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
@@ -334,6 +368,18 @@ describe("pull request toolkit handlers", () => {
}),
);
it("reports an older Forgejo link's HTTP port when listing thread links", () => {
const result = listThreadPullRequests(
makeThread([
makeLink(42, {
host: "forge.example",
url: "http://forge.example:3000/t3tools/t3code/pulls/42",
}),
]),
);
expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
});
it.effect("fails cleanly when the token's thread no longer exists", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ thread: null });
@@ -9,6 +9,7 @@ import {
} from "@t3tools/contracts";
import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import {
normalizeThreadPullRequestKey,
resolveThreadPullRequestChains,
threadPullRequestKeyOf,
visibleThreadPullRequests,
@@ -71,7 +72,7 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
if (parsed === null) {
return yield* new PullRequestUrlInvalidError({});
}
return { ...parsed, url: input.url } satisfies ResolvedTarget;
return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
}
if (input.repository === undefined || input.number === undefined) {
return yield* new PullRequestTargetIncompleteError({});
@@ -89,8 +90,12 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
host,
repository,
input.number,
project?.repositoryIdentity?.locator.remoteUrl,
) ?? `https://${host}/${repository}/pull/${input.number}`;
return { host, repository, number: input.number, url } satisfies ResolvedTarget;
return {
...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
url,
} satisfies ResolvedTarget;
});
function entryOf(
@@ -108,7 +113,7 @@ function entryOf(
}
}
return {
host: link.host,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
url: link.url,
@@ -889,6 +889,39 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-pull
assert.deepEqual(yield* readLinks(), []);
assert.deepEqual(yield* readThreadUpdatedAt(), [{ updatedAt: "2026-01-01T00:00:05.000Z" }]);
// Older Forgejo rows stored a portless host; unlink by their URL's authority.
yield* eventStore.append({
...base("2026-01-01T00:00:05.100Z"),
type: "thread.pull-request-linked",
payload: {
threadId,
link: {
host: "forge.example",
repository: "team/repo",
number: 42,
url: "http://forge.example:3000/team/repo/pulls/42",
source: "agent",
linkedAt: "2026-01-01T00:00:05.100Z",
snapshot: null,
stack: null,
},
updatedAt: "2026-01-01T00:00:05.100Z",
},
});
yield* eventStore.append({
...base("2026-01-01T00:00:05.200Z"),
type: "thread.pull-request-unlinked",
payload: {
threadId,
host: "forge.example:3000",
repository: "team/repo",
number: 42,
updatedAt: "2026-01-01T00:00:05.200Z",
},
});
yield* projectionPipeline.bootstrap;
assert.deepEqual(yield* readLinks(), []);
// Deleting the thread clears whatever links it still had.
yield* eventStore.append({
...base("2026-01-01T00:00:06.000Z"),
@@ -880,12 +880,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadPullRequestRepository.delete({
const links = yield* projectionThreadPullRequestRepository.listByThreadId({
threadId: event.payload.threadId,
host: event.payload.host.toLowerCase(),
repository: event.payload.repository.toLowerCase(),
number: event.payload.number,
});
const link = links.find((candidate) =>
threadPullRequestKeysEqual(candidate, event.payload),
);
if (link !== undefined) {
yield* projectionThreadPullRequestRepository.delete({
threadId: event.payload.threadId,
host: link.host,
repository: link.repository,
number: link.number,
});
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.payload.updatedAt,
@@ -420,6 +420,31 @@ describe("PullRequestSyncReactor", () => {
),
);
it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("one", {
pullRequests: [
makeLink(42, null, {
host: "forge.example",
url: "http://forge.example:3000/owner/repository/pulls/42",
}),
],
}),
]),
summary: (input) => Effect.succeed(makeSummary(input)),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("dispatches nothing when the host snapshot is unchanged", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -11,6 +11,7 @@ import {
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import {
threadPullRequestKeyOf,
normalizeThreadPullRequestKey,
threadPullRequestKeysEqual,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
@@ -191,7 +192,7 @@ export const make = Effect.gen(function* () {
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
threadId: thread.id,
host: link.host,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
snapshot: { ...fields, syncedAt: nowIso },
@@ -200,7 +201,11 @@ export const make = Effect.gen(function* () {
}
if (fetchedStack === null || fetchedStack.stack === null) return;
for (const layer of fetchedStack.stack.layers) {
const layerKey = { host: link.host, repository: link.repository, number: layer.number };
const layerKey = {
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: layer.number,
};
const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
if (linkedThisSweep.has(dedupeKey)) continue;
// Tombstones count as present: a dismissed layer is never re-added.
@@ -240,7 +245,7 @@ export const make = Effect.gen(function* () {
const first = entries[0]!;
const ref = {
projectId: first.thread.projectId,
host: first.link.host,
host: normalizeThreadPullRequestKey(first.link).host,
repository: first.link.repository,
number: first.link.number,
};
@@ -115,6 +115,49 @@ const snapshot: ThreadPullRequestSnapshot = {
};
it.layer(NodeServices.layer)("pull request link decider", (it) => {
it.effect("links the same Forgejo number on two ports and unlinks an older portless record", () =>
Effect.gen(function* () {
const existing = makeLink({
host: "forge.example",
url: "http://forge.example:3000/t3tools/t3code/pulls/42",
});
let model = makeReadModel([existing]);
const command = yield* decodeCommand({
type: "thread.pull-request.link",
commandId: "link-other-port",
threadId: THREAD_ID,
host: "forge.example",
repository: "t3tools/t3code",
number: 42,
url: "http://forge.example:4000/t3tools/t3code/pulls/42",
source: "manual",
});
const linked = expectSingleEvent(
yield* decideOrchestrationCommand({ readModel: model, command }),
"thread.pull-request-linked",
);
expect(linked.payload.link.host).toBe("forge.example:4000");
model = yield* projectEvent(model, { ...linked, sequence: 1 });
expect(model.threads[0]!.pullRequests).toHaveLength(2);
const unlink = yield* decodeCommand({
type: "thread.pull-request.unlink",
commandId: "unlink-old-port",
threadId: THREAD_ID,
host: "forge.example:3000",
repository: "t3tools/t3code",
number: 42,
});
const unlinked = expectSingleEvent(
yield* decideOrchestrationCommand({ readModel: model, command: unlink }),
"thread.pull-request-unlinked",
);
model = yield* projectEvent(model, { ...unlinked, sequence: 2 });
expect(model.threads[0]!.pullRequests.map((link) => link.url)).toEqual([
linked.payload.link.url,
]);
}),
);
it.effect("legacy unlink cannot remove a newer cross-host link", () =>
Effect.gen(function* () {
const own = makeLink();
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not.
import * as NodeFS from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { SourceControlProviderError } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -41,6 +42,9 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("refreshes the Git root only when requested", () => {
const calls: Array<ReadonlyArray<string>> = [];
let rootPath = "/repo";
let remoteUrl = "[email protected]:T3Tools/t3code.git";
let refinements = 0;
let refinementFails = false;
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.sync(() => {
@@ -48,7 +52,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
return {
stdout: input.args.includes("rev-parse")
? `${rootPath}\n`
: "origin\[email protected]:T3Tools/t3code.git (fetch)\n",
: `origin\t${remoteUrl} (fetch)\n`,
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
@@ -61,7 +65,29 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
});
const resolverLayer = Layer.effect(
RepositoryIdentityResolver.RepositoryIdentityResolver,
RepositoryIdentityResolver.make(),
RepositoryIdentityResolver.make({
refine: (identity) => {
refinements++;
if (refinementFails)
return Effect.fail(
new SourceControlProviderError({
provider: "forgejo",
operation: "detectProvider",
cwd: rootPath,
detail: "account unavailable",
}),
);
return Effect.succeed(
identity.canonicalKey.startsWith("ssh.forge.test/")
? {
...identity,
provider: "forgejo",
webUrl: "http://forge.test:3000/git/team/repo",
}
: identity,
);
},
}),
).pipe(Layer.provide(processRunner));
return Effect.gen(function* () {
@@ -72,6 +98,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
expect(first?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(second).toEqual(first);
expect(refinements).toBe(1);
expect(calls).toEqual([
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
["-C", "/repo", "remote", "-v"],
@@ -84,6 +111,18 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
["-C", "/repo/packages/web", "remote", "-v"],
]);
remoteUrl = "[email protected]:team/repo.git";
const forgejo = yield* resolver.resolve(rootPath, { refresh: true });
expect(forgejo?.webUrl).toBe("http://forge.test:3000/git/team/repo");
expect(forgejo?.provider).toBe("forgejo");
expect(forgejo?.canonicalKey).toBe("ssh.forge.test/team/repo");
expect(forgejo?.locator.remoteUrl).toBe(remoteUrl);
expect(yield* resolver.resolve(rootPath)).toEqual(forgejo);
expect(refinements).toBe(3);
refinementFails = true;
const unavailable = yield* resolver.resolve(rootPath, { refresh: true });
expect(unavailable?.webUrl).toBeUndefined();
expect(unavailable?.canonicalKey).toBe("ssh.forge.test/team/repo");
}).pipe(Effect.provide(resolverLayer));
});
@@ -1,4 +1,4 @@
import type { RepositoryIdentity } from "@t3tools/contracts";
import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
import {
detectSourceControlProviderFromGitRemoteUrl,
normalizeGitRemoteUrl,
@@ -20,6 +20,9 @@ export interface RepositoryIdentityResolverOptions {
readonly cacheCapacity?: number;
readonly positiveCacheTtl?: Duration.Input;
readonly negativeCacheTtl?: Duration.Input;
readonly refine?: (
identity: RepositoryIdentity,
) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
}
export class RepositoryIdentityResolver extends Context.Service<
@@ -158,6 +161,11 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
(cacheKey) =>
resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
Effect.flatMap((identity) =>
identity !== null && options.refine
? options.refine(identity).pipe(Effect.catch(() => Effect.succeed(identity)))
: Effect.succeed(identity),
),
),
{
capacity: cacheCapacity,
@@ -0,0 +1,584 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Result from "effect/Result";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { ForgejoCli, type ForgejoApiInput } from "../sourceControl/ForgejoCli.ts";
import {
PullRequestProviderError,
type ProviderChangeRequestDetail,
type ProviderRepositoryRef,
type PullRequestProviderApi,
} from "./PullRequestProvider.ts";
import {
ForgejoPullRequest,
ForgejoRepository,
ForgejoUser,
ForgejoComment,
ForgejoReview,
ForgejoReviewComment,
ForgejoCommit,
ForgejoStatus,
ForgejoLabel,
ForgejoReaction,
FORGEJO_REACTIONS,
forgejoChangeRequest,
forgejoActor,
forgejoComment,
forgejoReview,
forgejoReviewThread,
forgejoCommit,
forgejoChecks,
forgejoReactions,
} from "./forgejoPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: ["merge", "close", "reopen", "update-branch"],
mergeMethods: ["merge", "squash", "rebase"],
updateMethods: ["merge", "rebase"],
search: false,
reactions: true,
labels: true,
// Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
review: {
inlineComment: true,
reply: false,
resolve: false,
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
const repoPath = (input: ProviderRepositoryRef) =>
`repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>
`${repoPath(input)}/pulls/${input.number}`;
const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =>
`${repoPath(input)}/issues/${input.number}`;
// Review IDs differ from the issue-comment IDs used by Forgejo's reactions API.
const reviewCommentId = (review: typeof ForgejoReview.Type) =>
/#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
export const make = Effect.gen(function* () {
const cli = yield* ForgejoCli;
const failure = (operation: string, detail: string, cause?: unknown) =>
new PullRequestProviderError({
provider: "forgejo",
operation,
reason: "failed",
detail,
...(cause === undefined ? {} : { cause }),
});
const request = (input: ForgejoApiInput) =>
cli.api(input).pipe(
Effect.mapError(
(error) =>
new PullRequestProviderError({
provider: "forgejo",
operation: input.path,
detail: error.detail,
cause: error,
reason:
error.reason === "missing-cli"
? "missing-tool"
: error.reason === "authentication"
? "unauthenticated"
: error.reason === "rate-limit"
? "rate-limited"
: "failed",
}),
),
);
const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(
input: ForgejoApiInput,
schema: Schema.Codec<A, unknown, never, never>,
) {
const result = yield* request(input);
if (result.stdoutTruncated)
return yield* failure(input.path, "Forgejo response exceeded the output limit.");
const decoded = decodeJsonResult(schema)(result.stdout);
return Result.isSuccess(decoded)
? decoded.success
: yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
});
const readArray = <A>(input: ForgejoApiInput, schema: Schema.Codec<A, unknown, never, never>) =>
read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));
const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(
input: ForgejoApiInput,
schema: Schema.Codec<A, unknown, never, never>,
index: number,
) {
const result = yield* request({
...input,
path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,
});
if (result.stdoutTruncated)
return yield* failure(input.path, "Forgejo response exceeded the output limit.");
const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
if (Result.isFailure(decoded))
return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
const rows = decoded.success ?? [];
const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
return {
rows,
more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)),
};
});
// Use a stable, small page size that also works with Forgejo's default maximum of 50.
const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>(
input: ForgejoApiInput,
schema: Schema.Codec<A, unknown, never, never>,
limit = 500,
) {
const items: A[] = [];
for (let index = 1; items.length < limit; index++) {
const { rows, more } = yield* readPage(input, schema, index);
items.push(...rows);
if (!more) return { items, truncated: false };
}
return { items, truncated: true };
});
const write = (input: ForgejoApiInput) => request(input).pipe(Effect.asVoid);
const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
read(
{
cwd: input.cwd,
repository: input.repository,
host: input.host,
path: pullPath(input),
},
ForgejoPullRequest,
);
const getRepo = (input: ProviderRepositoryRef) =>
read({ ...input, path: repoPath(input) }, ForgejoRepository);
const getViewer = (input: {
readonly cwd: string;
readonly repository?: string;
readonly host?: string;
}) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
const permissions = (
repo: typeof ForgejoRepository.Type,
pr: typeof ForgejoPullRequest.Type,
viewer: string,
): PullRequestViewerPermissions => {
const canWrite = repo.permissions?.push ?? false;
const canEdit = canWrite || pr.user?.login === viewer;
const active = !repo.archived;
return {
actions: active
? CAPABILITIES.actions.filter((action) =>
action === "merge" || action === "update-branch" ? canWrite : canEdit,
)
: [],
comment: active && (!pr.is_locked || canWrite),
resolve: false,
verdicts: active
? pr.user?.login === viewer
? ["comment"]
: CAPABILITIES.review.verdicts
: [],
requestReviewers: active && canEdit,
labels: active && canWrite,
updateMethods:
active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [],
};
};
const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* (
input: ProviderRepositoryRef & { readonly number: number },
) {
const [repo, pr, viewer] = yield* Effect.all(
[getRepo(input), getPull(input), getViewer(input)],
{ concurrency: 3 },
);
return permissions(repo, pr, viewer);
});
const unsupported = (operation: string) =>
Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
const provider: PullRequestProviderApi = {
kind: "forgejo",
capabilities: CAPABILITIES,
getViewer,
listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(
function* (input) {
const offset = input.cursor?.delivered ?? 0;
const items: ReturnType<typeof forgejoChangeRequest>[] = [];
const state = input.state === "merged" ? "closed" : input.state;
const query = {
...input,
path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,
};
// Self-hosted servers may cap pages below 50. Establish their actual page size before
// translating the service's row offset into an API page number.
const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);
const pageSize = first.rows.length || 50;
const firstIndex = Math.floor(offset / pageSize) + 1;
let consumed = 0;
let more = true;
for (let index = firstIndex; more && consumed < input.limit; index++) {
const result =
index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);
const rows = result.rows;
const start = index === firstIndex ? offset % pageSize : 0;
const countBefore = consumed;
for (const row of rows.slice(start)) {
if (consumed >= input.limit) break;
consumed++;
if (row) items.push(forgejoChangeRequest(row));
}
more = result.more || rows.length - start > consumed - countBefore;
}
return { items, truncated: more, continues: true, cursorAdvance: consumed };
},
),
getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
const [pr, repo, viewer] = yield* Effect.all(
[getPull(input), getRepo(input), getViewer(input)],
{ concurrency: 3 },
);
const statuses = yield* page(
{
...input,
path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
},
ForgejoStatus,
);
return {
...forgejoChangeRequest(pr),
body: pr.body ?? "",
changedFiles: pr.changed_files ?? 0,
reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
const actor = forgejoActor(user);
return actor ? [actor] : [];
}),
checks: forgejoChecks(statuses.items),
baseComparison: !pr.merge_base
? "unknown"
: pr.merge_base === pr.base.sha
? "up-to-date"
: "behind",
viewerPermissions: permissions(repo, pr, viewer),
mergeCapabilities: {
merge: repo.allow_merge_commits ?? true,
squash: repo.allow_squash_merge ?? true,
rebase: repo.allow_rebase ?? true,
},
} satisfies ProviderChangeRequestDetail;
}),
getViewerPermissions: getPermissions,
getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
function* (input) {
const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
[
// Issue comments ignore page/limit; fetch this unpaginated endpoint once.
readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
Effect.map((items) => ({
items: items.slice(0, 500),
truncated: items.length > 500,
})),
),
page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),
page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
getViewer(input),
],
{ concurrency: 5 },
);
const reviewComments = yield* Effect.forEach(
reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
(review) =>
readArray(
{ ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
ForgejoReviewComment,
),
{ concurrency: 4 },
);
const allInline = reviewComments.flat();
const inline = allInline.slice(0, 500);
const entries = [
...comments.items.map((comment) => ({
comment: forgejoComment(comment),
reactionId: String(comment.id),
})),
...reviews.items
.filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
.map((review) => ({
comment: forgejoReview(review),
reactionId: reviewCommentId(review),
})),
...inline.map((comment) => ({
comment: {
...forgejoComment(comment),
kind: "review-comment" as const,
path: comment.path,
},
reactionId: String(comment.id),
})),
];
const enriched = yield* Effect.forEach(
entries,
({ comment, reactionId }) =>
(reactionId === undefined
? Effect.succeed([])
: readArray(
{ ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
ForgejoReaction,
)
).pipe(
Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
),
{ concurrency: 4 },
);
const byId = new Map(enriched.map((comment) => [comment.id, comment]));
const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
return {
comments: timeline,
commentCount: timeline.length,
commentsTruncated:
comments.truncated || reviews.truncated || allInline.length > inline.length,
reviewThreads: inline.map((comment) => ({
...forgejoReviewThread(comment),
comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
})),
commits: commits.items.map(forgejoCommit),
reactions: forgejoReactions(reactions.items, viewer),
};
},
),
getDiff: (input) =>
request({
...input,
path: input.commit
? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
: `${pullPath(input)}.diff`,
}).pipe(
Effect.map((result) => ({
patch: result.stdout,
truncated: result.stdoutTruncated,
nextCursor: null,
})),
),
getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
function* (input) {
const pr = yield* getPull(input);
const commit = input.commit
? yield* read(
{
...input,
path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}`,
},
ForgejoCommit,
)
: null;
const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
const newRef = input.commit ?? pr.head.sha;
const content = (repository: string, ref: string, path: string) =>
read(
{
...input,
repository,
path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
},
Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
const [oldContents, newContents] = yield* Effect.all(
[
input.changeType === "new" || !oldRef
? Effect.succeed("")
: content(input.repository, oldRef, input.oldPath),
input.changeType === "deleted"
? Effect.succeed("")
: content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
],
{ concurrency: 2 },
);
return { oldContents, newContents };
},
),
runAction: (input) => {
switch (input.action) {
case "merge":
return write({
...input,
path: `${pullPath(input)}/merge`,
method: "POST",
body: { Do: input.mergeMethod ?? "merge" },
});
case "close":
case "reopen":
return write({
...input,
path: pullPath(input),
method: "PATCH",
body: { state: input.action === "close" ? "closed" : "open" },
});
case "update-branch":
return write({
...input,
path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
method: "POST",
});
default:
return unsupported(input.action);
}
},
updateChangeRequest: (input) =>
write({
...input,
path: pullPath(input),
method: "PATCH",
body: {
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
},
}),
comment: (input) =>
write({
...input,
path: `${issuePath(input)}/comments`,
method: "POST",
body: { body: input.body },
}),
updateComment: (input) =>
write({
...input,
path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
method: "PATCH",
body: { body: input.body },
}),
submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
const pr = yield* getPull(input);
yield* write({
...input,
path: `${pullPath(input)}/reviews`,
method: "POST",
body: {
event:
input.verdict === "approve"
? "APPROVED"
: input.verdict === "request-changes"
? "REQUEST_CHANGES"
: "COMMENT",
body: input.body,
commit_id: pr.head.sha,
comments: input.comments.map((comment) => {
const position = comment.position;
const old =
position.kind === "deleted" ||
(position.kind === "context" && position.side === "left");
return {
path: old ? (comment.oldPath ?? comment.path) : comment.path,
body: comment.body,
old_position: old ? position.oldLine : 0,
new_position: old ? 0 : position.newLine,
};
}),
},
});
}),
listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
function* (input) {
const [pr, users] = yield* Effect.all(
[getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],
{ concurrency: 2 },
);
return {
candidates: users.items
.filter((user) => user.login !== pr.user?.login)
.flatMap((user) => {
const actor = forgejoActor(user);
return actor
? [
{
...actor,
id: user.login,
kind: "user" as const,
isRequested:
pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
false,
},
]
: [];
}),
truncated: users.truncated,
};
},
),
setReviewerRequest: (input) =>
write({
...input,
path: `${pullPath(input)}/requested_reviewers`,
method: input.requested ? "POST" : "DELETE",
body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
}),
listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
function* (input) {
const [pr, labels] = yield* Effect.all(
[getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
{ concurrency: 2 },
);
return {
candidates: labels.items.map((label) => ({
name: label.name,
color: label.color ?? null,
description: label.description ?? null,
isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
})),
truncated: labels.truncated,
};
},
),
setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
const selected = labels.items.filter((label) => input.labels.includes(label.name));
if (selected.length !== input.labels.length)
return yield* failure("setLabels", "One or more requested labels could not be found.");
if (input.applied)
yield* write({
...input,
path: `${issuePath(input)}/labels`,
method: "POST",
body: { labels: selected.map((label) => label.id) },
});
else
yield* Effect.forEach(
selected,
(label) =>
write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
{ concurrency: 1 },
);
}),
setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
let commentId = input.subjectId;
if (commentId?.startsWith("review:")) {
const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
const review = yield* read(
{ ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
ForgejoReview,
);
commentId = reviewCommentId(review);
if (!commentId)
return yield* failure(
"setReaction",
"Forgejo did not return a comment ID for this review.",
);
}
if (commentId && !/^[1-9]\d*$/.test(commentId))
return yield* failure("setReaction", "Invalid Forgejo comment ID.");
yield* write({
...input,
path: commentId
? `${repoPath(input)}/issues/comments/${commentId}/reactions`
: `${issuePath(input)}/reactions`,
method: input.reacted ? "POST" : "DELETE",
body: { content: FORGEJO_REACTIONS[input.content] },
});
}),
replyToThread: () => unsupported("thread replies"),
setThreadResolution: () => unsupported("thread resolution"),
};
return provider;
});
@@ -282,6 +282,7 @@ export interface PullRequestProviderApi {
/** The signed-in account, which is what involvement filtering compares against. */
readonly getViewer: (input: {
readonly cwd: string;
readonly host?: string;
}) => Effect.Effect<string, PullRequestProviderError>;
readonly listChangeRequests: (
@@ -8,6 +8,8 @@ import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
@@ -48,6 +50,7 @@ export const make = Effect.map(
Effect.all([
GitHubPullRequestProvider.make,
GitLabPullRequestProvider.make,
ForgejoPullRequestProvider.make,
BitbucketPullRequestProvider.make,
AzureDevOpsPullRequestProvider.make,
]),
@@ -62,6 +65,7 @@ export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
),
),
Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),
Layer.provide(ForgejoCli.layer),
Layer.provide(BitbucketPullRequestApi.layer.pipe(Layer.provide(BitbucketApi.layer))),
Layer.provide(AzureDevOpsPullRequestCli.layer.pipe(Layer.provide(AzureDevOpsCli.layer))),
);
@@ -1659,6 +1659,118 @@ it.effect("reads a host-native stack through the provider and null where it has
}),
);
it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after refinement", () =>
Effect.gen(function* () {
for (const provider of ["forgejo", "unknown"] as const) {
const seen: string[] = [];
const viewers: Array<string | undefined> = [];
const service = yield* makeService({
projects: [
project({
id: "ssh",
title: "ssh",
workspaceRoot: "/ssh",
repository: "team/repo",
provider,
host: "ssh.code.example",
remoteUrl: "[email protected]:team/repo.git",
}),
],
providers: [
fakeProvider("forgejo", {
getViewer: (input) => {
viewers.push(input.host);
assert.strictEqual(input.host, "code.example:3000");
return Effect.succeed("bilal");
},
listChangeRequests: (input) => {
assert.strictEqual(input.host, "code.example:3000");
return Effect.succeed({ items: [], truncated: false, continues: true });
},
getChangeRequest: (input) => {
assert.strictEqual(input.host, "code.example:3000");
return Effect.succeed({ ...hostedChangeRequest("Forgejo detail"), number: 42 });
},
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push(input.host);
return changeRequest(42, "2026-07-02T00:00:00Z");
}),
}),
],
resolveHandle: ({ context }) => {
if (context?.requestedHost === undefined) {
return Effect.succeed({ context: context!, provider: undefined as never });
}
assert.strictEqual(context.requestedHost, "code.example:3000");
return Effect.succeed({
context: {
...context,
provider: { kind: "forgejo", name: "Forgejo", baseUrl: "http://code.example:3000" },
},
provider: undefined as never,
});
},
});
yield* service.summary(
{
projectId: "ssh" as ProjectId,
host: "code.example:3000",
repository: "team/repo",
number: 42,
},
{ recoverTransientFailure: false },
);
assert.deepStrictEqual(seen, ["code.example:3000"]);
const listed = yield* service.list({
projectId: "ssh" as ProjectId,
host: "code.example:3000",
state: "open",
});
assert.strictEqual(listed.viewers["code.example:3000"], "bilal");
const detail = yield* service.detail({
projectId: "ssh" as ProjectId,
host: "code.example:3000",
repository: "team/repo",
number: 42,
});
assert.strictEqual(detail.body, "Forgejo detail");
assert.deepStrictEqual(viewers, ["code.example:3000"]);
}
}),
);
it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({
id: "http",
title: "http",
workspaceRoot: "/http",
repository: "team/repo",
provider: "forgejo",
host: "code.example",
remoteUrl: "http://code.example:4000/team/repo.git",
}),
],
providers: [fakeProvider("forgejo")],
});
const failure = yield* service
.summary(
{
projectId: "http" as ProjectId,
host: "code.example:3000",
repository: "team/repo",
number: 42,
},
{ recoverTransientFailure: false },
)
.pipe(Effect.flip);
assert.strictEqual(failure._tag, "PullRequestUnavailableError");
}),
);
it.effect("routes a hosted reference to another repository through a project on that host", () =>
Effect.gen(function* () {
const seen: Array<{ cwd: string; repository: string; host: string }> = [];
@@ -1,5 +1,6 @@
import {
canonicalRepositoryKey,
isSshRemoteUrl,
sourceControlRepositorySelector,
} from "@t3tools/shared/sourceControl";
import * as Cache from "effect/Cache";
@@ -553,14 +554,21 @@ export const make = Effect.gen(function* () {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
const identity = project.repositoryIdentity;
if (
identity?.provider !== "unknown" ||
(identity?.provider !== "unknown" &&
!(identity?.provider === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))) ||
sourceControlRepositorySelector(project.repositoryIdentity) === null
)
continue;
const host = pullRequestHostOf(identity, "unknown");
// A legacy identity has no canonical host until its provider is refined, so it must reach
// the refinement before a host filter can decide whether it belongs in the result.
if (filter.host !== undefined && host !== "unknown" && host !== filter.host.toLowerCase()) {
if (
filter.host !== undefined &&
host !== "unknown" &&
host !== filter.host.toLowerCase() &&
pullRequestHostOf(identity, "forgejo") !== filter.host.toLowerCase() &&
!isSshRemoteUrl(identity.locator.remoteUrl)
) {
continue;
}
const { remoteName, remoteUrl } = identity.locator;
@@ -581,20 +589,28 @@ export const make = Effect.gen(function* () {
Effect.suspend(() =>
sourceControlProviders.resolveHandle({
cwd: project.workspaceRoot,
context: { provider, remoteName, remoteUrl },
context: {
provider:
provider.kind === "forgejo" ? { ...provider, kind: "unknown" } : provider,
remoteName,
remoteUrl,
...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)
? { requestedHost: filter.host }
: {}),
},
}),
).pipe(
Effect.flatMap((handle) => {
const kind = handle.context?.provider.kind;
return kind === undefined || kind === "unknown"
const refined = handle.context?.provider;
return refined === undefined || refined.kind === "unknown"
? Effect.fail(undefined)
: Effect.succeed(kind);
: Effect.succeed(refined);
}),
),
),
).pipe(
Effect.map((kind) => [baseUrl, kind] as const),
Effect.orElseSucceed(() => [baseUrl, "unknown"] as const),
Effect.map((provider) => [baseUrl, provider] as const),
Effect.orElseSucceed(() => [baseUrl, null] as const),
),
{ concurrency: REPOSITORY_CONCURRENCY },
).pipe(Effect.map((resolved) => new Map(resolved)));
@@ -617,10 +633,10 @@ export const make = Effect.gen(function* () {
),
Effect.flatMap((projects) =>
refineUnknownProjectKinds(projects, filter).pipe(
Effect.map((refinedKinds) => ({ refinedKinds, projects })),
Effect.map((refinedProviders) => ({ refinedProviders, projects })),
),
),
Effect.map(({ refinedKinds, projects }) => {
Effect.map(({ refinedProviders, projects }) => {
const supported: SupportedProject[] = [];
const unimplemented = new Map<
string,
@@ -638,12 +654,22 @@ export const make = Effect.gen(function* () {
// Worktrees of one repository are separate projects; reading the remote once keeps
// the page from repeating every change request per local checkout. The host is part
// of the key, so the same `owner/repo` on two hosts stays two repositories.
if (kind === "unknown") {
let refinedProvider: SourceControlProviderInfo | null | undefined;
if (
kind === "unknown" ||
(kind === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))
) {
const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);
kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);
refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl);
kind = refinedProvider?.kind ?? kind;
}
const host =
refinedProvider?.kind === "forgejo"
? new URL(refinedProvider.baseUrl).host.toLowerCase()
: pullRequestHostOf(identity, kind);
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
continue;
}
const host = pullRequestHostOf(identity, kind);
if (filter.host !== undefined && host !== filter.host.toLowerCase()) continue;
const api = registry.get(kind);
// Recorded before the de-duplication below, so the viewer lookup keeps the alternates
// the listing is about to drop.
@@ -816,7 +842,7 @@ export const make = Effect.gen(function* () {
return Effect.die(new Error(`Missing pull request provider: ${kind}`));
}
const api = withRateLimitBackoff(registered, host, rateLimits);
return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd }))).pipe(
return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd, host }))).pipe(
Effect.map((viewer) => ({
host,
kind,
@@ -0,0 +1,262 @@
import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import type {
PullRequestActor,
PullRequestCheck,
PullRequestComment,
PullRequestCommit,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewThread,
} from "@t3tools/contracts";
import type { ProviderChangeRequest } from "./PullRequestProvider.ts";
import { dedupeChecks } from "./pullRequestChecks.ts";
export const ForgejoUser = Schema.Struct({
login: Schema.String,
full_name: Schema.optional(Schema.NullOr(Schema.String)),
avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
});
export const ForgejoLabel = Schema.Struct({
id: Schema.Int,
name: Schema.String,
color: Schema.optional(Schema.NullOr(Schema.String)),
description: Schema.optional(Schema.NullOr(Schema.String)),
});
export const ForgejoRepository = Schema.Struct({
full_name: Schema.String,
permissions: Schema.optional(Schema.Struct({ push: Schema.Boolean, admin: Schema.Boolean })),
archived: Schema.optional(Schema.Boolean),
allow_merge_commits: Schema.optional(Schema.Boolean),
allow_squash_merge: Schema.optional(Schema.Boolean),
allow_rebase: Schema.optional(Schema.Boolean),
allow_rebase_update: Schema.optional(Schema.Boolean),
});
const Branch = Schema.Struct({
ref: Schema.String,
sha: Schema.String,
repo: Schema.NullOr(ForgejoRepository),
});
export const ForgejoPullRequest = Schema.Struct({
number: Schema.Int,
title: Schema.String,
body: Schema.NullOr(Schema.String),
html_url: Schema.String,
user: Schema.NullOr(ForgejoUser),
state: Schema.String,
draft: Schema.optional(Schema.Boolean),
merged: Schema.Boolean,
mergeable: Schema.optional(Schema.Boolean),
is_locked: Schema.optional(Schema.Boolean),
head: Branch,
base: Branch,
merge_base: Schema.optional(Schema.String),
created_at: Schema.String,
updated_at: Schema.String,
closed_at: Schema.NullOr(Schema.String),
merged_at: Schema.NullOr(Schema.String),
additions: Schema.optional(Schema.NullOr(Schema.Int)),
deletions: Schema.optional(Schema.NullOr(Schema.Int)),
changed_files: Schema.optional(Schema.NullOr(Schema.Int)),
comments: Schema.optional(Schema.Int),
labels: Schema.NullOr(Schema.Array(ForgejoLabel)),
requested_reviewers: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
});
export const ForgejoComment = Schema.Struct({
id: Schema.Int,
body: Schema.String,
user: Schema.NullOr(ForgejoUser),
created_at: Schema.String,
html_url: Schema.optional(Schema.String),
});
export const ForgejoReview = Schema.Struct({
id: Schema.Int,
body: Schema.String,
user: Schema.NullOr(ForgejoUser),
state: Schema.String,
submitted_at: Schema.String,
html_url: Schema.optional(Schema.String),
comments_count: Schema.Int,
});
export const ForgejoReviewComment = Schema.Struct({
...ForgejoComment.fields,
path: Schema.String,
position: Schema.Int,
original_position: Schema.Int,
commit_id: Schema.String,
original_commit_id: Schema.String,
resolver: Schema.NullOr(ForgejoUser),
});
export const ForgejoCommit = Schema.Struct({
sha: Schema.String,
author: Schema.NullOr(ForgejoUser),
commit: Schema.Struct({
message: Schema.String,
committer: Schema.Struct({ date: Schema.String }),
}),
parents: Schema.Array(Schema.Struct({ sha: Schema.String })),
stats: Schema.optional(
Schema.NullOr(Schema.Struct({ additions: Schema.Int, deletions: Schema.Int })),
),
});
export const ForgejoStatus = Schema.Struct({
context: Schema.String,
status: Schema.String,
description: Schema.NullOr(Schema.String),
target_url: Schema.NullOr(Schema.String),
updated_at: Schema.String,
});
export const ForgejoReaction = Schema.Struct({
content: Schema.String,
user: Schema.NullOr(ForgejoUser),
});
export function forgejoActor(
user: typeof ForgejoUser.Type | null | undefined,
): PullRequestActor | null {
return user?.login
? { login: user.login, name: user.full_name || null, avatarUrl: user.avatar_url || null }
: null;
}
function toIsoUtc(value: string): string {
return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });
}
export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) {
return {
number: pr.number,
title: pr.title,
url: pr.html_url,
author: forgejoActor(pr.user),
headBranch: pr.head.ref,
baseBranch: pr.base.ref,
headRepositoryNameWithOwner: pr.head.repo?.full_name ?? null,
state: pr.merged ? "merged" : pr.state === "closed" ? "closed" : "open",
isDraft: pr.draft ?? /^(?:\[WIP\]|WIP:)/i.test(pr.title),
mergeability:
pr.mergeable === undefined ? "unknown" : pr.mergeable ? "mergeable" : "conflicting",
additions: pr.additions ?? 0,
deletions: pr.deletions ?? 0,
createdAt: toIsoUtc(pr.created_at),
updatedAt: toIsoUtc(pr.updated_at),
closedAt: pr.closed_at === null ? null : toIsoUtc(pr.closed_at),
mergedAt: pr.merged_at === null ? null : toIsoUtc(pr.merged_at),
reviewRequestLogins: (pr.requested_reviewers ?? []).map((user) => user.login),
labels: (pr.labels ?? []).map((label) => ({ name: label.name, color: label.color ?? null })),
} satisfies ProviderChangeRequest;
}
export function forgejoComment(comment: typeof ForgejoComment.Type): PullRequestComment {
return {
id: String(comment.id),
kind: "issue-comment",
author: forgejoActor(comment.user),
body: comment.body,
createdAt: toIsoUtc(comment.created_at),
url: comment.html_url || null,
path: null,
reviewState: null,
};
}
export function forgejoReview(review: typeof ForgejoReview.Type): PullRequestComment {
return {
id: `review:${review.id}`,
kind: "review",
author: forgejoActor(review.user),
body: review.body,
createdAt: toIsoUtc(review.submitted_at),
url: review.html_url || null,
path: null,
reviewState:
review.state === "REQUEST_CHANGES"
? "CHANGES_REQUESTED"
: review.state === "COMMENT"
? "COMMENTED"
: review.state,
};
}
export function forgejoReviewThread(
comment: typeof ForgejoReviewComment.Type,
): PullRequestReviewThread {
const oldSide = comment.position === 0 && comment.original_position > 0;
const line = oldSide ? comment.original_position : comment.position;
return {
id: String(comment.id),
path: comment.path,
line: line > 0 ? line : null,
side: oldSide ? "left" : "right",
isResolved: comment.resolver !== null,
isOutdated: false,
comments: [forgejoComment(comment)],
};
}
export function forgejoCommit(commit: typeof ForgejoCommit.Type): PullRequestCommit {
const author = forgejoActor(commit.author);
return {
oid: commit.sha,
messageHeadline: commit.commit.message.split("\n")[0] ?? "",
committedDate: toIsoUtc(commit.commit.committer.date),
authors: author ? [author] : [],
...(commit.stats
? { additions: commit.stats.additions, deletions: commit.stats.deletions }
: {}),
};
}
export function forgejoChecks(
statuses: ReadonlyArray<typeof ForgejoStatus.Type>,
): ReadonlyArray<PullRequestCheck> {
return dedupeChecks(
statuses.map((status) => ({
workflowName: null,
at: status.updated_at,
check: {
name: status.context || "check",
description: status.description || null,
url: status.target_url || null,
status:
status.status === "success"
? "success"
: status.status === "failure" || status.status === "error"
? "failure"
: "pending",
},
})),
);
}
export const FORGEJO_REACTIONS: Record<PullRequestReactionContent, string> = {
"thumbs-up": "+1",
"thumbs-down": "-1",
laugh: "laugh",
hooray: "hooray",
confused: "confused",
heart: "heart",
rocket: "rocket",
eyes: "eyes",
};
export function forgejoReactions(
reactions: ReadonlyArray<typeof ForgejoReaction.Type>,
viewer: string,
): ReadonlyArray<PullRequestReaction> {
return Object.entries(FORGEJO_REACTIONS).flatMap(([content, emoji]) => {
const matching = reactions.filter((reaction) => reaction.content === emoji);
return matching.length === 0
? []
: [
{
content: content as PullRequestReactionContent,
count: matching.length,
actors: matching.flatMap((reaction) =>
reaction.user?.login && reaction.user.login !== viewer ? [reaction.user.login] : [],
),
viewerHasReacted: matching.some((reaction) => reaction.user?.login === viewer),
},
];
});
}
@@ -17,6 +17,22 @@ it.effect(
VALUES ('project-1', 'Project', '/tmp/project', '[]', ${createdAt}, ${createdAt})
`;
const fixtures = [
{
id: "forgejo-old",
host: "forge.example",
repository: "acme/web",
number: 7,
source: "manual",
url: "http://forge.example:3000/acme/web/pulls/7",
},
{
id: "forgejo-other-port",
host: "forge.example:4000",
repository: "acme/web",
number: 7,
source: "manual",
url: "http://forge.example:4000/acme/web/pulls/7",
},
{
id: "azure",
host: "dev.azure.com",
@@ -83,10 +99,24 @@ it.effect(
yield* sql`
INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)
VALUES (${fixture.id}, ${fixture.host}, ${fixture.repository}, ${fixture.number},
'https://github.com/acme/web/pull/7', ${fixture.source}, ${createdAt})
${fixture.url ?? "https://github.com/acme/web/pull/7"}, ${fixture.source}, ${createdAt})
`;
}
expect(
(yield* listLinkedPullRequestThreads({
host: "forge.example:3000",
repository: "acme/web",
number: 7,
})).threads.map((thread) => thread.id),
).toEqual(["forgejo-old"]);
expect(
(yield* listLinkedPullRequestThreads({
host: "forge.example:4000",
repository: "acme/web",
number: 7,
})).threads.map((thread) => thread.id),
).toEqual(["forgejo-other-port"]);
expect(
(yield* listLinkedPullRequestThreads({
host: "org.visualstudio.com",
+20 -4
View File
@@ -1,4 +1,7 @@
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import {
normalizeThreadPullRequestKey,
threadPullRequestKeysEqual,
} from "@t3tools/shared/threadPullRequests";
import {
PullRequestLinkedThreadsResult,
PullRequestOperationError,
@@ -13,19 +16,32 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(PullRequestLinkedThreadsR
export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreads")(
function* (input: ThreadPullRequestKey) {
const key = normalizeThreadPullRequestKey(input);
const hostname = key.host.replace(/:\d+$/u, "");
const sql = yield* SqlClient.SqlClient;
const threads = yield* sql`
const rows = yield* sql<{
id: string;
projectId: string;
title: string;
archivedAt: string | null;
host: string;
repository: string;
number: number;
url: string;
}>`
SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
t.archived_at AS "archivedAt"
t.archived_at AS "archivedAt", link.host, link.repository, link.number, link.url
FROM projection_thread_pull_requests AS link
JOIN projection_threads AS t ON t.thread_id = link.thread_id
WHERE link.host = ${key.host.toLowerCase()}
WHERE (link.host = ${key.host} OR link.host = ${hostname})
AND link.repository = ${key.repository.toLowerCase()}
AND link.number = ${key.number}
AND link.source != 'stack-dismissed'
AND t.deleted_at IS NULL
ORDER BY t.updated_at DESC, t.thread_id ASC
`;
const threads = rows
.filter((row) => threadPullRequestKeysEqual(row, key))
.map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt }));
return yield* decodeLinkedThreads({ threads });
},
Effect.mapError(
+50 -3
View File
@@ -1,4 +1,8 @@
import { EnvironmentHttpApi, ProviderDriverKind } from "@t3tools/contracts";
import {
EnvironmentHttpApi,
ProviderDriverKind,
type RepositoryIdentity,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Deferred from "effect/Deferred";
@@ -51,6 +55,7 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import * as TerminalManager from "./terminal/Manager.ts";
@@ -313,12 +318,54 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
Layer.mergeAll(
AzureDevOpsCli.layer,
BitbucketApi.layer,
GitHubCli.layer,
GitLabCli.layer,
ForgejoCli.layer,
),
),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const RepositoryIdentityResolverLayerLive = Layer.effect(
RepositoryIdentityResolver.RepositoryIdentityResolver,
Effect.gen(function* () {
const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
return yield* RepositoryIdentityResolver.make({
refine: Effect.fn(function* (identity: RepositoryIdentity) {
const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
if (
!remote ||
!identity.rootPath ||
(identity.provider !== undefined &&
identity.provider !== "unknown" &&
identity.provider !== "forgejo")
)
return identity;
const handle = yield* registry.resolveHandle({
cwd: identity.rootPath,
context: {
provider: { kind: "unknown", name: "Unknown", baseUrl: "" },
remoteName: identity.locator.remoteName,
remoteUrl: identity.locator.remoteUrl,
},
});
if (handle.context?.provider.kind !== "forgejo") return identity;
const baseUrl = handle.context.provider.baseUrl.replace(/\/+$/, "");
const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
const path =
!remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
? remote.path.slice(basePath.length + 1)
: remote.path;
return { ...identity, provider: "forgejo", webUrl: `${baseUrl}/${path}` };
}),
});
}),
).pipe(Layer.provide(SourceControlProviderRegistryLayerLive), Layer.provide(ProcessRunner.layer));
const PullRequestServiceLive = PullRequestService.layer.pipe(
Layer.provide(PullRequestProviderRegistry.layer),
Layer.provide(PullRequestReadCache.layer),
@@ -512,7 +559,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(RepositoryIdentityResolverLayerLive),
Layer.provideMerge(ServerEnvironmentLayerLive),
Layer.provideMerge(AuthLayerLive),
Layer.provideMerge(ServerSecretStore.layer),
+720
View File
@@ -0,0 +1,720 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Result from "effect/Result";
import * as Clock from "effect/Clock";
import * as FileSystem from "effect/FileSystem";
import * as Semaphore from "effect/Semaphore";
import * as NodeOS from "node:os";
// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
import * as NodePath from "node:path";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
import type { SourceControlProviderContext } from "./SourceControlProvider.ts";
const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
command: Schema.Literals(["fj", "tea"]),
cwd: Schema.String,
detail: Schema.String,
reason: Schema.optional(
Schema.Literals([
"missing-cli",
"authentication",
"forbidden",
"not-found",
"rate-limit",
"invalid-response",
]),
),
httpStatus: Schema.optional(Schema.Int),
cause: Schema.optional(Schema.Defect()),
}) {}
export const ForgejoLoginSchema = Schema.Struct({
name: Schema.String,
url: Schema.String,
ssh_host: Schema.optional(Schema.String),
valid: Schema.optional(Schema.String),
user: Schema.String,
default: Schema.String,
});
export function parseForgejoLogins(raw: string) {
const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);
return Result.isSuccess(decoded) ? decoded.success : [];
}
export const ForgejoKeysSchema = Schema.Struct({
hosts: Schema.Record(
Schema.String,
Schema.Struct({
type: Schema.Literals(["Application", "OAuth"]),
token: Schema.String,
}),
),
aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
});
const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
/** Matches fj's directories::ProjectDirs, including its pre-0.6 organization name. */
function forgejoKeysPaths(input: {
readonly platform: string;
readonly home: string;
readonly dataHome?: string;
readonly appData?: string;
}) {
if (input.platform === "darwin")
return ["forgejo-cli", "Cyborus"].map((organization) =>
NodePath.join(
input.home,
"Library",
"Application Support",
`${organization}.forgejo-cli`,
"keys.json",
),
);
if (input.platform === "win32")
return ["forgejo-cli", "Cyborus"].map((organization) =>
NodePath.win32.join(
input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
organization,
"forgejo-cli",
"data",
"keys.json",
),
);
return [
NodePath.join(
input.dataHome && NodePath.isAbsolute(input.dataHome)
? input.dataHome
: NodePath.join(input.home, ".local", "share"),
"forgejo-cli",
"keys.json",
),
];
}
export interface ForgejoRepositoryInput {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly repository?: string;
readonly reference?: string;
readonly host?: string;
}
export interface ForgejoRepository {
readonly command?: "fj" | "tea";
readonly login: string;
readonly repository: string;
readonly baseUrl: string;
}
export interface ForgejoApiInput extends ForgejoRepositoryInput {
readonly path: string;
readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
readonly body?: unknown;
}
export class ForgejoCli extends Context.Service<
ForgejoCli,
{
readonly execute: (input: {
readonly command?: "fj" | "tea";
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
readonly listLogins?: (input: {
readonly cwd: string;
readonly command: "fj" | "tea";
readonly remoteUrl?: string;
}) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
readonly getAccount?: (input: {
readonly cwd: string;
readonly baseUrl: string;
}) => Effect.Effect<string, ForgejoCliError>;
readonly resolveRepository: (
input: ForgejoRepositoryInput,
) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
readonly api: (
input: ForgejoApiInput,
) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
}
>()("t3/sourceControl/ForgejoCli") {}
export function parseForgejoRemote(value: string) {
if (/^(?:https?|ssh):\/\//i.test(value)) {
try {
const url = new URL(value);
return {
host: url.host.toLowerCase(),
hostname: url.hostname.toLowerCase(),
ssh: url.protocol === "ssh:",
path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
};
} catch {
return null;
}
}
// SCP remotes may omit the username; URL treats these as a custom scheme.
const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
return ssh?.[1] && ssh[2]
? {
host: ssh[1].toLowerCase(),
hostname: ssh[1].toLowerCase(),
ssh: true,
path: ssh[2].replace(/\.git$/, ""),
}
: null;
}
export function matchForgejoLogin(
logins: ReturnType<typeof parseForgejoLogins>,
remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
requestedHost?: string,
hostOnly = false,
) {
const matches = [
...new Map(
logins
.filter((login) => {
const url = parseForgejoRemote(login.url);
if (!url) return false;
if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
return remote.ssh
? login.ssh_host?.toLowerCase() === remote.host ||
login.ssh_host?.toLowerCase() === remote.hostname ||
url.hostname === remote.hostname
: url.host === remote.host &&
((hostOnly && !remote.path) ||
!url.path ||
remote.path === url.path ||
remote.path.startsWith(`${url.path}/`));
})
.map((login) => [login.name, login]),
).values(),
];
return matches.length === 1
? matches[0]
: new Set(matches.map((login) => login.url)).size === 1
? matches.find((login) => login.default === "true")
: undefined;
}
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const fileSystem = yield* FileSystem.FileSystem;
const httpClient = yield* HttpClient.HttpClient;
const authLock = yield* Semaphore.make(1);
const authenticated = new Map<string, { token: string; time: number }>();
const execute: ForgejoCli["Service"]["execute"] = (input) =>
process
.run({
...input,
operation: "ForgejoCli.execute",
command: input.command ?? "tea",
timeoutMs: input.timeoutMs ?? 30_000,
})
.pipe(
Effect.mapError(
(cause) =>
new ForgejoCliError({
command: input.command ?? "tea",
cwd: input.cwd,
...(input.command === "fj" ? {} : { cause }),
...(cause._tag === "VcsProcessSpawnError"
? { reason: "missing-cli" as const }
: cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
? { reason: "authentication" as const }
: {}),
detail:
cause._tag === "VcsProcessSpawnError"
? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."
: cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."
: "Forgejo CLI command failed.",
}),
),
);
const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
for (const path of forgejoKeysPaths({
platform: yield* HostProcessPlatform,
home: NodeOS.homedir(),
...(globalThis.process.env.XDG_DATA_HOME
? { dataHome: globalThis.process.env.XDG_DATA_HOME }
: {}),
...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),
})) {
const exists = yield* fileSystem.exists(path).pipe(
Effect.mapError(
() =>
new ForgejoCliError({
command: "fj",
cwd,
reason: "authentication",
detail: "Could not read fj authentication storage.",
}),
),
);
if (!exists) continue;
const raw = yield* fileSystem.readFileString(path).pipe(
Effect.mapError(
() =>
new ForgejoCliError({
command: "fj",
cwd,
reason: "authentication",
detail: "Could not read fj authentication storage.",
}),
),
);
const decoded = parseForgejoKeys(raw);
if (Result.isFailure(decoded))
return yield* new ForgejoCliError({
command: "fj",
cwd,
reason: "authentication",
detail: "fj authentication storage is invalid. Authenticate again with fj.",
});
return decoded.success;
}
const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
return empty;
});
const publicLogins = (
keys: typeof ForgejoKeysSchema.Type,
remoteUrl?: string,
): ReturnType<typeof parseForgejoLogins> => {
const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
return Object.keys(keys.hosts).flatMap((host) => {
const url = parseForgejoRemote(`https://${host}`);
// fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.
if (!url || url.path) return [];
// fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
const scheme =
remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
? "http"
: "https";
const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
const aliases = Object.entries(keys.aliases ?? {})
.filter(([, target]) => target === host)
.map(([alias]) => ({ ...login, ssh_host: alias }));
return aliases.length ? aliases : [login];
});
};
const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
"ForgejoCli.listLogins",
)(function* (input) {
if (input.command === "fj") {
const keys = yield* readKeys(input.cwd).pipe(Effect.result);
if (Result.isFailure(keys)) {
// Stale credentials from an uninstalled fj must not disable an available tea login.
const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
Effect.result,
);
if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
return yield* keys.failure;
}
return publicLogins(keys.success, input.remoteUrl);
}
return parseForgejoLogins(
(yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,
);
});
const requestFj = Effect.fn("ForgejoCli.requestFj")(
function* (input: {
readonly cwd: string;
readonly baseUrl: string;
readonly token: string;
readonly path: string;
readonly method?: ForgejoApiInput["method"];
readonly body?: string;
}) {
const base = new URL(`${input.baseUrl}/api/v1/`);
const url = new URL(input.path, base);
if (
url.origin !== base.origin ||
!url.pathname.startsWith(base.pathname) ||
url.username ||
url.password
)
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
detail: "Invalid Forgejo API path.",
});
let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(
HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
);
if (input.body !== undefined)
request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
const response = yield* httpClient
.execute(request)
.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
const status = response.status;
if (status < 200 || status >= 300)
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
httpStatus: status,
...(status === 401
? { reason: "authentication" as const }
: status === 403
? { reason: "forbidden" as const }
: status === 404
? { reason: "not-found" as const }
: status === 429
? { reason: "rate-limit" as const }
: {}),
detail:
status === 404
? "Forgejo repository or pull request was not found."
: `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`,
});
const body =
status === 204 || status === 205
? { text: "", truncated: false, invalidUtf8: false }
: yield* collectUint8StreamText({
stream: response.stream,
maxBytes: 8 * 1024 * 1024,
});
if (body.truncated || body.invalidUtf8)
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
reason: "invalid-response",
detail: "Forgejo returned an oversized or invalid response.",
});
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: body.text,
stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,
stdoutTruncated: false,
stderrTruncated: false,
};
},
(effect, input) =>
effect.pipe(
Effect.timeout(30_000),
Effect.mapError((error) =>
error._tag === "ForgejoCliError"
? error
: new ForgejoCliError({
command: "fj",
cwd: input.cwd,
detail: "Forgejo API request failed or timed out.",
}),
),
),
);
const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
cwd: string,
login: typeof ForgejoLoginSchema.Type,
) {
const keys = yield* readKeys(cwd);
const token = keys.hosts[login.name]?.token;
const now = yield* Clock.currentTimeMillis;
const cached = authenticated.get(login.url);
if (token && cached?.token === token && now - cached.time < 30_000) return token;
yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });
// fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
if (!refreshed)
return yield* new ForgejoCliError({
command: "fj",
cwd,
reason: "authentication",
detail: "fj has no credentials for this server. Authenticate again with fj.",
});
authenticated.set(login.url, { token: refreshed, time: now });
return refreshed;
}, authLock.withPermits(1));
const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
"ForgejoCli.getAccount",
)(function* (input) {
const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
const login = logins.find(
(item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
);
if (!login)
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
reason: "authentication",
detail: "fj has no credentials for this server.",
});
const token = yield* authenticateFj(input.cwd, login);
const currentUser = yield* requestFj({
cwd: input.cwd,
baseUrl: login.url.replace(/\/+$/, ""),
token,
path: "user",
});
const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
if (Result.isFailure(user) || !user.success.login.trim())
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
reason: "invalid-response",
detail: "Forgejo returned an invalid account response.",
});
return user.success.login;
});
const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
input: ForgejoRepositoryInput,
hostOnly = false,
) {
const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
(value) => value && parseForgejoRemote(value),
);
let remote =
referenceRemote ??
(input.repository ? parseForgejoRemote(input.repository) : null) ??
(input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
if (!remote && (!input.repository || input.host)) {
const result = yield* process
.run({
operation: "ForgejoCli.remote",
command: "git",
args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
cwd: input.cwd,
allowNonZeroExit: true,
})
.pipe(
Effect.mapError(
(cause) =>
new ForgejoCliError({
command: "tea",
cwd: input.cwd,
detail: "Could not resolve the Forgejo repository remote.",
cause,
}),
),
);
if (input.host) {
const matchingUrls = [
...new Set(
result.stdout.split("\n").flatMap((line) => {
const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)$/.exec(line.trim())?.[1];
return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
? [url]
: [];
}),
),
];
const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
remoteUrl =
matchingUrls.length === 1
? matchingUrls[0]
: origins.length === 1
? origins[0]
: undefined;
} else {
remoteUrl = result.stdout.trim();
}
remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
}
if (
input.host &&
!remote?.ssh &&
remote?.host !== input.host.toLowerCase() &&
remote?.hostname !== input.host.toLowerCase()
)
remote = {
host: input.host.toLowerCase(),
hostname: input.host.split(":")[0] ?? input.host,
ssh: false,
path: remote?.path ?? "",
};
const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
const fjLogins = yield* listLogins({
cwd: input.cwd,
command: "fj",
...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
});
const requestedHost = input.host ?? input.context?.requestedHost;
const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
remote
? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
: (logins.find((item) => item.default === "true") ??
(new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
let login = selectLogin(fjLogins);
let command: "fj" | "tea" = "fj";
if (
!login &&
fjLogins.some(
(item) =>
!remote ||
matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
)
) {
const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
Effect.result,
);
if (Result.isSuccess(available))
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
reason: "authentication",
detail: "Multiple fj logins match this repository. Specify its full server URL.",
});
if (available.failure.reason !== "missing-cli") return yield* available.failure;
}
if (login) {
const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
if (Result.isFailure(auth)) {
if (auth.failure.reason === "missing-cli") login = undefined;
else return yield* auth.failure;
}
}
if (!login) {
command = "tea";
login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
}
if (!login)
return yield* new ForgejoCliError({
command: "tea",
cwd: input.cwd,
reason: "authentication",
detail:
"No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",
});
if (hostOnly)
return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
const path =
referenceRemote?.path ??
(input.repository && !parseForgejoRemote(input.repository)
? input.repository
: remote?.path) ??
"";
const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
const relativePath =
basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
? path.slice(basePath.length + 1)
: path;
const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
if (command === "fj" && !repositoryPath.includes("/")) {
login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
}
const repository = repositoryPath.includes("/")
? repositoryPath
: `${login.user}/${repositoryPath}`;
if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
return yield* new ForgejoCliError({
command,
cwd: input.cwd,
detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
});
return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
});
const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
const repository = yield* resolveTarget(
input,
input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
);
const stdin =
input.body === undefined
? undefined
: yield* encodeApiBody(input.body).pipe(
Effect.mapError(
(cause) =>
new ForgejoCliError({
command: "tea",
cwd: input.cwd,
detail: "Could not encode the Forgejo request body.",
cause,
}),
),
);
let path = input.path.replace(/^\/+/, "");
if (input.repository && input.repository !== repository.repository) {
// Repository identities retain the server mount path; API routes do not.
const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
}
}
if (repository.command === "fj") {
const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
if (!token)
return yield* new ForgejoCliError({
command: "fj",
cwd: input.cwd,
reason: "authentication",
detail: "fj has no credentials for this server.",
});
return yield* requestFj({
cwd: input.cwd,
baseUrl: repository.baseUrl,
token,
path,
...(input.method === undefined ? {} : { method: input.method }),
...(stdin === undefined ? {} : { body: stdin }),
});
}
const result = yield* execute({
cwd: input.cwd,
args: [
"api",
"--include",
"--login",
repository.login,
...(repository.repository ? ["--repo", repository.repository] : []),
"--method",
input.method ?? "GET",
...(input.body === undefined ? [] : ["--data", "@-"]),
`${repository.baseUrl}/api/v1/${path}`,
],
...(stdin === undefined ? {} : { stdin }),
});
// tea reports HTTP failures with exit code zero; use its response status.
const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
if (!status || status >= 400)
return yield* new ForgejoCliError({
command: "tea",
cwd: input.cwd,
...(status ? { httpStatus: status } : {}),
...(status === 401
? { reason: "authentication" as const }
: status === 403
? { reason: "forbidden" as const }
: status === 404
? { reason: "not-found" as const }
: status === 429
? { reason: "rate-limit" as const }
: {}),
detail:
status === 401 || status === 403
? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
: status === 404
? "Forgejo repository or pull request was not found."
: status === 429
? "Forgejo API rate limit exceeded."
: `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
});
return result;
});
return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
});
export const layer = Layer.effect(ForgejoCli, make);
@@ -0,0 +1,387 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import * as Result from "effect/Result";
import { SourceControlProviderError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as ForgejoCli from "./ForgejoCli.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import {
providerAuth,
probeSourceControlProvider,
type SourceControlCliDiscoverySpec,
type SourceControlManagedCliDiscoverySpec,
} from "./SourceControlProviderDiscovery.ts";
import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts";
const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
export const discovery = {
type: "cli",
kind: "forgejo",
label: "Forgejo / Gitea",
executable: "tea",
versionArgs: ["--version"],
authArgs: ["login", "status", "--output", "json"],
remoteRefinementArgs: ["login", "list", "--output", "json"],
parseAuth: (input) => {
const logins = ForgejoCli.parseForgejoLogins(input.stdout);
const login = logins.find((entry) => entry.default === "true") ?? logins[0];
return login
? providerAuth({
status: login.valid === "true" ? "authenticated" : "unauthenticated",
account: login.user,
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
})
: providerAuth({
status: "unauthenticated",
detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.",
});
},
refineUnknownRemote: (input) => {
const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
const login =
remote &&
ForgejoCli.matchForgejoLogin(
ForgejoCli.parseForgejoLogins(input.auth.stdout),
remote,
input.context.requestedHost,
);
return login ? { kind: "forgejo", name: "Forgejo / Gitea", baseUrl: login.url } : null;
},
installHint:
"Install `fj` 0.6 or later from https://codeberg.org/forgejo-contrib/forgejo-cli and run `fj --host <server-url> auth add-token`, or install `tea` 0.16 or later from https://gitea.com/gitea/tea and run `tea login add` for each Forgejo or Gitea server.",
} satisfies SourceControlCliDiscoverySpec;
export const makeDiscovery = Effect.gen(function* () {
const cli = yield* ForgejoCli.ForgejoCli;
const process = yield* VcsProcess.VcsProcess;
const listLogins = cli.listLogins;
if (!listLogins) return discovery;
return {
type: "managed-cli",
kind: "forgejo",
label: discovery.label,
installHint: discovery.installHint,
probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) {
const remoteUrl = yield* process
.run({
operation: "source-control.discovery.remote",
command: "git",
args: ["remote", "get-url", "origin"],
cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
})
.pipe(
Effect.map((result) => result.stdout.trim()),
Effect.orElseSucceed(() => ""),
);
const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl }));
const logins = Result.isSuccess(credentials) ? credentials.success : [];
const remote = ForgejoCli.parseForgejoRemote(remoteUrl);
const login =
(remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||
logins.find((entry) => entry.default === "true") ||
logins[0];
const fj = yield* probeSourceControlProvider({
cwd,
process,
spec: {
...discovery,
executable: "fj",
versionArgs: ["version"],
authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],
parseAuth: (result) =>
Result.isFailure(credentials)
? providerAuth({
status: "unknown",
detail: "Could not read fj authentication storage. Authenticate again with fj.",
})
: login && result.exitCode === 0
? providerAuth({
status: "authenticated",
account: login.user,
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
})
: providerAuth({
status: "unauthenticated",
detail:
"Authenticate this server with `fj --host <server-url> auth add-token`.",
}),
},
});
// A configured fj account owns its requests, including authentication errors.
if (fj.status === "available" && (login || Result.isFailure(credentials))) {
if (login && fj.auth.status === "authenticated" && cli.getAccount) {
const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
return {
...fj,
auth: Result.isSuccess(account)
? providerAuth({
status: "authenticated",
account: account.success,
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
})
: providerAuth({
status: "unknown",
detail: account.failure.detail,
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
}),
};
}
return fj;
}
const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
return tea.status === "available" || fj.status === "missing" ? tea : fj;
}),
refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
function* (input: {
readonly cwd: string;
readonly context: SourceControlProvider.SourceControlProviderContext;
}) {
const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
if (!remote) return null;
for (const command of ["fj", "tea"] as const) {
const logins = yield* listLogins({
cwd: input.cwd,
command,
remoteUrl: input.context.remoteUrl,
}).pipe(Effect.orElseSucceed(() => []));
const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);
if (login) return { kind: "forgejo" as const, name: discovery.label, baseUrl: login.url };
}
return null;
},
),
} satisfies SourceControlManagedCliDiscoverySpec;
});
const RepositorySchema = Schema.Struct({
full_name: Schema.String,
clone_url: Schema.String,
ssh_url: Schema.String,
default_branch: Schema.optional(Schema.NullOr(Schema.String)),
});
const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
nameWithOwner: raw.full_name,
url: raw.clone_url,
sshUrl: raw.ssh_url,
});
const repositoryPath = (repository: string) =>
`repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
export const make = Effect.gen(function* () {
const cli = yield* ForgejoCli.ForgejoCli;
const fs = yield* FileSystem.FileSystem;
const process = yield* VcsProcess.VcsProcess;
const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
input: ForgejoCli.ForgejoApiInput,
schema: S,
) =>
cli.api(input).pipe(
Effect.flatMap((result) =>
Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
Effect.mapError(
(cause) =>
new ForgejoCli.ForgejoCliError({
command: "tea",
cwd: input.cwd,
detail: "Forgejo API returned an invalid response.",
reason: "invalid-response",
cause,
}),
),
),
),
);
const mapError = (operation: string, cwd: string) =>
Effect.mapError(
(cause: unknown) =>
new SourceControlProviderError({
provider: "forgejo",
operation,
cwd,
...(isForgejoCliError(cause) ? { command: cause.command } : {}),
detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
cause,
}),
);
const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
input: Parameters<
SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
>[0],
) {
const repo = yield* cli.resolveRepository(input);
const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
if (!number)
return yield* new ForgejoCli.ForgejoCliError({
command: "tea",
cwd: input.cwd,
detail: "Specify a pull request number or Forgejo pull request URL.",
});
return yield* request(
{ ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
ForgejoPullRequestSchema,
);
});
return SourceControlProvider.SourceControlProvider.of({
kind: "forgejo",
listChangeRequests: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
const branch = SourceControlProvider.sourceBranch(input);
const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
const limit = input.limit ?? 20;
for (let page = 1; results.length < limit; page++) {
const items = yield* request(
{
...input,
path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&sort=recentupdate&limit=50&page=${page}`,
},
Schema.Array(ForgejoPullRequestSchema),
);
for (const item of items) {
if (
item.head.ref !== branch ||
(source?.repository && item.head.repo?.full_name !== source.repository) ||
(source?.owner && item.head.repo?.owner.login !== source.owner)
)
continue;
const normalized = toForgejoChangeRequest(item);
if (input.state === "all" || normalized.state === input.state) results.push(normalized);
}
if (items.length === 0) break;
}
return results.slice(0, limit);
}).pipe(mapError("listChangeRequests", input.cwd)),
getChangeRequest: (input) =>
getPull(input).pipe(
Effect.map(toForgejoChangeRequest),
mapError("getChangeRequest", input.cwd),
),
createChangeRequest: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
const owner = source?.owner ?? source?.repository?.split("/")[0];
const head = SourceControlProvider.sourceBranch(input);
yield* cli.api({
...input,
path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
method: "POST",
body: {
base: input.target?.refName ?? input.baseRefName,
head: owner ? `${owner}:${head}` : head,
title: input.title,
body: yield* fs.readFileString(input.bodyFile),
},
});
}).pipe(mapError("createChangeRequest", input.cwd)),
getRepositoryCloneUrls: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
return cloneUrls(
yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
);
}).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
createRepository: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
const user = yield* request(
{ ...input, path: "user" },
Schema.Struct({ login: Schema.String }),
);
const [owner, name] = repo.repository.split("/");
return cloneUrls(
yield* request(
{
...input,
path:
owner === user.login
? "user/repos"
: `orgs/${encodeURIComponent(owner ?? "")}/repos`,
method: "POST",
body: { name, private: input.visibility === "private", auto_init: false },
},
RepositorySchema,
),
);
}).pipe(mapError("createRepository", input.cwd)),
getDefaultBranch: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
return (
(yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
.default_branch ?? null
);
}).pipe(mapError("getDefaultBranch", input.cwd)),
checkoutChangeRequest: (input) =>
Effect.gen(function* () {
const repo = yield* cli.resolveRepository(input);
const pull = yield* getPull(input);
if (repo.command === "fj") {
// fj checkout cannot target a repository outside the local remotes.
const urls = yield* request(
{ ...input, path: repositoryPath(repo.repository) },
RepositorySchema,
);
const remote = input.context?.remoteUrl;
const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
yield* process.run({
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
command: "git",
cwd: input.cwd,
args: [
"fetch",
"--",
useSsh ? urls.ssh_url : urls.clone_url,
`refs/pull/${pull.number}/head`,
],
});
const branch = `pulls/${pull.number}`;
const existing = yield* process.run({
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
command: "git",
cwd: input.cwd,
args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
allowNonZeroExit: true,
});
yield* process.run({
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
command: "git",
cwd: input.cwd,
args:
existing.exitCode === 0
? ["checkout", branch]
: ["checkout", "-b", branch, "FETCH_HEAD"],
});
} else
yield* cli.execute({
cwd: input.cwd,
args: [
"pulls",
"checkout",
"--login",
repo.login,
"--repo",
repo.repository,
"--branch",
String(pull.number),
],
});
if (input.force) {
// tea leaves an existing PR branch at its old tip. Keep dirty files safe
// while bringing the selected branch to the PR revision we fetched.
yield* process.run({
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
command: "git",
cwd: input.cwd,
args: ["reset", "--keep", pull.head.sha],
});
}
}).pipe(mapError("checkoutChangeRequest", input.cwd)),
});
});
File diff suppressed because it is too large. Load diff
@@ -14,6 +14,8 @@ export interface SourceControlProviderContext {
readonly provider: SourceControlProviderInfo;
readonly remoteName: string;
readonly remoteUrl: string;
/** An explicit web authority can disambiguate Forgejo logins sharing an SSH alias. */
readonly requestedHost?: string;
}
export interface SourceControlRefSelector {
@@ -1,3 +1,4 @@
import * as NodeUtil from "node:util";
import type {
SourceControlProviderAuth,
SourceControlProviderDiscoveryItem,
@@ -33,6 +34,7 @@ export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
readonly authArgs: ReadonlyArray<string>;
readonly remoteRefinementArgs?: ReadonlyArray<string>;
readonly probeTimeoutMs?: number;
readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
readonly refineUnknownRemote?: (
@@ -45,8 +47,18 @@ export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
};
export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly type: "managed-cli";
readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
readonly refineUnknownRemote: (input: {
readonly cwd: string;
readonly context: SourceControlProvider.SourceControlProviderContext;
}) => Effect.Effect<SourceControlProviderInfo | null>;
};
export type SourceControlProviderDiscoverySpec =
| SourceControlCliDiscoverySpec
| SourceControlManagedCliDiscoverySpec
| SourceControlApiDiscoverySpec;
type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {
@@ -72,7 +84,7 @@ interface DiscoveryProbeResult {
}
export function firstNonEmptyLine(text: string): Option.Option<string> {
const line = text
const line = NodeUtil.stripVTControlCharacters(text)
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
@@ -214,6 +226,7 @@ export function probeSourceControlProvider(input: {
readonly process: VcsProcess.VcsProcess["Service"];
readonly cwd: string;
}): Effect.Effect<SourceControlProviderDiscoveryItem> {
if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);
if (input.spec.type === "api") {
return input.spec.probeAuth.pipe(
Effect.map(
@@ -288,12 +301,16 @@ export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvide
}
const context = input.context;
const providers = yield* Effect.forEach(input.specs.filter(isCliRemoteRefinementSpec), (spec) =>
input.process
const providers = yield* Effect.forEach(input.specs, (spec) => {
if (spec.type === "managed-cli") {
return spec.refineUnknownRemote({ cwd: input.cwd, context });
}
if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
return input.process
.run({
operation: "source-control.discovery.refine-unknown-remote",
command: spec.executable,
args: spec.authArgs,
args: spec.remoteRefinementArgs ?? spec.authArgs,
cwd: input.cwd,
allowNonZeroExit: true,
timeoutMs: probeTimeoutMs(spec),
@@ -309,8 +326,8 @@ export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvide
}),
),
Effect.orElseSucceed(() => null),
),
);
);
});
const provider = providers.find((candidate) => candidate !== null);
return provider ? { ...context, provider } : context;
@@ -15,6 +15,7 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as ForgejoCli from "./ForgejoCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
@@ -86,12 +87,14 @@ function makeRegistry(input: {
return SourceControlProviderRegistry.make.pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
registryLayer,
processLayer,
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-source-control-registry-test-",
}).pipe(Layer.provide(NodeServices.layer)),
@@ -15,6 +15,7 @@ import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlPro
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import {
probeSourceControlProvider,
@@ -296,6 +297,8 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
export const make = Effect.gen(function* () {
const github = yield* GitHubSourceControlProvider.make;
const gitlab = yield* GitLabSourceControlProvider.make;
const forgejo = yield* ForgejoSourceControlProvider.make;
const forgejoDiscovery = yield* ForgejoSourceControlProvider.makeDiscovery;
const bitbucket = yield* BitbucketSourceControlProvider.make;
const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;
const azureDevOps = yield* AzureDevOpsSourceControlProvider.make;
@@ -320,6 +323,7 @@ export const make = Effect.gen(function* () {
provider: bitbucket,
discovery: bitbucketDiscovery,
},
{ kind: "forgejo", provider: forgejo, discovery: forgejoDiscovery },
]);
});
@@ -0,0 +1,47 @@
import * as Schema from "effect/Schema";
import * as Option from "effect/Option";
import type { ChangeRequest } from "@t3tools/contracts";
const Repository = Schema.Struct({
full_name: Schema.String,
owner: Schema.Struct({ login: Schema.String }),
});
const Branch = Schema.Struct({
ref: Schema.String,
sha: Schema.String,
repo: Schema.NullOr(Repository),
});
export const ForgejoPullRequestSchema = Schema.Struct({
number: Schema.Int,
title: Schema.String,
html_url: Schema.String,
state: Schema.String,
merged: Schema.Boolean,
draft: Schema.optional(Schema.Boolean),
base: Branch,
head: Branch,
closed_at: Schema.optional(Schema.NullOr(Schema.String)),
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
});
export function toForgejoChangeRequest(raw: typeof ForgejoPullRequestSchema.Type): ChangeRequest {
return {
provider: "forgejo",
number: raw.number,
title: raw.title,
url: raw.html_url,
state: raw.merged ? "merged" : raw.state === "closed" ? "closed" : "open",
isDraft: raw.draft ?? /^(?:\[WIP\]|WIP:)/i.test(raw.title),
baseRefName: raw.base.ref,
headRefName: raw.head.ref,
closedAt: raw.closed_at ?? null,
mergedAt: raw.merged_at ?? null,
updatedAt: raw.updated_at ?? Option.none(),
isCrossRepository:
raw.head.repo !== null &&
raw.base.repo !== null &&
raw.head.repo.full_name !== raw.base.repo.full_name,
headRepositoryNameWithOwner: raw.head.repo?.full_name ?? null,
headRepositoryOwnerLogin: raw.head.repo?.owner.login ?? null,
};
}
+2
View File
@@ -155,6 +155,7 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
@@ -3111,6 +3112,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
BitbucketApi.layer,
GitHubCli.layer,
GitLabCli.layer,
ForgejoCli.layer,
),
),
Layer.provideMerge(GitVcsDriver.layer),
+11 -2
View File
@@ -150,7 +150,7 @@ import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sideb
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteContent } from "./CommandPaletteContent";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon, ForgejoIcon } from "./Icons";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { ProjectFavicon } from "./ProjectFavicon";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
@@ -244,7 +244,7 @@ interface AddProjectEnvironmentOption {
type AddProjectRemoteProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
"github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops"
>;
type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
@@ -267,12 +267,14 @@ const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
"url",
"github",
"gitlab",
"forgejo",
"bitbucket",
"azure-devops",
];
const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
"github",
"gitlab",
"forgejo",
"bitbucket",
"azure-devops",
];
@@ -281,6 +283,8 @@ function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
switch (source) {
case "github":
return "GitHub";
case "forgejo":
return "Forgejo / Gitea";
case "gitlab":
return "GitLab";
case "bitbucket":
@@ -294,6 +298,7 @@ function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string {
switch (source) {
case "forgejo":
case "github":
return "owner/repo";
case "gitlab":
@@ -317,6 +322,8 @@ function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: stri
switch (source) {
case "github":
return <GitHubIcon className={className} />;
case "forgejo":
return <ForgejoIcon className={className} />;
case "gitlab":
return <GitLabIcon className={className} />;
case "bitbucket":
@@ -370,6 +377,7 @@ function buildAddProjectRemoteSourceReadiness(
url: { ready: true, hint: null },
github: unavailable,
gitlab: unavailable,
forgejo: unavailable,
bitbucket: unavailable,
"azure-devops": unavailable,
};
@@ -1759,6 +1767,7 @@ function OpenCommandPaletteDialog(props: {
"git",
"github",
"gitlab",
"forgejo",
"bitbucket",
"azure",
"devops",
+25 -3
View File
@@ -39,7 +39,13 @@ import {
GlobeIcon,
} from "lucide-react";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "~/components/Icons";
import {
AzureDevOpsIcon,
BitbucketIcon,
GitHubIcon,
GitLabIcon,
ForgejoIcon,
} from "~/components/Icons";
import { RadioGroup } from "~/components/ui/radio-group";
import { Spinner } from "~/components/ui/spinner";
import { toggleVariants } from "~/components/ui/toggle";
@@ -123,7 +129,7 @@ interface PendingDefaultBranchAction {
type PublishProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
"github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops"
>;
type GitActionToastId = ReturnType<typeof toastManager.add>;
@@ -171,6 +177,14 @@ function requestVcsStatusRefresh(
const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const;
const PUBLISH_PROVIDER_OPTIONS = [
{
value: "forgejo",
label: "Forgejo / Gitea",
description: "Your signed-in server",
host: "your server",
pathPlaceholder: "owner/repo",
Icon: ForgejoIcon,
},
{
value: "github",
label: "GitHub",
@@ -425,6 +439,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const accounts: Record<PublishProviderKind, string | null> = {
github: null,
gitlab: null,
forgejo: null,
bitbucket: null,
"azure-devops": null,
};
@@ -476,7 +491,14 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
: "";
const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;
const currentPublishProvider = publishProviderOption(publishProvider);
const publishHost = currentPublishProvider.host;
const publishHost =
publishProvider === "forgejo"
? (Option.getOrNull(
sourceControlDiscovery.data?.sourceControlProviders.find(
(provider) => provider.kind === "forgejo",
)?.auth.host ?? Option.none(),
) ?? currentPublishProvider.host)
: currentPublishProvider.host;
const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
const publishProviderLabel = currentPublishProvider.label;
const publishWizardSteps = ["Provider", "Repository", "Summary"] as const;
+13
View File
@@ -768,3 +768,16 @@ export const PiAgentIcon: Icon = ({ className, ...props }) => (
<path fill="#fff" d="M517.36 400H634.72V634.72H517.36Z" />
</svg>
);
// Official two-color mark from https://forgejo.org/favicon.svg.
export const ForgejoIcon: Icon = (props) => (
<svg viewBox="0 0 212 212" aria-hidden="true" {...props}>
<g transform="translate(6 6)" fill="none">
<path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" stroke="#ff6600" strokeWidth="25" />
<path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" stroke="#d40000" strokeWidth="25" />
<circle cx="142" cy="20" r="18" stroke="#ff6600" strokeWidth="15" />
<circle cx="142" cy="88" r="18" stroke="#d40000" strokeWidth="15" />
<circle cx="58" cy="180" r="18" stroke="#d40000" strokeWidth="15" />
</g>
</svg>
);
@@ -102,7 +102,9 @@ export function linkedPullRequestSnapshotStatus(
? "azure-devops"
: link.url.includes("/pull-requests/")
? "bitbucket"
: "github";
: link.url.includes("/pulls/")
? "forgejo"
: "github";
return {
pr: {
number: link.number,
@@ -144,7 +144,10 @@ function LinkPullRequestDialog({
return {
host,
repository,
webUrl: (number: number) => changeRequestWebUrl(kind, host, repository, number),
webUrl: (number: number) =>
kind === "forgejo" && identity.webUrl
? `${identity.webUrl.replace(/\/+$/, "")}/pulls/${number}`
: changeRequestWebUrl(kind, host, repository, number, identity.locator.remoteUrl),
};
}, [environmentProjects, projectId]);
const linking = usePullRequestLinking(threadRef.environmentId);
@@ -976,6 +976,7 @@ function PullRequestCodeTab({
environmentId={environmentId}
reference={reference}
verdicts={review.verdicts}
requestChangesSummaryRequired={detail.provider === "forgejo"}
onSubmitted={() => {
onRefresh();
setReviewOpen(false);
@@ -727,6 +727,7 @@ export function PullRequestDetailPanel({
detail.number,
detail.headBranch,
detail.headRepositoryNameWithOwner,
repositoryUrl,
)
: null;
const branchRefsQuery = useEnvironmentQuery(
@@ -784,11 +785,14 @@ export function PullRequestDetailPanel({
if (!coreDetail) return;
const next = { key: tabScopeKey, updatedAt: coreDetail.updatedAt };
if (shouldRefreshPullRequestActivity(activityRevision.current, next)) {
// Let an existing read settle before revalidating the new revision. Interrupting a
// mutation's activity refresh can leave SWR displaying its previous value.
if (activityQuery.isPending) return;
activityQuery.refresh();
setRefreshToken((token) => token + 1);
}
activityRevision.current = next;
}, [activityQuery.refresh, coreDetail, tabScopeKey]);
}, [activityQuery.isPending, activityQuery.refresh, coreDetail, tabScopeKey]);
// Reuse activity and diff until core detail reports a changed revision. Keyed by
// the pull request rather than by the panel, because this one panel shows a different pull
// request every time it is opened.
@@ -50,11 +50,13 @@ export function PullRequestReviewBar({
environmentId,
reference,
verdicts,
requestChangesSummaryRequired,
onSubmitted,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
verdicts: ReadonlyArray<PullRequestReviewVerdict>;
requestChangesSummaryRequired: boolean;
onSubmitted: () => void;
}) {
const [pending, setPending] = useState(false);
@@ -106,9 +108,11 @@ export function PullRequestReviewBar({
onSubmitted();
};
// An approval needs no words; anything else does, unless it carries line comments instead.
// Forgejo requires a summary when requesting changes, even with inline comments.
const canSubmit = (verdict: PullRequestReviewVerdict) =>
verdict === "approve" || body.trim().length > 0 || comments.length > 0;
verdict === "request-changes" && requestChangesSummaryRequired
? body.trim().length > 0
: verdict === "approve" || body.trim().length > 0 || comments.length > 0;
return (
<div className="px-4 py-3">
@@ -128,7 +132,11 @@ export function PullRequestReviewBar({
size="sm"
className="mt-2"
value={body}
placeholder="Summarize your review (optional)"
placeholder={
requestChangesSummaryRequired && verdicts.includes("request-changes")
? "Summarize your review (required to request changes)"
: "Summarize your review (optional)"
}
aria-label="Review summary"
onChange={(event) => setSummary(reviewKey, event.target.value)}
/>
@@ -7,6 +7,7 @@ import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-r
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
@@ -56,7 +57,10 @@ function EnabledPullRequestThreadLinks({
linking.mode === "multiple" && display !== "menu-item"
? pullRequestEnvironment.linkedThreads({
environmentId,
input: parsed === null ? reference : { ...reference, ...parsed },
input:
parsed === null
? reference
: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
})
: null,
);
@@ -85,7 +89,10 @@ function EnabledPullRequestThreadLinks({
}
if (linking.mode === "multiple") {
appAtomRegistry.refresh(
pullRequestEnvironment.linkedThreads({ environmentId, input: { ...reference, ...parsed } }),
pullRequestEnvironment.linkedThreads({
environmentId,
input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
}),
);
}
onPickerOpenChange?.(false);
@@ -55,6 +55,7 @@ describe("pull request checkout commands", () => {
it.each([
["github", "feature", null, "gh pr checkout 42"],
["gitlab", "feature", null, "glab mr checkout 42"],
["forgejo", "feature", null, null],
["azure-devops", "feature", null, "az repos pr checkout --id 42"],
[
"bitbucket",
@@ -66,6 +67,32 @@ describe("pull request checkout commands", () => {
] as const)("builds the %s command", (provider, branch, repository, expected) => {
expect(pullRequestCheckoutCommand(provider, 42, branch, repository)).toBe(expected);
});
it("fetches Forgejo pull refs from the actual repository, including a mounted host and port", () => {
expect(
pullRequestCheckoutCommand(
"forgejo",
42,
"feature",
null,
"https://forgejo.local:3000/git/maria/repo",
),
).toBe(
"git fetch 'https://forgejo.local:3000/git/maria/repo' refs/pull/42/head && git checkout -B pulls/42 FETCH_HEAD",
);
});
it("quotes shell metacharacters in Forgejo repository URLs", () => {
expect(
pullRequestCheckoutCommand(
"forgejo",
42,
"feature",
null,
"https://forgejo.local/maria/repo'$(echo nope)",
),
).toBe(
"git fetch 'https://forgejo.local/maria/repo'\\''$(echo nope)' refs/pull/42/head && git checkout -B pulls/42 FETCH_HEAD",
);
});
});
const TIMELINE_SOURCE: Pick<
@@ -104,12 +104,17 @@ export function pullRequestCheckoutCommand(
number: number,
headBranch: string,
headRepositoryNameWithOwner?: string | null,
repositoryUrl?: string | null,
): string | null {
switch (provider) {
case "github":
return `gh pr checkout ${number}`;
case "gitlab":
return `glab mr checkout ${number}`;
case "forgejo":
return repositoryUrl
? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' refs/pull/${number}/head && git checkout -B pulls/${number} FETCH_HEAD`
: null;
case "azure-devops":
return `az repos pr checkout --id ${number}`;
case "bitbucket": {
@@ -11,6 +11,7 @@ export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";
const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
github: "Open on GitHub",
gitlab: "Open on GitLab",
forgejo: "Open on Forgejo",
bitbucket: "Open on Bitbucket",
"azure-devops": "Open on Azure DevOps",
};
@@ -52,6 +52,7 @@ import {
GitHubIcon,
GitIcon,
GitLabIcon,
ForgejoIcon,
JujutsuIcon,
type Icon,
} from "../Icons";
@@ -75,6 +76,7 @@ const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
github: GitHubIcon,
gitlab: GitLabIcon,
forgejo: ForgejoIcon,
"azure-devops": AzureDevOpsIcon,
bitbucket: BitbucketIcon,
};
@@ -567,7 +567,7 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/source-control",
scope: "environment-defaults",
searchTerms: [
"version control git github gitlab bitbucket azure devops hosting integrations credentials scan server environment",
"version control git github gitlab forgejo gitea tea codeberg bitbucket azure devops hosting integrations credentials scan server environment",
],
},
{
@@ -170,6 +170,37 @@ describe("matchesLinkedPullRequestUrl", () => {
).toBe(true);
});
it.each([
["http://forge.example:3000/git/team/repo/pulls/42/files", true],
["http://forge.example:4000/git/team/repo/pulls/42", false],
["http://forge.example/git/team/repo/pulls/42", false],
])("matches Forgejo links by web authority: %s", (url, expected) => {
expect(
matchesLinkedPullRequestUrl(
{ ...linkedPullRequest, url: "http://forge.example:3000/git/team/repo/pulls/42" },
url,
),
).toBe(expected);
});
it("keeps other providers' existing port normalization", () => {
expect(
matchesLinkedPullRequestUrl(
linkedPullRequest,
"https://github.com:8443/pingdotgg/t3code/pull/42",
),
).toBe(true);
});
it("keeps Forgejo and GitHub path shapes distinct on a GitHub-named host", () => {
expect(
matchesLinkedPullRequestUrl(
{ ...linkedPullRequest, url: "https://github.internal/team/repo/pulls/42" },
"https://github.internal/team/repo/pull/42",
),
).toBe(false);
});
it("rejects a different pull request or host", () => {
expect(
matchesLinkedPullRequestUrl(linkedPullRequest, "https://github.com/pingdotgg/t3code/pull/43"),
@@ -350,6 +381,59 @@ describe("findProjectOnChangeRequestHost", () => {
).toBe(backend);
});
it("selects the Forgejo HTTP port for repository and host-level matches", () => {
const projects = [3000, 4000].map((port) =>
project(`forgejo-${port}`, {
canonicalKey: "forge.example/git/team/repo",
provider: "forgejo",
displayName: "git/team/repo",
locator: { remoteUrl: `http://forge.example:${port}/git/team/repo.git` },
}),
);
const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;
expect(findProjectForChangeRequest(projects, reference)).toBe(projects[1]);
expect(findProjectOnChangeRequestHost(projects, reference)).toBe(projects[1]);
expect(
findProjectOnChangeRequestHost(projects, { ...reference, repository: "git/team/other" }),
).toBe(projects[1]);
expect(findProjectForChangeRequest([projects[0]!], reference)).toBeUndefined();
expect(findProjectOnChangeRequestHost([projects[0]!], reference)).toBeUndefined();
});
it("lets tea resolve the web port for Forgejo SSH remotes", () => {
const checkout = project("forgejo-ssh", {
canonicalKey: "forge.example/git/team/repo",
provider: "forgejo",
displayName: "git/team/repo",
locator: { remoteUrl: "[email protected]:git/team/repo.git" },
});
const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;
expect(findProjectForChangeRequest([checkout], reference)).toBe(checkout);
const aliased = project("forgejo-alias", {
canonicalKey: "ssh.forge.example/team/repo",
provider: "forgejo",
displayName: "team/repo",
locator: { remoteUrl: "[email protected]:team/repo.git" },
webUrl: "http://forge.example:4000/git/team/repo",
});
expect(findProjectForChangeRequest([aliased], reference)).toBe(aliased);
expect(findProjectOnChangeRequestHost([aliased], reference)).toBe(aliased);
expect(
findProjectOnChangeRequestHost([aliased], { ...reference, repository: "git/team/other" }),
).toBe(aliased);
for (const url of [
"http://other.example:4000/git/team/repo/pulls/42",
"http://forge.example:3000/git/team/repo/pulls/42",
]) {
const other = parseChangeRequestUrl(url)!;
expect(findProjectForChangeRequest([aliased], other)).toBeUndefined();
expect(findProjectOnChangeRequestHost([aliased], other)).toBeUndefined();
}
const otherMount = parseChangeRequestUrl("http://forge.example:4000/other/team/repo/pulls/42")!;
expect(findProjectForChangeRequest([aliased], otherMount)).toBeUndefined();
expect(findProjectOnChangeRequestHost([aliased], otherMount)).toBeUndefined();
});
it("lends any project on the host to a repository nobody has checked out", () => {
expect(
findProjectOnChangeRequestHost([frontend], {
+55 -13
View File
@@ -26,13 +26,34 @@ export {
changeRequestRepositoryUrl,
} from "@t3tools/shared/changeRequestUrl";
/**
* Returns a click handler that opens a pull request URL in the system browser.
*
* Stops event propagation/default so activating the link does not also trigger
* an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
* toast when the local API is unavailable or the open fails.
*/
function resolvedForgejoRepository(project: EnvironmentProject): URL | null {
const identity = project.repositoryIdentity;
if (identity?.provider !== "forgejo" || !identity.webUrl) return null;
try {
const url = new URL(identity.webUrl);
return url.protocol === "http:" || url.protocol === "https:" ? url : null;
} catch {
return null;
}
}
/** Keep Forgejo servers on different HTTP ports separate when selecting a project. */
function matchesChangeRequestAuthority(
project: EnvironmentProject,
link: ChangeRequestLink,
): boolean {
if (link.authority === undefined) return true;
try {
const remote = new URL(project.repositoryIdentity?.locator.remoteUrl ?? "");
if (remote.protocol === "http:" || remote.protocol === "https:") {
return remote.host.toLowerCase() === link.authority;
}
} catch {
// SSH remotes do not specify the server's HTTP port; tea resolves the configured login.
}
return true;
}
/**
* The project a link belongs to, or nothing. Matched the way the server matches: the repository
* identity is the full path below the host where one was recorded — which is what nested GitLab
@@ -45,9 +66,15 @@ export function findProjectForChangeRequest(
): EnvironmentProject | undefined {
return projects.find((project) => {
const identity = project.repositoryIdentity;
if (!identity) return false;
if (!identity || !matchesChangeRequestAuthority(project, link)) return false;
const kind = identity.provider as SourceControlProviderKind | undefined;
if (kind === undefined) return false;
const web = resolvedForgejoRepository(project);
if (web)
return (
web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase()
);
if (kind === "azure-devops") {
return (
canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===
@@ -60,7 +87,8 @@ export function findProjectForChangeRequest(
return (
repository !== null &&
repository.toLowerCase() === link.repository.toLowerCase() &&
pullRequestHostOf(identity, kind) === link.host.toLowerCase()
(pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||
pullRequestHostOf(identity, kind) === link.authority)
);
});
}
@@ -86,11 +114,25 @@ export function findProjectOnChangeRequestHost(
return projects.find((project) => {
const identity = project.repositoryIdentity;
const kind = identity?.provider as SourceControlProviderKind | undefined;
const web = resolvedForgejoRepository(project);
if (web) {
const mount = web.pathname
.replace(/^\/+|\/+$/g, "")
.split("/")
.slice(0, -2)
.join("/");
return (
web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
(!mount || link.repository.toLowerCase().startsWith(`${mount.toLowerCase()}/`))
);
}
return (
identity != null &&
kind !== undefined &&
kind !== "azure-devops" &&
pullRequestHostOf(identity, kind) === link.host.toLowerCase()
matchesChangeRequestAuthority(project, link) &&
(pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||
pullRequestHostOf(identity, kind) === link.authority)
);
});
}
@@ -188,7 +230,7 @@ export function useOpenChangeRequestLink(
projectId: project.id,
...(serverConfigs.get(project.environmentId)?.environment.capabilities
.threadPullRequests === true
? { host: parsed.host }
? { host: parsed.authority ?? parsed.host }
: {}),
repository,
url: targetUrl,
@@ -203,7 +245,7 @@ export function useOpenChangeRequestLink(
state: previous.state ?? "all",
repository,
number: parsed.number,
selectedHost: parsed.host,
selectedHost: parsed.authority ?? parsed.host,
selectedProjectId: project.id,
selectedEnvironmentId: project.environmentId,
}),
@@ -221,7 +263,7 @@ export function useOpenChangeRequestLink(
state: "all",
repository,
number: parsed.number,
selectedHost: parsed.host,
selectedHost: parsed.authority ?? parsed.host,
selectedProjectId: project.id,
// Named so the page opens the right one of two servers holding this project.
selectedEnvironmentId: project.environmentId,
+5
View File
@@ -1,3 +1,6 @@
const FORGEJO_PULL_REQUEST_URL_PATTERN =
/^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)+[^/\s]+\/pulls\/(\d+)(?:[/?#].*)?$/i;
const FORGEJO_CLI_PR_CHECKOUT_PATTERN = /^tea\s+(?:pr|pulls)\s+checkout\s+(.+)$/i;
const GITHUB_PULL_REQUEST_URL_PATTERN =
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
const GITLAB_MERGE_REQUEST_URL_PATTERN =
@@ -32,6 +35,7 @@ export function parsePullRequestReference(input: string): string | null {
const glabCliCheckoutMatch = GITLAB_CLI_MR_CHECKOUT_PATTERN.exec(trimmed);
const azureDevOpsCliCheckoutMatch = AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
const normalizedInput =
FORGEJO_CLI_PR_CHECKOUT_PATTERN.exec(trimmed)?.[1]?.trim() ??
ghCliCheckoutMatch?.[1]?.trim() ??
glabCliCheckoutMatch?.[1]?.trim() ??
(azureDevOpsCliCheckoutMatch?.[1]
@@ -43,6 +47,7 @@ export function parsePullRequestReference(input: string): string | null {
}
const urlMatch =
FORGEJO_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??
GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??
GITLAB_MERGE_REQUEST_URL_PATTERN.exec(normalizedInput) ??
AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
+13 -1
View File
@@ -13,7 +13,13 @@ import {
resolveChangeRequestPresentation,
type ChangeRequestTerminology,
} from "@t3tools/shared/sourceControl";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./components/Icons";
import {
AzureDevOpsIcon,
BitbucketIcon,
GitHubIcon,
GitLabIcon,
ForgejoIcon,
} from "./components/Icons";
export interface SourceControlPresentation {
readonly providerName: string;
@@ -32,6 +38,12 @@ export function getSourceControlPresentation(
terminology: getChangeRequestTerminology(provider),
Icon: GitHubIcon,
};
case "forgejo":
return {
providerName: provider?.name || presentation.providerName,
terminology: getChangeRequestTerminology(provider),
Icon: ForgejoIcon,
};
case "gitlab":
return {
providerName: provider?.name || presentation.providerName,
+1 -1
View File
@@ -269,7 +269,7 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi
);
const action = useCallback(
async (input: {
provider: "github" | "gitlab" | "bitbucket" | "azure-devops";
provider: "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops";
repository: string;
visibility: SourceControlRepositoryVisibility;
remoteName: string;
+21 -1
View File
@@ -1,6 +1,6 @@
# Source control
T3 Code integrates with GitHub, GitLab, Bitbucket, and Azure DevOps to clone and publish
T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, and Azure DevOps to clone and publish
repositories, create pull requests, and review changes.
## Connect an account
@@ -17,6 +17,26 @@ Install [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, then sign in:
gh auth login
```
### Forgejo and Gitea
Install [Forgejo CLI (`fj`)](https://codeberg.org/forgejo-contrib/forgejo-cli) or
[Gitea CLI (`tea`)](https://gitea.com/gitea/tea) 0.16 or later on your T3 Code server.
Sign in with `fj --host https://your-server auth add-token` or `tea login add`.
Repeat for each server you use, including Codeberg.
T3 Code prefers a matching `fj` login and falls back to `tea` when `fj` is unavailable
or has no login for that server. Once an account is selected, failed actions stay on that
account. Settings shows the detected CLI. Forgejo and Gitea share one integration entry.
Servers hosted under a URL subpath, such as `https://example.com/forgejo`, use `tea` because
fj 0.6 does not preserve the subpath when checking its account.
When cloning or publishing, use a full repository URL to select a specific server.
You can use `owner/repo` when only one fj server is configured, or with your default `tea`
login when fj is unavailable or unconfigured. With multiple fj servers, use the full URL.
If you have multiple `tea` accounts on one server, select one with
`tea login default <login-name>`. Git push and clone also need Git credentials or an SSH key
for that server.
### GitLab
Install [GitLab CLI](https://gitlab.com/gitlab-org/cli), then sign in:
@@ -76,6 +76,13 @@ describe("add project shared logic", () => {
sshUrl: "[email protected]:imputnet/helium.git",
}),
).toBe("https://github.com/imputnet/helium");
expect(
getDefaultCloneUrl({
provider: "forgejo",
url: "https://forgejo.example.test:8443/owner/repo.git",
sshUrl: "ssh://[email protected]:2222/owner/repo.git",
}),
).toBe("https://forgejo.example.test:8443/owner/repo.git");
});
it("preserves existing clone transport behavior for other providers", () => {
@@ -25,7 +25,7 @@ import type { EnvironmentProject } from "../state/models.ts";
export type AddProjectRemoteProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
"github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops"
>;
export type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
@@ -59,6 +59,7 @@ const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
"url",
"github",
"gitlab",
"forgejo",
"bitbucket",
"azure-devops",
];
@@ -66,6 +67,7 @@ const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
"github",
"gitlab",
"forgejo",
"bitbucket",
"azure-devops",
];
@@ -74,6 +76,8 @@ export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): str
switch (source) {
case "github":
return "GitHub";
case "forgejo":
return "Forgejo / Gitea";
case "gitlab":
return "GitLab";
case "bitbucket":
@@ -87,6 +91,7 @@ export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): str
export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
switch (source) {
case "forgejo":
case "github":
return "owner/repo";
case "gitlab":
@@ -117,11 +122,13 @@ export function normalizePastedCloneUrl(input: string): string {
return `https://github.com/${repository}`;
}
/** GitHub defaults to HTTPS; other providers retain their existing SSH default. */
/** GitHub and Forgejo default to HTTPS; other providers retain their existing SSH default. */
export function getDefaultCloneUrl(
repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
): string {
return repository.provider === "github" ? repository.url : repository.sshUrl;
return repository.provider === "github" || repository.provider === "forgejo"
? repository.url
: repository.sshUrl;
}
export function sortAddProjectProviderSources(
@@ -153,6 +160,7 @@ export function buildAddProjectRemoteSourceReadiness(
url: { ready: true, hint: null },
github: unavailable,
gitlab: unavailable,
forgejo: unavailable,
bitbucket: unavailable,
"azure-devops": unavailable,
};
@@ -19,6 +19,24 @@ const input = {
};
describe("thread pull request capability negotiation", () => {
it.each([true, false])(
"preserves Forgejo ports in a multi-link mutation: linked=%s",
(linked) => {
const mutation = planThreadPullRequestMutation({
...input,
linked,
capabilities: { threadPullRequests: true },
reference: {
host: "forge.example",
repository: "team/repo",
number: 7,
url: "http://forge.example:3000/team/repo/pulls/7",
},
});
expect(mutation).toMatchObject({ input: { host: "forge.example:3000", number: 7 } });
},
);
it.each([undefined, {}, { threadPullRequests: false, threadPullRequestLinking: false }])(
"does not dispatch when linking is unadvertised: %j",
(capabilities) => {
@@ -4,6 +4,7 @@ import type {
ThreadId,
ThreadPullRequestKey,
} from "@t3tools/contracts";
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
type LinkingCapabilities = Pick<
ExecutionEnvironmentCapabilities,
@@ -36,20 +37,19 @@ export function planThreadPullRequestMutation({
legacyRepository?: string | undefined;
linked: boolean;
}) {
const key = normalizeThreadPullRequestKey(reference);
switch (threadPullRequestLinkMode(capabilities)) {
case "multiple":
return linked
? {
type: "thread.pull-request.link" as const,
input: { threadId, ...reference, source: "manual" as const },
input: { threadId, ...reference, ...key, source: "manual" as const },
}
: {
type: "thread.pull-request.unlink" as const,
input: {
threadId,
host: reference.host,
repository: reference.repository,
number: reference.number,
...key,
},
};
case "single":
+2
View File
@@ -192,6 +192,8 @@ export type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;
export const RepositoryIdentity = Schema.Struct({
canonicalKey: TrimmedNonEmptyString,
locator: RepositoryIdentityLocator,
/** Repository browser URL resolved from the server's configured hosting account. */
webUrl: Schema.optionalKey(TrimmedNonEmptyString),
rootPath: Schema.optionalKey(TrimmedNonEmptyString),
displayName: Schema.optionalKey(TrimmedNonEmptyString),
provider: Schema.optionalKey(TrimmedNonEmptyString),
@@ -7,6 +7,7 @@ import {
PullRequestListInput,
PullRequestListResult,
PullRequestReviewerRequestInput,
pullRequestHostOf,
resolvePullRequestAuthorFilter,
} from "./pullRequest.ts";
@@ -65,6 +66,20 @@ const LIST_RESULT: PullRequestListResult = {
};
describe("PullRequestListResult", () => {
it("separates Forgejo HTTP ports while preserving other provider host identities", () => {
const identity = {
canonicalKey: "forge.example/team/repo",
locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },
};
expect(pullRequestHostOf(identity, "forgejo")).toBe("forge.example:3000");
expect(pullRequestHostOf(identity, "gitlab")).toBe("forge.example");
expect(
pullRequestHostOf(
{ ...identity, locator: { remoteUrl: "ssh://[email protected]:2222/team/repo.git" } },
"forgejo",
),
).toBe("forge.example");
});
/**
* The RPC builds this codec at call time, so a shape it cannot lower — an open-keyed record
* with an optional value, for one — fails as an interrupted request rather than as a schema
+22 -1
View File
@@ -1134,6 +1134,12 @@ const PROVIDER_REQUIREMENT: Partial<
"GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",
unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
},
forgejo: {
missing:
"Install Forgejo CLI (`fj` 0.6 or later) from https://codeberg.org/forgejo-contrib/forgejo-cli or Gitea CLI (`tea` 0.16 or later) from https://gitea.com/gitea/tea to browse Forgejo pull requests.",
unauthenticated:
"Authenticate your Forgejo or Gitea server with `fj --host <server-url> auth add-token` on the T3 Code server. If fj is missing or unconfigured for that server, use `tea login add`. A configured fj account must be repaired with fj.",
},
gitlab: {
missing:
"GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",
@@ -1161,9 +1167,24 @@ const PROVIDER_REQUIREMENT: Partial<
* knows its hosts before the listing answers, and the two must agree on what they are called.
*/
export function pullRequestHostOf(
identity: { readonly canonicalKey?: string | undefined } | null | undefined,
identity:
| {
readonly canonicalKey?: string | undefined;
readonly locator?: { readonly remoteUrl: string } | undefined;
}
| null
| undefined,
kind: SourceControlProviderKind,
): string {
if (kind === "forgejo") {
try {
const remote = new URL(identity?.locator?.remoteUrl ?? "");
if (remote.protocol === "http:" || remote.protocol === "https:")
return remote.host.toLowerCase();
} catch {
// SSH remotes retain their canonical host; the CLI resolves their web endpoint.
}
}
const host = identity?.canonicalKey?.split("/")[0]?.trim();
return host === undefined || host.length === 0 ? kind : host.toLowerCase();
}
+1
View File
@@ -5,6 +5,7 @@ import { VcsDriverKind } from "./vcs.ts";
export const SourceControlProviderKind = Schema.Literals([
"github",
"gitlab",
"forgejo",
"azure-devops",
"bitbucket",
"unknown",
@@ -24,6 +24,15 @@ describe("parseChangeRequestUrl", () => {
});
});
it("reads Forgejo URLs even when the hostname contains github", () => {
expect(parseChangeRequestUrl("https://github.internal/team/repo/pulls/7")).toEqual({
host: "github.internal",
authority: "github.internal",
repository: "team/repo",
number: 7,
});
});
it("reads a supported GitHub host with a middle DNS label", () => {
expect(parseChangeRequestUrl("https://code.github.example.com/acme/web/pull/42")).toEqual({
host: "code.github.example.com",
@@ -90,7 +99,23 @@ describe("parseChangeRequestUrl", () => {
});
describe("siblingPullRequestUrl", () => {
it("recognizes Forgejo on custom HTTP hosts", () => {
expect(parseChangeRequestUrl("http://git.example.test:3000/team/repo/pulls/42/files")).toEqual({
host: "git.example.test",
authority: "git.example.test:3000",
repository: "team/repo",
number: 42,
});
});
it.each([
[
"http://git.example.test:3000/team/repo/pulls/42/files",
"http://git.example.test:3000/team/repo/pulls/43",
],
[
"https://git.example.test/forgejo/team/repo/pulls/42/files",
"https://git.example.test/forgejo/team/repo/pulls/43",
],
["https://github.com/pull/1/pull/42/files", "https://github.com/pull/1/pull/43"],
[
"https://git.acme.test/team/merge_requests/1/repo/-/merge_requests/42/diffs",
@@ -125,6 +150,29 @@ describe("siblingPullRequestUrl", () => {
});
describe("changeRequestUrlFor", () => {
it("preserves the origin when the Forgejo host already contains its port", () => {
expect(
changeRequestUrlFor(
"forgejo",
"forge.example:3000",
"team/repo",
42,
"http://forge.example:3000/team/repo.git",
),
).toBe("http://forge.example:3000/team/repo/pulls/42");
});
it.each([
["http://forge.example:3000/git/owner/repo.git", "http://forge.example:3000"],
["https://forge.example:8443/git/owner/repo.git", "https://forge.example:8443"],
["[email protected]:git/owner/repo.git", "https://forge.example"],
["http://other.example:3000/git/owner/repo.git", "https://forge.example"],
])("preserves the matching Forgejo web origin from %s", (remoteUrl, origin) => {
expect(changeRequestUrlFor("forgejo", "forge.example", "git/owner/repo", 42, remoteUrl)).toBe(
`${origin}/git/owner/repo/pulls/42`,
);
});
it.each([
["ssh.dev.azure.com", "v3/org/project/web"],
["vs-ssh.visualstudio.com", "v3/org/project/web"],
+29 -4
View File
@@ -13,6 +13,8 @@ export interface ChangeRequestLink {
readonly host: string;
readonly repository: string;
readonly number: number;
/** Forgejo's HTTP host and port, separate from the portless repository identity. */
readonly authority?: string;
}
/** The host itself, one of its subdomains, or an install named after the provider. */
@@ -49,7 +51,13 @@ export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | nu
// GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
if (isHostOf(host, "github.com", "github")) {
const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
return claim(host, match);
if (match) return claim(host, match);
}
// Forgejo and Gitea use /pulls/ on arbitrary self-hosted domains.
const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
if (forgejo) {
const link = claim(host, forgejo);
return link === null ? null : { ...link, authority: url.host.toLowerCase() };
}
// GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
// separator is GitLab's own, so the hostname is not asked about.
@@ -83,10 +91,26 @@ export function changeRequestUrlFor(
host: string,
repository: string,
number: number,
remoteUrl?: string,
): string | null {
switch (kind) {
case "github":
return `https://${host}/${repository}/pull/${number}`;
case "forgejo": {
try {
const remote = new URL(remoteUrl ?? "");
if (
(remote.protocol === "http:" || remote.protocol === "https:") &&
(remote.hostname.toLowerCase() === host.toLowerCase() ||
remote.host.toLowerCase() === host.toLowerCase())
) {
return `${remote.origin}/${repository}/pulls/${number}`;
}
} catch {
// SSH remotes do not specify the server's web origin.
}
return `https://${host}/${repository}/pulls/${number}`;
}
case "gitlab":
return `https://${host}/${repository}/-/merge_requests/${number}`;
case "bitbucket":
@@ -174,7 +198,8 @@ export function matchesLinkedPullRequestUrl(
target !== null &&
linked.host === target.host &&
linked.repository === target.repository &&
linked.number === target.number
linked.number === target.number &&
linked.authority === target.authority
);
}
@@ -185,7 +210,7 @@ export function changeRequestRepositoryUrl(targetUrl: string): string | null {
const url = new URL(targetUrl);
const repositoryPath =
/^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
/^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
/^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
url.pathname,
)?.[1];
if (!repositoryPath) return null;
@@ -199,7 +224,7 @@ export function siblingPullRequestUrl(url: string, number: number): string | nul
const reference = parseChangeRequestUrl(url);
if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
const sibling = new URL(url);
const route = /^\/(-\/merge_requests|pull|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
sibling.pathname.slice(reference.repository.length + 1),
)?.[1];
if (route === undefined) return null;
+16
View File
@@ -59,6 +59,22 @@ describe("detectSourceControlProviderFromRemoteUrl", () => {
).toBe("bitbucket");
});
it("detects Forgejo and Gitea hosts while preserving HTTP origins", () => {
for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {
expect(detectSourceControlProviderFromRemoteUrl(`http://${host}:3000/team/repo.git`)).toEqual(
{
kind: "forgejo",
name: "Forgejo",
baseUrl: `http://${host}:3000`,
},
);
}
expect(getChangeRequestTerminologyForKind("forgejo")).toEqual({
shortLabel: "PR",
singular: "pull request",
});
});
it("detects Azure DevOps SSH remotes", () => {
// The default Azure DevOps SSH clone URL uses the ssh.dev.azure.com host.
expect(
+28 -1
View File
@@ -5,7 +5,7 @@ import type {
} from "@t3tools/contracts";
export interface ChangeRequestPresentation {
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
readonly icon: "github" | "gitlab" | "forgejo" | "azure-devops" | "bitbucket" | "change-request";
readonly providerName: string;
readonly shortName: string;
readonly longName: string;
@@ -47,6 +47,17 @@ const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
};
const FORGEJO_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "forgejo",
providerName: "Forgejo",
shortName: "PR",
longName: "pull request",
pluralLongName: "pull requests",
providerLongName: "Forgejo pull request",
checkoutCommandExample: "tea pr checkout 123",
urlExample: "https://codeberg.org/owner/repo/pulls/42",
};
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "azure-devops",
providerName: "Azure DevOps",
@@ -87,6 +98,8 @@ export function resolveChangeRequestPresentation(
return GITHUB_CHANGE_REQUEST_PRESENTATION;
case "gitlab":
return GITLAB_CHANGE_REQUEST_PRESENTATION;
case "forgejo":
return FORGEJO_CHANGE_REQUEST_PRESENTATION;
case "azure-devops":
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
case "bitbucket":
@@ -200,6 +213,20 @@ export function detectSourceControlProviderFromRemoteUrl(
}
const hostname = parseHostName(host);
if (
hostname === "codeberg.org" ||
hasDnsLabel(hostname, "forgejo") ||
hasDnsLabel(hostname, "gitea")
) {
return {
kind: "forgejo",
name: "Forgejo",
baseUrl: /^https?:/iu.test(remoteUrl.trim())
? new URL(remoteUrl.trim()).origin
: toBaseUrl(host),
};
}
if (isGitHubHost(hostname)) {
return {
kind: "github",
@@ -62,6 +62,28 @@ function link(
}
describe("threadPullRequestKeysEqual", () => {
it("recovers Forgejo ports from old stored URLs and keeps separate servers distinct", () => {
const old = link(1, {
host: "forge.example",
repository: "team/repo",
url: "http://forge.example:3000/team/repo/pulls/1",
});
expect(threadPullRequestKeysEqual(old, { ...old, host: "forge.example:3000" })).toBe(true);
expect(
threadPullRequestKeysEqual(old, {
host: "forge.example:3000",
repository: "team/repo",
number: 1,
}),
).toBe(true);
expect(
threadPullRequestKeysEqual(old, {
...old,
url: "http://forge.example:4000/team/repo/pulls/1",
}),
).toBe(false);
});
it("ignores host and repository case", () => {
expect(
threadPullRequestKeysEqual(
+40 -10
View File
@@ -10,10 +10,23 @@ import { pullRequestHostOf } from "@t3tools/contracts";
import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";
/** Normalize stored link identity, including Azure's SSH and browser host aliases. */
export function normalizeThreadPullRequestKey(key: ThreadPullRequestKey): ThreadPullRequestKey {
type ThreadPullRequestKeySource = ThreadPullRequestKey & {
readonly authority?: string;
readonly url?: string;
};
/** Normalize stored links, recovering Forgejo HTTP ports from old links' URLs. */
export function normalizeThreadPullRequestKey(
key: ThreadPullRequestKeySource,
): ThreadPullRequestKey {
const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);
const authority =
key.authority ??
(parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
? parsed.authority
: undefined);
const canonical = canonicalRepositoryKey(
`${key.host.trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
`${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
);
const separator = canonical.indexOf("/");
return {
@@ -31,7 +44,7 @@ export function legacyThreadPullRequestKey(
const parsed = parseChangeRequestUrl(linked.url);
if (parsed !== null && parsed.number === linked.number) {
const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
if (canonical.startsWith("dev.azure.com/")) {
if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
return normalizeThreadPullRequestKey(parsed);
}
}
@@ -52,13 +65,13 @@ export function legacyThreadPullRequestKey(
/** Identity comparison for links: host-level, case-insensitive on host and repository. */
export function threadPullRequestKeysEqual(
left: ThreadPullRequestKey,
right: ThreadPullRequestKey,
left: ThreadPullRequestKeySource,
right: ThreadPullRequestKeySource,
): boolean {
return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
}
export function threadPullRequestKeyOf(key: ThreadPullRequestKey): string {
export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
const normalized = normalizeThreadPullRequestKey(key);
return `${normalized.host}/${normalized.repository}#${normalized.number}`;
}
@@ -157,6 +170,20 @@ export function legacyLinkedPullRequestOf(
const key = legacyThreadPullRequestKey(link, link.host);
return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
}
const parsed = parseChangeRequestUrl(link.url);
if (parsed?.authority !== undefined) {
try {
const remote = new URL(identity.locator.remoteUrl);
if (remote.protocol === "http:" || remote.protocol === "https:") {
return (
parsed.authority === remote.host && parsed.repository === repository.toLowerCase()
);
}
} catch {
// SSH web ports are resolved by the provider's configured login.
}
return parsed.host === host && parsed.repository === repository.toLowerCase();
}
return (
link.host.toLowerCase() === host.toLowerCase() &&
link.repository.toLowerCase() === repository.toLowerCase()
@@ -193,7 +220,8 @@ export function resolveThreadPullRequestChains(
const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
for (const link of visible) {
if (link.stack === null) continue;
const stackKey = `${link.host.toLowerCase()}/${link.repository.toLowerCase()}#stack:${link.stack.id}`;
const key = normalizeThreadPullRequestKey(link);
const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
const members = nativeStacks.get(stackKey) ?? [];
members.push(link);
nativeStacks.set(stackKey, members);
@@ -206,8 +234,10 @@ export function resolveThreadPullRequestChains(
}
const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
const branchKey = (link: ThreadPullRequestLink, branch: string) =>
`${link.host.toLowerCase()}/${link.repository.toLowerCase()}:${branch}`;
const branchKey = (link: ThreadPullRequestLink, branch: string) => {
const key = normalizeThreadPullRequestKey(link);
return `${key.host}/${key.repository}:${branch}`;
};
// Reused head names cannot identify a parent unambiguously.
const byHead = new Map<string, ThreadPullRequestLink | null>();
for (const link of remaining) {