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

projects.ts

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