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 return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed;
132}
133
134export function getDefaultCloneUrl(
135 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
136): string {
137 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
138 ? repository.url
139 : repository.sshUrl;
140}
141
142export function sortAddProjectProviderSources(
143 readiness: AddProjectRemoteSourceReadiness,
144): ReadonlyArray<SourceControlProviderKind> {
145 return Arr.sort(
146 ADD_PROJECT_REMOTE_PROVIDER_SOURCES,
147 Order.mapInput(
148 Order.Struct({
149 ready: Order.flip(Order.Boolean),
150 label: Order.String,
151 }),
152 (source: SourceControlProviderKind) => ({
153 ready: readiness(source).ready,
154 label: addProjectRemoteSourceLabel(source),
155 }),
156 ),
157 );
158}
159
160const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
161const UNAVAILABLE: AddProjectRemoteSourceReadinessEntry = {
162 ready: false,
163 hint: "Provider status unavailable. Open Source Control settings and rescan.",
164};
165
166export function buildAddProjectRemoteSourceReadiness(
167 discovery: SourceControlDiscoveryResult | null,
168): AddProjectRemoteSourceReadiness {
169 const providerByKind = new Map(
170 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
171 );
172 return (source) => {
173 if (source === "url") return READY;
174 const provider = providerByKind.get(source);
175 if (!provider) return UNAVAILABLE;
176 if (provider.status !== "available") return { ready: false, hint: provider.installHint };
177 if (provider.auth.status === "unauthenticated") {
178 return {
179 ready: false,
180 hint:
181 Option.getOrNull(provider.auth.detail) ??
182 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,
183 };
184 }
185 return READY;
186 };
187}
188
189export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
190 const trimmed = baseDirectory?.trim() ?? "";
191 return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
192}
193
194export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
195 const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? "";
196 const schemeIndex = withoutQuery.indexOf("://");
197 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
198 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
199 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
200 if (hasHost && segments.length < 2) {
201 return "";
202 }
203
204 const lastSegment = segments.at(-1)?.trim() ?? "";
205 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
206 return "";
207 }
208 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
209}
210
211/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
212export function getCloneDirectoryPath(
213 remoteUrl: string,
214 ghqCloneLayout: boolean,
215 repository = remoteUrl,
216): string {
217 return (
218 (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
219 );
220}
221
222/** The clone's own folder, which folder browsing keeps at the end of the destination. */
223export function getCloneDirectoryLeafName(
224 remoteUrl: string,
225 ghqCloneLayout: boolean,
226 repository = remoteUrl,
227): string {
228 return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
229}
230
231export function getCloneDestinationPath(
232 directoryPath: string,
233 directoryName: string | null | undefined,
234): string {
235 const name = directoryName?.trim() ?? "";
236 if (name.length === 0) {
237 return directoryPath;
238 }
239 const base = ensureBrowseDirectoryPath(directoryPath);
240 return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
241}
242
243export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
244 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
245}
246
247export interface NewProjectPublishTarget {
248 readonly definition: SourceControlDefinition;
249 readonly owner: string | null;
250}
251
252export function getNewProjectPublishTargets(
253 discovery: SourceControlDiscoveryResult | null,
254): ReadonlyArray<NewProjectPublishTarget> {
255 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
256 return sourceControlClients.definitions.flatMap((definition) => {
257 if (!readiness(definition.kind).ready) return [];
258 const provider = discovery?.sourceControlProviders.find(
259 (candidate) => candidate.kind === definition.kind,
260 );
261 const placement = definition.newRepositoryOwner(
262 provider ? Option.getOrNull(provider.auth.account) : null,
263 );
264 return placement === null ? [] : [{ definition, owner: placement.owner }];
265 });
266}
267
268export function getNewProjectPublishTarget(
269 targets: ReadonlyArray<NewProjectPublishTarget>,
270 kind: SourceControlProviderKind | null,
271): NewProjectPublishTarget | null {
272 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
273}
274
275export function getNewProjectRepository(
276 target: Pick<NewProjectPublishTarget, "owner">,
277 workspaceRoot: string,
278): string {
279 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
280 return target.owner ? `${target.owner}/${folderName}` : folderName;
281}
282
283export function getCloneDestinationBrowsePath(input: {
284 readonly browseDirectoryPath: string;
285 readonly selectedDirectoryName: string;
286 readonly cloneDirectoryName: string;
287 readonly caseSensitive: boolean;
288}): string {
289 const selectedDirectoryPath = appendBrowsePathSegment(
290 input.browseDirectoryPath,
291 input.selectedDirectoryName,
292 );
293 const selectedDirectoryMatches = input.caseSensitive
294 ? input.selectedDirectoryName === input.cloneDirectoryName
295 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
296 return selectedDirectoryMatches
297 ? selectedDirectoryPath
298 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
299}
300
301export function resolveAddProjectPath(input: {
302 readonly rawPath: string;
303 readonly currentProjectCwd?: string | null;
304 readonly platform: string;
305}): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
306 const rawPath = input.rawPath.trim();
307 if (rawPath.length === 0) {
308 return { ok: false, error: "Enter a project path." };
309 }
310 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
311 return { ok: false, error: "Windows-style paths are only supported on Windows environments." };
312 }
313 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
314 return { ok: false, error: "Relative paths require an active project in this environment." };
315 }
316 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
317 return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path };
318}
319
320export function findExistingAddProject(input: {
321 readonly projects: ReadonlyArray<EnvironmentProject>;
322 readonly environmentId: EnvironmentId;
323 readonly path: string;
324}): EnvironmentProject | null {
325 return (
326 findProjectByPath(
327 input.projects.filter((project) => project.environmentId === input.environmentId),
328 input.path,
329 ) ?? null
330 );
331}
332
333export function buildProjectCreateCommand(input: {
334 readonly commandId: CommandId;
335 readonly projectId: ProjectId;
336 readonly workspaceRoot: string;
337}): Extract<ProjectMutation, { type: "project.create" }> {
338 return {
339 type: "project.create",
340 commandId: input.commandId,
341 projectId: input.projectId,
342 title: inferProjectTitleFromPath(input.workspaceRoot),
343 workspaceRoot: input.workspaceRoot,
344 createWorkspaceRootIfMissing: true,
345 defaultModelSelection: null,
346 };
347}