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

projects.ts

306 lines10.8 KB

1import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
2import type {
3 CommandId,
4 EnvironmentId,
5 ProjectMutation,
6 ProjectId,
7 ServerConfig,
8 SourceControlDiscoveryResult,
9 SourceControlRepositoryInfo,
10} from "@t3tools/contracts";
11import { SourceControlProviderKind } from "@t3tools/contracts";
12import { newProjectFolderName } from "@t3tools/shared/path";
13import * as Arr from "effect/Array";
14import * as Option from "effect/Option";
15import * as Order from "effect/Order";
16​
17import {
18 appendBrowsePathSegment,
19 ensureBrowseDirectoryPath,
20 findProjectByPath,
21 inferProjectTitleFromPath,
22 isExplicitRelativeProjectPath,
23 isUnsupportedWindowsProjectPath,
24 resolveProjectPathForDispatch,
25} from "../state/projects.ts";
26import type { EnvironmentProject } from "../state/models.ts";
27import { sourceControlClients } from "../sourceControlClients.ts";
28import type { SourceControlDefinition } from "../sourceControlClients.ts";
29​
30export type AddProjectRemoteSource = SourceControlProviderKind | "url";
31​
32export function canCreateProjectInEnvironment(
33 connectionPhase: EnvironmentConnectionPhase | null | undefined,
34): boolean {
35 return connectionPhase === "connected";
37​
38export function availableScratchWorkspaceRoot(
39 connectionPhase: EnvironmentConnectionPhase | null | undefined,
40 serverConfig: Pick<ServerConfig, "scratchWorkspaceRoot"> | null | undefined,
41): string | null {
42 return canCreateProjectInEnvironment(connectionPhase)
43 ? (serverConfig?.scratchWorkspaceRoot ?? null)
44 : null;
46​
47export interface AddProjectRemoteSourceReadinessEntry {
48 readonly ready: boolean;
49 readonly hint: string | null;
51​
52export type AddProjectRemoteSourceReadiness = (
53 source: AddProjectRemoteSource,
54) => AddProjectRemoteSourceReadinessEntry;
55​
56export type AddProjectCloneFlow =
57 | {
58 readonly step: "repository";
59 readonly environmentId: EnvironmentId;
60 readonly source: AddProjectRemoteSource;
61 }
62 | {
63 readonly step: "confirm";
64 readonly environmentId: EnvironmentId;
65 readonly source: AddProjectRemoteSource;
66 readonly repositoryInput: string;
67 readonly repository: SourceControlRepositoryInfo | null;
68 readonly remoteUrl: string;
69 };
70​
71const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<SourceControlProviderKind> =
72 sourceControlClients.definitions.map((definition) => definition.kind);
73​
74export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): string {
75 return source === "url" ? "Git URL" : sourceControlClients.get(source).pickerLabel;
77​
78export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
79 return source === "url" ? "URL" : sourceControlClients.get(source).repositoryPathHint;
81​
82export function addProjectRemoteSourceProvider(
83 source: AddProjectRemoteSource,
84): SourceControlProviderKind | null {
85 return source === "url" ? null : source;
87​
88export function parseAddProjectRemoteSource(
89 value: string | null | undefined,
90): AddProjectRemoteSource {
91 return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
93​
94const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
95​
96/**
97 * The clone URL of `owner/name` on the public host of the host a repository reads as before it
98 * reports one. Null when that host has no public host.
99 */
100export function defaultHostCloneUrl(repository: string): string | null {
101 const definition = sourceControlClients.get(undefined);
102 if (definition.publicHost === null) return null;
103 const path = repository.endsWith(".git") ? repository : `${repository}.git`;
104 return definition.defaultCloneTransport === "https"
105 ? `https://${definition.publicHost}/${path}`
106 : `git@${definition.publicHost}:${path}`;
108​
109export function normalizePastedCloneUrl(input: string): string {
110 const trimmed = input.trim();
111 return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed;
113​
114export function getDefaultCloneUrl(
115 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
116): string {
117 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
118 ? repository.url
119 : repository.sshUrl;
121​
122export function sortAddProjectProviderSources(
123 readiness: AddProjectRemoteSourceReadiness,
124): ReadonlyArray<SourceControlProviderKind> {
125 return Arr.sort(
126 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
127 Order.mapInput(
128 Order.Struct({
129 ready: Order.flip(Order.Boolean),
130 label: Order.String,
131 }),
132 (source: SourceControlProviderKind) => ({
133 ready: readiness(source).ready,
134 label: addProjectRemoteSourceLabel(source),
135 }),
136 ),
137 );
139​
140const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
141const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
142 ready: false,
143 hint: "Provider status unavailable. Open Source Control settings and rescan.",
144};
145​
146export function buildAddProjectRemoteSourceReadiness(
147 discovery: SourceControlDiscoveryResult | null,
148): AddProjectRemoteSourceReadiness {
149 const providerByKind = new Map(
150 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
151 );
152 return (source) => {
153 if (source === "url") return READY;
154 const provider = providerByKind.get(source);
155 if (!provider) return UNAVAILABLE;
156 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
157 if (provider.auth.status === "unauthenticated") {
158 return {
159 ready: false,
160 hint:
161 Option.getOrNull(provider.auth.detail) ??
162 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
163 };
164 }
165 return READY;
166 };
168​
169export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
170 const trimmed = baseDirectory?.trim() ?? "";
171 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
173​
174export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
175 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
176 const schemeIndex = withoutQuery.indexOf("://");
177 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
178 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
179 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
180 if (hasHost && segments.length < 2) {
181 return "";
182 }
183​
184 const lastSegment = segments.at(-1)?.trim() ?? "";
185 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
186 return "";
187 }
188 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
190​
191export function getCloneDestinationPath(
192 directoryPath: string,
193 directoryName: string | null | undefined,
194): string {
195 const name = directoryName?.trim() ?? "";
196 if (name.length === 0) {
197 return directoryPath;
198 }
199 return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
201​
202export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
203 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
205​
206export interface NewProjectPublishTarget {
207 readonly definition: SourceControlDefinition;
208 readonly owner: string | null;
210​
211export function getNewProjectPublishTargets(
212 discovery: SourceControlDiscoveryResult | null,
213): ReadonlyArray<NewProjectPublishTarget> {
214 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
215 return sourceControlClients.definitions.flatMap((definition) => {
216 if (!readiness(definition.kind).ready) return [];
217 const provider = discovery?.sourceControlProviders.find(
218 (candidate) => candidate.kind === definition.kind,
219 );
220 const placement = definition.newRepositoryOwner(
221 provider ? Option.getOrNull(provider.auth.account) : null,
222 );
223 return placement === null ? [] : [{ definition, owner: placement.owner }];
224 });
226​
227export function getNewProjectPublishTarget(
228 targets: ReadonlyArray<NewProjectPublishTarget>,
229 kind: SourceControlProviderKind | null,
230): NewProjectPublishTarget | null {
231 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
233​
234export function getNewProjectRepository(
235 target: Pick<NewProjectPublishTarget, "owner">,
236 workspaceRoot: string,
237): string {
238 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
239 return target.owner ? `${target.owner}/${folderName}` : folderName;
241​
242export function getCloneDestinationBrowsePath(input: {
243 readonly browseDirectoryPath: string;
244 readonly selectedDirectoryName: string;
245 readonly cloneDirectoryName: string;
246 readonly caseSensitive: boolean;
247}): string {
248 const selectedDirectoryPath = appendBrowsePathSegment(
249 input.browseDirectoryPath,
250 input.selectedDirectoryName,
251 );
252 const selectedDirectoryMatches = input.caseSensitive
253 ? input.selectedDirectoryName === input.cloneDirectoryName
254 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
255 return selectedDirectoryMatches
256 ? selectedDirectoryPath
257 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
259​
260export function resolveAddProjectPath(input: {
261 readonly rawPath: string;
262 readonly currentProjectCwd?: string | null;
263 readonly platform: string;
264}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
265 const rawPath = input.rawPath.trim();
266 if (rawPath.length === 0) {
267 return { ok: false, error: "Enter a project path." };
268 }
269 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
270 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
271 }
272 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
273 return { ok: false, error: "Relative paths require an active project in this environment." };
274 }
275 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
276 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
278​
279export function findExistingAddProject(input: {
280 readonly projects: ReadonlyArray<EnvironmentProject>;
281 readonly environmentId: EnvironmentId;
282 readonly path: string;
283}): EnvironmentProject | null {
284 return (
285 findProjectByPath(
286 input.projects.filter((project) => project.environmentId === input.environmentId),
287 input.path,
288 ) ?? null
289 );
291​
292export function buildProjectCreateCommand(input: {
293 readonly commandId: CommandId;
294 readonly projectId: ProjectId;
295 readonly workspaceRoot: string;
296}): Extract<ProjectMutation, { type: "project.create" }> {
297 return {
298 type: "project.create",
299 commandId: input.commandId,
300 projectId: input.projectId,
301 title: inferProjectTitleFromPath(input.workspaceRoot),
302 workspaceRoot: input.workspaceRoot,
303 createWorkspaceRootIfMissing: true,
304 defaultModelSelection: null,
305 };