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

projects.ts

445 lines15.6 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 { MFunctionType } from "gt-i18n/types";
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: MFunctionType = mFallback,
94): string {
95 return source === "url" ? resolve(msg("Git URL")) : sourceControlClients.get(source).pickerLabel;
97​
98export function addProjectRemoteSourcePathHint(
99 source: AddProjectRemoteSource,
100 resolve: MFunctionType = mFallback,
101): string {
102 return source === "url"
103 ? resolve(msg("URL", { $context: "placeholder for a git URL field" }))
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: MFunctionType = 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: MFunctionType = 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(
223 "{provider} is not authenticated. Open Source Control settings for setup guidance.",
224 { provider: provider.label },
225 ),
226 ),
227 };
228 }
229 return READY;
230 };
232​
233export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
234 const trimmed = baseDirectory?.trim() ?? "";
235 if (trimmed.length === 0) return "~/";
236 // A bare relative setting such as `Desktop/dev` means a folder under home. The browser
237 // navigates `~/` but not `~\` home paths.
238 const isAnchored =
239 trimmed === "~" ||
240 isAbsolutePath(trimmed) ||
241 trimmed.startsWith("~/") ||
242 isExplicitRelativePath(trimmed);
243 return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`);
245​
246export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
247 const trimmed = (repositoryOrRemoteUrl ?? "").trim();
248 // Local paths keep both delimiters. SSH remotes keep a literal # in the repository path.
249 const isLocalPath =
250 !trimmed.includes("://") && (isHostPath(trimmed) || isExplicitRelativePath(trimmed));
251 const withoutQuery = isLocalPath
252 ? trimmed
253 : isScpLikeCloneUrl(trimmed)
254 ? withoutScpQuery(trimmed)
255 : trimmed.split(cloneUrlProtocol(trimmed) === "ssh" ? "?" : /[?#]/, 1)[0]!;
256 const schemeIndex = withoutQuery.indexOf("://");
257 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
258 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
259 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
260 if (hasHost && segments.length < 2) {
261 return "";
262 }
263​
264 const lastSegment = segments.at(-1)?.trim() ?? "";
265 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
266 return "";
267 }
268 const name = lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
269 return name === "." || name === ".." ? "" : name;
271​
272/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
273export function getCloneDirectoryPath(
274 remoteUrl: string,
275 ghqCloneLayout: boolean,
276 repository = remoteUrl,
277): string {
278 return (
279 (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
280 );
282​
283/** The clone's own folder, which folder browsing keeps at the end of the destination. */
284export function getCloneDirectoryLeafName(
285 remoteUrl: string,
286 ghqCloneLayout: boolean,
287 repository = remoteUrl,
288): string {
289 return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
291​
292export function getCloneDestinationPath(
293 directoryPath: string,
294 directoryName: string | null | undefined,
295): string {
296 const name = directoryName?.trim() ?? "";
297 if (name.length === 0) {
298 return directoryPath;
299 }
300 const base = ensureBrowseDirectoryPath(directoryPath);
301 return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
303​
304export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
305 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
307​
308export interface NewProjectPublishTarget {
309 readonly definition: SourceControlDefinition;
310 readonly owner: string | null;
312​
313export function getNewProjectPublishTargets(
314 discovery: SourceControlDiscoveryResult | null,
315 offered: OfferedSourceControlProviders | undefined,
316): ReadonlyArray<NewProjectPublishTarget> {
317 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
318 return sourceControlClients.definitions.flatMap((definition) => {
319 if (!isSourceControlProviderOffered(offered, definition.kind)) return [];
320 if (!readiness(definition.kind).ready) return [];
321 const provider = discovery?.sourceControlProviders.find(
322 (candidate) => candidate.kind === definition.kind,
323 );
324 const placement = definition.newRepositoryOwner(
325 provider ? Option.getOrNull(provider.auth.account) : null,
326 );
327 return placement === null ? [] : [{ definition, owner: placement.owner }];
328 });
330​
331export function getNewProjectPublishTarget(
332 targets: ReadonlyArray<NewProjectPublishTarget>,
333 kind: SourceControlProviderKind | null,
334): NewProjectPublishTarget | null {
335 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
337​
338export function getNewProjectRepository(
339 target: Pick<NewProjectPublishTarget, "owner">,
340 workspaceRoot: string,
341): string {
342 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
343 return target.owner ? `${target.owner}/${folderName}` : folderName;
345​
346export function getCloneDestinationBrowsePath(input: {
347 readonly browseDirectoryPath: string;
348 readonly selectedDirectoryName: string;
349 readonly cloneDirectoryName: string;
350 readonly caseSensitive: boolean;
351}): string {
352 const selectedDirectoryPath = appendBrowsePathSegment(
353 input.browseDirectoryPath,
354 input.selectedDirectoryName,
355 );
356 const selectedDirectoryMatches = input.caseSensitive
357 ? input.selectedDirectoryName === input.cloneDirectoryName
358 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
359 return selectedDirectoryMatches
360 ? selectedDirectoryPath
361 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
363​
364// The native picker returns a full path, not a name under the browsed directory.
365// Split it and reuse the in-app rules so a folder already named after the
366// repository stays that folder instead of becoming repo/repo.
367export function getCloneDestinationForPickedFolder(input: {
368 readonly pickedPath: string;
369 readonly cloneDirectoryName: string;
370 readonly caseSensitive: boolean;
371}): string {
372 const parentPath = getBrowseParentPath(input.pickedPath);
373 if (parentPath === null) {
374 return getCloneDestinationPath(input.pickedPath, input.cloneDirectoryName);
375 }
376 return getCloneDestinationBrowsePath({
377 browseDirectoryPath: parentPath,
378 selectedDirectoryName: inferProjectTitleFromPath(input.pickedPath),
379 cloneDirectoryName: input.cloneDirectoryName,
380 caseSensitive: input.caseSensitive,
381 });
383​
384export function resolveAddProjectPath(
385 input: {
386 readonly rawPath: string;
387 readonly currentProjectCwd?: string | null;
388 readonly platform: string;
389 },
390 resolve: MFunctionType = mFallback,
391): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
392 const rawPath = input.rawPath.trim();
393 if (rawPath.length === 0) {
394 return { ok: false, error: resolve(msg("Enter a project path.")) };
395 }
396 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
397 return {
398 ok: false,
399 error: resolve(msg("Windows-style paths are only supported on Windows environments.")),
400 };
401 }
402 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
403 return {
404 ok: false,
405 error: resolve(msg("Relative paths require an active project in this environment.")),
406 };
407 }
408 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
409 return path.length === 0
410 ? { ok: false, error: resolve(msg("Enter a project path.")) }
411 : { ok: true, path };
413​
414export function findExistingAddProject(input: {
415 readonly projects: ReadonlyArray<EnvironmentProject>;
416 readonly environmentId: EnvironmentId;
417 readonly path: string;
418}): EnvironmentProject | null {
419 return (
420 findProjectByPath(
421 input.projects.filter((project) => project.environmentId === input.environmentId),
422 input.path,
423 ) ?? null
424 );
426​
427export function buildProjectCreateCommand(input: {
428 readonly commandId: CommandId;
429 readonly projectId: ProjectId;
430 readonly workspaceRoot: string;
431 readonly trackedFolders?: ReadonlyArray<ProjectTrackedFolder>;
432}): Extract<ProjectMutation, { type: "project.create" }> {
433 return {
434 type: "project.create",
435 commandId: input.commandId,
436 projectId: input.projectId,
437 title: inferProjectTitleFromPath(input.workspaceRoot),
438 workspaceRoot: input.workspaceRoot,
439 createWorkspaceRootIfMissing: true,
440 defaultModelSelection: null,
441 ...(input.trackedFolders === undefined || input.trackedFolders.length === 0
442 ? {}
443 : { trackedFolders: input.trackedFolders }),
444 };