Skip to content
TypeScript

refactor(clients): pull request surfaces ask the forge instead of assuming GitHub (#23997)

Julius Marmingea6009faba02b
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx
index 66a68b2ebae..9ac01547d03 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx
+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx
@@ -21,6 +21,7 @@ import {
getNewProjectPublishTarget,
getNewProjectPublishTargets,
getNewProjectRepository,
+ defaultHostCloneUrl,
normalizePastedCloneUrl,
parseAddProjectRemoteSource,
resolveAddProjectPath,
@@ -821,7 +822,7 @@ export function AddProjectRepositoryScreen(props: {
autoCorrect={false}
placeholder={
source === "url"
- ? "https://github.com/org/repo.git"
+ ? (defaultHostCloneUrl("org/repo") ?? "https://example.com/org/repo.git")
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
index 6ee6c572625..68ab91b3a3f 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
@@ -124,10 +124,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
const canReply = permissions.canReply && Boolean(thread);
const resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";
return (
- <PullRequestMarkdownRepository
- params={params}
- value={detail.data?.provider === "github" ? detail.data.url : null}
- >
+ <PullRequestMarkdownRepository params={params} changeRequest={detail.data}>
<KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">
<NativeStackScreenOptions
options={{ title: "Discussion", unstable_headerSubtitle: `#${params.number}` }}
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
index 3aacc5f84a1..93615a47a7d 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
@@ -10,7 +10,9 @@ import {
} from "./PullRequestMedia";
import { videoMimeType } from "@t3tools/shared/video";
import { createContext, useContext, useCallback, useMemo, useState } from "react";
-import { githubMarkdownLinks } from "@t3tools/shared/githubMarkdownLinks";
+import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
+import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
+import { linkReferenceAutolinks } from "./pullRequestAutolinks";
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
@@ -26,13 +28,25 @@ import {
import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";
import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
-const RepositoryContext = createContext<string | null>(null);
+const AutolinksContext = createContext<((text: string) => ReadonlyArray<ReferenceAutolink>) | null>(
+ null,
+);
export function PullRequestMarkdownRepository(props: {
- readonly value: string | null;
+ /** The change request the markdown belongs to, whose host decides what its text links. */
+ readonly changeRequest: { readonly provider: string; readonly url: string } | null | undefined;
readonly params: PullRequestParams;
readonly children: ReactNode;
}) {
+ const provider = props.changeRequest?.provider;
+ const url = props.changeRequest?.url;
+ const autolinks = useMemo(
+ () =>
+ provider === undefined || url === undefined
+ ? null
+ : changeRequestReferenceAutolinker({ provider, url }),
+ [provider, url],
+ );
const target = pullRequestTarget(props.params);
const project = useProject({
environmentId: target.environmentId,
@@ -44,9 +58,9 @@ export function PullRequestMarkdownRepository(props: {
[target.environmentId, cwd],
);
return (
- <RepositoryContext value={props.value}>
+ <AutolinksContext value={autolinks}>
<PullRequestMediaContext value={media}>{props.children}</PullRequestMediaContext>
- </RepositoryContext>
+ </AutolinksContext>
);
}
@@ -103,11 +117,11 @@ function PullRequestMarkdownContent(props: {
readonly markdown: string;
readonly imageGroupMarkdown?: string;
}) {
- const repositoryUrl = useContext(RepositoryContext);
+ const autolinks = useContext(AutolinksContext);
const mediaContext = useContext(PullRequestMediaContext);
const markdown = useMemo(
- () => githubMarkdownLinks(props.markdown, repositoryUrl),
- [props.markdown, repositoryUrl],
+ () => linkReferenceAutolinks(props.markdown, autolinks),
+ [props.markdown, autolinks],
);
const openPullRequest = useOpenPullRequest();
const openLink = useCallback(
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index f83ef07eb15..c12bd873964 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -387,10 +387,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
}
};
return (
- <PullRequestMarkdownRepository
- params={params}
- value={pr?.provider === "github" ? pr.url : null}
- >
+ <PullRequestMarkdownRepository params={params} changeRequest={pr}>
<View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
<NativeStackScreenOptions
options={{
diff --git a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
index e086259a11f..19d02bc47e6 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
@@ -2,6 +2,7 @@ import { usePullRequestConnected } from "./usePullRequestConnected";
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import type { PullRequestAction, PullRequestDetail } from "@t3tools/contracts";
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import Animated from "react-native-reanimated";
import { PR_ROW_LAYOUT, PR_DISCLOSURE_ENTER, PR_ROW_EXIT } from "./pullRequestAnimations";
import { useState } from "react";
@@ -162,7 +163,9 @@ export function PullRequestChecksRow(props: RowProps) {
icon="arrow.up.right"
onPress={() =>
void Linking.openURL(
- props.pr.provider === "github" ? `${props.pr.url}/checks` : props.pr.url,
+ sourceControlClients
+ .get(props.pr.provider)
+ .changeRequestChecksUrl?.(props.pr.url) ?? props.pr.url,
)
}
/>
diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
index cfc18131873..08fdfb1ab18 100644
--- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
@@ -161,10 +161,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideSto
</Toolbar.MenuAction>
</Toolbar.Menu>
</Toolbar>
- <PullRequestMarkdownRepository
- params={route.params}
- value={`https://${route.params.host ?? "github.com"}/${route.params.repository}`}
- >
+ <PullRequestMarkdownRepository params={route.params} changeRequest={detail.data}>
<ScreenScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24, gap: 20 }}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts b/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts
index bd1170a0b8b..af19f3aa9c3 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts
@@ -4,7 +4,7 @@ import { DEFAULT_ACTIVITY_FILTER, filterPullRequestActivity } from "./pullReques
const date = IsoDateTime.make("2026-10-11T00:00:00.000Z");
const human: PullRequestActor = { login: "reader", name: null, avatarUrl: null };
-const bot: PullRequestActor = { ...human, login: "reviewer[bot]" };
+const bot: PullRequestActor = { ...human, login: "reviewer[bot]", isBot: true };
const comment = (id: string, author = human, reviewState: string | null = null) => ({
id,
author,
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts
index 46c4cfda2ac..85b50b2fcf6 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts
@@ -15,7 +15,7 @@ export const DEFAULT_ACTIVITY_FILTER: ActivityFilter = {
};
function isBot(actor: PullRequestActor | null) {
- return actor?.isBot === true || actor?.login.endsWith("[bot]") === true;
+ return actor?.isBot === true;
}
function eventCount(activity: PullRequestActivity) {
diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts
new file mode 100644
index 00000000000..4aeeb1f388a
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts
@@ -0,0 +1,38 @@
+import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
+import { describe, expect, it } from "vite-plus/test";
+
+import { linkReferenceAutolinks } from "./pullRequestAutolinks";
+
+const github = changeRequestReferenceAutolinker({
+ provider: "github",
+ url: "https://github.com/team/repo/pull/8",
+});
+
+describe("linkReferenceAutolinks", () => {
+ it("links the host's references in prose", () => {
+ expect(linkReferenceAutolinks("Closes #123, see @julius", github)).toBe(
+ "Closes [#123](https://github.com/team/repo/issues/123), see [@julius](https://github.com/julius)",
+ );
+ });
+
+ it("leaves code, links, images, escapes and definitions alone", () => {
+ const text =
+ "`#123 @person abc1234`\n\n```\n#123\n```\n\n[#123](https://example.com) ![#123](image.png) https://example.com/#123 [email protected] \\#123 1234567\n\n[ref]: https://example.com/#123";
+ expect(linkReferenceAutolinks(text, github)).toBe(text);
+ });
+
+ it("does not nest links inside HTML anchors or code", () => {
+ const text = 'See <a href="https://example.com">#12</a> and <code>#13</code>, then #14.';
+ expect(linkReferenceAutolinks(text, github)).toBe(
+ 'See <a href="https://example.com">#12</a> and <code>#13</code>, then [#14](https://github.com/team/repo/issues/14).',
+ );
+ });
+
+ it("leaves markdown unchanged for a host that links nothing", () => {
+ const gitlab = changeRequestReferenceAutolinker({
+ provider: "gitlab",
+ url: "https://gitlab.com/group/project/-/merge_requests/7",
+ });
+ expect(linkReferenceAutolinks("Closes #123", gitlab)).toBe("Closes #123");
+ });
+});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts
new file mode 100644
index 00000000000..d46b2b11a66
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts
@@ -0,0 +1,73 @@
+import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+
+type MarkdownNode = {
+ readonly type: string;
+ readonly position?:
+ | {
+ readonly start: { readonly offset?: number | undefined };
+ readonly end: { readonly offset?: number | undefined };
+ }
+ | undefined;
+ readonly children?: readonly MarkdownNode[] | undefined;
+};
+
+const parser = unified().use(remarkParse).use(remarkGfm);
+const UNLINKED_TYPES = new Set([
+ "link",
+ "linkReference",
+ "image",
+ "imageReference",
+ "code",
+ "inlineCode",
+ "html",
+ "definition",
+]);
+
+/**
+ * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, because the
+ * native renderer takes markdown text. Text is searched as written, escapes included.
+ */
+export function linkReferenceAutolinks(
+ markdown: string,
+ autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null,
+): string {
+ if (autolinks === null) return markdown;
+ const edits: { start: number; end: number; value: string }[] = [];
+ const visit = (node: MarkdownNode) => {
+ if (UNLINKED_TYPES.has(node.type)) return;
+ if (node.type === "text") {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start === undefined || end === undefined) return;
+ for (const link of autolinks(markdown.slice(start, end))) {
+ edits.push({
+ start: start + link.index,
+ end: start + link.index + link.text.length,
+ value: `[${link.label}](${link.url})`,
+ });
+ }
+ } else if (node.children !== undefined) {
+ let protectedHtmlDepth = 0;
+ for (const child of node.children) {
+ if (child.type === "html") {
+ const start = child.position?.start.offset;
+ const end = child.position?.end.offset;
+ const tag = start === undefined || end === undefined ? "" : markdown.slice(start, end);
+ for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/giu)) {
+ protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
+ }
+ } else if (protectedHtmlDepth === 0) visit(child);
+ }
+ }
+ };
+ visit(parser.parse(markdown));
+ let linked = markdown;
+ for (let index = edits.length - 1; index >= 0; index--) {
+ const edit = edits[index]!;
+ linked = linked.slice(0, edit.start) + edit.value + linked.slice(edit.end);
+ }
+ return linked;
+}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
index 512e9c46036..5656e1d18ab 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
@@ -202,12 +202,7 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
const statsKey = JSON.stringify(
targets.flatMap(({ environmentId }) => {
const refs = visibleRows
- .filter(
- (row) =>
- row.environmentId === environmentId &&
- row.provider === "github" &&
- row.additions + row.deletions === 0,
- )
+ .filter((row) => row.environmentId === environmentId && row.additions + row.deletions === 0)
.map(({ projectId, host, repository, number }) => ({
projectId,
host,
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index f2f4e9a3986..5d29e519917 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -188,11 +188,9 @@ import {
} from "../../lib/appearancePreferences";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
-import { markdownLinkIconSource } from "../../lib/markdownLinkIcons";
import {
normalizeNativeMarkdownUrl,
resolveMarkdownInlineCodePresentation,
- resolveMarkdownLinkIcon,
resolveMarkdownLinkPresentation,
} from "../../lib/markdownLinks";
import {
diff --git a/apps/mobile/src/lib/markdownLinkIcons.ts b/apps/mobile/src/lib/markdownLinkIcons.ts
index 13eee7bbfac..f88ac2f52bc 100644
--- a/apps/mobile/src/lib/markdownLinkIcons.ts
+++ b/apps/mobile/src/lib/markdownLinkIcons.ts
@@ -1,11 +1,13 @@
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import type { ImageSourcePropType } from "react-native";
-import type { MarkdownLinkIcon } from "./markdownLinks";
-
-const MARKDOWN_LINK_ICON_SOURCES = {
+// The native renderer draws a link's icon from an image, so a host's mark is a bundled image keyed
+// by its definition's `icon`. A host without one keeps a plain link.
+const SOURCE_CONTROL_LINK_ICON_SOURCES: Partial<Record<string, ImageSourcePropType>> = {
github: require("../../assets/link-icons/github.png"),
-} as const satisfies Readonly<Record<MarkdownLinkIcon, ImageSourcePropType>>;
+};
-export function markdownLinkIconSource(icon: MarkdownLinkIcon): ImageSourcePropType {
- return MARKDOWN_LINK_ICON_SOURCES[icon];
+export function markdownLinkIconSource(host: string): ImageSourcePropType | null {
+ const icon = sourceControlClients.findByPublicDomain(host)?.icon;
+ return (icon === undefined ? undefined : SOURCE_CONTROL_LINK_ICON_SOURCES[icon]) ?? null;
}
diff --git a/apps/mobile/src/lib/markdownLinks.ts b/apps/mobile/src/lib/markdownLinks.ts
index f68add2bf7f..8020c1de5b1 100644
--- a/apps/mobile/src/lib/markdownLinks.ts
+++ b/apps/mobile/src/lib/markdownLinks.ts
@@ -34,14 +34,6 @@ export type MarkdownLinkPresentation =
export type MarkdownFileIcon = keyof typeof MARKDOWN_FILE_ICON_SOURCES;
-export type MarkdownLinkIcon = "github";
-
-export function resolveMarkdownLinkIcon(host: string): MarkdownLinkIcon | null {
- const hostname = host.toLowerCase();
- if (hostname === "github.com" || hostname.endsWith(".github.com")) return "github";
- return null;
-}
-
const FILE_ICON_BY_NAME: Readonly<Record<string, MarkdownFileIcon>> = {
".babelrc": "babel",
".babelrc.json": "babel",
diff --git a/apps/mobile/src/native/useEnrichedLinkVariants.ts b/apps/mobile/src/native/useEnrichedLinkVariants.ts
index 2b32956f5e0..dda01bd7545 100644
--- a/apps/mobile/src/native/useEnrichedLinkVariants.ts
+++ b/apps/mobile/src/native/useEnrichedLinkVariants.ts
@@ -13,7 +13,7 @@ import { contextChipIconSource } from "../lib/contextChipIconSource";
import { markdownFileIconSource } from "../lib/markdownFileIcons";
import { markdownLinkIconSource } from "../lib/markdownLinkIcons";
import { useUniwindTheme } from "../lib/useUniwindTheme";
-import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
+import { resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
import type {
MarkdownLinkCustomization,
SelectableMarkdownTextProps,
@@ -83,11 +83,11 @@ function presentation(
icon: markdownFileIconSource(link.icon),
chip: { accent: contextChipPresentation("mention").accent, tintsIcon: false },
};
- const icon = link.kind === "external" ? resolveMarkdownLinkIcon(link.host) : null;
+ const icon = link.kind === "external" ? markdownLinkIconSource(link.host) : null;
return icon
? {
color: props.textStyle.linkColor,
- icon: markdownLinkIconSource(icon),
+ icon,
iconTintColor: props.textStyle.linkColor,
}
: undefined;
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 2a3c7158342..847d5dcd8d5 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -1102,8 +1102,8 @@ const CHAT_MARKDOWN_COMPONENTS = {
);
const pullRequestCopy =
pullRequestAutolink === "commit"
- ? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]
- : pullRequestAutolink === "reference"
+ ? /\/commit\/([0-9a-f]{7,40})$/iu.exec(href ?? "")?.[1]
+ : pullRequestAutolink === "reference" || pullRequestAutolink === "mention"
? plainHastText(node)
: undefined;
const isPullRequestAutolink = pullRequestCopy !== undefined;
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index 53a39007574..0d760535ee7 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -1540,7 +1540,22 @@ function OpenCommandPaletteDialog(props: {
actionItems.push({
kind: "action",
value: "action:pull-requests",
- searchTerms: ["pull requests", "prs", "pr", "github", "review", "merge", "branch"],
+ searchTerms: [
+ ...new Set(
+ sourceControlClients.definitions.flatMap((definition) => {
+ const shortLabel = definition.changeRequest.shortLabel.toLowerCase();
+ return [
+ `${definition.changeRequest.singular}s`,
+ `${shortLabel}s`,
+ shortLabel,
+ ...definition.label.toLowerCase().split(/[^a-z0-9]+/u),
+ ].filter(Boolean);
+ }),
+ ),
+ "review",
+ "merge",
+ "branch",
+ ],
title: "Open pull requests",
icon: <PullRequestGlyph.pullRequest className={ITEM_ICON_CLASS} />,
run: async () => {
diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx
index 7a66512ccad..d540cc8e06f 100644
--- a/apps/web/src/components/ThreadStatusIndicators.tsx
+++ b/apps/web/src/components/ThreadStatusIndicators.tsx
@@ -114,7 +114,11 @@ export function useLinkedThreadPullRequest(
? null
: {
pr: pullRequestDetailToVcsStatus(detail),
- sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
+ sourceControlProvider: {
+ kind: detail.provider,
+ name: sourceControlClients.get(detail.provider).label,
+ baseUrl: "",
+ },
};
}
diff --git a/apps/web/src/components/chat/MarkdownExternalLink.tsx b/apps/web/src/components/chat/MarkdownExternalLink.tsx
index fae6a9fad48..b3efae29406 100644
--- a/apps/web/src/components/chat/MarkdownExternalLink.tsx
+++ b/apps/web/src/components/chat/MarkdownExternalLink.tsx
@@ -2,21 +2,25 @@ import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
import { GlobeIcon } from "lucide-react";
import { Children, Fragment, memo, useState, type ReactNode } from "react";
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
+
import { cn } from "../../lib/utils";
-import { GitHubIcon } from "../Icons";
+import { sourceControlIcon } from "../../sourceControlPresentation";
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
const failedFaviconHosts = new Set<string>();
-function isGitHubHost(host: string): boolean {
- const hostname = host.toLowerCase();
- return hostname === "github.com" || hostname.endsWith(".github.com");
+function sourceControlHostIcon(host: string): ReactNode {
+ const definition = sourceControlClients.findByPublicDomain(host);
+ if (definition === undefined) return null;
+ const Icon = sourceControlIcon(definition);
+ return <Icon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />;
}
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
const [failedHost, setFailedHost] = useState<string | null>(null);
- const brandIcon = isGitHubHost(host);
+ const brandIcon = sourceControlHostIcon(host);
const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
return (
<span
@@ -24,7 +28,7 @@ const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host:
aria-hidden
>
{brandIcon ? (
- <GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
+ brandIcon
) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
) : (
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx
index de1af5536fb..c4956c01996 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx
@@ -131,7 +131,7 @@ export function PullRequestCheckoutMenu({
<span className="flex min-w-0 flex-col">
<span>In this repository</span>
<span className="text-xs text-muted-foreground">
- Switches the branch you are working in, like `gh pr checkout`.
+ Switches the branch you are working in.
</span>
</span>
</MenuItem>
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index d8a1f51a933..385f9c416d6 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -1,4 +1,5 @@
import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
+import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
import { useAtomValue } from "@effect/atom-react";
import { usePullRequestStack } from "~/state/usePullRequestStack";
import {
@@ -233,15 +234,10 @@ function resolvePullRequestReference(
}
function pullRequestMarkdownContext(
- hostClient: ReturnType<typeof sourceControlClients.get>,
- repositoryUrl: string | null,
+ detail: Pick<PullRequestDetail, "provider" | "url"> | null,
threadRef: ScopedThreadRef | null,
) {
- return {
- repositoryUrl:
- repositoryUrl === null ? null : hostClient.referenceAutolinkRepositoryUrl(repositoryUrl),
- threadRef,
- };
+ return { autolinks: changeRequestReferenceAutolinker(detail), threadRef };
}
function pullRequestStackReference(
@@ -477,7 +473,7 @@ export function PullRequestDetailPanel({
: (sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl ?? null);
const hostClient = sourceControlClients.get(detail?.provider);
const openOnHostText = openOnHostLabel(hostClient);
- const markdownContext = pullRequestMarkdownContext(hostClient, repositoryUrl, threadRef);
+ const markdownContext = pullRequestMarkdownContext(detail, threadRef);
const authorProfileUrl =
detail?.author && repositoryUrl !== null
? hostClient.authorProfileUrl(detail.author.login, repositoryUrl)
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index 91dec8acdac..a9fdf0f0980 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -1,6 +1,9 @@
import { ExternalLinkIcon, PaperclipIcon } from "lucide-react";
import { markdownImageSourceFragment } from "@t3tools/client-runtime/markdown-images";
-import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
+import {
+ sourceControlClients,
+ type ReferenceAutolink,
+} from "@t3tools/client-runtime/source-control-clients";
import {
SOURCE_CONTROL_MEDIA_ASSET,
type AssetResource,
@@ -19,7 +22,7 @@ import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
import { remarkPullRequestAutolinks, splitPullRequestBody } from "./pullRequestMarkdown.logic";
export const PullRequestMarkdownContext = createContext<{
- repositoryUrl: string | null;
+ autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null;
threadRef: ScopedThreadRef | null;
} | null>(null);
@@ -66,10 +69,10 @@ export function PullRequestMarkdown({
}) {
const segments = splitPullRequestBody(text);
const context = useContext(PullRequestMarkdownContext);
- const repositoryUrl = context?.repositoryUrl;
+ const autolinks = context?.autolinks;
const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
- const extraRemarkPlugins: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = repositoryUrl
- ? [[remarkPullRequestAutolinks, { repositoryUrl }]]
+ const extraRemarkPlugins: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = autolinks
+ ? [[remarkPullRequestAutolinks, { autolinks }]]
: [];
return (
<div
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
index 2883897daf5..d7b3d879e74 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
@@ -54,6 +54,7 @@ import {
resolveBaseFreshness,
buildPullRequestTimeline,
writePullRequestDetailSnapshot,
+ readableFailure,
} from "./pullRequestDetail.logic";
import type { ReviewCommentContext } from "~/reviewCommentContext";
@@ -1498,3 +1499,18 @@ describe("single-PR merge compatibility during stack discovery", () => {
},
);
});
+
+describe("readableFailure", () => {
+ it("replaces a host tool's bare failure with the hint, for every host", () => {
+ for (const message of [
+ "GitHub CLI failed.",
+ "Azure DevOps API failed",
+ "Forgejo command failed",
+ ]) {
+ expect(readableFailure(new Error(message), "Try again.")).toBe("Try again.");
+ }
+ expect(readableFailure(new Error("Branch is protected."), "Try again.")).toBe(
+ "Branch is protected.",
+ );
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
index 9dabaea0992..8f5446811a0 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
@@ -646,8 +646,7 @@ export function filterPullRequestConversationItems(
// Matching any member keeps the finding beside a human reply to a bot.
pullRequestConversationItemComments(item).some(
(comment) =>
- (filter.bots ||
- !(comment.author?.isBot === true || comment.author?.login.endsWith("[bot]"))) &&
+ (filter.bots || comment.author?.isBot !== true) &&
(filter.resolved ||
!isPullRequestCommentFinished(comment, item.kind === "thread" ? item.thread : undefined)),
),
@@ -1216,8 +1215,12 @@ export function isPullRequestNotFound(failure: unknown): boolean {
const OPERATION_PREFIX = /^Pull request operation \w+ failed:\s*/iu;
+const HOST_LABELS = sourceControlClients.definitions
+ .map((definition) => definition.label.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"))
+ .join("|");
+
const TOOL_NOISE = [
- /^(github|gitlab|bitbucket|azure devops)?\s*(cli|api)?\s*(command\s*)?failed\.?$/iu,
+ new RegExp(`^(${HOST_LABELS})?\\s*(cli|api)?\\s*(command\\s*)?failed\\.?$`, "iu"),
/^exited? with (code|status) \d+\.?$/iu,
/^unknown error\.?$/iu,
];
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
index 58f6964e4b9..7f3c6bfd0bd 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
@@ -701,10 +701,11 @@ describe("pull request quick actions", () => {
...(actions === undefined ? {} : { actions }),
});
- it("offers what each host reports, and GitHub's legacy set when a server reports none", () => {
+ it("offers what each host reports, and the host's own set when a server reports none", () => {
const actionsOf = pullRequestHostActions([
summary("bitbucket.org", "bitbucket", ["merge", "close"]),
summary("github.com", "github"),
+ summary("gitlab.com", "gitlab"),
]);
const bitbucket = actionsOf({
host: "bitbucket.org",
@@ -719,6 +720,11 @@ describe("pull request quick actions", () => {
"close",
"ready",
]);
+ const gitlab = actionsOf({
+ host: "gitlab.com",
+ provider: SourceControlProviderKind.make("gitlab"),
+ });
+ expect(pullRequestQuickActions({ state: "open", isDraft: false }, gitlab)).toEqual([]);
});
});
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
index 656913257a1..5bf0b6f4c02 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
@@ -1015,10 +1015,11 @@ export function pullRequestHostActions(
: [[provider.host.toLowerCase(), new Set(provider.actions)] as const],
),
);
- const legacy = new Set<PullRequestAction>(["close", "merge", "ready", "reopen"]);
const none = new Set<PullRequestAction>();
return (entry) =>
- byHost.get(entry.host.toLowerCase()) ?? (entry.provider === "github" ? legacy : none);
+ byHost.get(entry.host.toLowerCase()) ??
+ sourceControlClients.find(entry.provider)?.changeRequestActionsWhenUnreported ??
+ none;
}
export function pullRequestQuickActions(
@@ -1042,7 +1043,9 @@ export function largestPullRequestReadCount(
const counts = new Map<string, number>();
for (const entry of entries) {
const read = `${entry.environmentId} ${entry.host.toLowerCase()} ${
- entry.provider === "github" ? "" : entry.repository.toLowerCase()
+ sourceControlClients.find(entry.provider)?.changeRequestListScope === "host"
+ ? ""
+ : entry.repository.toLowerCase()
}`;
counts.set(read, (counts.get(read) ?? 0) + 1);
}
diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts
new file mode 100644
index 00000000000..19c2e903844
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts
@@ -0,0 +1,46 @@
+import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import { describe, expect, it } from "vite-plus/test";
+
+import { remarkPullRequestAutolinks } from "./pullRequestMarkdown.logic";
+
+type Node = {
+ type: string;
+ value?: string;
+ url?: string;
+ data?: { hProperties?: Record<string, unknown> };
+ children?: Node[];
+};
+
+function links(markdown: string) {
+ const autolinks = changeRequestReferenceAutolinker({
+ provider: "github",
+ url: "https://github.com/team/repo/pull/8",
+ })!;
+ const tree = unified().use(remarkParse).parse(markdown) as Node;
+ remarkPullRequestAutolinks({ autolinks })(tree as never);
+ const found: Array<[string | undefined, string | undefined, unknown]> = [];
+ const visit = (node: Node) => {
+ if (node.type === "link") {
+ found.push([
+ node.children?.[0]?.value,
+ node.url,
+ node.data?.hProperties?.["dataPullRequestAutolink"],
+ ]);
+ }
+ node.children?.forEach(visit);
+ };
+ visit(tree);
+ return found;
+}
+
+describe("remarkPullRequestAutolinks", () => {
+ it("links the host's references in prose and leaves links and code alone", () => {
+ expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([
+ ["#12", "https://github.com/team/repo/issues/12", "reference"],
+ ["abcdef1", "https://github.com/team/repo/commit/abcdef1", "commit"],
+ ["#13", "https://example.com", undefined],
+ ]);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
index 659236fc2e5..bb38f3d6caf 100644
--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
@@ -1,52 +1,54 @@
-import {
- findAndReplaceText,
- type MarkdownNode,
- type TextMatch,
-} from "~/vendor/mdast-find-and-replace";
+import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
export {
splitPullRequestBody,
type PullRequestBodySegment,
} from "@t3tools/client-runtime/pull-request-markdown";
-const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;
-const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;
-const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;
+type MarkdownNode = {
+ type: string;
+ value?: string;
+ children?: MarkdownNode[];
+ url?: string;
+ data?: unknown;
+};
+
const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
-export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {
- const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");
- return (tree: MarkdownNode) => {
- findAndReplaceText(
- tree,
- AUTOLINK_CANDIDATE_PATTERN,
- (matched: string, match: TextMatch) => {
- const reference = matched.startsWith("#");
- const before = match.input[match.index - 1];
- const after = match.input[match.index + matched.length];
- if (
- (before !== undefined &&
- (reference
- ? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)
- : !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||
- (after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))
- ) {
- return false;
+export function remarkPullRequestAutolinks(options: {
+ readonly autolinks: (text: string) => ReadonlyArray<ReferenceAutolink>;
+}) {
+ const visit = (node: MarkdownNode): void => {
+ const children = node.children;
+ if (children === undefined) return;
+ for (let index = 0; index < children.length; index += 1) {
+ const child = children[index]!;
+ if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue;
+ if (child.type !== "text" || child.value === undefined) {
+ visit(child);
+ continue;
+ }
+ const value = child.value;
+ const links = options.autolinks(value);
+ if (links.length === 0) continue;
+ const replacements: MarkdownNode[] = [];
+ let start = 0;
+ for (const link of links) {
+ if (start < link.index) {
+ replacements.push({ type: "text", value: value.slice(start, link.index) });
}
- return {
+ replacements.push({
type: "link",
- url: reference
- ? `${repositoryUrl}/issues/${matched.slice(1)}`
- : `${repositoryUrl}/commit/${matched}`,
- data: {
- hProperties: {
- dataPullRequestAutolink: reference ? "reference" : "commit",
- },
- },
- children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],
- };
- },
- AUTOLINK_IGNORED_TYPES,
- );
+ url: link.url,
+ data: { hProperties: { dataPullRequestAutolink: link.kind } },
+ children: [{ type: "text", value: link.label }],
+ });
+ start = link.index + link.text.length;
+ }
+ if (start < value.length) replacements.push({ type: "text", value: value.slice(start) });
+ children.splice(index, 1, ...replacements);
+ index += replacements.length - 1;
+ }
};
+ return (tree: MarkdownNode) => visit(tree);
}
diff --git a/apps/web/src/components/settings/ThemeSearchSection.tsx b/apps/web/src/components/settings/ThemeSearchSection.tsx
index b754391c459..0afa8cff9af 100644
--- a/apps/web/src/components/settings/ThemeSearchSection.tsx
+++ b/apps/web/src/components/settings/ThemeSearchSection.tsx
@@ -1,6 +1,7 @@
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { RefreshIcon } from "~/components/ui/refresh-icon";
import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";
-import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
import {
importOpenVsxThemeExtension,
searchOpenVsxThemes,
@@ -14,7 +15,7 @@ import {
replaceCustomThemeCollection,
type ThemeDefinition,
} from "../../themePalette";
-import { GitHubIcon, GitLabIcon } from "../Icons";
+import { sourceControlIcon } from "../../sourceControlPresentation";
import {
AlertDialog,
AlertDialogClose,
@@ -51,13 +52,11 @@ function sourceHost(url: string): string | null {
}
}
-function SourceLinkIcon({ url }: { url: string }) {
+function sourceLinkIcon(url: string): ReactNode {
const host = sourceHost(url);
- if (host === "github.com" || host?.endsWith(".github.com"))
- return <GitHubIcon className="size-3.5" />;
- if (host === "gitlab.com" || host?.endsWith(".gitlab.com"))
- return <GitLabIcon className="size-3.5" monochrome />;
- return <ExternalLinkIcon className="size-3.5" />;
+ const definition = host === null ? undefined : sourceControlClients.findByPublicDomain(host);
+ const Icon = definition ? sourceControlIcon(definition) : ExternalLinkIcon;
+ return <Icon className="size-3.5" />;
}
function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
@@ -415,7 +414,7 @@ export function ThemeSearchSection({
size="icon-micro"
variant="ghost-muted"
>
- <SourceLinkIcon url={extension.sourceUrl} />
+ {sourceLinkIcon(extension.sourceUrl)}
</Button>
) : null}
</div>
diff --git a/apps/web/src/vendor/mdast-find-and-replace.ts b/apps/web/src/vendor/mdast-find-and-replace.ts
deleted file mode 100644
index f1bd1cbdfee..00000000000
--- a/apps/web/src/vendor/mdast-find-and-replace.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Adapted from mdast-util-find-and-replace:
- * https://github.com/syntax-tree/mdast-util-find-and-replace/blob/main/lib/index.js
- *
- * The MIT License
- *
- * Copyright (c) Titus Wormer <[email protected]>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-export type MarkdownNode = {
- type: string;
- value?: string;
- children?: MarkdownNode[];
- url?: string;
- data?: unknown;
-};
-
-export type TextMatch = {
- index: number;
- input: string;
-};
-
-export function findAndReplaceText(
- tree: MarkdownNode,
- find: RegExp,
- replace: (matched: string, match: TextMatch) => MarkdownNode | false,
- ignoredTypes: ReadonlySet<string>,
-): void {
- visit(tree);
-
- function visit(node: MarkdownNode): void {
- if (node.children === undefined) return;
- for (let childIndex = 0; childIndex < node.children.length; childIndex += 1) {
- const child = node.children[childIndex]!;
- if (ignoredTypes.has(child.type)) continue;
- if (child.type !== "text" || child.value === undefined) {
- visit(child);
- continue;
- }
-
- const replacements: MarkdownNode[] = [];
- let start = 0;
- let changed = false;
- find.lastIndex = 0;
- let match = find.exec(child.value);
- while (match !== null) {
- const position = match.index;
- const replacement = replace(match[0], { index: position, input: match.input });
- if (replacement === false) {
- find.lastIndex = position + 1;
- } else {
- if (start < position) {
- replacements.push({ type: "text", value: child.value.slice(start, position) });
- }
- replacements.push(replacement);
- start = position + match[0].length;
- changed = true;
- }
- if (!find.global) break;
- match = find.exec(child.value);
- }
-
- if (!changed) continue;
- if (start < child.value.length) {
- replacements.push({ type: "text", value: child.value.slice(start) });
- }
- node.children.splice(childIndex, 1, ...replacements);
- childIndex += replacements.length - 1;
- }
- }
-}
diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts
index 90729a64046..182c95d6d71 100644
--- a/packages/client-runtime/src/operations/projects.ts
+++ b/packages/client-runtime/src/operations/projects.ts
@@ -91,14 +91,24 @@ export function parseAddProjectRemoteSource(
return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
}
-const GITHUB_REPOSITORY_SHORTHAND =
- /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
+const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
+
+/**
+ * The clone URL of `owner/name` on the public host of the host a repository reads as before it
+ * reports one. Null when that host has no public host.
+ */
+export function defaultHostCloneUrl(repository: string): string | null {
+ const definition = sourceControlClients.get(undefined);
+ if (definition.publicHost === null) return null;
+ const path = repository.endsWith(".git") ? repository : `${repository}.git`;
+ return definition.defaultCloneTransport === "https"
+ ? `https://${definition.publicHost}/${path}`
+ : `git@${definition.publicHost}:${path}`;
+}
export function normalizePastedCloneUrl(input: string): string {
const trimmed = input.trim();
- if (!GITHUB_REPOSITORY_SHORTHAND.test(trimmed)) return trimmed;
- const repository = trimmed.endsWith(".git") ? trimmed : `${trimmed}.git`;
- return `https://github.com/${repository}`;
+ return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed;
}
export function getDefaultCloneUrl(
diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts
index 5c0b3d84f27..3395d78313b 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.test.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { splitPullRequestBody } from "./pullRequestMarkdown.ts";
+import { changeRequestReferenceAutolinker, splitPullRequestBody } from "./pullRequestMarkdown.ts";
describe("pull request body segmentation", () => {
// GitHub writes a dropped image into the body as an `<img>` tag, so a bare attachment link on
@@ -123,3 +123,20 @@ describe("media on custom hosts", () => {
]);
});
});
+
+describe("change request reference autolinks", () => {
+ const urls = (provider: string, url: string, text: string) =>
+ changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
+
+ it("links references against the change request's own repository", () => {
+ expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
+ "https://ghe.example.com/acme/web/issues/5",
+ ]);
+ });
+
+ // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
+ it("links nothing on a host whose grammar is not applied", () => {
+ expect(urls("gitlab", "https://gitlab.com/group/project/-/merge_requests/7", "#5")).toBeNull();
+ expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
+ });
+});
diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts
index 8e342c425db..1e03c32509e 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.ts
@@ -1,4 +1,4 @@
-import { sourceControlClients } from "./sourceControlClients.ts";
+import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
export type PullRequestBodySegment =
@@ -131,3 +131,19 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
flushMarkdown();
return segments;
}
+
+/**
+ * Finds the references the change request's host links in plain text, resolved against the change
+ * request's repository. Null when the host links none.
+ */
+export function changeRequestReferenceAutolinker(
+ changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
+): ((text: string) => ReadonlyArray<ReferenceAutolink>) | null {
+ if (!changeRequest) return null;
+ const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
+ const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
+ .repositoryUrl;
+ return find === undefined || repositoryUrl === undefined
+ ? null
+ : (text) => find(text, repositoryUrl);
+}
diff --git a/packages/client-runtime/src/sourceControlClients.test.ts b/packages/client-runtime/src/sourceControlClients.test.ts
index 9a2cb20e4a4..a47b6ddfe53 100644
--- a/packages/client-runtime/src/sourceControlClients.test.ts
+++ b/packages/client-runtime/src/sourceControlClients.test.ts
@@ -350,3 +350,18 @@ describe("sourceControlClients project hosts", () => {
expect(sourceControlClients.repositorySelector({ owner: "o", name: "r" })).toBe("o/r");
});
});
+
+describe("sourceControlClients.findByPublicDomain", () => {
+ it("names the host a link is on, subdomains included", () => {
+ const kindOf = (hostname: string) => sourceControlClients.findByPublicDomain(hostname)?.kind;
+ expect(kindOf("gist.github.com")).toBe("github");
+ expect(kindOf("GitLab.com")).toBe("gitlab");
+ expect(kindOf("codeberg.org")).toBe("forgejo");
+ expect(kindOf("notgithub.com")).toBeUndefined();
+ expect(kindOf("github.com.example")).toBeUndefined();
+ });
+
+ it("leaves findByPublicHost to the public host alone", () => {
+ expect(sourceControlClients.findByPublicHost("gist.github.com")).toBeUndefined();
+ });
+});
diff --git a/packages/client-runtime/src/sourceControlClients.ts b/packages/client-runtime/src/sourceControlClients.ts
index ac67c682c52..87da337cdee 100644
--- a/packages/client-runtime/src/sourceControlClients.ts
+++ b/packages/client-runtime/src/sourceControlClients.ts
@@ -11,6 +11,7 @@ export {
type ChangeRequestLink,
type ChangeRequestTerminology,
type ParsedChangeRequestUrl,
+ type ReferenceAutolink,
type SourceControlClientDefinition,
} from "@t3tools/source-control-core/client/definition";
import * as Forgejo from "@t3tools/source-control-forgejo/client/definition";
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 0fcf52cc880..81f26b66384 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -7,10 +7,6 @@
"types": "./src/changedFileKind.ts",
"import": "./src/changedFileKind.ts"
},
- "./githubMarkdownLinks": {
- "types": "./src/githubMarkdownLinks.ts",
- "import": "./src/githubMarkdownLinks.ts"
- },
"./authScopeOptions": {
"types": "./src/authScopeOptions.ts",
"import": "./src/authScopeOptions.ts"
diff --git a/packages/shared/src/githubMarkdownLinks.test.ts b/packages/shared/src/githubMarkdownLinks.test.ts
deleted file mode 100644
index be31e63603c..00000000000
--- a/packages/shared/src/githubMarkdownLinks.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { describe, expect, it } from "vite-plus/test";
-import { githubMarkdownLinks } from "./githubMarkdownLinks.ts";
-
-const url = "https://github.com/team/repo/pull/8";
-describe("githubMarkdownLinks", () => {
- it("links closing references, cross-repository references, commits and mentions", () => {
- expect(
- githubMarkdownLinks(
- "Closes #123, fixes other/project#9; other#4 @julius @team/mobile abc1234 other/project@abcdef1",
- url,
- ),
- ).toBe(
- "Closes [#123](https://github.com/team/repo/issues/123), fixes [other/project#9](https://github.com/other/project/issues/9); [other#4](https://github.com/other/repo/issues/4) [@julius](https://github.com/julius) [@team/mobile](https://github.com/orgs/team/teams/mobile) [abc1234](https://github.com/team/repo/commit/abc1234) [other/project@abcdef1](https://github.com/other/project/commit/abcdef1)",
- );
- });
- it("leaves code, links, images, URLs, escapes, emails, and plain numbers alone", () => {
- const text =
- "`#123 @person abc1234`\n\n```\n#123\n```\n\n[#123](https://example.com) ![#123](image.png) https://example.com/#123 [email protected] \\#123 1234567\n\n[ref]: https://example.com/#123";
- expect(githubMarkdownLinks(text, url)).toBe(text);
- });
- it("does not nest links inside HTML anchors or code", () => {
- const text = 'See <a href="https://example.com">#12</a> and <code>#13</code>, then #14.';
- expect(githubMarkdownLinks(text, url)).toBe(
- 'See <a href="https://example.com">#12</a> and <code>#13</code>, then [#14](https://github.com/team/repo/issues/14).',
- );
- });
-});
diff --git a/packages/shared/src/githubMarkdownLinks.ts b/packages/shared/src/githubMarkdownLinks.ts
deleted file mode 100644
index 21777947b67..00000000000
--- a/packages/shared/src/githubMarkdownLinks.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { unified } from "unified";
-import remarkParse from "remark-parse";
-import remarkGfm from "remark-gfm";
-
-type MarkdownNode = {
- readonly type: string;
- readonly position?:
- | {
- readonly start: { readonly offset?: number | undefined };
- readonly end: { readonly offset?: number | undefined };
- }
- | undefined;
- readonly children?: readonly MarkdownNode[] | undefined;
-};
-
-const parser = unified().use(remarkParse).use(remarkGfm);
-const reference =
- /(?<![\w/\\])(?:([\w.-]+\/[\w.-]+|[\w-]+)?#([1-9]\d*)|(?:([\w.-]+\/[\w.-]+|[\w-]+)@)?([a-f\d]{7,40})(?![\w])|@([a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d][a-z\d-]*)?))(?![\w])/gi;
-
-export function githubMarkdownLinks(markdown: string, pullRequestUrl: string | null): string {
- if (!pullRequestUrl || !/[#@]|\b[a-f\d]{7,40}\b/i.test(markdown)) return markdown;
- let url: URL;
- try {
- url = new URL(pullRequestUrl);
- } catch {
- return markdown;
- }
- const [owner, repo] = url.pathname.split("/").filter(Boolean);
- if (!owner || !repo || !/^https?:$/.test(url.protocol)) return markdown;
- const edits: { start: number; end: number; value: string }[] = [];
- const repository = (qualifier: string | undefined) =>
- qualifier?.includes("/") ? qualifier : qualifier ? `${qualifier}/${repo}` : `${owner}/${repo}`;
- const visit = (node: MarkdownNode) => {
- if (
- [
- "link",
- "linkReference",
- "image",
- "imageReference",
- "code",
- "inlineCode",
- "html",
- "definition",
- ].includes(node.type)
- )
- return;
- if (node.type === "text") {
- const start = node.position?.start.offset;
- const end = node.position?.end.offset;
- if (start === undefined || end === undefined) return;
- const source = markdown.slice(start, end);
- for (const match of source.matchAll(reference)) {
- const [label, issueRepo, number, commitRepo, sha, mention] = match;
- if (sha && !/[a-f]/i.test(sha)) continue;
- const path = number
- ? `${repository(issueRepo)}/issues/${number}`
- : sha
- ? `${repository(commitRepo)}/commit/${sha}`
- : mention?.includes("/")
- ? `orgs/${mention.split("/")[0]}/teams/${mention.split("/")[1]}`
- : mention;
- if (!path) continue;
- edits.push({
- start: start + match.index,
- end: start + match.index + label.length,
- value: `[${label}](${url.origin}/${path})`,
- });
- }
- } else if ("children" in node) {
- let protectedHtmlDepth = 0;
- for (const child of node.children ?? []) {
- if (child.type === "html") {
- const start = child.position?.start.offset;
- const end = child.position?.end.offset;
- const tag = start === undefined || end === undefined ? "" : markdown.slice(start, end);
- for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/gi)) {
- protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
- }
- } else if (protectedHtmlDepth === 0) visit(child);
- }
- }
- };
- visit(parser.parse(markdown));
- for (let index = edits.length - 1; index >= 0; index--) {
- const edit = edits[index]!;
- markdown = markdown.slice(0, edit.start) + edit.value + markdown.slice(edit.end);
- }
- return markdown;
-}
diff --git a/packages/source-control-azure-devops/src/client/definition.ts b/packages/source-control-azure-devops/src/client/definition.ts
index 1f63cf9fe95..bc203ef1dcf 100644
--- a/packages/source-control-azure-devops/src/client/definition.ts
+++ b/packages/source-control-azure-devops/src/client/definition.ts
@@ -102,7 +102,6 @@ export const definition = defineSourceControlClient({
changeRequestCloseCommand:
/\baz\s+repos\s+pr\s+update\b[^;&|]*--status[\s=]+["']?(?:completed|abandoned)\b/u,
authorProfileUrl: () => null,
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: (input) => {
const args = CHECKOUT_COMMAND.exec(input)?.[1];
diff --git a/packages/source-control-bitbucket/src/client/definition.ts b/packages/source-control-bitbucket/src/client/definition.ts
index 3ad2e97aefd..3ed6ddeaad8 100644
--- a/packages/source-control-bitbucket/src/client/definition.ts
+++ b/packages/source-control-bitbucket/src/client/definition.ts
@@ -93,7 +93,6 @@ export const definition = defineSourceControlClient({
? `git clone --single-branch --branch ${headBranch} https://bitbucket.org/${headRepositoryNameWithOwner}.git t3code-pr-${number}`
: null,
authorProfileUrl: () => null,
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: () => null,
isChangeRequestReference: () => false,
diff --git a/packages/source-control-core/src/client/definition.ts b/packages/source-control-core/src/client/definition.ts
index 2796f24df06..53101b59955 100644
--- a/packages/source-control-core/src/client/definition.ts
+++ b/packages/source-control-core/src/client/definition.ts
@@ -84,6 +84,16 @@ export interface SourceControlMediaUrl {
readonly kind?: "image" | "video";
}
+export interface ReferenceAutolink {
+ /** Where `text` starts in the string that was searched. */
+ readonly index: number;
+ readonly text: string;
+ /** What to show for the link, which can be shorter than `text`, as for a commit SHA. */
+ readonly label: string;
+ readonly url: string;
+ readonly kind: "reference" | "commit" | "mention";
+}
+
export interface SourceControlClientDefinition {
readonly kind: SourceControlProviderKind;
readonly label: string;
@@ -117,7 +127,28 @@ export interface SourceControlClientDefinition {
*/
readonly changeRequestCloseCommand?: RegExp;
readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
- readonly referenceAutolinkRepositoryUrl: (repositoryUrl: string) => string | null;
+ /**
+ * The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
+ * resolved against `repositoryUrl`, in the order they appear. Absent for a host whose grammar
+ * T3 does not apply.
+ */
+ readonly referenceAutolinks?: (
+ text: string,
+ repositoryUrl: string,
+ ) => ReadonlyArray<ReferenceAutolink>;
+ /** Where the host lists a change request's checks. Absent means the change request's own page. */
+ readonly changeRequestChecksUrl?: (changeRequestUrl: string) => string;
+ /**
+ * The actions a server too old to report `capabilities.actions` could still take on this host's
+ * change requests. Absent means none.
+ */
+ readonly changeRequestActionsWhenUnreported?: ReadonlySet<PullRequestAction>;
+ /**
+ * `host` when the server lists change requests in many repositories on this host with one read,
+ * so a page's size bounds the rows of every repository together. Absent means one read per
+ * repository.
+ */
+ readonly changeRequestListScope?: "host" | "repository";
readonly reviewSummaryRequired: (verdict: PullRequestReviewVerdict) => boolean;
readonly checkoutCommandArgument: (input: string) => string | null;
readonly isChangeRequestReference: (url: string) => boolean;
@@ -346,7 +377,6 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
changeRequestActions: new Set(),
checkoutCommand: () => null,
authorProfileUrl: () => null,
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: () => null,
isChangeRequestReference: () => false,
@@ -376,6 +406,11 @@ export interface SourceControlClientRegistry {
readonly get: (kind: string | null | undefined) => SourceControlClientDefinition;
readonly find: (kind: string) => SourceControlClientDefinition | undefined;
readonly findByPublicHost: (hostname: string) => SourceControlClientDefinition | undefined;
+ /**
+ * The host whose `publicHost` is `hostname` or a parent domain of it, such as GitHub for
+ * `gist.github.com`: which host a link is on, not one T3 can read from.
+ */
+ readonly findByPublicDomain: (hostname: string) => SourceControlClientDefinition | undefined;
/** The first host, in registry order, that reads `url` as one of its change requests. */
readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
readonly findByChangeRequestUrl: (url: string) => SourceControlClientDefinition | undefined;
@@ -471,6 +506,14 @@ export function makeSourceControlClientRegistry(
const host = hostname.toLowerCase();
return definitions.find((definition) => definition.publicHost === host);
},
+ findByPublicDomain: (hostname) => {
+ const host = hostname.toLowerCase();
+ return definitions.find(
+ (definition) =>
+ definition.publicHost !== null &&
+ (host === definition.publicHost || host.endsWith(`.${definition.publicHost}`)),
+ );
+ },
parseChangeRequestUrl,
findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
hostLabelForChangeRequestUrl: (url) =>
diff --git a/packages/source-control-forgejo/src/client/definition.ts b/packages/source-control-forgejo/src/client/definition.ts
index d6c8698f591..ea2759a61b7 100644
--- a/packages/source-control-forgejo/src/client/definition.ts
+++ b/packages/source-control-forgejo/src/client/definition.ts
@@ -84,7 +84,6 @@ export const definition = defineSourceControlClient({
changeRequestCloseCommand: /\b(?:tea\s+(?:pr|pulls)|fj\s+pr)\s+(?:merge|close)\b/u,
authorProfileUrl: () => null,
// Forgejo refuses a change request review without a summary, even with inline comments.
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: (verdict) => verdict === "request-changes",
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
diff --git a/packages/source-control-gitcafe/src/client/definition.ts b/packages/source-control-gitcafe/src/client/definition.ts
index 50a4b33e51c..22c96ce70c8 100644
--- a/packages/source-control-gitcafe/src/client/definition.ts
+++ b/packages/source-control-gitcafe/src/client/definition.ts
@@ -71,7 +71,6 @@ export const definition = defineSourceControlClient({
checkoutCommand: ({ number }) => `cafe pr checkout ${number}`,
changeRequestCloseCommand: /\bcafe\s+(?:pr|stack)\s+(?:merge|close)\b/u,
authorProfileUrl: () => null,
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: () => null,
isChangeRequestReference: () => false,
diff --git a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts
index 7257f8fd133..f3b08b6c647 100644
--- a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts
+++ b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts
@@ -118,6 +118,25 @@ describe("toChangeRequest", () => {
assert.strictEqual(row.author?.login, "remote-user");
assert.deepStrictEqual(row.reviewRequestLogins, ["alice", "upstream", "linked-local"]);
});
+
+ it("marks a mirrored GitHub bot account as a bot", () => {
+ const row = (accountType: string) =>
+ GitCafePullRequestJson.toChangeRequest(
+ decodePull({
+ ...pull,
+ author: {
+ kind: "github",
+ actorId: "act_bot",
+ login: "coderabbitai[bot]",
+ accountType,
+ avatarUrl: null,
+ },
+ }),
+ { repository: "owner/repo", host: "git.cafe" },
+ );
+ assert.isTrue(row("bot").author?.isBot);
+ assert.isUndefined(row("user").author?.isBot);
+ });
});
describe("toViewerPermissions", () => {
diff --git a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
index f6c700dba19..a3ba916bd3b 100644
--- a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
+++ b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
@@ -37,6 +37,7 @@ const Actor = Schema.Union([
actorId: Schema.String,
login: TrimmedNonEmptyString,
avatarUrl: Schema.NullOr(Schema.String),
+ accountType: Schema.optional(Schema.NullOr(Schema.String)),
linkedProfile: Schema.optional(
Schema.NullOr(
Schema.Struct({ handle: TrimmedNonEmptyString, actorId: Schema.optional(Schema.String) }),
@@ -300,7 +301,11 @@ function toActor(actor: Actor, host: string): PullRequestActor | null {
return {
login: actor.kind === "local" ? actor.handle : actor.login,
name: actor.kind === "local" ? actor.displayName : null,
- ...(actor.kind === "local" && actor.bot === true ? { isBot: true } : {}),
+ // A mirrored GitHub account says it is a bot by its account type, not its login.
+ ...((actor.kind === "local" && actor.bot === true) ||
+ (actor.kind === "github" && actor.accountType === "bot")
+ ? { isBot: true }
+ : {}),
// GitCafe serves its own avatars by path, so a relative one is read against the host.
avatarUrl: actor.avatarUrl === null ? null : new URL(actor.avatarUrl, `https://${host}`).href,
};
diff --git a/packages/source-control-github/src/client/definition.ts b/packages/source-control-github/src/client/definition.ts
index ffc58c2dec6..1a45ab704cd 100644
--- a/packages/source-control-github/src/client/definition.ts
+++ b/packages/source-control-github/src/client/definition.ts
@@ -19,6 +19,7 @@ import {
} from "@t3tools/source-control-core/client/definition";
import { gitHubMediaUrl } from "./gitHubMedia.ts";
+import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
const CHANGE_REQUEST_REFERENCE =
@@ -117,7 +118,12 @@ export const definition = defineSourceControlClient({
login.endsWith("[bot]")
? null
: new URL(`/${encodeURIComponent(login)}`, repositoryUrl).toString(),
- referenceAutolinkRepositoryUrl: (repositoryUrl) => repositoryUrl,
+ referenceAutolinks: gitHubReferenceAutolinks,
+ changeRequestChecksUrl: (changeRequestUrl) => `${changeRequestUrl.replace(/\/+$/u, "")}/checks`,
+ // Before servers reported their actions, GitHub was the only host they acted on from a list.
+ changeRequestActionsWhenUnreported: new Set(["close", "merge", "ready", "reopen"] as const),
+ // One search reads every repository on the host.
+ changeRequestListScope: "host",
reviewSummaryRequired: () => false,
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
diff --git a/packages/source-control-github/src/client/referenceAutolinks.test.ts b/packages/source-control-github/src/client/referenceAutolinks.test.ts
new file mode 100644
index 00000000000..c3ce130b909
--- /dev/null
+++ b/packages/source-control-github/src/client/referenceAutolinks.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
+
+const repositoryUrl = "https://github.com/team/repo";
+const linked = (text: string) =>
+ gitHubReferenceAutolinks(text, repositoryUrl).map(({ label, url, kind }) => [label, url, kind]);
+
+describe("gitHubReferenceAutolinks", () => {
+ it("links references, cross-repository references, commits and mentions", () => {
+ expect(
+ linked(
+ "Closes #123, fixes other/project#9; other#4 @julius @team/mobile abc1234 other/project@abcdef1",
+ ),
+ ).toEqual([
+ ["#123", "https://github.com/team/repo/issues/123", "reference"],
+ ["other/project#9", "https://github.com/other/project/issues/9", "reference"],
+ ["other#4", "https://github.com/other/repo/issues/4", "reference"],
+ ["@julius", "https://github.com/julius", "mention"],
+ ["@team/mobile", "https://github.com/orgs/team/teams/mobile", "mention"],
+ ["abc1234", "https://github.com/team/repo/commit/abc1234", "commit"],
+ ["other/project@abcdef1", "https://github.com/other/project/commit/abcdef1", "commit"],
+ ]);
+ });
+
+ it("shows a full SHA by its first seven characters", () => {
+ const sha = "0123456789abcdef0123456789abcdef01234567";
+ expect(linked(`Reverts ${sha}.`)).toEqual([
+ ["0123456", `https://github.com/team/repo/commit/${sha}`, "commit"],
+ ]);
+ });
+
+ it("leaves URLs, escapes, emails, words and plain numbers alone", () => {
+ expect(linked("https://example.com/#123 [email protected] \\#123 1234567 issue#x a#1b")).toEqual(
+ [],
+ );
+ });
+
+ it("links against the repository's own host", () => {
+ expect(
+ gitHubReferenceAutolinks("See #5", "https://ghe.example.com/acme/web").map(({ url }) => url),
+ ).toEqual(["https://ghe.example.com/acme/web/issues/5"]);
+ });
+});
diff --git a/packages/source-control-github/src/client/referenceAutolinks.ts b/packages/source-control-github/src/client/referenceAutolinks.ts
new file mode 100644
index 00000000000..93f7a5514e4
--- /dev/null
+++ b/packages/source-control-github/src/client/referenceAutolinks.ts
@@ -0,0 +1,58 @@
+import type { ReferenceAutolink } from "@t3tools/source-control-core/client/definition";
+
+// GitHub's autolinked references: `#12`, `repo#12` and `owner/repo#12`; a SHA of 7 to 40
+// characters, optionally `repo@` or `owner/repo@` qualified; `@user` and `@org/team`.
+const REFERENCE =
+ /(?<![\w/\\])(?:([\w.-]+\/[\w.-]+|[\w-]+)?#([1-9]\d*)|(?:([\w.-]+\/[\w.-]+|[\w-]+)@)?([a-f\d]{7,40})(?![\w])|@([a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d][a-z\d-]*)?))(?![\w])/giu;
+const CANDIDATE = /[#@]|\b[a-f\d]{7,40}\b/iu;
+const SHORT_SHA_LENGTH = 7;
+
+export function gitHubReferenceAutolinks(
+ text: string,
+ repositoryUrl: string,
+): ReadonlyArray<ReferenceAutolink> {
+ if (!CANDIDATE.test(text)) return [];
+ let url: URL;
+ try {
+ url = new URL(repositoryUrl);
+ } catch {
+ return [];
+ }
+ const [owner, repo] = url.pathname.split("/").filter(Boolean);
+ if (!owner || !repo || !/^https?:$/u.test(url.protocol)) return [];
+ const repository = (qualifier: string | undefined) =>
+ qualifier?.includes("/") ? qualifier : qualifier ? `${qualifier}/${repo}` : `${owner}/${repo}`;
+ const links: ReferenceAutolink[] = [];
+ for (const match of text.matchAll(REFERENCE)) {
+ const [matched, issueRepo, number, commitRepo, sha, mention] = match;
+ if (number) {
+ links.push({
+ index: match.index,
+ text: matched,
+ label: matched,
+ url: `${url.origin}/${repository(issueRepo)}/issues/${number}`,
+ kind: "reference",
+ });
+ } else if (sha) {
+ // A run of digits is a number far more often than a SHA.
+ if (!/[a-f]/iu.test(sha)) continue;
+ links.push({
+ index: match.index,
+ text: matched,
+ label: `${commitRepo ? `${commitRepo}@` : ""}${sha.slice(0, SHORT_SHA_LENGTH)}`,
+ url: `${url.origin}/${repository(commitRepo)}/commit/${sha}`,
+ kind: "commit",
+ });
+ } else if (mention) {
+ const [organization, team] = mention.split("/");
+ links.push({
+ index: match.index,
+ text: matched,
+ label: matched,
+ url: `${url.origin}/${team ? `orgs/${organization}/teams/${team}` : mention}`,
+ kind: "mention",
+ });
+ }
+ }
+ return links;
+}
diff --git a/packages/source-control-gitlab/src/client/definition.ts b/packages/source-control-gitlab/src/client/definition.ts
index 801de8ca561..ce1262f42fb 100644
--- a/packages/source-control-gitlab/src/client/definition.ts
+++ b/packages/source-control-gitlab/src/client/definition.ts
@@ -48,7 +48,6 @@ export const definition = defineSourceControlClient({
checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,
authorProfileUrl: () => null,
- referenceAutolinkRepositoryUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),