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