208 lines
6.3 KiB
TypeScript
208 lines
6.3 KiB
TypeScript
import { constants as fsConstants } from "node:fs";
|
|
import { access, lstat, mkdir, mkdtemp, realpath, rename, rm, stat } from "node:fs/promises";
|
|
import { homedir } from "node:os";
|
|
import path from "node:path";
|
|
import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
|
|
import { execCommand } from "@getpaseo/plugin/server";
|
|
import {
|
|
normalizeRemoteUrl,
|
|
parseGitUrl,
|
|
validateBranchName,
|
|
validateDirectoryName,
|
|
type gitCloneRepoRpc,
|
|
type gitCloneStatusRpc,
|
|
} from "../shared/git-clone";
|
|
|
|
const GIT_CHECK_TIMEOUT_MS = 15_000;
|
|
const CLONE_TIMEOUT_MS = 5 * 60_000;
|
|
const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
const AUTH_ERROR_PATTERN =
|
|
/could not read Username|Authentication failed|Permission denied \(publickey\)|fatal: could not read Password/iu;
|
|
|
|
type StatusOutput = RpcOutput<typeof gitCloneStatusRpc>;
|
|
type CloneInput = RpcInput<typeof gitCloneRepoRpc>;
|
|
type CloneOutput = RpcOutput<typeof gitCloneRepoRpc>;
|
|
|
|
interface ExecError extends Error {
|
|
code?: unknown;
|
|
stdout?: string;
|
|
stderr?: string;
|
|
}
|
|
|
|
function formatGitError(error: unknown): Error {
|
|
const execError = error as ExecError;
|
|
if (execError?.code === "ENOENT") {
|
|
return new Error("The git command was not found on the daemon PATH.");
|
|
}
|
|
const detail = [execError?.stderr, execError?.stdout, execError?.message]
|
|
.filter((value): value is string => typeof value === "string" && value.trim().length > 0)
|
|
.join("\n")
|
|
.trim()
|
|
.slice(0, 1500);
|
|
if (!detail) return new Error("git failed");
|
|
if (AUTH_ERROR_PATTERN.test(detail)) {
|
|
return new Error(
|
|
`${detail}\n\nCloning runs non-interactively and uses the daemon's configured Git credentials or SSH keys.`,
|
|
);
|
|
}
|
|
return new Error(detail);
|
|
}
|
|
|
|
async function runGit(
|
|
args: string[],
|
|
options: { cwd?: string; timeout?: number } = {},
|
|
): Promise<string> {
|
|
try {
|
|
const result = await execCommand("git", args, {
|
|
cwd: options.cwd,
|
|
timeout: options.timeout ?? GIT_CHECK_TIMEOUT_MS,
|
|
maxBuffer: MAX_OUTPUT_BYTES,
|
|
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
});
|
|
return result.stdout;
|
|
} catch (error) {
|
|
throw formatGitError(error);
|
|
}
|
|
}
|
|
|
|
async function isWritableDirectory(dirPath: string): Promise<boolean> {
|
|
try {
|
|
const info = await stat(dirPath);
|
|
if (!info.isDirectory()) return false;
|
|
await access(dirPath, fsConstants.W_OK);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function detectSuggestedTargetDirectory(): Promise<string> {
|
|
const home = homedir();
|
|
const candidates = ["/workspace", path.join(home, "Projects")];
|
|
for (const candidate of candidates) {
|
|
if (await isWritableDirectory(candidate)) return candidate;
|
|
}
|
|
return home;
|
|
}
|
|
|
|
export async function getStatus(): Promise<StatusOutput> {
|
|
const [gitVersionResult, suggestedTargetDirectory] = await Promise.all([
|
|
runGit(["--version"])
|
|
.then((stdout) => stdout.trim() || "git")
|
|
.catch(() => null),
|
|
detectSuggestedTargetDirectory(),
|
|
]);
|
|
|
|
return {
|
|
gitAvailable: gitVersionResult !== null,
|
|
gitVersion: gitVersionResult,
|
|
suggestedTargetDirectory,
|
|
};
|
|
}
|
|
|
|
function expandHome(value: string): string {
|
|
if (value === "~") return homedir();
|
|
if (value.startsWith("~/")) return path.join(homedir(), value.slice(2));
|
|
return value;
|
|
}
|
|
|
|
function isPathWithin(parent: string, candidate: string): boolean {
|
|
const relative = path.relative(parent, candidate);
|
|
return relative === "" || (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
}
|
|
|
|
async function existingCheckoutMatches(checkoutPath: string, cloneUrl: string): Promise<boolean> {
|
|
try {
|
|
const info = await stat(checkoutPath);
|
|
if (!info.isDirectory()) return false;
|
|
const remote = await runGit(["-C", checkoutPath, "remote", "get-url", "origin"]);
|
|
return normalizeRemoteUrl(remote) === normalizeRemoteUrl(cloneUrl);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function cloneRepository(input: CloneInput): Promise<CloneOutput> {
|
|
const parsed = parseGitUrl(input.url);
|
|
if (!parsed.ok) {
|
|
throw new Error(parsed.error);
|
|
}
|
|
|
|
let folderName = parsed.repoName;
|
|
if (input.directoryName && input.directoryName.trim()) {
|
|
const dirCheck = validateDirectoryName(input.directoryName);
|
|
if (!dirCheck.ok) {
|
|
throw new Error(dirCheck.error);
|
|
}
|
|
folderName = dirCheck.value;
|
|
}
|
|
|
|
let branch: string | null = null;
|
|
if (input.branch && input.branch.trim()) {
|
|
const branchCheck = validateBranchName(input.branch);
|
|
if (!branchCheck.ok) {
|
|
throw new Error(branchCheck.error);
|
|
}
|
|
branch = branchCheck.value;
|
|
}
|
|
|
|
const requestedParent = expandHome(input.targetDirectory.trim());
|
|
if (!path.isAbsolute(requestedParent)) {
|
|
throw new Error("Target directory must be an absolute path");
|
|
}
|
|
await mkdir(requestedParent, { recursive: true });
|
|
const targetParent = await realpath(requestedParent);
|
|
|
|
const paseoHome = path.resolve(process.env.PASEO_HOME ?? path.join(homedir(), ".paseo"));
|
|
if (isPathWithin(paseoHome, targetParent)) {
|
|
throw new Error("Choose a target directory outside the Paseo home directory");
|
|
}
|
|
|
|
const checkoutPath = path.join(targetParent, folderName);
|
|
if (!isPathWithin(targetParent, checkoutPath) || path.dirname(checkoutPath) !== targetParent) {
|
|
throw new Error("Resolved checkout path must stay inside the target directory");
|
|
}
|
|
|
|
try {
|
|
await lstat(checkoutPath);
|
|
if (await existingCheckoutMatches(checkoutPath, parsed.url)) {
|
|
return {
|
|
path: checkoutPath,
|
|
url: parsed.url,
|
|
name: folderName,
|
|
alreadyExists: true,
|
|
};
|
|
}
|
|
throw new Error(`Checkout path already exists: ${checkoutPath}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
|
|
const stagingPath = await mkdtemp(path.join(targetParent, ".paseo-git-clone-"));
|
|
const args = [
|
|
"-c",
|
|
"protocol.ext.allow=never",
|
|
"-c",
|
|
"protocol.file.allow=never",
|
|
"clone",
|
|
...(branch ? ["--branch", branch] : []),
|
|
"--",
|
|
parsed.url,
|
|
stagingPath,
|
|
];
|
|
try {
|
|
await runGit(args, { cwd: targetParent, timeout: CLONE_TIMEOUT_MS });
|
|
await rename(stagingPath, checkoutPath);
|
|
} catch (error) {
|
|
await rm(stagingPath, { recursive: true, force: true }).catch(() => undefined);
|
|
throw error;
|
|
}
|
|
|
|
return {
|
|
path: checkoutPath,
|
|
url: parsed.url,
|
|
name: folderName,
|
|
alreadyExists: false,
|
|
};
|
|
}
|