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

projects.ts

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