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