Initial git-clone Paseo plugin (refactored from gitea-clone)

This commit is contained in:
nandi committed 2026-11-20 14:43:26 -08:00
commit 2fa79ffc69
14 files changed
+5229

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
node_modules/
dist/
*.tsbuildinfo
.DS_Store
+7
View File
@@ -0,0 +1,7 @@
# Clone from Git URL
Clone from Git URL lets you clone any Git repository onto a Paseo daemon host by pasting its URL and immediately open the checkout as a Paseo workspace.
Open **Clone from Git URL** from the sidebar footer or the Command Center, paste an HTTPS, HTTP, SSH (`ssh://` or `user@host:org/repo.git`), or `git://` repository URL, and choose a destination directory on the daemon. You can optionally override the cloned folder name or specify a branch/tag to check out.
Setup requires `git` on the daemon `PATH`. Cloning runs non-interactively using the daemon's existing Git credential helpers or SSH keys. Requires Paseo 0.16.1 or newer.
+33
View File
@@ -0,0 +1,33 @@
# git-clone
Paseo plugin to clone any Git repository URL onto a Paseo daemon host and open it as a workspace.
## Features
- Accepts `https://`, `http://`, `ssh://`, `git://`, and SCP-like (`user@host:owner/repo.git`) Git URLs.
- Validates URLs, folder names, and branch/tag names on both client and server (blocking unsafe schemes like `file://` and `ext::`, argument injection, and path traversal).
- Supports optional destination folder name override and optional branch/tag checkout (`--branch`).
- Reuses an existing checkout if the target directory already has a matching `origin` remote.
- Clones atomically via a temporary staging directory before renaming into place and opening the workspace in Paseo.
## Installation
Install from Gitea into a Paseo daemon:
```bash
paseo plugin install git:https://git.site.latha.org/experiments/git-clone.git
```
Or install from a local checkout:
```bash
paseo plugin install /path/to/git-clone
```
## Development
```bash
npm install
npm run typecheck
npm test
```
+347
View File
@@ -0,0 +1,347 @@
import type { PluginScreenProps } from "@getpaseo/plugin/client";
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, Text, TextInput, View } from "react-native";
import {
destinationPreview,
gitCloneRepoRpc,
gitCloneStatusRpc,
parseGitUrl,
validateBranchName,
validateDirectoryName,
} from "../shared/git-clone";
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function GitCloneScreen({ theme, host, layout, navigation }: PluginScreenProps) {
const paseo = usePaseo();
const getStatus = useRpc(gitCloneStatusRpc);
const cloneRepository = useRpc(gitCloneRepoRpc);
const [url, setUrl] = useState("");
const [targetDirectory, setTargetDirectory] = useState("");
const [targetTouched, setTargetTouched] = useState(false);
const [directoryName, setDirectoryName] = useState("");
const [branch, setBranch] = useState("");
const status = useQuery({
queryKey: ["git-clone", host.id, "status"],
queryFn: () => getStatus({}),
retry: false,
staleTime: 15_000,
});
useEffect(() => {
if (!targetTouched && status.data) {
setTargetDirectory(status.data.suggestedTargetDirectory);
}
}, [status.data, targetTouched]);
const trimmedUrl = url.trim();
const parsedUrl = useMemo(() => (trimmedUrl ? parseGitUrl(trimmedUrl) : null), [trimmedUrl]);
const trimmedDirName = directoryName.trim();
const dirNameValidation = useMemo(
() => (trimmedDirName ? validateDirectoryName(trimmedDirName) : null),
[trimmedDirName],
);
const trimmedBranch = branch.trim();
const branchValidation = useMemo(
() => (trimmedBranch ? validateBranchName(trimmedBranch) : null),
[trimmedBranch],
);
const effectiveFolderName =
dirNameValidation && dirNameValidation.ok
? dirNameValidation.value
: parsedUrl && parsedUrl.ok
? parsedUrl.repoName
: null;
const clone = useMutation({
mutationFn: async () => {
const check = parseGitUrl(url);
if (!check.ok) throw new Error(check.error);
const directory = targetDirectory.trim();
if (!directory) throw new Error("Enter a target directory");
const result = await cloneRepository({
url: check.url,
targetDirectory: directory,
directoryName: trimmedDirName || undefined,
branch: trimmedBranch || undefined,
});
try {
const workspace = await paseo.workspaces.open(result.path);
return { ...result, workspaceId: workspace.id };
} catch (error) {
throw new Error(
`Cloned to ${result.path}, but Paseo could not open it: ${errorMessage(error)}`,
);
}
},
onSuccess: (data) => {
navigation?.openWorkspace({ workspaceId: data.workspaceId, serverId: host.id });
},
});
const styles = useMemo(
() => ({
screen: {
flex: 1,
backgroundColor: theme.colors.surface0,
},
content: {
padding: layout.compact ? 16 : 24,
gap: 16,
},
title: {
color: theme.colors.foreground,
fontSize: layout.compact ? 22 : 28,
fontWeight: "600" as const,
},
detail: { color: theme.colors.foregroundMuted, fontSize: 14, lineHeight: 20 },
label: { color: theme.colors.foreground, fontSize: 14, fontWeight: "600" as const },
input: {
minHeight: 44,
borderWidth: 1,
borderColor: theme.colors.border,
borderRadius: 8,
backgroundColor: theme.colors.surface1,
color: theme.colors.foreground,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 15,
},
card: {
borderWidth: 1,
borderColor: theme.colors.border,
borderRadius: 8,
backgroundColor: theme.colors.surface1,
padding: layout.compact ? 14 : 18,
gap: 14,
},
row: {
flexDirection: layout.compact ? ("column" as const) : ("row" as const),
gap: 12,
},
col: {
flex: 1,
gap: 8,
},
button: {
minHeight: 44,
borderRadius: 8,
backgroundColor: theme.colors.accent,
alignItems: "center" as const,
justifyContent: "center" as const,
paddingHorizontal: 16,
paddingVertical: 11,
},
buttonDisabled: { opacity: 0.55 },
buttonText: {
color: theme.colors.accentForeground,
fontSize: 15,
fontWeight: "600" as const,
textAlign: "center" as const,
},
secondaryButton: {
minHeight: 40,
borderRadius: 8,
borderWidth: 1,
borderColor: theme.colors.border,
alignItems: "center" as const,
justifyContent: "center" as const,
paddingHorizontal: 14,
paddingVertical: 9,
},
secondaryButtonText: {
color: theme.colors.foreground,
fontSize: 14,
fontWeight: "600" as const,
},
error: { color: theme.colors.statusDanger, fontSize: 14, lineHeight: 20 },
success: { color: theme.colors.statusSuccess, fontSize: 14, lineHeight: 20 },
state: {
paddingVertical: 24,
alignItems: "center" as const,
gap: 10,
},
}),
[theme, layout.compact],
);
const canClone =
Boolean(status.data?.gitAvailable) &&
Boolean(parsedUrl && parsedUrl.ok) &&
targetDirectory.trim().length > 0 &&
(!dirNameValidation || dirNameValidation.ok) &&
(!branchValidation || branchValidation.ok) &&
!clone.isPending;
return (
<ScrollView style={styles.screen} contentContainerStyle={styles.content}>
<View style={{ gap: 6 }}>
<Text style={styles.title}>Clone from Git URL</Text>
<Text style={styles.detail}>
Clone any Git repository by URL onto {host.label} and open it as a workspace.
</Text>
</View>
{status.isPending ? (
<View style={styles.state}>
<ActivityIndicator color={theme.colors.accent} />
<Text style={styles.detail}>Checking Git availability...</Text>
</View>
) : status.error ? (
<View style={{ gap: 12 }}>
<Text style={styles.error}>{errorMessage(status.error)}</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Retry checking Git availability"
style={styles.secondaryButton}
onPress={() => void status.refetch()}
>
<Text style={styles.secondaryButtonText}>Retry</Text>
</Pressable>
</View>
) : !status.data.gitAvailable ? (
<View style={styles.card}>
<Text style={styles.label}>Git is not available on this host</Text>
<Text style={styles.detail}>
Install git on {host.label} and make sure it is on the daemon PATH, then retry.
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Recheck Git availability"
style={styles.secondaryButton}
onPress={() => void status.refetch()}
>
<Text style={styles.secondaryButtonText}>Recheck</Text>
</Pressable>
</View>
) : (
<View style={styles.card}>
<View style={{ gap: 8 }}>
<Text style={styles.label}>Repository URL</Text>
<TextInput
accessibilityLabel="Git repository URL"
value={url}
onChangeText={(value) => {
setUrl(value);
if (clone.error || clone.data) clone.reset();
}}
placeholder="https://github.com/owner/repo.git or git@host:owner/repo.git"
placeholderTextColor={theme.colors.foregroundMuted}
autoCapitalize="none"
autoCorrect={false}
style={styles.input}
/>
{parsedUrl ? (
parsedUrl.ok ? (
<Text style={styles.detail}>
Host: {parsedUrl.host} · Repo: {parsedUrl.repoPath}
</Text>
) : (
<Text style={styles.error}>{parsedUrl.error}</Text>
)
) : (
<Text style={styles.detail}>
Supports https://, http://, ssh://, git://, and user@host:owner/repo.git.
</Text>
)}
</View>
<View style={{ gap: 8 }}>
<Text style={styles.label}>Clone into</Text>
<TextInput
accessibilityLabel="Target parent directory"
value={targetDirectory}
onChangeText={(value) => {
setTargetTouched(true);
setTargetDirectory(value);
if (clone.error || clone.data) clone.reset();
}}
placeholder={status.data.suggestedTargetDirectory}
placeholderTextColor={theme.colors.foregroundMuted}
autoCapitalize="none"
autoCorrect={false}
style={styles.input}
/>
{effectiveFolderName && targetDirectory.trim() ? (
<Text style={styles.detail}>
Destination: {destinationPreview(targetDirectory, effectiveFolderName)}
</Text>
) : null}
</View>
<View style={styles.row}>
<View style={styles.col}>
<Text style={styles.label}>Folder name (optional)</Text>
<TextInput
accessibilityLabel="Folder name override"
value={directoryName}
onChangeText={(value) => {
setDirectoryName(value);
if (clone.error || clone.data) clone.reset();
}}
placeholder={parsedUrl && parsedUrl.ok ? parsedUrl.repoName : "Defaults to repo name"}
placeholderTextColor={theme.colors.foregroundMuted}
autoCapitalize="none"
autoCorrect={false}
style={styles.input}
/>
{dirNameValidation && !dirNameValidation.ok ? (
<Text style={styles.error}>{dirNameValidation.error}</Text>
) : null}
</View>
<View style={styles.col}>
<Text style={styles.label}>Branch or tag (optional)</Text>
<TextInput
accessibilityLabel="Branch or tag name"
value={branch}
onChangeText={(value) => {
setBranch(value);
if (clone.error || clone.data) clone.reset();
}}
placeholder="Default branch"
placeholderTextColor={theme.colors.foregroundMuted}
autoCapitalize="none"
autoCorrect={false}
style={styles.input}
/>
{branchValidation && !branchValidation.ok ? (
<Text style={styles.error}>{branchValidation.error}</Text>
) : null}
</View>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Clone repository and open workspace"
disabled={!canClone}
style={[styles.button, !canClone ? styles.buttonDisabled : null]}
onPress={() => clone.mutate()}
>
<Text style={styles.buttonText}>
{clone.isPending ? "Cloning..." : "Clone and open workspace"}
</Text>
</Pressable>
{clone.error ? <Text style={styles.error}>{errorMessage(clone.error)}</Text> : null}
{clone.data ? (
<Text style={styles.success}>
{clone.data.alreadyExists ? "Opened existing checkout" : "Cloned"}: {clone.data.path}
</Text>
) : null}
{status.data.gitVersion ? (
<Text style={styles.detail}>Using {status.data.gitVersion} on {host.label}.</Text>
) : null}
</View>
)}
</ScrollView>
);
}
+44
View File
@@ -0,0 +1,44 @@
import type { PluginClientContext, PluginSidebarItemProps } from "@getpaseo/plugin/client";
import { SidebarRow } from "@getpaseo/plugin/client/ui";
import { GitCloneScreen } from "./client/git-clone";
function GitCloneItem({ currentScreen, openScreen }: PluginSidebarItemProps) {
return (
<SidebarRow
icon="FolderGit2"
label="Clone from Git URL"
active={currentScreen?.screenId === "clone"}
onPress={() => openScreen({ screenId: "clone" })}
/>
);
}
export default function contribute(client: PluginClientContext) {
client.addScreen({ id: "clone", title: "Clone from Git URL", Component: GitCloneScreen });
client.addSidebarFooterItem({
id: "clone",
title: "Clone from Git URL",
Component: GitCloneItem,
});
client.addCommandCenterItem({
id: "clone-from-git-url",
title: "Clone from Git URL",
icon: "FolderGit2",
keywords: [
"git",
"clone",
"url",
"repository",
"repo",
"github",
"gitlab",
"gitea",
"project",
],
context: "global",
onSelect({ openScreen }) {
openScreen({ screenId: "clone" });
},
});
return () => {};
}
+9
View File
@@ -0,0 +1,9 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { cloneRepository, getStatus } from "./server/git-clone";
import { gitCloneRepoRpc, gitCloneStatusRpc } from "./shared/git-clone";
export default function contribute(server: PluginServerContext) {
server.handle(gitCloneStatusRpc, getStatus);
server.handle(gitCloneRepoRpc, cloneRepository);
return () => {};
}
+4148
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
{
"name": "git-clone",
"description": "Clone any Git repository by URL onto the Paseo daemon and open it as a workspace.",
"private": true,
"version": "0.1.0",
"files": [
"paseo-plugin.json",
"OVERVIEW.md",
"OVERVIEW.*.md",
"index.client.ts",
"index.client.tsx",
"index.server.ts",
"index.server.tsx",
"client/",
"server/",
"shared/"
],
"scripts": {
"typecheck": "tsc --noEmit",
"test": "node --test test/git-clone.test.ts"
},
"devDependencies": {
"@getpaseo/plugin": "0.16.1",
"@tanstack/react-query": "^5.90.11",
"@types/node": "^22.15.3",
"@types/react": "~19.2.0",
"react": "19.1.0",
"react-native": "0.81.5",
"typescript": "^5.9.3",
"zod": "^4.4.3"
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"id": "git-clone",
"name": "Clone from Git URL",
"description": "Clone any Git repository by URL onto the daemon and open it as a Paseo workspace.",
"media": [],
"requirements": {
"paseo": ">=0.16.1"
}
}
+207
View File
@@ -0,0 +1,207 @@
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,
};
}
+30
View File
@@ -0,0 +1,30 @@
import { defineRpc } from "@getpaseo/plugin";
import { z } from "zod";
export * from "./git-url";
export const gitCloneStatusRpc = defineRpc({
name: "gitClone.status",
input: z.object({}),
output: z.object({
gitAvailable: z.boolean(),
gitVersion: z.string().nullable(),
suggestedTargetDirectory: z.string(),
}),
});
export const gitCloneRepoRpc = defineRpc({
name: "gitClone.clone",
input: z.object({
url: z.string().min(1).max(2000),
targetDirectory: z.string().min(1).max(1000),
directoryName: z.string().max(255).optional(),
branch: z.string().max(255).optional(),
}),
output: z.object({
path: z.string(),
url: z.string(),
name: z.string(),
alreadyExists: z.boolean(),
}),
});
+185
View File
@@ -0,0 +1,185 @@
const ALLOWED_PROTOCOLS = new Set(["https:", "http:", "ssh:", "git:"]);
const SCP_PATTERN = /^([A-Za-z0-9._-]+@)?([A-Za-z0-9][A-Za-z0-9.-]*):([^\s]+)$/;
const CONTROL_OR_SPACE = /[\s\0-\x1f\x7f]/u;
export type ParseGitUrlResult =
| {
ok: true;
url: string;
host: string;
repoPath: string;
repoName: string;
}
| {
ok: false;
error: string;
};
export type ValidationResult =
| {
ok: true;
value: string;
}
| {
ok: false;
error: string;
};
/** Validate a single directory name used for a cloned repository folder. */
export function validateDirectoryName(name: string): ValidationResult {
const trimmed = name.trim();
if (!trimmed) {
return { ok: false, error: "Folder name cannot be empty" };
}
if (trimmed === "." || trimmed === "..") {
return { ok: false, error: "Folder name cannot be '.' or '..'" };
}
if (trimmed.startsWith("-")) {
return { ok: false, error: "Folder name cannot start with '-'" };
}
if (/[/\\\0-\x1f\x7f]/u.test(trimmed)) {
return { ok: false, error: "Folder name contains invalid characters" };
}
return { ok: true, value: trimmed };
}
/** Validate an optional branch or tag ref passed to `git clone --branch`. */
export function validateBranchName(branch: string): ValidationResult {
const trimmed = branch.trim();
if (!trimmed) {
return { ok: false, error: "Branch name cannot be empty" };
}
if (trimmed.startsWith("-")) {
return { ok: false, error: "Branch name cannot start with '-'" };
}
if (CONTROL_OR_SPACE.test(trimmed)) {
return { ok: false, error: "Branch name cannot contain whitespace or control characters" };
}
if (
trimmed.includes("..") ||
trimmed.includes("@{") ||
trimmed.includes("//") ||
/[\\~^:?*[]/.test(trimmed) ||
trimmed.startsWith("/") ||
trimmed.endsWith("/") ||
trimmed.endsWith(".") ||
trimmed.endsWith(".lock")
) {
return { ok: false, error: "Branch name contains invalid Git ref characters" };
}
return { ok: true, value: trimmed };
}
function derivePathAndName(rawPath: string): { repoPath: string; repoName: string } | { error: string } {
const segments = rawPath.split("/").filter(Boolean);
if (segments.length === 0) {
return { error: "Git URL must include a repository path" };
}
const lastRaw = segments[segments.length - 1] ?? "";
const repoName = lastRaw.replace(/\.git$/iu, "");
const nameCheck = validateDirectoryName(repoName);
if (!nameCheck.ok) {
return { error: `Invalid repository name in URL: ${nameCheck.error}` };
}
const normalizedSegments = [...segments.slice(0, -1), nameCheck.value];
return {
repoPath: normalizedSegments.join("/"),
repoName: nameCheck.value,
};
}
/** Parse and validate an external Git clone URL (`https://`, `http://`, `ssh://`, `git://`, or `user@host:path`). */
export function parseGitUrl(raw: string): ParseGitUrlResult {
const trimmed = raw.trim();
if (!trimmed) {
return { ok: false, error: "Enter a Git repository URL" };
}
if (CONTROL_OR_SPACE.test(trimmed)) {
return { ok: false, error: "Git URL cannot contain whitespace or control characters" };
}
if (trimmed.startsWith("-")) {
return { ok: false, error: "Git URL cannot start with '-'" };
}
if (/^ext::/iu.test(trimmed)) {
return { ok: false, error: "ext:: Git URLs are not supported" };
}
if (trimmed.includes("://")) {
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
return { ok: false, error: "Invalid Git URL" };
}
const protocol = parsed.protocol.toLowerCase();
if (!ALLOWED_PROTOCOLS.has(protocol)) {
return {
ok: false,
error: `Unsupported Git URL protocol '${protocol.replace(/:$/u, "")}'. Use https://, http://, ssh://, git://, or user@host:path.`,
};
}
const host = parsed.hostname.toLowerCase();
if (!host || host.startsWith("-")) {
return { ok: false, error: "Git URL must include a valid host" };
}
let decodedPath: string;
try {
decodedPath = decodeURIComponent(parsed.pathname);
} catch {
return { ok: false, error: "Git URL contains invalid percent-encoding" };
}
const derived = derivePathAndName(decodedPath);
if ("error" in derived) {
return { ok: false, error: derived.error };
}
return {
ok: true,
url: trimmed,
host,
repoPath: derived.repoPath,
repoName: derived.repoName,
};
}
const scpMatch = trimmed.match(SCP_PATTERN);
if (scpMatch) {
const host = (scpMatch[2] ?? "").toLowerCase();
const rawRepoPath = scpMatch[3] ?? "";
if (!host || host.startsWith("-") || rawRepoPath.startsWith("//")) {
return { ok: false, error: "Invalid SSH Git URL" };
}
const derived = derivePathAndName(rawRepoPath);
if ("error" in derived) {
return { ok: false, error: derived.error };
}
return {
ok: true,
url: trimmed,
host,
repoPath: derived.repoPath,
repoName: derived.repoName,
};
}
return {
ok: false,
error: "Enter a full Git URL (https://, http://, ssh://, git://, or user@host:owner/repo.git)",
};
}
/** Normalize a Git remote URL across HTTPS/HTTP/SSH/SCP forms for origin comparison. */
export function normalizeRemoteUrl(raw: string): string {
const parsed = parseGitUrl(raw);
if (parsed.ok) {
return `${parsed.host}/${parsed.repoPath}`.toLowerCase();
}
return raw.trim().replace(/\/+$/u, "").replace(/\.git$/iu, "").toLowerCase();
}
/** Preview the full destination checkout path for a parent directory and folder name. */
export function destinationPreview(parent: string, folderName: string): string {
const trimmed = parent.trim().replace(/[\\/]+$/u, "");
if (!trimmed) return folderName;
const separator = trimmed.includes("\\") && !trimmed.includes("/") ? "\\" : "/";
return `${trimmed}${separator}${folderName}`;
}
+149
View File
@@ -0,0 +1,149 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
destinationPreview,
normalizeRemoteUrl,
parseGitUrl,
validateBranchName,
validateDirectoryName,
} from "../shared/git-url.ts";
test("parseGitUrl parses standard HTTPS, HTTP, SSH, and git URLs", () => {
const httpsRes = parseGitUrl("https://github.com/octocat/Hello-World.git");
assert.deepEqual(httpsRes, {
ok: true,
url: "https://github.com/octocat/Hello-World.git",
host: "github.com",
repoPath: "octocat/Hello-World",
repoName: "Hello-World",
});
const subgroupRes = parseGitUrl("https://gitlab.example.com:8443/org/team/sub/repo/");
assert.deepEqual(subgroupRes, {
ok: true,
url: "https://gitlab.example.com:8443/org/team/sub/repo/",
host: "gitlab.example.com",
repoPath: "org/team/sub/repo",
repoName: "repo",
});
const httpRes = parseGitUrl("http://git.site.latha.org/experiments/git-clone");
assert.deepEqual(httpRes, {
ok: true,
url: "http://git.site.latha.org/experiments/git-clone",
host: "git.site.latha.org",
repoPath: "experiments/git-clone",
repoName: "git-clone",
});
const sshRes = parseGitUrl("ssh://git@git.site.latha.org:2222/nandi/cluster.git");
assert.deepEqual(sshRes, {
ok: true,
url: "ssh://git@git.site.latha.org:2222/nandi/cluster.git",
host: "git.site.latha.org",
repoPath: "nandi/cluster",
repoName: "cluster",
});
const gitRes = parseGitUrl("git://example.com/project.git");
assert.deepEqual(gitRes, {
ok: true,
url: "git://example.com/project.git",
host: "example.com",
repoPath: "project",
repoName: "project",
});
});
test("parseGitUrl parses SCP-like SSH syntax", () => {
const res = parseGitUrl("git@github.com:org/my-repo.git");
assert.deepEqual(res, {
ok: true,
url: "git@github.com:org/my-repo.git",
host: "github.com",
repoPath: "org/my-repo",
repoName: "my-repo",
});
const customUser = parseGitUrl("deploy@git.site.latha.org:experiments/k3s");
assert.deepEqual(customUser, {
ok: true,
url: "deploy@git.site.latha.org:experiments/k3s",
host: "git.site.latha.org",
repoPath: "experiments/k3s",
repoName: "k3s",
});
});
test("parseGitUrl rejects unsafe schemes, leading dashes, whitespace, and missing paths", () => {
for (const bad of [
"",
" ",
"file:///etc/passwd",
"ext::sh -c id",
"EXT::sh -c id",
"--upload-pack=evil",
"https://github.com/org/repo extra",
"https://github.com/",
"https://github.com/.",
"https://github.com/org/..",
"not-a-url",
"git@github.com://weird",
"ftp://example.com/repo.git",
]) {
const res = parseGitUrl(bad);
assert.equal(res.ok, false, `Expected failure for: ${bad}`);
}
});
test("validateDirectoryName enforces safe single folder names", () => {
assert.deepEqual(validateDirectoryName(" my-repo "), { ok: true, value: "my-repo" });
for (const bad of ["", ".", "..", "-bad", "a/b", "a\\b", "bad\0name"]) {
assert.equal(validateDirectoryName(bad).ok, false, `Expected failure for: ${bad}`);
}
});
test("validateBranchName accepts valid refs and rejects injection or invalid refs", () => {
assert.deepEqual(validateBranchName("main"), { ok: true, value: "main" });
assert.deepEqual(validateBranchName("feat/git-url-v1.0"), {
ok: true,
value: "feat/git-url-v1.0",
});
for (const bad of [
"",
"-bad",
"--upload-pack",
"a b",
"a..b",
"a@{0}",
"a//b",
"/main",
"main/",
"main.",
"main.lock",
"a~1",
"a^1",
"a:b",
"a?b",
"a*b",
"a[b",
]) {
assert.equal(validateBranchName(bad).ok, false, `Expected failure for: ${bad}`);
}
});
test("normalizeRemoteUrl equates HTTPS, ssh://, and SCP forms for the same repo", () => {
const https = normalizeRemoteUrl("https://user@git.site.latha.org/experiments/git-clone.git");
const sshUrl = normalizeRemoteUrl("ssh://git@git.site.latha.org:2222/experiments/git-clone.git");
const scp = normalizeRemoteUrl("git@git.site.latha.org:experiments/git-clone");
assert.equal(https, "git.site.latha.org/experiments/git-clone");
assert.equal(sshUrl, https);
assert.equal(scp, https);
});
test("destinationPreview joins parent directory and folder name cleanly", () => {
assert.equal(destinationPreview("/workspace/", "git-clone"), "/workspace/git-clone");
assert.equal(destinationPreview("/home/nandi/Projects", "repo"), "/home/nandi/Projects/repo");
assert.equal(destinationPreview("C:\\code\\", "repo"), "C:\\code\\repo");
assert.equal(destinationPreview("", "repo"), "repo");
});
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": [
"ES2023"
],
"types": [
"node",
"react"
],
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"include": [
"**/*.ts",
"**/*.tsx"
]
}