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