Open History to see the last commit
1import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
2import type {
3 CommandId,
4 EnvironmentId,
5 ProjectMutation,
6 ProjectTrackedFolder,
7 ProjectId,
8 ServerConfig,
9 ServerSettings,
10 SourceControlDiscoveryResult,
11 SourceControlRepositoryInfo,
12} from "@t3tools/contracts";
13import { SourceControlProviderKind } from "@t3tools/contracts";
14import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl";
15import { newProjectFolderName } from "@t3tools/shared/path";
16import * as Arr from "effect/Array";
17import * as Option from "effect/Option";
18import * as Order from "effect/Order";
19
20import {
21 appendBrowsePathSegment,
22 ensureBrowseDirectoryPath,
23 findProjectByPath,
24 getBrowseParentPath,
25 inferProjectTitleFromPath,
26 isExplicitRelativeProjectPath,
27 isUnsupportedWindowsProjectPath,
28 resolveProjectPathForDispatch,
29} from "../state/projects.ts";
30import type { EnvironmentProject } from "../state/models.ts";
31import { sourceControlClients } from "../sourceControlClients.ts";
32import type { SourceControlDefinition } from "../sourceControlClients.ts";
33
34export type AddProjectRemoteSource = SourceControlProviderKind | "url";
35
36export function canCreateProjectInEnvironment(
37 connectionPhase: EnvironmentConnectionPhase | null | undefined,
38): boolean {
39 return connectionPhase === "connected";
40}
41
42export function availableScratchWorkspaceRoot(
43 connectionPhase: EnvironmentConnectionPhase | null | undefined,
44 serverConfig: Pick<ServerConfig, "scratchWorkspaceRoot"> | null | undefined,
45): string | null {
46 return canCreateProjectInEnvironment(connectionPhase)
47 ? (serverConfig?.scratchWorkspaceRoot ?? null)
48 : null;
49}
50
51export interface AddProjectRemoteSourceReadinessEntry {
52 readonly ready: boolean;
53 readonly hint: string | null;
54}
55
56export type AddProjectRemoteSourceReadiness = (
57 source: AddProjectRemoteSource,
58) => AddProjectRemoteSourceReadinessEntry;
59
60export type AddProjectCloneFlow =
61 | {
62 readonly step: "repository";
63 readonly environmentId: EnvironmentId;
64 readonly source: AddProjectRemoteSource;
65 }
66 | {
67 readonly step: "confirm";
68 readonly environmentId: EnvironmentId;
69 readonly source: AddProjectRemoteSource;
70 readonly repositoryInput: string;
71 readonly repository: SourceControlRepositoryInfo | null;
72 readonly remoteUrl: string;
73 };
74
75const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<SourceControlProviderKind> =
76 sourceControlClients.definitions.map((definition) => definition.kind);
77
78export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): string {
79 return source === "url" ? "Git URL" : sourceControlClients.get(source).pickerLabel;
80}
81
82export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
83 return source === "url" ? "URL" : sourceControlClients.get(source).repositoryPathHint;
84}
85
86export function addProjectRemoteSourceProvider(
87 source: AddProjectRemoteSource,
88): SourceControlProviderKind | null {
89 return source === "url" ? null : source;
90}
91
92export function parseAddProjectRemoteSource(
93 value: string | null | undefined,
94): AddProjectRemoteSource {
95 return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
96}
97
98const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
99
100/**
101 * The clone URL of `owner/name` on the public host of the host a repository reads as before it
102 * reports one. Null when that host has no public host.
103 */
104export function defaultHostCloneUrl(repository: string): string | null {
105 const definition = sourceControlClients.get(undefined);
106 if (definition.publicHost === null) return null;
107 const path = repository.endsWith(".git") ? repository : `${repository}.git`;
108 return definition.defaultCloneTransport === "https"
109 ? `https://${definition.publicHost}/${path}`
110 : `git@${definition.publicHost}:${path}`;
111}
112
113/** Owner present, repository name missing: `owner/` or `owner//`. */
114const INCOMPLETE_GITHUB_OWNER_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})\/+$/;
115
116const INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE = "Enter the full owner/repository name.";
117
118/**
119 * Message to show when a GitHub add-project field is only `owner/`.
120 * Lookup would send that to GitHub and come back as a generic failure.
121 * Returns null for complete names, bare repo names, URLs, and other sources.
122 */
123export function githubIncompleteOwnerRepositoryMessage(
124 source: AddProjectRemoteSource,
125 input: string,
126): string | null {
127 if (source !== "github") return null;
128 if (!INCOMPLETE_GITHUB_OWNER_PATH.test(input.trim())) return null;
129 return INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE;
130}
131
132export function normalizePastedCloneUrl(input: string): string {
133 const trimmed = input.trim();
134 if (REPOSITORY_SHORTHAND.test(trimmed)) return defaultHostCloneUrl(trimmed) ?? trimmed;
135 return sourceControlClients.repositoryUrlFromPage(trimmed) ?? trimmed;
136}
137
138export function getDefaultCloneUrl(
139 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
140): string {
141 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
142 ? repository.url
143 : repository.sshUrl;
144}
145
146export type OfferedSourceControlProviders = ServerSettings["offeredSourceControlProviders"];
147
148/** Whether the project pickers offer a host. Only the default host is on until the user turns others on. */
149export function isSourceControlProviderOffered(
150 offered: OfferedSourceControlProviders | undefined,
151 kind: SourceControlProviderKind,
152): boolean {
153 return offered?.[kind] ?? kind === sourceControlClients.get(undefined).kind;
154}
155
156export function sortAddProjectProviderSources(
157 readiness: AddProjectRemoteSourceReadiness,
158 offered: OfferedSourceControlProviders | undefined,
159): ReadonlyArray<SourceControlProviderKind> {
160 return Arr.sort(
161 ADD_PROJECT_REMOTE_PROVIDER_SOURCES.filter((source) =>
162 isSourceControlProviderOffered(offered, source),
163 ),
164 Order.mapInput(
165 Order.Struct({
166 ready: Order.flip(Order.Boolean),
167 label: Order.String,
168 }),
169 (source: SourceControlProviderKind) => ({
170 ready: readiness(source).ready,
171 label: addProjectRemoteSourceLabel(source),
172 }),
173 ),
174 );
175}
176
177const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
178const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
179 ready: false,
180 hint: "Provider status unavailable. Open Source Control settings and rescan.",
181};
182
183export function buildAddProjectRemoteSourceReadiness(
184 discovery: SourceControlDiscoveryResult | null,
185): AddProjectRemoteSourceReadiness {
186 const providerByKind = new Map(
187 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
188 );
189 return (source) => {
190 if (source === "url") return READY;
191 const provider = providerByKind.get(source);
192 if (!provider) return UNAVAILABLE;
193 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
194 if (provider.auth.status === "unauthenticated") {
195 return {
196 ready: false,
197 hint:
198 Option.getOrNull(provider.auth.detail) ??
199 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
200 };
201 }
202 return READY;
203 };
204}
205
206export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
207 const trimmed = baseDirectory?.trim() ?? "";
208 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
209}
210
211export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
212 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
213 const schemeIndex = withoutQuery.indexOf("://");
214 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
215 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
216 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
217 if (hasHost && segments.length < 2) {
218 return "";
219 }
220
221 const lastSegment = segments.at(-1)?.trim() ?? "";
222 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
223 return "";
224 }
225 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
226}
227
228/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
229export function getCloneDirectoryPath(
230 remoteUrl: string,
231 ghqCloneLayout: boolean,
232 repository = remoteUrl,
233): string {
234 return (
235 (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
236 );
237}
238
239/** The clone's own folder, which folder browsing keeps at the end of the destination. */
240export function getCloneDirectoryLeafName(
241 remoteUrl: string,
242 ghqCloneLayout: boolean,
243 repository = remoteUrl,
244): string {
245 return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
246}
247
248export function getCloneDestinationPath(
249 directoryPath: string,
250 directoryName: string | null | undefined,
251): string {
252 const name = directoryName?.trim() ?? "";
253 if (name.length === 0) {
254 return directoryPath;
255 }
256 const base = ensureBrowseDirectoryPath(directoryPath);
257 return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
258}
259
260export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
261 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
262}
263
264export interface NewProjectPublishTarget {
265 readonly definition: SourceControlDefinition;
266 readonly owner: string | null;
267}
268
269export function getNewProjectPublishTargets(
270 discovery: SourceControlDiscoveryResult | null,
271 offered: OfferedSourceControlProviders | undefined,
272): ReadonlyArray<NewProjectPublishTarget> {
273 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
274 return sourceControlClients.definitions.flatMap((definition) => {
275 if (!isSourceControlProviderOffered(offered, definition.kind)) return [];
276 if (!readiness(definition.kind).ready) return [];
277 const provider = discovery?.sourceControlProviders.find(
278 (candidate) => candidate.kind === definition.kind,
279 );
280 const placement = definition.newRepositoryOwner(
281 provider ? Option.getOrNull(provider.auth.account) : null,
282 );
283 return placement === null ? [] : [{ definition, owner: placement.owner }];
284 });
285}
286
287export function getNewProjectPublishTarget(
288 targets: ReadonlyArray<NewProjectPublishTarget>,
289 kind: SourceControlProviderKind | null,
290): NewProjectPublishTarget | null {
291 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
292}
293
294export function getNewProjectRepository(
295 target: Pick<NewProjectPublishTarget, "owner">,
296 workspaceRoot: string,
297): string {
298 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
299 return target.owner ? `${target.owner}/${folderName}` : folderName;
300}
301
302export function getCloneDestinationBrowsePath(input: {
303 readonly browseDirectoryPath: string;
304 readonly selectedDirectoryName: string;
305 readonly cloneDirectoryName: string;
306 readonly caseSensitive: boolean;
307}): string {
308 const selectedDirectoryPath = appendBrowsePathSegment(
309 input.browseDirectoryPath,
310 input.selectedDirectoryName,
311 );
312 const selectedDirectoryMatches = input.caseSensitive
313 ? input.selectedDirectoryName === input.cloneDirectoryName
314 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
315 return selectedDirectoryMatches
316 ? selectedDirectoryPath
317 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
318}
319
320// The native picker returns a full path, not a name under the browsed directory.
321// Split it and reuse the in-app rules so a folder already named after the
322// repository stays that folder instead of becoming repo/repo.
323export function getCloneDestinationForPickedFolder(input: {
324 readonly pickedPath: string;
325 readonly cloneDirectoryName: string;
326 readonly caseSensitive: boolean;
327}): string {
328 const parentPath = getBrowseParentPath(input.pickedPath);
329 if (parentPath === null) {
330 return getCloneDestinationPath(input.pickedPath, input.cloneDirectoryName);
331 }
332 return getCloneDestinationBrowsePath({
333 browseDirectoryPath: parentPath,
334 selectedDirectoryName: inferProjectTitleFromPath(input.pickedPath),
335 cloneDirectoryName: input.cloneDirectoryName,
336 caseSensitive: input.caseSensitive,
337 });
338}
339
340export function resolveAddProjectPath(input: {
341 readonly rawPath: string;
342 readonly currentProjectCwd?: string | null;
343 readonly platform: string;
344}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
345 const rawPath = input.rawPath.trim();
346 if (rawPath.length === 0) {
347 return { ok: false, error: "Enter a project path." };
348 }
349 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
350 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
351 }
352 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
353 return { ok: false, error: "Relative paths require an active project in this environment." };
354 }
355 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
356 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
357}
358
359export function findExistingAddProject(input: {
360 readonly projects: ReadonlyArray<EnvironmentProject>;
361 readonly environmentId: EnvironmentId;
362 readonly path: string;
363}): EnvironmentProject | null {
364 return (
365 findProjectByPath(
366 input.projects.filter((project) => project.environmentId === input.environmentId),
367 input.path,
368 ) ?? null
369 );
370}
371
372export function buildProjectCreateCommand(input: {
373 readonly commandId: CommandId;
374 readonly projectId: ProjectId;
375 readonly workspaceRoot: string;
376 readonly trackedFolders?: ReadonlyArray<ProjectTrackedFolder>;
377}): Extract<ProjectMutation, { type: "project.create" }> {
378 return {
379 type: "project.create",
380 commandId: input.commandId,
381 projectId: input.projectId,
382 title: inferProjectTitleFromPath(input.workspaceRoot),
383 workspaceRoot: input.workspaceRoot,
384 createWorkspaceRootIfMissing: true,
385 defaultModelSelection: null,
386 ...(input.trackedFolders === undefined || input.trackedFolders.length === 0
387 ? {}
388 : { trackedFolders: input.trackedFolders }),
389 };
390}