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 SourceControlRepositoryInfo,
10} from "@t3tools/contracts";
11import { SourceControlProviderKind } from "@t3tools/contracts";
12import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl";
13import { newProjectFolderName } from "@t3tools/shared/path";
14import * as Arr from "effect/Array";
15import * as Option from "effect/Option";
16import * as Order from "effect/Order";
17
18import {
19 appendBrowsePathSegment,
20 ensureBrowseDirectoryPath,
21 findProjectByPath,
22 getBrowseParentPath,
23 inferProjectTitleFromPath,
24 isExplicitRelativeProjectPath,
25 isUnsupportedWindowsProjectPath,
26 resolveProjectPathForDispatch,
27} from "../state/projects.ts";
28import type { EnvironmentProject } from "../state/models.ts";
29import { sourceControlClients } from "../sourceControlClients.ts";
30import type { SourceControlDefinition } from "../sourceControlClients.ts";
31
32export type AddProjectRemoteSource = SourceControlProviderKind | "url";
33
34export function canCreateProjectInEnvironment(
35 connectionPhase: EnvironmentConnectionPhase | null | undefined,
36): boolean {
37 return connectionPhase === "connected";
38}
39
40export function availableScratchWorkspaceRoot(
41 connectionPhase: EnvironmentConnectionPhase | null | undefined,
42 serverConfig: Pick<ServerConfig, "scratchWorkspaceRoot"> | null | undefined,
43): string | null {
44 return canCreateProjectInEnvironment(connectionPhase)
45 ? (serverConfig?.scratchWorkspaceRoot ?? null)
46 : null;
47}
48
49export interface AddProjectRemoteSourceReadinessEntry {
50 readonly ready: boolean;
51 readonly hint: string | null;
52}
53
54export type AddProjectRemoteSourceReadiness = (
55 source: AddProjectRemoteSource,
56) => AddProjectRemoteSourceReadinessEntry;
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_PROVIDER_SOURCES: ReadonlyArray<SourceControlProviderKind> =
74 sourceControlClients.definitions.map((definition) => definition.kind);
75
76export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): string {
77 return source === "url" ? "Git URL" : sourceControlClients.get(source).pickerLabel;
78}
79
80export function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {
81 return source === "url" ? "URL" : sourceControlClients.get(source).repositoryPathHint;
82}
83
84export function addProjectRemoteSourceProvider(
85 source: AddProjectRemoteSource,
86): SourceControlProviderKind | null {
87 return source === "url" ? null : source;
88}
89
90export function parseAddProjectRemoteSource(
91 value: string | null | undefined,
92): AddProjectRemoteSource {
93 return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
94}
95
96const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
97
98/**
99 * The clone URL of `owner/name` on the public host of the host a repository reads as before it
100 * reports one. Null when that host has no public host.
101 */
102export function defaultHostCloneUrl(repository: string): string | null {
103 const definition = sourceControlClients.get(undefined);
104 if (definition.publicHost === null) return null;
105 const path = repository.endsWith(".git") ? repository : `${repository}.git`;
106 return definition.defaultCloneTransport === "https"
107 ? `https://${definition.publicHost}/${path}`
108 : `git@${definition.publicHost}:${path}`;
109}
110
111/** Owner present, repository name missing: `owner/` or `owner//`. */
112const INCOMPLETE_GITHUB_OWNER_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})\/+$/;
113
114const INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE = "Enter the full owner/repository name.";
115
116/**
117 * Message to show when a GitHub add-project field is only `owner/`.
118 * Lookup would send that to GitHub and come back as a generic failure.
119 * Returns null for complete names, bare repo names, URLs, and other sources.
120 */
121export function githubIncompleteOwnerRepositoryMessage(
122 source: AddProjectRemoteSource,
123 input: string,
124): string | null {
125 if (source !== "github") return null;
126 if (!INCOMPLETE_GITHUB_OWNER_PATH.test(input.trim())) return null;
127 return INCOMPLETE_GITHUB_OWNER_REPOSITORY_MESSAGE;
128}
129
130export function normalizePastedCloneUrl(input: string): string {
131 const trimmed = input.trim();
132 if (REPOSITORY_SHORTHAND.test(trimmed)) return defaultHostCloneUrl(trimmed) ?? trimmed;
133 return sourceControlClients.repositoryUrlFromPage(trimmed) ?? trimmed;
134}
135
136export function getDefaultCloneUrl(
137 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
138): string {
139 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
140 ? repository.url
141 : repository.sshUrl;
142}
143
144export function sortAddProjectProviderSources(
145 readiness: AddProjectRemoteSourceReadiness,
146): ReadonlyArray<SourceControlProviderKind> {
147 return Arr.sort(
148 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
149 Order.mapInput(
150 Order.Struct({
151 ready: Order.flip(Order.Boolean),
152 label: Order.String,
153 }),
154 (source: SourceControlProviderKind) => ({
155 ready: readiness(source).ready,
156 label: addProjectRemoteSourceLabel(source),
157 }),
158 ),
159 );
160}
161
162const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
163const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
164 ready: false,
165 hint: "Provider status unavailable. Open Source Control settings and rescan.",
166};
167
168export function buildAddProjectRemoteSourceReadiness(
169 discovery: SourceControlDiscoveryResult | null,
170): AddProjectRemoteSourceReadiness {
171 const providerByKind = new Map(
172 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
173 );
174 return (source) => {
175 if (source === "url") return READY;
176 const provider = providerByKind.get(source);
177 if (!provider) return UNAVAILABLE;
178 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
179 if (provider.auth.status === "unauthenticated") {
180 return {
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 }
187 return READY;
188 };
189}
190
191export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
192 const trimmed = baseDirectory?.trim() ?? "";
193 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
194}
195
196export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
197 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
198 const schemeIndex = withoutQuery.indexOf("://");
199 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
200 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
201 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
202 if (hasHost && segments.length < 2) {
203 return "";
204 }
205
206 const lastSegment = segments.at(-1)?.trim() ?? "";
207 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
208 return "";
209 }
210 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
211}
212
213/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
214export function getCloneDirectoryPath(
215 remoteUrl: string,
216 ghqCloneLayout: boolean,
217 repository = remoteUrl,
218): string {
219 return (
220 (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
221 );
222}
223
224/** The clone's own folder, which folder browsing keeps at the end of the destination. */
225export function getCloneDirectoryLeafName(
226 remoteUrl: string,
227 ghqCloneLayout: boolean,
228 repository = remoteUrl,
229): string {
230 return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
231}
232
233export function getCloneDestinationPath(
234 directoryPath: string,
235 directoryName: string | null | undefined,
236): string {
237 const name = directoryName?.trim() ?? "";
238 if (name.length === 0) {
239 return directoryPath;
240 }
241 const base = ensureBrowseDirectoryPath(directoryPath);
242 return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
243}
244
245export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
246 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
247}
248
249export interface NewProjectPublishTarget {
250 readonly definition: SourceControlDefinition;
251 readonly owner: string | null;
252}
253
254export function getNewProjectPublishTargets(
255 discovery: SourceControlDiscoveryResult | null,
256): ReadonlyArray<NewProjectPublishTarget> {
257 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
258 return sourceControlClients.definitions.flatMap((definition) => {
259 if (!readiness(definition.kind).ready) return [];
260 const provider = discovery?.sourceControlProviders.find(
261 (candidate) => candidate.kind === definition.kind,
262 );
263 const placement = definition.newRepositoryOwner(
264 provider ? Option.getOrNull(provider.auth.account) : null,
265 );
266 return placement === null ? [] : [{ definition, owner: placement.owner }];
267 });
268}
269
270export function getNewProjectPublishTarget(
271 targets: ReadonlyArray<NewProjectPublishTarget>,
272 kind: SourceControlProviderKind | null,
273): NewProjectPublishTarget | null {
274 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
275}
276
277export function getNewProjectRepository(
278 target: Pick<NewProjectPublishTarget, "owner">,
279 workspaceRoot: string,
280): string {
281 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
282 return target.owner ? `${target.owner}/${folderName}` : folderName;
283}
284
285export function getCloneDestinationBrowsePath(input: {
286 readonly browseDirectoryPath: string;
287 readonly selectedDirectoryName: string;
288 readonly cloneDirectoryName: string;
289 readonly caseSensitive: boolean;
290}): string {
291 const selectedDirectoryPath = appendBrowsePathSegment(
292 input.browseDirectoryPath,
293 input.selectedDirectoryName,
294 );
295 const selectedDirectoryMatches = input.caseSensitive
296 ? input.selectedDirectoryName === input.cloneDirectoryName
297 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
298 return selectedDirectoryMatches
299 ? selectedDirectoryPath
300 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
301}
302
303// The native picker returns a full path, not a name under the browsed directory.
304// Split it and reuse the in-app rules so a folder already named after the
305// repository stays that folder instead of becoming repo/repo.
306export function getCloneDestinationForPickedFolder(input: {
307 readonly pickedPath: string;
308 readonly cloneDirectoryName: string;
309 readonly caseSensitive: boolean;
310}): string {
311 const parentPath = getBrowseParentPath(input.pickedPath);
312 if (parentPath === null) {
313 return getCloneDestinationPath(input.pickedPath, input.cloneDirectoryName);
314 }
315 return getCloneDestinationBrowsePath({
316 browseDirectoryPath: parentPath,
317 selectedDirectoryName: inferProjectTitleFromPath(input.pickedPath),
318 cloneDirectoryName: input.cloneDirectoryName,
319 caseSensitive: input.caseSensitive,
320 });
321}
322
323export function resolveAddProjectPath(input: {
324 readonly rawPath: string;
325 readonly currentProjectCwd?: string | null;
326 readonly platform: string;
327}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
328 const rawPath = input.rawPath.trim();
329 if (rawPath.length === 0) {
330 return { ok: false, error: "Enter a project path." };
331 }
332 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
333 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
334 }
335 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
336 return { ok: false, error: "Relative paths require an active project in this environment." };
337 }
338 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
339 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
340}
341
342export function findExistingAddProject(input: {
343 readonly projects: ReadonlyArray<EnvironmentProject>;
344 readonly environmentId: EnvironmentId;
345 readonly path: string;
346}): EnvironmentProject | null {
347 return (
348 findProjectByPath(
349 input.projects.filter((project) => project.environmentId === input.environmentId),
350 input.path,
351 ) ?? null
352 );
353}
354
355export function buildProjectCreateCommand(input: {
356 readonly commandId: CommandId;
357 readonly projectId: ProjectId;
358 readonly workspaceRoot: string;
359}): Extract<ProjectMutation, { type: "project.create" }> {
360 return {
361 type: "project.create",
362 commandId: input.commandId,
363 projectId: input.projectId,
364 title: inferProjectTitleFromPath(input.workspaceRoot),
365 workspaceRoot: input.workspaceRoot,
366 createWorkspaceRootIfMissing: true,
367 defaultModelSelection: null,
368 };
369}