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

projects.ts

325 lines11.6 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​
109/** Owner present, repository name missing: `owner/` or `owner//`. */
110const INCOMPLETE_GITHUB_OWNER_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})\/+$/;
111​
112const INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE = "Enter the full owner/repository name.";
113​
114/**
115 * Message to show when a GitHub add-project field is only `owner/`.
116 * Lookup would send that to GitHub and come back as a generic failure.
117 * Returns null for complete names, bare repo names, URLs, and other sources.
118 */
119export function githubIncompleteOwnerRepositoryMessage(
120 source: AddProjectRemoteSource,
121 input: string,
122): string | null {
123 if (source !== "github") return null;
124 if (!INCOMPLETE_GITHUB_OWNER_PATH.test(input.trim())) return null;
125 return INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE;
127​
128export function normalizePastedCloneUrl(input: string): string {
129 const trimmed = input.trim();
130 return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed;
132​
133export function getDefaultCloneUrl(
134 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
135): string {
136 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
137 ? repository.url
138 : repository.sshUrl;
140​
141export function sortAddProjectProviderSources(
142 readiness: AddProjectRemoteSourceReadiness,
143): ReadonlyArray<SourceControlProviderKind> {
144 return Arr.sort(
145 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
146 Order.mapInput(
147 Order.Struct({
148 ready: Order.flip(Order.Boolean),
149 label: Order.String,
150 }),
151 (source: SourceControlProviderKind) => ({
152 ready: readiness(source).ready,
153 label: addProjectRemoteSourceLabel(source),
154 }),
155 ),
156 );
158​
159const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
160const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
161 ready: false,
162 hint: "Provider status unavailable. Open Source Control settings and rescan.",
163};
164​
165export function buildAddProjectRemoteSourceReadiness(
166 discovery: SourceControlDiscoveryResult | null,
167): AddProjectRemoteSourceReadiness {
168 const providerByKind = new Map(
169 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
170 );
171 return (source) => {
172 if (source === "url") return READY;
173 const provider = providerByKind.get(source);
174 if (!provider) return UNAVAILABLE;
175 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
176 if (provider.auth.status === "unauthenticated") {
177 return {
178 ready: false,
179 hint:
180 Option.getOrNull(provider.auth.detail) ??
181 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
182 };
183 }
184 return READY;
185 };
187​
188export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
189 const trimmed = baseDirectory?.trim() ?? "";
190 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
192​
193export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
194 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
195 const schemeIndex = withoutQuery.indexOf("://");
196 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
197 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
198 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
199 if (hasHost && segments.length < 2) {
200 return "";
201 }
202​
203 const lastSegment = segments.at(-1)?.trim() ?? "";
204 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
205 return "";
206 }
207 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
209​
210export function getCloneDestinationPath(
211 directoryPath: string,
212 directoryName: string | null | undefined,
213): string {
214 const name = directoryName?.trim() ?? "";
215 if (name.length === 0) {
216 return directoryPath;
217 }
218 return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
220​
221export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
222 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
224​
225export interface NewProjectPublishTarget {
226 readonly definition: SourceControlDefinition;
227 readonly owner: string | null;
229​
230export function getNewProjectPublishTargets(
231 discovery: SourceControlDiscoveryResult | null,
232): ReadonlyArray<NewProjectPublishTarget> {
233 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
234 return sourceControlClients.definitions.flatMap((definition) => {
235 if (!readiness(definition.kind).ready) return [];
236 const provider = discovery?.sourceControlProviders.find(
237 (candidate) => candidate.kind === definition.kind,
238 );
239 const placement = definition.newRepositoryOwner(
240 provider ? Option.getOrNull(provider.auth.account) : null,
241 );
242 return placement === null ? [] : [{ definition, owner: placement.owner }];
243 });
245​
246export function getNewProjectPublishTarget(
247 targets: ReadonlyArray<NewProjectPublishTarget>,
248 kind: SourceControlProviderKind | null,
249): NewProjectPublishTarget | null {
250 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
252​
253export function getNewProjectRepository(
254 target: Pick<NewProjectPublishTarget, "owner">,
255 workspaceRoot: string,
256): string {
257 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
258 return target.owner ? `${target.owner}/${folderName}` : folderName;
260​
261export function getCloneDestinationBrowsePath(input: {
262 readonly browseDirectoryPath: string;
263 readonly selectedDirectoryName: string;
264 readonly cloneDirectoryName: string;
265 readonly caseSensitive: boolean;
266}): string {
267 const selectedDirectoryPath = appendBrowsePathSegment(
268 input.browseDirectoryPath,
269 input.selectedDirectoryName,
270 );
271 const selectedDirectoryMatches = input.caseSensitive
272 ? input.selectedDirectoryName === input.cloneDirectoryName
273 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
274 return selectedDirectoryMatches
275 ? selectedDirectoryPath
276 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
278​
279export function resolveAddProjectPath(input: {
280 readonly rawPath: string;
281 readonly currentProjectCwd?: string | null;
282 readonly platform: string;
283}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
284 const rawPath = input.rawPath.trim();
285 if (rawPath.length === 0) {
286 return { ok: false, error: "Enter a project path." };
287 }
288 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
289 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
290 }
291 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
292 return { ok: false, error: "Relative paths require an active project in this environment." };
293 }
294 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
295 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
297​
298export function findExistingAddProject(input: {
299 readonly projects: ReadonlyArray<EnvironmentProject>;
300 readonly environmentId: EnvironmentId;
301 readonly path: string;
302}): EnvironmentProject | null {
303 return (
304 findProjectByPath(
305 input.projects.filter((project) => project.environmentId === input.environmentId),
306 input.path,
307 ) ?? null
308 );
310​
311export function buildProjectCreateCommand(input: {
312 readonly commandId: CommandId;
313 readonly projectId: ProjectId;
314 readonly workspaceRoot: string;
315}): Extract<ProjectMutation, { type: "project.create" }> {
316 return {
317 type: "project.create",
318 commandId: input.commandId,
319 projectId: input.projectId,
320 title: inferProjectTitleFromPath(input.workspaceRoot),
321 workspaceRoot: input.workspaceRoot,
322 createWorkspaceRootIfMissing: true,
323 defaultModelSelection: null,
324 };