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

projects.ts

296 lines10.4 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 { SourceControlClientDefinition } 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 GITHUB_REPOSITORY_SHORTHAND =
95 /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
96​
97export function normalizePastedCloneUrl(input: string): string {
98 const trimmed = input.trim();
99 if (!GITHUB_REPOSITORY_SHORTHAND.test(trimmed)) return trimmed;
100 const repository = trimmed.endsWith(".git") ? trimmed : `${trimmed}.git`;
101 return `https://github.com/${repository}`;
103​
104export function getDefaultCloneUrl(
105 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
106): string {
107 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
108 ? repository.url
109 : repository.sshUrl;
111​
112export function sortAddProjectProviderSources(
113 readiness: AddProjectRemoteSourceReadiness,
114): ReadonlyArray<SourceControlProviderKind> {
115 return Arr.sort(
116 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
117 Order.mapInput(
118 Order.Struct({
119 ready: Order.flip(Order.Boolean),
120 label: Order.String,
121 }),
122 (source: SourceControlProviderKind) => ({
123 ready: readiness(source).ready,
124 label: addProjectRemoteSourceLabel(source),
125 }),
126 ),
127 );
129​
130const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
131const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
132 ready: false,
133 hint: "Provider status unavailable. Open Source Control settings and rescan.",
134};
135​
136export function buildAddProjectRemoteSourceReadiness(
137 discovery: SourceControlDiscoveryResult | null,
138): AddProjectRemoteSourceReadiness {
139 const providerByKind = new Map(
140 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
141 );
142 return (source) => {
143 if (source === "url") return READY;
144 const provider = providerByKind.get(source);
145 if (!provider) return UNAVAILABLE;
146 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
147 if (provider.auth.status === "unauthenticated") {
148 return {
149 ready: false,
150 hint:
151 Option.getOrNull(provider.auth.detail) ??
152 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
153 };
154 }
155 return READY;
156 };
158​
159export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
160 const trimmed = baseDirectory?.trim() ?? "";
161 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
163​
164export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
165 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
166 const schemeIndex = withoutQuery.indexOf("://");
167 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
168 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
169 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
170 if (hasHost && segments.length < 2) {
171 return "";
172 }
173​
174 const lastSegment = segments.at(-1)?.trim() ?? "";
175 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
176 return "";
177 }
178 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
180​
181export function getCloneDestinationPath(
182 directoryPath: string,
183 directoryName: string | null | undefined,
184): string {
185 const name = directoryName?.trim() ?? "";
186 if (name.length === 0) {
187 return directoryPath;
188 }
189 return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
191​
192export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
193 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
195​
196export interface NewProjectPublishTarget {
197 readonly definition: SourceControlClientDefinition;
198 readonly owner: string | null;
200​
201export function getNewProjectPublishTargets(
202 discovery: SourceControlDiscoveryResult | null,
203): ReadonlyArray<NewProjectPublishTarget> {
204 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
205 return sourceControlClients.definitions.flatMap((definition) => {
206 if (!readiness(definition.kind).ready) return [];
207 const provider = discovery?.sourceControlProviders.find(
208 (candidate) => candidate.kind === definition.kind,
209 );
210 const placement = definition.newRepositoryOwner(
211 provider ? Option.getOrNull(provider.auth.account) : null,
212 );
213 return placement === null ? [] : [{ definition, owner: placement.owner }];
214 });
216​
217export function getNewProjectPublishTarget(
218 targets: ReadonlyArray<NewProjectPublishTarget>,
219 kind: SourceControlProviderKind | null,
220): NewProjectPublishTarget | null {
221 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
223​
224export function getNewProjectRepository(
225 target: Pick<NewProjectPublishTarget, "owner">,
226 workspaceRoot: string,
227): string {
228 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
229 return target.owner ? `${target.owner}/${folderName}` : folderName;
231​
232export function getCloneDestinationBrowsePath(input: {
233 readonly browseDirectoryPath: string;
234 readonly selectedDirectoryName: string;
235 readonly cloneDirectoryName: string;
236 readonly caseSensitive: boolean;
237}): string {
238 const selectedDirectoryPath = appendBrowsePathSegment(
239 input.browseDirectoryPath,
240 input.selectedDirectoryName,
241 );
242 const selectedDirectoryMatches = input.caseSensitive
243 ? input.selectedDirectoryName === input.cloneDirectoryName
244 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
245 return selectedDirectoryMatches
246 ? selectedDirectoryPath
247 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
249​
250export function resolveAddProjectPath(input: {
251 readonly rawPath: string;
252 readonly currentProjectCwd?: string | null;
253 readonly platform: string;
254}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
255 const rawPath = input.rawPath.trim();
256 if (rawPath.length === 0) {
257 return { ok: false, error: "Enter a project path." };
258 }
259 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
260 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
261 }
262 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
263 return { ok: false, error: "Relative paths require an active project in this environment." };
264 }
265 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
266 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
268​
269export function findExistingAddProject(input: {
270 readonly projects: ReadonlyArray<EnvironmentProject>;
271 readonly environmentId: EnvironmentId;
272 readonly path: string;
273}): EnvironmentProject | null {
274 return (
275 findProjectByPath(
276 input.projects.filter((project) => project.environmentId === input.environmentId),
277 input.path,
278 ) ?? null
279 );
281​
282export function buildProjectCreateCommand(input: {
283 readonly commandId: CommandId;
284 readonly projectId: ProjectId;
285 readonly workspaceRoot: string;
286}): Extract<ProjectMutation, { type: "project.create" }> {
287 return {
288 type: "project.create",
289 commandId: input.commandId,
290 projectId: input.projectId,
291 title: inferProjectTitleFromPath(input.workspaceRoot),
292 workspaceRoot: input.workspaceRoot,
293 createWorkspaceRootIfMissing: true,
294 defaultModelSelection: null,
295 };