Skip to content
TypeScript

feat: optionally clone repos into ghq-style <host>/<owner>/<repo> folders (#24904)

shivam707dcdaa16b7
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
index b208a1719ab..4d1f199e636 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
+++ b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
@@ -1,6 +1,22 @@
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
-import type { EnvironmentId } from "@t3tools/contracts";
+import { type EnvironmentId, FilesystemBrowseError } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+
+const isFilesystemBrowseError = Schema.is(FilesystemBrowseError);
+
+/** Clone destinations may name folders that do not exist yet; cloning creates them. */
+export function isMissingCloneParentBrowseFailure(input: {
+ readonly cloning: boolean;
+ readonly failure: unknown;
+}): boolean {
+ return (
+ input.cloning &&
+ isFilesystemBrowseError(input.failure) &&
+ input.failure.failure === "read_directory_failed" &&
+ input.failure.pathMissing === true
+ );
+}
export function resolveAddProjectEnvironment<
T extends {
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx
index 88e24801b82..ddd6ec120d3 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx
+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx
@@ -17,6 +17,7 @@ import {
getAddProjectInitialQuery,
getCloneDestinationBrowsePath,
getCloneDestinationPath,
+ getCloneDirectoryPath,
getCloneDirectoryName,
getDefaultCloneUrl,
getNewProjectPathPreview,
@@ -96,7 +97,10 @@ import {
useRemoteEnvironmentRuntime,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
-import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
+import {
+ isMissingCloneParentBrowseFailure,
+ resolveAddProjectEnvironment,
+} from "./AddProjectScreen.logic";
import {
createNewTaskDraft,
setComposerDraftText,
@@ -113,6 +117,7 @@ interface EnvironmentOption {
readonly connectionState: EnvironmentConnectionPhase;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
+ readonly ghqCloneLayout: boolean;
}
const environmentOptionOrder = Order.mapInput(
@@ -290,13 +295,17 @@ function ProjectPathInput(props: {
);
}
-function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
+function useBrowsePathInput(
+ environment: EnvironmentOption | null,
+ pinnedDirectoryName = "",
+ cloneDirectoryPath = pinnedDirectoryName,
+) {
const environmentId = environment?.environmentId ?? null;
const environmentBaseDirectory = environment?.baseDirectory ?? null;
const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
const seedPath = getCloneDestinationPath(
getAddProjectInitialQuery(environmentBaseDirectory),
- pinnedDirectoryName,
+ cloneDirectoryPath,
);
// Each host keeps the path last typed or browsed for it, and shows its own default until then,
// so switching hosts and back loses nothing. With no host selected (one dropping out briefly),
@@ -403,6 +412,7 @@ function useEnvironmentOptions(
connectionState: runtime?.connectionState ?? "available",
connectionError: runtime?.connectionError ?? null,
connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
+ ghqCloneLayout: config?.settings.ghqCloneLayout === true,
};
});
return Arr.sort(
@@ -914,6 +924,7 @@ function FolderBrowser(props: {
readonly selectedDirectoryName?: string;
}) => Promise<boolean>;
readonly pinnedDirectoryName?: string;
+ readonly cloning?: boolean;
}) {
const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
const browseInput =
@@ -953,7 +964,16 @@ function FolderBrowser(props: {
{!canReadFiles && !fileAccess.isPending ? (
<ErrorBanner message={fileAccess.error ?? "This connection cannot browse host folders."} />
) : null}
- {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
+ {browseState.error === null ? null : isMissingCloneParentBrowseFailure({
+ cloning: props.cloning === true,
+ failure: browseState.failure,
+ }) ? (
+ <Text className="text-sm text-foreground-muted">
+ This folder does not exist yet. Cloning creates it.
+ </Text>
+ ) : (
+ <ErrorBanner message={browseState.error} />
+ )}
<ListSection>
{fileAccess.isPending || (browseState.isPending && browseState.data === null) ? (
<View className="items-center py-5">
@@ -1367,9 +1387,15 @@ export function AddProjectDestinationScreen(props: {
const repositoryTitle = stringParam(props.repositoryTitle);
const prompt = stringParam(props.prompt);
const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
+ const ghqDirectoryPath =
+ remoteUrl && environment?.ghqCloneLayout
+ ? getCloneDirectoryPath(remoteUrl, true, repositoryName)
+ : null;
+ const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName;
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
environment,
- repositoryName,
+ cloneDirectoryName,
+ ghqDirectoryPath ?? repositoryName,
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -1474,7 +1500,8 @@ export function AddProjectDestinationScreen(props: {
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
- pinnedDirectoryName={repositoryName}
+ pinnedDirectoryName={cloneDirectoryName}
+ cloning={Boolean(remoteUrl)}
/>
</>
) : (
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index 2c282db9e80..fc36729d672 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -437,6 +437,16 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
onValueChange={(value) => write({ defaultAutoPull: value })}
/>
</SettingsSection>
+ <SettingsSection title="Clones">
+ <SettingsSwitchRow
+ icon="folder"
+ label="Clone into host folders"
+ subtitle="Clones go to github.com/owner/repo under the Add project folder, like ghq."
+ value={uniform("ghqCloneLayout")}
+ disabled={disabledFor("ghqCloneLayout")}
+ onValueChange={(value) => write({ ghqCloneLayout: value })}
+ />
+ </SettingsSection>
</>
) : null}
diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts
index c11a89a7c3a..9dcaf7b6bf0 100644
--- a/apps/mobile/src/features/settings/settings-search.ts
+++ b/apps/mobile/src/features/settings/settings-search.ts
@@ -75,6 +75,8 @@ const SETTINGS_SEARCH_TERMS = {
"agent credits",
"default branch",
"automatically pull",
+ "clone into host folders",
+ "ghq",
],
SettingsWorktrees: [
"worktree",
diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts
index eedff4fc79c..b96b7b5df55 100644
--- a/apps/server/src/workspace/WorkspaceEntries.test.ts
+++ b/apps/server/src/workspace/WorkspaceEntries.test.ts
@@ -789,5 +789,30 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
});
}),
);
+
+ it.effect("marks only a missing directory as missing when browsing fails", () =>
+ Effect.gen(function* () {
+ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
+ const path = yield* Path.Path;
+ const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-missing-" });
+ yield* writeTextFile(cwd, "file.txt", "");
+
+ const missing = yield* workspaceEntries
+ .browse({ partialPath: `${path.join(cwd, "absent", "nested")}${path.sep}` })
+ .pipe(Effect.flip);
+ const underFile = yield* workspaceEntries
+ .browse({ partialPath: `${path.join(cwd, "file.txt")}${path.sep}` })
+ .pipe(Effect.flip);
+
+ expect(missing).toMatchObject({
+ _tag: "WorkspaceEntriesReadDirectoryError",
+ pathMissing: true,
+ });
+ expect(underFile).toMatchObject({
+ _tag: "WorkspaceEntriesReadDirectoryError",
+ pathMissing: false,
+ });
+ }),
+ );
});
});
diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts
index d388170f93f..7b2a0aa0a7c 100644
--- a/apps/server/src/workspace/WorkspaceEntries.ts
+++ b/apps/server/src/workspace/WorkspaceEntries.ts
@@ -64,6 +64,10 @@ export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<Works
cause: Schema.Defect(),
},
) {
+ get pathMissing(): boolean {
+ return (this.cause as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
+ }
+
override get message(): string {
const cwd = this.cwd ? ` from '${this.cwd}'` : "";
return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 2bd0acc22b8..1b078b192c1 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -561,6 +561,7 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
readonly failure: FilesystemBrowseFailure;
readonly parentPath?: string;
readonly platform?: string;
+ readonly pathMissing?: boolean;
} {
switch (error._tag) {
case "WorkspaceEntriesWindowsPathUnsupportedError":
@@ -568,7 +569,11 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
case "WorkspaceEntriesCurrentProjectRequiredError":
return { failure: "current_project_required" };
case "WorkspaceEntriesReadDirectoryError":
- return { failure: "read_directory_failed", parentPath: error.parentPath };
+ return {
+ failure: "read_directory_failed",
+ parentPath: error.parentPath,
+ ...(error.pathMissing ? { pathMissing: true } : {}),
+ };
default:
return unexpectedCompatibilityError(error);
}
diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx
index a1f2c544262..3a5752fcae1 100644
--- a/apps/web/src/components/AddProjectToMachineDialog.tsx
+++ b/apps/web/src/components/AddProjectToMachineDialog.tsx
@@ -3,7 +3,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import {
getAddProjectInitialQuery,
getCloneDestinationPath,
- getCloneDirectoryName,
+ getCloneDirectoryPath,
} from "@t3tools/client-runtime/operations/projects";
import { resolvePastedPath } from "@t3tools/shared/path";
import {
@@ -113,7 +113,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
const defaultPath = getCloneDestinationPath(
getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
- getCloneDirectoryName(sourceUrl),
+ getCloneDirectoryPath(
+ sourceUrl,
+ targetEnvironment?.serverConfig?.settings.ghqCloneLayout === true,
+ ),
);
const [pathOverride, setPathOverride] = useState<string | null>(null);
const destinationPath = pathOverride ?? defaultPath;
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index f14a483d533..196cb0215cc 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -10,7 +10,8 @@ import {
canCreateProjectInEnvironment,
getCloneDestinationBrowsePath,
getCloneDestinationPath,
- getCloneDirectoryName,
+ getCloneDirectoryLeafName,
+ getCloneDirectoryPath,
getDefaultCloneUrl,
getNewProjectPathPreview,
getNewProjectPublishTarget,
@@ -638,7 +639,11 @@ function OpenCommandPaletteDialog(props: {
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
const pinnedCloneDirectoryName =
addProjectCloneFlow?.step === "confirm"
- ? getCloneDirectoryName(
+ ? getCloneDirectoryLeafName(
+ addProjectCloneFlow.remoteUrl,
+ environments.find(
+ (candidate) => candidate.environmentId === addProjectCloneFlow.environmentId,
+ )?.serverConfig?.settings.ghqCloneLayout === true,
addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.remoteUrl,
)
: "";
@@ -1940,8 +1945,20 @@ function OpenCommandPaletteDialog(props: {
if (created.value) setOpen(false);
}
- function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
- return getAddProjectInitialQueryForEnvironment(environmentId);
+ function getDefaultCloneDestination(
+ environmentId: EnvironmentId,
+ remoteUrl: string,
+ repository: string,
+ ): string {
+ const environment = environments.find((candidate) => candidate.environmentId === environmentId);
+ return getCloneDestinationPath(
+ getAddProjectInitialQueryForEnvironment(environmentId),
+ getCloneDirectoryPath(
+ remoteUrl,
+ environment?.serverConfig?.settings.ghqCloneLayout === true,
+ repository,
+ ),
+ );
}
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
@@ -1982,9 +1999,11 @@ function OpenCommandPaletteDialog(props: {
const provider = addProjectRemoteSourceProvider(addProjectCloneFlow.source);
if (!provider) {
- const destinationPath = getCloneDestinationPath(
- getDefaultCloneParentPath(addProjectCloneFlow.environmentId),
- getCloneDirectoryName(rawRepository),
+ const remoteUrl = normalizePastedCloneUrl(rawRepository);
+ const destinationPath = getDefaultCloneDestination(
+ addProjectCloneFlow.environmentId,
+ remoteUrl,
+ rawRepository,
);
setAddProjectCloneFlow({
step: "confirm",
@@ -1992,7 +2011,7 @@ function OpenCommandPaletteDialog(props: {
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository: null,
- remoteUrl: normalizePastedCloneUrl(rawRepository),
+ remoteUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
@@ -2024,9 +2043,11 @@ function OpenCommandPaletteDialog(props: {
return;
}
const repository = lookupResult.value;
- const destinationPath = getCloneDestinationPath(
- getDefaultCloneParentPath(addProjectCloneFlow.environmentId),
- getCloneDirectoryName(repository.nameWithOwner),
+ const remoteUrl = getDefaultCloneUrl(repository);
+ const destinationPath = getDefaultCloneDestination(
+ addProjectCloneFlow.environmentId,
+ remoteUrl,
+ repository.nameWithOwner,
);
setAddProjectCloneFlow({
step: "confirm",
@@ -2034,7 +2055,7 @@ function OpenCommandPaletteDialog(props: {
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
- remoteUrl: getDefaultCloneUrl(repository),
+ remoteUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
diff --git a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx
index f8e76b565d6..918e3912b0a 100644
--- a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx
+++ b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx
@@ -1,5 +1,9 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
-import { getCloneDestinationPath } from "@t3tools/client-runtime/operations/projects";
+import {
+ getAddProjectInitialQuery,
+ getCloneDestinationPath,
+ getCloneDirectoryPath,
+} from "@t3tools/client-runtime/operations/projects";
import {
findPromptLinkProjects,
findPromptLinkPullRequestThread,
@@ -198,8 +202,9 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
const cloneRepository = async (repository: PromptLinkRepository) => {
const environmentId = lastActiveEnvironmentId();
const environment = environments.find((entry) => entry.environmentId === environmentId);
- const newProjectsRoot = environment?.serverConfig?.newProjectsRoot ?? null;
- if (environmentId === null || newProjectsRoot === null) {
+ const serverConfig = environment?.serverConfig ?? null;
+ const newProjectsRoot = serverConfig?.newProjectsRoot ?? null;
+ if (environmentId === null || serverConfig === null || newProjectsRoot === null) {
setState({
status: "failed",
message:
@@ -209,14 +214,21 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
}
setState({ status: "opening" });
const projectId = newProjectId();
+ const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`;
+ const settings = serverConfig.settings;
const result = await startProjectClone({
environmentId,
input: {
projectId,
title: repository.name,
createdAt: new Date().toISOString(),
- remoteUrl: `https://github.com/${repository.owner}/${repository.name}.git`,
- destinationPath: getCloneDestinationPath(newProjectsRoot, repository.name),
+ remoteUrl,
+ destinationPath: getCloneDestinationPath(
+ settings.ghqCloneLayout
+ ? getAddProjectInitialQuery(settings.addProjectBaseDirectory)
+ : newProjectsRoot,
+ getCloneDirectoryPath(remoteUrl, settings.ghqCloneLayout === true),
+ ),
},
});
if (result._tag === "Failure") {
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 362210f96ee..d408d6c8d5d 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -552,6 +552,9 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
+ ...(settings.ghqCloneLayout !== DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout
+ ? ["Clone into host folders"]
+ : []),
...(settings.confirmThreadUnpin !== DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin
? ["Unpin confirmation"]
: []),
@@ -665,6 +668,7 @@ export function useSettingsRestore(onRestored?: () => void) {
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
+ ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
confirmThreadUnpin: DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin,
@@ -1585,6 +1589,30 @@ export function ThreadsSettingsPanel() {
/>
}
/>
+ <SettingsRow
+ serverScoped
+ settingKeys={["ghqCloneLayout"]}
+ {...searchableSetting("ghq-clone-layout")}
+ description="Clones go to github.com/owner/repo under the folder above, like ghq."
+ resetAction={
+ settings.ghqCloneLayout !== DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout ? (
+ <SettingResetButton
+ label="clone into host folders"
+ onClick={() =>
+ updateSettings({ ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout })
+ }
+ />
+ ) : null
+ }
+ control={
+ <ScopedSwitch
+ settingKeys={["ghqCloneLayout"]}
+ checked={settings.ghqCloneLayout}
+ onCheckedChange={(checked) => updateSettings({ ghqCloneLayout: Boolean(checked) })}
+ aria-label="Clone into host folders"
+ />
+ }
+ />
</SettingsSection>
<ProjectDefaultsSettings category="general" />
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index e61a064431c..23d32bb35e9 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -655,6 +655,13 @@ export const SETTINGS_SEARCH_ITEMS = [
scope: "environment-defaults",
searchTerms: ["base directory folder browser path home"],
},
+ {
+ id: "ghq-clone-layout",
+ title: "Clone into host folders",
+ to: "/settings/threads",
+ scope: "environment-defaults",
+ searchTerms: ["ghq clone destination host owner repository root layout"],
+ },
{
id: "unpin-confirmation",
title: "Unpin confirmation",
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index 9eb2751f931..c32219a02a5 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -148,6 +148,11 @@ toast or from the banner above the composer. When the host refuses the machine's
clones over HTTPS with Git's credentials for that host instead, and the project's remote uses the
HTTPS URL.
+To lay clones out like [ghq](https://github.com/x-motemen/ghq), turn on **Clone into host folders**
+under **Settings → Threads** (or **Source control** on mobile). Clones then default to
+`<host>/<owner>/<repo>` under **Add project starts in**, so set that to `~/ghq` to share ghq's
+folders. You can still change the destination before cloning.
+
For a local Git repository without a remote, **Publish Repository** creates a hosted repository,
adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote;
make your first commit before pushing.
diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts
index 398f6bf92e3..5b55a40f4eb 100644
--- a/packages/client-runtime/src/operations/projects.test.ts
+++ b/packages/client-runtime/src/operations/projects.test.ts
@@ -4,7 +4,10 @@ import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import {
findExistingAddProject,
+ getCloneDestinationPath,
+ getCloneDirectoryLeafName,
getCloneDirectoryName,
+ getCloneDirectoryPath,
getDefaultCloneUrl,
githubIncompleteOwnerRepositoryMessage,
normalizePastedCloneUrl,
@@ -94,6 +97,38 @@ describe("add project shared logic", () => {
expect(getCloneDirectoryName(" https://github.com/owner/repo.git ")).toBe("repo");
});
+ it("lays clone folders out like ghq only when asked, and only when the URL is safe", () => {
+ expect(getCloneDirectoryPath("[email protected]:owner/repo.git", false)).toBe("repo");
+ expect(getCloneDirectoryPath("[email protected]:owner/repo.git", true)).toBe(
+ "github.com/owner/repo",
+ );
+ expect(getCloneDirectoryPath("ssh://[email protected]:2222/group/sub/repo.git", true)).toBe(
+ "gitlab.com/group/sub/repo",
+ );
+ expect(getCloneDirectoryPath("https://github.com/owner/../../repo", true)).toBe("repo");
+ expect(getCloneDirectoryPath("/srv/git/repo.git", true)).toBe("repo");
+ expect(
+ getCloneDirectoryPath(
+ "[email protected]:v3/org/Project/My%20Repo",
+ false,
+ "Project/My Repo",
+ ),
+ ).toBe("My Repo");
+ expect(
+ getCloneDirectoryLeafName(
+ "[email protected]:v3/org/Project/My%20Repo",
+ true,
+ "Project/My Repo",
+ ),
+ ).toBe("My%20Repo");
+ expect(
+ getCloneDestinationPath(
+ "C:\\Users\\me\\ghq",
+ getCloneDirectoryPath("[email protected]:owner/repo.git", true),
+ ),
+ ).toBe("C:\\Users\\me\\ghq\\github.com\\owner\\repo");
+ });
+
it("keeps a numeric repository name that sits on a path", () => {
expect(getCloneDirectoryName("https://github.com/acme/123.git")).toBe("123");
expect(getCloneDirectoryName("https://github.com/acme/123")).toBe("123");
diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts
index cbdb885bdaa..aab4f0f2842 100644
--- a/packages/client-runtime/src/operations/projects.ts
+++ b/packages/client-runtime/src/operations/projects.ts
@@ -9,6 +9,7 @@ import type {
SourceControlRepositoryInfo,
} from "@t3tools/contracts";
import { SourceControlProviderKind } from "@t3tools/contracts";
+import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl";
import { newProjectFolderName } from "@t3tools/shared/path";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
@@ -207,6 +208,26 @@ export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | und
return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
}
+/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
+export function getCloneDirectoryPath(
+ remoteUrl: string,
+ ghqCloneLayout: boolean,
+ repository = remoteUrl,
+): string {
+ return (
+ (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
+ );
+}
+
+/** The clone's own folder, which folder browsing keeps at the end of the destination. */
+export function getCloneDirectoryLeafName(
+ remoteUrl: string,
+ ghqCloneLayout: boolean,
+ repository = remoteUrl,
+): string {
+ return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
+}
+
export function getCloneDestinationPath(
directoryPath: string,
directoryName: string | null | undefined,
@@ -215,7 +236,8 @@ export function getCloneDestinationPath(
if (name.length === 0) {
return directoryPath;
}
- return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
+ const base = ensureBrowseDirectoryPath(directoryPath);
+ return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
}
export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
diff --git a/packages/contracts/src/filesystem.ts b/packages/contracts/src/filesystem.ts
index 7270ba78c9a..a1f6c293e90 100644
--- a/packages/contracts/src/filesystem.ts
+++ b/packages/contracts/src/filesystem.ts
@@ -64,6 +64,8 @@ export class FilesystemBrowseError extends Schema.TaggedError<FilesystemBrowseEr
failure: Schema.optional(FilesystemBrowseFailure),
parentPath: Schema.optional(TrimmedNonEmptyString),
platform: Schema.optional(TrimmedNonEmptyString),
+ /** Set when the directory does not exist; older clients ignore it. */
+ pathMissing: Schema.optional(Schema.Boolean),
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect()),
},
@@ -75,6 +77,7 @@ export class FilesystemBrowseError extends Schema.TaggedError<FilesystemBrowseEr
readonly failure: FilesystemBrowseFailure;
readonly parentPath?: string;
readonly platform?: string;
+ readonly pathMissing?: boolean;
readonly cause?: unknown;
}) {
const cwd = props.cwd === undefined ? "" : ` from '${props.cwd}'`;
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 7f6e8a4aea8..798e076495a 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1315,6 +1315,8 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
+ /** Clones default to `<addProjectBaseDirectory>/<host>/<owner>/<repo>`, like ghq. */
+ ghqCloneLayout: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
textGenerationModelSelection: ModelSelection.pipe(
Schema.withDecodingDefault(
Effect.succeed({
@@ -1675,6 +1677,7 @@ export const ServerSettingsPatch = Schema.Struct({
newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
worktreeSubmodules: Schema.optionalKey(Schema.NullOr(WorktreeSubmodules)),
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
+ ghqCloneLayout: Schema.optionalKey(Schema.Boolean),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
threadTitleInstructions: Schema.optionalKey(TrimmedString),
branchNamingMode: Schema.optionalKey(BranchNamingMode),
diff --git a/packages/shared/src/cloneUrl.test.ts b/packages/shared/src/cloneUrl.test.ts
index 16503923d8a..50ab17f9114 100644
--- a/packages/shared/src/cloneUrl.test.ts
+++ b/packages/shared/src/cloneUrl.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { cloneUrlForProtocol, cloneUrlProtocol } from "./cloneUrl.ts";
+import { cloneUrlForProtocol, cloneUrlProtocol, cloneUrlRepositoryPath } from "./cloneUrl.ts";
describe("cloneUrlForProtocol", () => {
it.each([
@@ -138,3 +138,29 @@ describe("cloneUrlForProtocol", () => {
expect(cloneUrlProtocol("file:///srv/git/repo.git")).toBeNull();
});
});
+
+describe("cloneUrlRepositoryPath", () => {
+ it("rejects Windows device names and trailing dots or spaces in every folder", () => {
+ for (const segment of [
+ "CON",
+ "nul.txt",
+ "COM1",
+ "LPT0",
+ "com¹",
+ "CONIN$",
+ "conout$",
+ "aux .txt",
+ "repo.",
+ "repo ",
+ ]) {
+ expect(cloneUrlRepositoryPath(`https://github.com/${segment}/repo.git`)).toBeNull();
+ expect(cloneUrlRepositoryPath(`https://${segment}/owner/repo.git`)).toBeNull();
+ expect(cloneUrlRepositoryPath(`https://github.com/owner/${segment}.git`)).toBeNull();
+ }
+ expect(cloneUrlRepositoryPath("https://github.com/acme/repo.git")).toBe("github.com/acme/repo");
+ expect(cloneUrlRepositoryPath("ssh://[email protected]:2222/group/sub/repo.git")).toBe(
+ "gitlab.com/group/sub/repo",
+ );
+ expect(cloneUrlRepositoryPath("C:/repos/project.git")).toBeNull();
+ });
+});
diff --git a/packages/shared/src/cloneUrl.ts b/packages/shared/src/cloneUrl.ts
index cface92a89a..597f21d1d1f 100644
--- a/packages/shared/src/cloneUrl.ts
+++ b/packages/shared/src/cloneUrl.ts
@@ -1,3 +1,5 @@
+import { isWindowsDrivePath } from "./path.ts";
+
export type CloneProtocol = "ssh" | "https";
const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
@@ -46,3 +48,26 @@ export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): strin
? `git@${parsed.host}:${parsed.path}`
: `https://${parsed.host}/${parsed.path}`;
}
+
+const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
+const WINDOWS_DEVICE_NAME =
+ /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
+
+/**
+ * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
+ * anything with a folder that could leave the root.
+ */
+export function cloneUrlRepositoryPath(url: string): string | null {
+ if (isWindowsDrivePath(url.trim())) return null;
+ const parsed = parseCloneUrl(url);
+ if (!parsed) return null;
+ const segments = [parsed.host, ...parsed.path.split(/[?#]/)[0]!.split("/").filter(Boolean)];
+ const last = segments.at(-1)!;
+ if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
+ if (
+ segments.length < 2 ||
+ segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
+ )
+ return null;
+ return segments.join("/");
+}