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

projects.ts

298 lines9.8 KB

1import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
2import type {
3 CommandId,
4 EnvironmentId,
5 OrchestrationCommand,
6 ProjectId,
7 SourceControlDiscoveryResult,
8 SourceControlProviderKind,
9 SourceControlRepositoryInfo,
10} from "@t3tools/contracts";
11import * as Arr from "effect/Array";
12import * as Option from "effect/Option";
13import * as Order from "effect/Order";
14​
15import {
16 appendBrowsePathSegment,
17 ensureBrowseDirectoryPath,
18 findProjectByPath,
19 inferProjectTitleFromPath,
20 isExplicitRelativeProjectPath,
21 isUnsupportedWindowsProjectPath,
22 resolveProjectPathForDispatch,
23} from "../state/projects.ts";
24import type { EnvironmentProject } from "../state/models.ts";
25​
26export type AddProjectRemoteProviderKind = Extract<
27 SourceControlProviderKind,
28 "github" | "gitlab" | "bitbucket" | "azure-devops"
29>;
30export type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
31​
32export function canCreateProjectInEnvironment(
33 connectionPhase: EnvironmentConnectionPhase | null | undefined,
34): boolean {
35 return connectionPhase === "connected";
37​
38export type AddProjectRemoteSourceReadiness = Record<
39 AddProjectRemoteSource,
40 { readonly ready: boolean; readonly hint: string | null }
41>;
42​
43export type AddProjectCloneFlow =
44 | {
45 readonly step: "repository";
46 readonly environmentId: EnvironmentId;
47 readonly source: AddProjectRemoteSource;
48 }
49 | {
50 readonly step: "confirm";
51 readonly environmentId: EnvironmentId;
52 readonly source: AddProjectRemoteSource;
53 readonly repositoryInput: string;
54 readonly repository: SourceControlRepositoryInfo | null;
55 readonly remoteUrl: string;
56 };
57​
58const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
59 "url",
60 "github",
61 "gitlab",
62 "bitbucket",
63 "azure-devops",
64];
65​
66const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
67 "github",
68 "gitlab",
69 "bitbucket",
70 "azure-devops",
71];
72​
73export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): string {
74 switch (source) {
75 case "github":
76 return "GitHub";
77 case "gitlab":
78 return "GitLab";
79 case "bitbucket":
80 return "Bitbucket";
81 case "azure-devops":
82 return "Azure DevOps";
83 case "url":
84 return "Git URL";
85 }
87​
88export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
89 switch (source) {
90 case "github":
91 return "owner/repo";
92 case "gitlab":
93 return "group/project";
94 case "bitbucket":
95 return "workspace/repository";
96 case "azure-devops":
97 return "project/repository";
98 case "url":
99 return "URL";
100 }
102​
103export function addProjectRemoteSourceProvider(
104 source: AddProjectRemoteSource,
105): AddProjectRemoteProviderKind | null {
106 return source === "url" ? null : source;
108​
109export function sortAddProjectProviderSources(
110 readinessBySource: AddProjectRemoteSourceReadiness,
111): ReadonlyArray<AddProjectRemoteProviderKind> {
112 return Arr.sort(
113 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
114 Order.mapInput(
115 Order.Struct({
116 ready: Order.flip(Order.Boolean),
117 label: Order.String,
118 }),
119 (source: AddProjectRemoteProviderKind) => ({
120 ready: readinessBySource[source].ready,
121 label: addProjectRemoteSourceLabel(source),
122 }),
123 ),
124 );
126​
127export function buildAddProjectRemoteSourceReadiness(
128 discovery: SourceControlDiscoveryResult | null,
129): AddProjectRemoteSourceReadiness {
130 const unavailable = {
131 ready: false,
132 hint: "Provider status unavailable. Open Source Control settings and rescan.",
133 } as const;
134 const readiness: AddProjectRemoteSourceReadiness = {
135 url: { ready: true, hint: null },
136 github: unavailable,
137 gitlab: unavailable,
138 bitbucket: unavailable,
139 "azure-devops": unavailable,
140 };
141​
142 if (!discovery) {
143 return readiness;
144 }
145​
146 const providerByKind = new Map(
147 discovery.sourceControlProviders.map((provider) => [provider.kind, provider]),
148 );
149 for (const source of ADD_PROJECT_REMOTE_SOURCES) {
150 const kind = addProjectRemoteSourceProvider(source);
151 if (!kind) continue;
152 const provider = providerByKind.get(kind);
153 if (!provider) {
154 readiness[source] = unavailable;
155 continue;
156 }
157 if (provider.status !== "available") {
158 readiness[source] = { ready: false, hint: provider.installHint };
159 continue;
160 }
161 if (provider.auth.status === "unauthenticated") {
162 readiness[source] = {
163 ready: false,
164 hint:
165 Option.getOrNull(provider.auth.detail) ??
166 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
167 };
168 continue;
169 }
170 readiness[source] = { ready: true, hint: null };
171 }
172 return readiness;
174​
175export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
176 const trimmed = baseDirectory?.trim() ?? "";
177 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
179​
180/**
181 * Folder name `git clone` would pick, from either a looked-up repository or a
182 * pasted clone URL. Providers report `owner/repo`, Azure DevOps reports
183 * `org/project/repo`, and a URL can arrive in any form: `https://host/owner/
184 * repo.git`, `ssh://git@host:22/owner/repo`, `git@host:owner/repo.git`, with
185 * or without a query, a fragment or a trailing slash. The repository is always
186 * the last segment, minus the `.git` suffix.
187 */
188export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
189 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
190 const schemeIndex = withoutQuery.indexOf("://");
191 // A remote URL carries a host before the repository path. The host is never
192 // the repository, so a link that stops at the host, or at a port, names
193 // nothing and the destination falls back to the browsed folder.
194 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
195 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
196 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
197 if (hasHost && segments.length < 2) {
198 return "";
199 }
200​
201 const lastSegment = segments.at(-1)?.trim() ?? "";
202 // A port can only sit directly behind the authority, so it is a port only
203 // when nothing follows it. Deeper segments are path, even when numeric: the
204 // repository in `https://host/acme/123` really is named `123`.
205 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
206 return "";
207 }
208 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
210​
211/**
212 * Clone destination proposed for a directory: the directory the user picked
213 * plus the repository folder inside it. Without a name the directory is the
214 * destination, which is what the raw clone URL flow keeps doing.
215 */
216export function getCloneDestinationPath(
217 directoryPath: string,
218 directoryName: string | null | undefined,
219): string {
220 const name = directoryName?.trim() ?? "";
221 if (name.length === 0) {
222 return directoryPath;
223 }
224 return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
226​
227/**
228 * Destination query after choosing a directory while the clone folder is
229 * pinned in the path input. Selecting an existing directory with the pinned
230 * name uses that directory directly instead of producing `repo/repo`.
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 readonly createdAt: string;
287}): Extract<OrchestrationCommand, { type: "project.create" }> {
288 return {
289 type: "project.create",
290 commandId: input.commandId,
291 projectId: input.projectId,
292 title: inferProjectTitleFromPath(input.workspaceRoot),
293 workspaceRoot: input.workspaceRoot,
294 createWorkspaceRootIfMissing: true,
295 defaultModelSelection: null,
296 createdAt: input.createdAt,
297 };