Open History to see the last commit
1import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
2import type {
3 CommandId,
4 EnvironmentId,
5 ProjectMutation,
6 ProjectId,
7 ServerConfig,
8 SourceControlDiscoveryResult,
9 SourceControlProviderKind,
10 SourceControlRepositoryInfo,
11} 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";
27
28export type AddProjectRemoteProviderKind = Extract<
29 SourceControlProviderKind,
30 "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops"
31>;
32export type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
33
34export function canCreateProjectInEnvironment(
35 connectionPhase: EnvironmentConnectionPhase | null | undefined,
36): boolean {
37 return connectionPhase === "connected";
38}
39
40/**
41 * The Scratch folder an environment offers threads without a project right
42 * now, or null while it is not connected or has none.
43 */
44export function availableScratchWorkspaceRoot(
45 connectionPhase: EnvironmentConnectionPhase | null | undefined,
46 serverConfig: Pick<ServerConfig, "scratchWorkspaceRoot"> | null | undefined,
47): string | null {
48 return canCreateProjectInEnvironment(connectionPhase)
49 ? (serverConfig?.scratchWorkspaceRoot ?? null)
50 : null;
51}
52
53export type AddProjectRemoteSourceReadiness = Record<
54 AddProjectRemoteSource,
55 { readonly ready: boolean; readonly hint: string | null }
56>;
57
58export type AddProjectCloneFlow =
59 | {
60 readonly step: "repository";
61 readonly environmentId: EnvironmentId;
62 readonly source: AddProjectRemoteSource;
63 }
64 | {
65 readonly step: "confirm";
66 readonly environmentId: EnvironmentId;
67 readonly source: AddProjectRemoteSource;
68 readonly repositoryInput: string;
69 readonly repository: SourceControlRepositoryInfo | null;
70 readonly remoteUrl: string;
71 };
72
73const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
74 "url",
75 "github",
76 "gitlab",
77 "forgejo",
78 "bitbucket",
79 "azure-devops",
80];
81
82const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
83 "github",
84 "gitlab",
85 "forgejo",
86 "bitbucket",
87 "azure-devops",
88];
89
90export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): string {
91 switch (source) {
92 case "github":
93 return "GitHub";
94 case "forgejo":
95 return "Forgejo / Gitea";
96 case "gitlab":
97 return "GitLab";
98 case "bitbucket":
99 return "Bitbucket";
100 case "azure-devops":
101 return "Azure DevOps";
102 case "url":
103 return "Git URL";
104 }
105}
106
107export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
108 switch (source) {
109 case "forgejo":
110 case "github":
111 return "owner/repo";
112 case "gitlab":
113 return "group/project";
114 case "bitbucket":
115 return "workspace/repository";
116 case "azure-devops":
117 return "project/repository";
118 case "url":
119 return "URL";
120 }
121}
122
123export function addProjectRemoteSourceProvider(
124 source: AddProjectRemoteSource,
125): AddProjectRemoteProviderKind | null {
126 return source === "url" ? null : source;
127}
128
129const GITHUB_REPOSITORY_SHORTHAND =
130 /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
131
132/** Treat the common owner/repository shorthand as a public GitHub HTTPS URL. */
133export function normalizePastedCloneUrl(input: string): string {
134 const trimmed = input.trim();
135 if (!GITHUB_REPOSITORY_SHORTHAND.test(trimmed)) return trimmed;
136 const repository = trimmed.endsWith(".git") ? trimmed : `${trimmed}.git`;
137 return `https://github.com/${repository}`;
138}
139
140/** GitHub and Forgejo default to HTTPS; other providers retain their existing SSH default. */
141export function getDefaultCloneUrl(
142 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
143): string {
144 return repository.provider === "github" || repository.provider === "forgejo"
145 ? repository.url
146 : repository.sshUrl;
147}
148
149export function sortAddProjectProviderSources(
150 readinessBySource: AddProjectRemoteSourceReadiness,
151): ReadonlyArray<AddProjectRemoteProviderKind> {
152 return Arr.sort(
153 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
154 Order.mapInput(
155 Order.Struct({
156 ready: Order.flip(Order.Boolean),
157 label: Order.String,
158 }),
159 (source: AddProjectRemoteProviderKind) => ({
160 ready: readinessBySource[source].ready,
161 label: addProjectRemoteSourceLabel(source),
162 }),
163 ),
164 );
165}
166
167export function buildAddProjectRemoteSourceReadiness(
168 discovery: SourceControlDiscoveryResult | null,
169): AddProjectRemoteSourceReadiness {
170 const unavailable = {
171 ready: false,
172 hint: "Provider status unavailable. Open Source Control settings and rescan.",
173 } as const;
174 const readiness: AddProjectRemoteSourceReadiness = {
175 url: { ready: true, hint: null },
176 github: unavailable,
177 gitlab: unavailable,
178 forgejo: unavailable,
179 bitbucket: unavailable,
180 "azure-devops": unavailable,
181 };
182
183 if (!discovery) {
184 return readiness;
185 }
186
187 const providerByKind = new Map(
188 discovery.sourceControlProviders.map((provider) => [provider.kind, provider]),
189 );
190 for (const source of ADD_PROJECT_REMOTE_SOURCES) {
191 const kind = addProjectRemoteSourceProvider(source);
192 if (!kind) continue;
193 const provider = providerByKind.get(kind);
194 if (!provider) {
195 readiness[source] = unavailable;
196 continue;
197 }
198 if (provider.status !== "available") {
199 readiness[source] = { ready: false, hint: provider.installHint };
200 continue;
201 }
202 if (provider.auth.status === "unauthenticated") {
203 readiness[source] = {
204 ready: false,
205 hint:
206 Option.getOrNull(provider.auth.detail) ??
207 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
208 };
209 continue;
210 }
211 readiness[source] = { ready: true, hint: null };
212 }
213 return readiness;
214}
215
216export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
217 const trimmed = baseDirectory?.trim() ?? "";
218 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
219}
220
221/**
222 * Folder name `git clone` would pick, from either a looked-up repository or a
223 * pasted clone URL. Providers report `owner/repo`, Azure DevOps reports
224 * `org/project/repo`, and a URL can arrive in any form: `https://host/owner/
225 * repo.git`, `ssh://git@host:22/owner/repo`, `git@host:owner/repo.git`, with
226 * or without a query, a fragment or a trailing slash. The repository is always
227 * the last segment, minus the `.git` suffix.
228 */
229export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
230 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
231 const schemeIndex = withoutQuery.indexOf("://");
232 // A remote URL carries a host before the repository path. The host is never
233 // the repository, so a link that stops at the host, or at a port, names
234 // nothing and the destination falls back to the browsed folder.
235 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
236 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
237 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
238 if (hasHost && segments.length < 2) {
239 return "";
240 }
241
242 const lastSegment = segments.at(-1)?.trim() ?? "";
243 // A port can only sit directly behind the authority, so it is a port only
244 // when nothing follows it. Deeper segments are path, even when numeric: the
245 // repository in `https://host/acme/123` really is named `123`.
246 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
247 return "";
248 }
249 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
250}
251
252/**
253 * Clone destination proposed for a directory: the directory the user picked
254 * plus the repository folder inside it. Without a name the directory is the
255 * destination, which is what the raw clone URL flow keeps doing.
256 */
257export function getCloneDestinationPath(
258 directoryPath: string,
259 directoryName: string | null | undefined,
260): string {
261 const name = directoryName?.trim() ?? "";
262 if (name.length === 0) {
263 return directoryPath;
264 }
265 return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
266}
267
268/**
269 * Where `projects.createNew` will put a project named `name`. The server adds
270 * `-2`, `-3`, ... when that folder is taken, so this is a preview.
271 */
272export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
273 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
274}
275
276/**
277 * The GitHub account a new project would be published under, or null when
278 * GitHub is not ready on that environment. A ready GitHub with an unknown
279 * account still publishes; `gh` picks the signed-in user.
280 */
281export function getNewProjectGitHubTarget(
282 discovery: SourceControlDiscoveryResult | null,
283): { readonly account: string | null } | null {
284 if (!buildAddProjectRemoteSourceReadiness(discovery).github.ready) return null;
285 const github = discovery?.sourceControlProviders.find((provider) => provider.kind === "github");
286 return { account: github ? Option.getOrNull(github.auth.account) : null };
287}
288
289/** `owner/folder` for publishing a new project, or just the folder for `gh` to place. */
290export function getNewProjectGitHubRepository(
291 target: { readonly account: string | null },
292 workspaceRoot: string,
293): string {
294 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
295 return target.account ? `${target.account}/${folderName}` : folderName;
296}
297
298/**
299 * Destination query after choosing a directory while the clone folder is
300 * pinned in the path input. Selecting an existing directory with the pinned
301 * name uses that directory directly instead of producing `repo/repo`.
302 */
303export function getCloneDestinationBrowsePath(input: {
304 readonly browseDirectoryPath: string;
305 readonly selectedDirectoryName: string;
306 readonly cloneDirectoryName: string;
307 readonly caseSensitive: boolean;
308}): string {
309 const selectedDirectoryPath = appendBrowsePathSegment(
310 input.browseDirectoryPath,
311 input.selectedDirectoryName,
312 );
313 const selectedDirectoryMatches = input.caseSensitive
314 ? input.selectedDirectoryName === input.cloneDirectoryName
315 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
316 return selectedDirectoryMatches
317 ? selectedDirectoryPath
318 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
319}
320
321export function resolveAddProjectPath(input: {
322 readonly rawPath: string;
323 readonly currentProjectCwd?: string | null;
324 readonly platform: string;
325}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
326 const rawPath = input.rawPath.trim();
327 if (rawPath.length === 0) {
328 return { ok: false, error: "Enter a project path." };
329 }
330 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
331 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
332 }
333 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
334 return { ok: false, error: "Relative paths require an active project in this environment." };
335 }
336 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
337 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
338}
339
340export function findExistingAddProject(input: {
341 readonly projects: ReadonlyArray<EnvironmentProject>;
342 readonly environmentId: EnvironmentId;
343 readonly path: string;
344}): EnvironmentProject | null {
345 return (
346 findProjectByPath(
347 input.projects.filter((project) => project.environmentId === input.environmentId),
348 input.path,
349 ) ?? null
350 );
351}
352
353export function buildProjectCreateCommand(input: {
354 readonly commandId: CommandId;
355 readonly projectId: ProjectId;
356 readonly workspaceRoot: string;
357}): Extract<ProjectMutation, { type: "project.create" }> {
358 return {
359 type: "project.create",
360 commandId: input.commandId,
361 projectId: input.projectId,
362 title: inferProjectTitleFromPath(input.workspaceRoot),
363 workspaceRoot: input.workspaceRoot,
364 createWorkspaceRootIfMissing: true,
365 defaultModelSelection: null,
366 };
367}