Open History to see the last commit
1import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
2import type {
3 CommandId,
4 EnvironmentId,
5 ProjectMutation,
6 ProjectTrackedFolder,
7 ProjectId,
8 ServerConfig,
9 ServerSettings,
10 SourceControlDiscoveryResult,
11 SourceControlRepositoryInfo,
12} from "@t3tools/contracts";
13import { SourceControlProviderKind } from "@t3tools/contracts";
14import {
15 cloneUrlRepositoryPath,
16 isScpLikeCloneUrl,
17 withoutScpQuery,
18} from "@t3tools/shared/cloneUrl";
19import {
20 isAbsolutePath,
21 isExplicitRelativePath,
22 isHostPath,
23 newProjectFolderName,
24} from "@t3tools/shared/path";
25import * as Arr from "effect/Array";
26import * as Option from "effect/Option";
27import * as Order from "effect/Order";
28
29import {
30 appendBrowsePathSegment,
31 ensureBrowseDirectoryPath,
32 findProjectByPath,
33 getBrowseParentPath,
34 inferProjectTitleFromPath,
35 isExplicitRelativeProjectPath,
36 isUnsupportedWindowsProjectPath,
37 resolveProjectPathForDispatch,
38} from "../state/projects.ts";
39import type { EnvironmentProject } from "../state/models.ts";
40import { sourceControlClients } from "../sourceControlClients.ts";
41import type { SourceControlDefinition } from "../sourceControlClients.ts";
42import { mFallback, msg } from "gt-i18n";
43import type { MFunctionType } from "gt-i18n/types";
44import { sourceControlInstallHintText } from "../contractLabels.ts";
45
46export type AddProjectRemoteSource = SourceControlProviderKind | "url";
47
48export function canCreateProjectInEnvironment(
49 connectionPhase: EnvironmentConnectionPhase | null | undefined,
50): boolean {
51 return connectionPhase === "connected";
52}
53
54export function availableScratchWorkspaceRoot(
55 connectionPhase: EnvironmentConnectionPhase | null | undefined,
56 serverConfig: Pick<ServerConfig, "scratchWorkspaceRoot"> | null | undefined,
57): string | null {
58 return canCreateProjectInEnvironment(connectionPhase)
59 ? (serverConfig?.scratchWorkspaceRoot ?? null)
60 : null;
61}
62
63export interface AddProjectRemoteSourceReadinessEntry {
64 readonly ready: boolean;
65 readonly hint: string | null;
66}
67
68export type AddProjectRemoteSourceReadiness = (
69 source: AddProjectRemoteSource,
70) => AddProjectRemoteSourceReadinessEntry;
71
72export type AddProjectCloneFlow =
73 | {
74 readonly step: "repository";
75 readonly environmentId: EnvironmentId;
76 readonly source: AddProjectRemoteSource;
77 }
78 | {
79 readonly step: "confirm";
80 readonly environmentId: EnvironmentId;
81 readonly source: AddProjectRemoteSource;
82 readonly repositoryInput: string;
83 readonly repository: SourceControlRepositoryInfo | null;
84 readonly remoteUrl: string;
85 };
86
87const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<SourceControlProviderKind> =
88 sourceControlClients.definitions.map((definition) => definition.kind);
89
90export function addProjectRemoteSourceLabel(
91 source: AddProjectRemoteSource,
92 resolve: MFunctionType = mFallback,
93): string {
94 return source === "url" ? resolve(msg("Git URL")) : sourceControlClients.get(source).pickerLabel;
95}
96
97export function addProjectRemoteSourcePathHint(
98 source: AddProjectRemoteSource,
99 resolve: MFunctionType = mFallback,
100): string {
101 return source === "url"
102 ? resolve(msg("URL", { $context: "placeholder for a git URL field" }))
103 : sourceControlClients.get(source).repositoryPathHint;
104}
105
106export function addProjectRemoteSourceProvider(
107 source: AddProjectRemoteSource,
108): SourceControlProviderKind | null {
109 return source === "url" ? null : source;
110}
111
112export function parseAddProjectRemoteSource(
113 value: string | null | undefined,
114): AddProjectRemoteSource {
115 return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
116}
117
118const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
119
120/**
121 * The clone URL of `owner/name` on the public host of the host a repository reads as before it
122 * reports one. Null when that host has no public host.
123 */
124export function defaultHostCloneUrl(repository: string): string | null {
125 const definition = sourceControlClients.get(undefined);
126 if (definition.publicHost === null) return null;
127 const path = repository.endsWith(".git") ? repository : `${repository}.git`;
128 return definition.defaultCloneTransport === "https"
129 ? `https://${definition.publicHost}/${path}`
130 : `git@${definition.publicHost}:${path}`;
131}
132
133/** Owner present, repository name missing: `owner/` or `owner//`. */
134const INCOMPLETE_GITHUB_OWNER_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})\/+$/;
135
136/**
137 * Message to show when a GitHub add-project field is only `owner/`.
138 * Lookup would send that to GitHub and come back as a generic failure.
139 * Returns null for complete names, bare repo names, URLs, and other sources.
140 */
141export function githubIncompleteOwnerRepositoryMessage(
142 source: AddProjectRemoteSource,
143 input: string,
144 resolve: MFunctionType = mFallback,
145): string | null {
146 if (source !== "github") return null;
147 if (!INCOMPLETE_GITHUB_OWNER_PATH.test(input.trim())) return null;
148 return resolve(msg("Enter the full owner/repository name."));
149}
150
151export function normalizePastedCloneUrl(input: string): string {
152 const trimmed = input.trim();
153 if (REPOSITORY_SHORTHAND.test(trimmed)) return defaultHostCloneUrl(trimmed) ?? trimmed;
154 return sourceControlClients.repositoryUrlFromPage(trimmed) ?? trimmed;
155}
156
157export function getDefaultCloneUrl(
158 repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,
159): string {
160 return sourceControlClients.get(repository.provider).defaultCloneTransport === "https"
161 ? repository.url
162 : repository.sshUrl;
163}
164
165export type OfferedSourceControlProviders = ServerSettings["offeredSourceControlProviders"];
166
167/** Whether the project pickers offer a host. Only the default host is on until the user turns others on. */
168export function isSourceControlProviderOffered(
169 offered: OfferedSourceControlProviders | undefined,
170 kind: SourceControlProviderKind,
171): boolean {
172 return offered?.[kind] ?? kind === sourceControlClients.get(undefined).kind;
173}
174
175export function sortAddProjectProviderSources(
176 readiness: AddProjectRemoteSourceReadiness,
177 offered: OfferedSourceControlProviders | undefined,
178): ReadonlyArray<SourceControlProviderKind> {
179 return Arr.sort(
180 ADD_PROJECT_REMOTE_PROVIDER_SOURCES.filter((source) =>
181 isSourceControlProviderOffered(offered, source),
182 ),
183 Order.mapInput(
184 Order.Struct({
185 ready: Order.flip(Order.Boolean),
186 label: Order.String,
187 }),
188 (source: SourceControlProviderKind) => ({
189 ready: readiness(source).ready,
190 label: addProjectRemoteSourceLabel(source),
191 }),
192 ),
193 );
194}
195
196const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null };
197const UNAVAILABLE_HINT = msg(
198 "Provider status unavailable. Open Source Control settings and rescan.",
199);
200
201export function buildAddProjectRemoteSourceReadiness(
202 discovery: SourceControlDiscoveryResult | null,
203 resolve: MFunctionType = mFallback,
204): AddProjectRemoteSourceReadiness {
205 const providerByKind = new Map(
206 (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]),
207 );
208 return (source) => {
209 if (source === "url") return READY;
210 const provider = providerByKind.get(source);
211 if (!provider) return { ready: false, hint: resolve(UNAVAILABLE_HINT) };
212 if (provider.status !== "available") {
213 return { ready: false, hint: sourceControlInstallHintText(provider.installHint, resolve) };
214 }
215 if (provider.auth.status === "unauthenticated") {
216 return {
217 ready: false,
218 hint:
219 Option.getOrNull(provider.auth.detail) ??
220 resolve(
221 msg(
222 "{provider} is not authenticated. Open Source Control settings for setup guidance.",
223 { provider: provider.label },
224 ),
225 ),
226 };
227 }
228 return READY;
229 };
230}
231
232export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string {
233 const trimmed = baseDirectory?.trim() ?? "";
234 if (trimmed.length === 0) return "~/";
235 // A bare relative setting such as `Desktop/dev` means a folder under home. The browser
236 // navigates `~/` but not `~\` home paths.
237 const isAnchored =
238 trimmed === "~" ||
239 isAbsolutePath(trimmed) ||
240 trimmed.startsWith("~/") ||
241 isExplicitRelativePath(trimmed);
242 return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`);
243}
244
245export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string {
246 const trimmed = (repositoryOrRemoteUrl ?? "").trim();
247 // Local paths keep both delimiters. SCP paths keep a literal # in the repository name.
248 const isLocalPath =
249 !trimmed.includes("://") && (isHostPath(trimmed) || isExplicitRelativePath(trimmed));
250 const withoutQuery = isLocalPath
251 ? trimmed
252 : isScpLikeCloneUrl(trimmed)
253 ? withoutScpQuery(trimmed)
254 : trimmed.split(/[?#]/, 1)[0]!;
255 const schemeIndex = withoutQuery.indexOf("://");
256 const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery);
257 const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery;
258 const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0);
259 if (hasHost && segments.length < 2) {
260 return "";
261 }
262
263 const lastSegment = segments.at(-1)?.trim() ?? "";
264 if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) {
265 return "";
266 }
267 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
268}
269
270/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
271export function getCloneDirectoryPath(
272 remoteUrl: string,
273 ghqCloneLayout: boolean,
274 repository = remoteUrl,
275): string {
276 return (
277 (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
278 );
279}
280
281/** The clone's own folder, which folder browsing keeps at the end of the destination. */
282export function getCloneDirectoryLeafName(
283 remoteUrl: string,
284 ghqCloneLayout: boolean,
285 repository = remoteUrl,
286): string {
287 return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
288}
289
290export function getCloneDestinationPath(
291 directoryPath: string,
292 directoryName: string | null | undefined,
293): string {
294 const name = directoryName?.trim() ?? "";
295 if (name.length === 0) {
296 return directoryPath;
297 }
298 const base = ensureBrowseDirectoryPath(directoryPath);
299 return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
300}
301
302export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
303 return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name));
304}
305
306export interface NewProjectPublishTarget {
307 readonly definition: SourceControlDefinition;
308 readonly owner: string | null;
309}
310
311export function getNewProjectPublishTargets(
312 discovery: SourceControlDiscoveryResult | null,
313 offered: OfferedSourceControlProviders | undefined,
314): ReadonlyArray<NewProjectPublishTarget> {
315 const readiness = buildAddProjectRemoteSourceReadiness(discovery);
316 return sourceControlClients.definitions.flatMap((definition) => {
317 if (!isSourceControlProviderOffered(offered, definition.kind)) return [];
318 if (!readiness(definition.kind).ready) return [];
319 const provider = discovery?.sourceControlProviders.find(
320 (candidate) => candidate.kind === definition.kind,
321 );
322 const placement = definition.newRepositoryOwner(
323 provider ? Option.getOrNull(provider.auth.account) : null,
324 );
325 return placement === null ? [] : [{ definition, owner: placement.owner }];
326 });
327}
328
329export function getNewProjectPublishTarget(
330 targets: ReadonlyArray<NewProjectPublishTarget>,
331 kind: SourceControlProviderKind | null,
332): NewProjectPublishTarget | null {
333 return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null;
334}
335
336export function getNewProjectRepository(
337 target: Pick<NewProjectPublishTarget, "owner">,
338 workspaceRoot: string,
339): string {
340 const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? "";
341 return target.owner ? `${target.owner}/${folderName}` : folderName;
342}
343
344export function getCloneDestinationBrowsePath(input: {
345 readonly browseDirectoryPath: string;
346 readonly selectedDirectoryName: string;
347 readonly cloneDirectoryName: string;
348 readonly caseSensitive: boolean;
349}): string {
350 const selectedDirectoryPath = appendBrowsePathSegment(
351 input.browseDirectoryPath,
352 input.selectedDirectoryName,
353 );
354 const selectedDirectoryMatches = input.caseSensitive
355 ? input.selectedDirectoryName === input.cloneDirectoryName
356 : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase();
357 return selectedDirectoryMatches
358 ? selectedDirectoryPath
359 : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName);
360}
361
362// The native picker returns a full path, not a name under the browsed directory.
363// Split it and reuse the in-app rules so a folder already named after the
364// repository stays that folder instead of becoming repo/repo.
365export function getCloneDestinationForPickedFolder(input: {
366 readonly pickedPath: string;
367 readonly cloneDirectoryName: string;
368 readonly caseSensitive: boolean;
369}): string {
370 const parentPath = getBrowseParentPath(input.pickedPath);
371 if (parentPath === null) {
372 return getCloneDestinationPath(input.pickedPath, input.cloneDirectoryName);
373 }
374 return getCloneDestinationBrowsePath({
375 browseDirectoryPath: parentPath,
376 selectedDirectoryName: inferProjectTitleFromPath(input.pickedPath),
377 cloneDirectoryName: input.cloneDirectoryName,
378 caseSensitive: input.caseSensitive,
379 });
380}
381
382export function resolveAddProjectPath(
383 input: {
384 readonly rawPath: string;
385 readonly currentProjectCwd?: string | null;
386 readonly platform: string;
387 },
388 resolve: MFunctionType = mFallback,
389): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } {
390 const rawPath = input.rawPath.trim();
391 if (rawPath.length === 0) {
392 return { ok: false, error: resolve(msg("Enter a project path.")) };
393 }
394 if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) {
395 return {
396 ok: false,
397 error: resolve(msg("Windows-style paths are only supported on Windows environments.")),
398 };
399 }
400 if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) {
401 return {
402 ok: false,
403 error: resolve(msg("Relative paths require an active project in this environment.")),
404 };
405 }
406 const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd);
407 return path.length === 0
408 ? { ok: false, error: resolve(msg("Enter a project path.")) }
409 : { ok: true, path };
410}
411
412export function findExistingAddProject(input: {
413 readonly projects: ReadonlyArray<EnvironmentProject>;
414 readonly environmentId: EnvironmentId;
415 readonly path: string;
416}): EnvironmentProject | null {
417 return (
418 findProjectByPath(
419 input.projects.filter((project) => project.environmentId === input.environmentId),
420 input.path,
421 ) ?? null
422 );
423}
424
425export function buildProjectCreateCommand(input: {
426 readonly commandId: CommandId;
427 readonly projectId: ProjectId;
428 readonly workspaceRoot: string;
429 readonly trackedFolders?: ReadonlyArray<ProjectTrackedFolder>;
430}): Extract<ProjectMutation, { type: "project.create" }> {
431 return {
432 type: "project.create",
433 commandId: input.commandId,
434 projectId: input.projectId,
435 title: inferProjectTitleFromPath(input.workspaceRoot),
436 workspaceRoot: input.workspaceRoot,
437 createWorkspaceRootIfMissing: true,
438 defaultModelSelection: null,
439 ...(input.trackedFolders === undefined || input.trackedFolders.length === 0
440 ? {}
441 : { trackedFolders: input.trackedFolders }),
442 };
443}