Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projects.ts

444 lines15.5 KB

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