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

projects.ts

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