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