дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
feat(vcs): offer an HTTPS clone when the SSH key cannot reach the repository (#7966)
When an SSH clone of a github.com, gitlab.com, bitbucket.org or codeberg.org repository fails with a refused key or "Repository not found", the dialog explains that the key may belong to another account and offers Clone with HTTPS, which uses the Git credential helper such as GitHub CLI.
Цей коміт міститься в:
1 джерело
587d964e42
коміт
5a44ccb615
6 files changed
+210
-10
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { cloneDirName, joinPath, parseCloneDepth, validateClone } from "../clone";
|
||||
import { cloneDirName, httpsCloneUrl, isSshAccessError, joinPath, parseCloneDepth, validateClone } from "../clone";
|
||||
import { outgoingQuery } from "../remoteUi";
|
||||
|
||||
describe("cloneDirName", () => {
|
||||
@@ -44,7 +44,34 @@ describe("parseCloneDepth", () => {
|
||||
|
||||
describe("outgoingQuery", () => {
|
||||
it("uses the upstream range when tracked", () => {
|
||||
expect(outgoingQuery("origin/main")).toEqual({ branch: "HEAD", range: "@{u}..HEAD", limit: 1000 });
|
||||
expect(outgoingQuery("origin/main")).toEqual({
|
||||
branch: "HEAD",
|
||||
range: "@{u}..HEAD",
|
||||
limit: 1000,
|
||||
});
|
||||
expect(outgoingQuery(null).range).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("httpsCloneUrl", () => {
|
||||
it("turns SSH addresses of hosting services into HTTPS", () => {
|
||||
expect(httpsCloneUrl("[email protected]:l0ng-ai/opengui.git")).toBe("https://github.com/l0ng-ai/opengui.git");
|
||||
expect(httpsCloneUrl("[email protected]:12345/repo.git")).toBe("https://github.com/12345/repo.git");
|
||||
expect(httpsCloneUrl("ssh://[email protected]/group/sub/app.git")).toBe("https://gitlab.com/group/sub/app.git");
|
||||
expect(httpsCloneUrl("ssh://[email protected]:22/12345/repo.git")).toBe("https://github.com/12345/repo.git");
|
||||
});
|
||||
it("leaves HTTPS, self-hosted, and malformed addresses alone", () => {
|
||||
expect(httpsCloneUrl("https://github.com/o/r.git")).toBeNull();
|
||||
expect(httpsCloneUrl("[email protected]:o/r.git")).toBeNull();
|
||||
expect(httpsCloneUrl("[email protected]/o/r.git")).toBeNull();
|
||||
expect(httpsCloneUrl("[email protected]:")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSshAccessError", () => {
|
||||
it("recognises refused keys and hidden repositories", () => {
|
||||
expect(isSshAccessError("ERROR: Repository not found.\nfatal: Could not read from remote repository.")).toBe(true);
|
||||
expect(isSshAccessError("[email protected]: Permission denied (publickey).")).toBe(true);
|
||||
expect(isSshAccessError("fatal: destination path 'x' already exists")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const desktop = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => false,
|
||||
callDesktop: desktop,
|
||||
nextRequestId: () => 4242,
|
||||
commands: { ...real.commands, recentProjects: async () => [] },
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: ((line: string) => void) | null = null;
|
||||
},
|
||||
}));
|
||||
|
||||
import { CloneDialog } from "../clone";
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem("openidea.vcs.cloneParent", "/work");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
desktop.mockReset();
|
||||
});
|
||||
|
||||
describe("CloneDialog HTTPS fallback", () => {
|
||||
it("offers Clone with HTTPS on SSH access errors, retries over HTTPS, and hides when URL changes", async () => {
|
||||
const onCloned = vi.fn(async () => {});
|
||||
desktop
|
||||
.mockRejectedValueOnce(new Error("ERROR: Repository not found.\nfatal: Could not read from remote repository."))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
render(<CloneDialog onClose={() => {}} onCloned={onCloned} initialUrl="[email protected]:12345/private-repo.git" />);
|
||||
|
||||
const cloneButton = screen.getByRole("button", { name: "Clone" });
|
||||
await waitFor(() => expect(cloneButton).toBeEnabled());
|
||||
await act(async () => fireEvent.click(cloneButton));
|
||||
|
||||
expect(desktop).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"vcs_clone",
|
||||
expect.objectContaining({
|
||||
url: "[email protected]:12345/private-repo.git",
|
||||
dest: "/work/private-repo",
|
||||
}),
|
||||
);
|
||||
|
||||
const retryButton = await screen.findByRole("button", { name: "Clone with HTTPS" });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
// Changing the URL hides the stale HTTPS fallback button.
|
||||
const urlInput = screen.getByLabelText("URL:");
|
||||
fireEvent.change(urlInput, { target: { value: "[email protected]:12345/other.git" } });
|
||||
expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument();
|
||||
|
||||
// Restoring the failed URL shows the button again and clicking retries with HTTPS.
|
||||
fireEvent.change(urlInput, { target: { value: "[email protected]:12345/private-repo.git" } });
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Clone with HTTPS" })));
|
||||
|
||||
expect(desktop).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"vcs_clone",
|
||||
expect.objectContaining({
|
||||
url: "https://github.com/12345/private-repo.git",
|
||||
dest: "/work/private-repo",
|
||||
}),
|
||||
);
|
||||
expect(onCloned).toHaveBeenCalledWith("/work/private-repo");
|
||||
expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not offer Clone with HTTPS for non-SSH errors", async () => {
|
||||
desktop.mockRejectedValueOnce(new Error("fatal: destination path '/work/repo' already exists"));
|
||||
|
||||
render(<CloneDialog onClose={() => {}} initialUrl="[email protected]:org/repo.git" />);
|
||||
const cloneButton = screen.getByRole("button", { name: "Clone" });
|
||||
await waitFor(() => expect(cloneButton).toBeEnabled());
|
||||
await act(async () => fireEvent.click(cloneButton));
|
||||
|
||||
expect(await screen.findByText(/already exists/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not offer Clone with HTTPS for self-hosted SSH URLs", async () => {
|
||||
desktop.mockRejectedValueOnce(new Error("[email protected]: Permission denied (publickey)."));
|
||||
|
||||
render(<CloneDialog onClose={() => {}} initialUrl="[email protected]:org/repo.git" />);
|
||||
const cloneButton = screen.getByRole("button", { name: "Clone" });
|
||||
await waitFor(() => expect(cloneButton).toBeEnabled());
|
||||
await act(async () => fireEvent.click(cloneButton));
|
||||
|
||||
expect(await screen.findByText(/Permission denied/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -167,6 +167,13 @@
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.httpsRetry {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
|
||||
.layout[data-compact] {
|
||||
flex-direction: column;
|
||||
|
||||
@@ -80,6 +80,23 @@ export function validateClone(url: string, dir: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const HTTPS_HOSTS = new Set(["github.com", "gitlab.com", "bitbucket.org", "codeberg.org"]);
|
||||
|
||||
/** The HTTPS address of an SSH `url` on a hosting service that serves both, or null. */
|
||||
export function httpsCloneUrl(url: string): string | null {
|
||||
const u = url.trim();
|
||||
const m = /^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/(.+)$/i.exec(u) ?? /^[\w.-]+@([\w.-]+):(.+)$/.exec(u);
|
||||
if (!m) return null;
|
||||
const host = (m[1] ?? "").toLowerCase();
|
||||
const path = (m[2] ?? "").replace(/^\/+/, "");
|
||||
return HTTPS_HOSTS.has(host) && path ? `https://${host}/${path}` : null;
|
||||
}
|
||||
|
||||
/** Whether git's `message` says the SSH key it used was refused or cannot see the repository. */
|
||||
export function isSshAccessError(message: string): boolean {
|
||||
return /Repository not found|Permission denied \(publickey|Could not read from remote repository/i.test(message);
|
||||
}
|
||||
|
||||
/** A valid `git clone --depth` value, or null while the field is invalid. */
|
||||
export function parseCloneDepth(value: string): number | null {
|
||||
const text = value.trim();
|
||||
@@ -143,7 +160,11 @@ export const CLONED = "openidea://clone/cloned";
|
||||
|
||||
export function showCloneDialog(initialUrl = "", initialSystem?: "git" | "subversion", initialRevision = "") {
|
||||
if (!isTauri()) {
|
||||
notifications().notify({ group: "vcs", level: "warning", title: "Cloning requires the desktop app" });
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "warning",
|
||||
title: "Cloning requires the desktop app",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const inPage = () =>
|
||||
@@ -283,8 +304,12 @@ export function CloneDialog({
|
||||
const [svnRevision, setSvnRevision] = useState(initialRevision);
|
||||
const [svnDepth, setSvnDepth] = useState<"infinity" | "immediates" | "files" | "empty">("infinity");
|
||||
const [svnIgnoreExternals, setSvnIgnoreExternals] = useState(false);
|
||||
const [progress, setProgress] = useState<{ line: string; fraction: number | null }>({ line: "", fraction: null });
|
||||
const [progress, setProgress] = useState<{
|
||||
line: string;
|
||||
fraction: number | null;
|
||||
}>({ line: "", fraction: null });
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [httpsRetry, setHttpsRetry] = useState<string | null>(null);
|
||||
const request = useRef<number | null>(null);
|
||||
const urlField = useRef<HTMLDivElement>(null);
|
||||
const layout = useRef<HTMLDivElement>(null);
|
||||
@@ -326,7 +351,11 @@ export function CloneDialog({
|
||||
if (!rect || !recentUrls.length) return;
|
||||
showContextMenu(
|
||||
{ x: rect.left, y: rect.bottom },
|
||||
recentUrls.map((item) => ({ label: item, verbatim: true, run: () => setUrl(item) })),
|
||||
recentUrls.map((item) => ({
|
||||
label: item,
|
||||
verbatim: true,
|
||||
run: () => setUrl(item),
|
||||
})),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -373,6 +402,7 @@ export function CloneDialog({
|
||||
if (validateClone(cloneUrl, target) || (shallow && !svn && depth === null) || svnRevInvalid || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setHttpsRetry(null);
|
||||
const id = nextRequestId();
|
||||
request.current = id;
|
||||
const channel = new Channel<string>();
|
||||
@@ -392,7 +422,13 @@ export function CloneDialog({
|
||||
ignoreExternals: svnIgnoreExternals,
|
||||
});
|
||||
else
|
||||
await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel });
|
||||
await callDesktop("vcs_clone", {
|
||||
request: id,
|
||||
url: cloneUrl.trim(),
|
||||
dest: target,
|
||||
depth,
|
||||
onOutput: channel,
|
||||
});
|
||||
writeParent(parentOf(target));
|
||||
rememberUrl(cloneUrl.trim());
|
||||
if (onCloned) {
|
||||
@@ -403,7 +439,11 @@ export function CloneDialog({
|
||||
await openCloned(target);
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) setError("Clone cancelled");
|
||||
else setError(e instanceof Error ? e.message : String(e));
|
||||
else {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
setError(message);
|
||||
if (!svn && isSshAccessError(message)) setHttpsRetry(httpsCloneUrl(cloneUrl));
|
||||
}
|
||||
} finally {
|
||||
request.current = null;
|
||||
setBusy(false);
|
||||
@@ -412,7 +452,12 @@ export function CloneDialog({
|
||||
};
|
||||
|
||||
const buttons: DialogButton[] = [
|
||||
{ label: svn ? "Checkout" : "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() },
|
||||
{
|
||||
label: svn ? "Checkout" : "Clone",
|
||||
role: "default",
|
||||
disabled: !!invalid || busy,
|
||||
onClick: () => void clone(),
|
||||
},
|
||||
{ label: "Cancel", role: "cancel", onClick: cancel },
|
||||
];
|
||||
const sourceList = (
|
||||
@@ -610,6 +655,19 @@ export function CloneDialog({
|
||||
</div>
|
||||
)}
|
||||
{error && <div className={styles.error}>{error}</div>}
|
||||
{!busy && error && httpsRetry && httpsRetry === httpsCloneUrl(url) && (
|
||||
<div className={styles.httpsRetry}>
|
||||
<span className={styles.hint}>
|
||||
<T>
|
||||
The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper,
|
||||
such as GitHub CLI.
|
||||
</T>
|
||||
</span>
|
||||
<Button size="small" onClick={() => void clone(httpsRetry)}>
|
||||
<T>Clone with HTTPS</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!busy && !error && url.trim() && invalid && (
|
||||
<div className={styles.hint}>
|
||||
<T>{invalid}</T>
|
||||
|
||||
@@ -5785,5 +5785,7 @@
|
||||
"Show Details": "Show Details",
|
||||
"Submit Request": "Submit Request",
|
||||
"{n} endpoint": "{n} endpoint",
|
||||
"{n} endpoints": "{n} endpoints"
|
||||
"{n} endpoints": "{n} endpoints",
|
||||
"Clone with HTTPS": "Clone with HTTPS",
|
||||
"The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI.": "The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI."
|
||||
}
|
||||
@@ -12676,5 +12676,7 @@
|
||||
"Show Details": "显示详情",
|
||||
"Submit Request": "提交请求",
|
||||
"{n} endpoint": "{n} 个端点",
|
||||
"{n} endpoints": "{n} 个端点"
|
||||
"{n} endpoints": "{n} 个端点",
|
||||
"Clone with HTTPS": "通过 HTTPS 克隆",
|
||||
"The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI.": "SSH 密钥可能属于另一个账号。HTTPS 会使用 Git 凭据助手(如 GitHub CLI)中的凭据。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача