import type { EnvironmentConnectionPhase } from "../connection/presentation.ts"; import type { CommandId, EnvironmentId, ProjectMutation, ProjectTrackedFolder, ProjectId, ServerConfig, ServerSettings, SourceControlDiscoveryResult, SourceControlRepositoryInfo, } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath, isScpLikeCloneUrl } from "@t3tools/shared/cloneUrl"; import { isAbsolutePath, isExplicitRelativePath, isHostPath, newProjectFolderName, } from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; import { appendBrowsePathSegment, ensureBrowseDirectoryPath, findProjectByPath, getBrowseParentPath, inferProjectTitleFromPath, isExplicitRelativeProjectPath, isUnsupportedWindowsProjectPath, resolveProjectPathForDispatch, } from "../state/projects.ts"; import type { EnvironmentProject } from "../state/models.ts"; import { sourceControlClients } from "../sourceControlClients.ts"; import type { SourceControlDefinition } from "../sourceControlClients.ts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; import { sourceControlInstallHintText } from "../contractLabels.ts"; export type AddProjectRemoteSource = SourceControlProviderKind | "url"; export function canCreateProjectInEnvironment( connectionPhase: EnvironmentConnectionPhase | null | undefined, ): boolean { return connectionPhase === "connected"; } export function availableScratchWorkspaceRoot( connectionPhase: EnvironmentConnectionPhase | null | undefined, serverConfig: Pick | null | undefined, ): string | null { return canCreateProjectInEnvironment(connectionPhase) ? (serverConfig?.scratchWorkspaceRoot ?? null) : null; } export interface AddProjectRemoteSourceReadinessEntry { readonly ready: boolean; readonly hint: string | null; } export type AddProjectRemoteSourceReadiness = ( source: AddProjectRemoteSource, ) => AddProjectRemoteSourceReadinessEntry; export type AddProjectCloneFlow = | { readonly step: "repository"; readonly environmentId: EnvironmentId; readonly source: AddProjectRemoteSource; } | { readonly step: "confirm"; readonly environmentId: EnvironmentId; readonly source: AddProjectRemoteSource; readonly repositoryInput: string; readonly repository: SourceControlRepositoryInfo | null; readonly remoteUrl: string; }; const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray = sourceControlClients.definitions.map((definition) => definition.kind); export function addProjectRemoteSourceLabel( source: AddProjectRemoteSource, resolve: MFunctionType = mFallback, ): string { return source === "url" ? resolve(msg("Git URL")) : sourceControlClients.get(source).pickerLabel; } export function addProjectRemoteSourcePathHint( source: AddProjectRemoteSource, resolve: MFunctionType = mFallback, ): string { return source === "url" ? resolve(msg("URL", { $context: "placeholder for a git URL field" })) : sourceControlClients.get(source).repositoryPathHint; } export function addProjectRemoteSourceProvider( source: AddProjectRemoteSource, ): SourceControlProviderKind | null { return source === "url" ? null : source; } export function parseAddProjectRemoteSource( value: string | null | undefined, ): AddProjectRemoteSource { return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url"; } const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/; /** * The clone URL of `owner/name` on the public host of the host a repository reads as before it * reports one. Null when that host has no public host. */ export function defaultHostCloneUrl(repository: string): string | null { const definition = sourceControlClients.get(undefined); if (definition.publicHost === null) return null; const path = repository.endsWith(".git") ? repository : `${repository}.git`; return definition.defaultCloneTransport === "https" ? `https://${definition.publicHost}/${path}` : `git@${definition.publicHost}:${path}`; } /** Owner present, repository name missing: `owner/` or `owner//`. */ const INCOMPLETE_GITHUB_OWNER_PATH = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})\/+$/; /** * Message to show when a GitHub add-project field is only `owner/`. * Lookup would send that to GitHub and come back as a generic failure. * Returns null for complete names, bare repo names, URLs, and other sources. */ export function githubIncompleteOwnerRepositoryMessage( source: AddProjectRemoteSource, input: string, resolve: MFunctionType = mFallback, ): string | null { if (source !== "github") return null; if (!INCOMPLETE_GITHUB_OWNER_PATH.test(input.trim())) return null; return resolve(msg("Enter the full owner/repository name.")); } export function normalizePastedCloneUrl(input: string): string { const trimmed = input.trim(); if (REPOSITORY_SHORTHAND.test(trimmed)) return defaultHostCloneUrl(trimmed) ?? trimmed; return sourceControlClients.repositoryUrlFromPage(trimmed) ?? trimmed; } export function getDefaultCloneUrl( repository: Pick, ): string { return sourceControlClients.get(repository.provider).defaultCloneTransport === "https" ? repository.url : repository.sshUrl; } export type OfferedSourceControlProviders = ServerSettings["offeredSourceControlProviders"]; /** Whether the project pickers offer a host. Only the default host is on until the user turns others on. */ export function isSourceControlProviderOffered( offered: OfferedSourceControlProviders | undefined, kind: SourceControlProviderKind, ): boolean { return offered?.[kind] ?? kind === sourceControlClients.get(undefined).kind; } export function sortAddProjectProviderSources( readiness: AddProjectRemoteSourceReadiness, offered: OfferedSourceControlProviders | undefined, ): ReadonlyArray { return Arr.sort( ADD_PROJECT_REMOTE_PROVIDER_SOURCES.filter((source) => isSourceControlProviderOffered(offered, source), ), Order.mapInput( Order.Struct({ ready: Order.flip(Order.Boolean), label: Order.String, }), (source: SourceControlProviderKind) => ({ ready: readiness(source).ready, label: addProjectRemoteSourceLabel(source), }), ), ); } const READY: AddProjectRemoteSourceReadinessEntry = { ready: true, hint: null }; const UNAVAILABLE_HINT = msg( "Provider status unavailable. Open Source Control settings and rescan.", ); export function buildAddProjectRemoteSourceReadiness( discovery: SourceControlDiscoveryResult | null, resolve: MFunctionType = mFallback, ): AddProjectRemoteSourceReadiness { const providerByKind = new Map( (discovery?.sourceControlProviders ?? []).map((provider) => [provider.kind, provider]), ); return (source) => { if (source === "url") return READY; const provider = providerByKind.get(source); if (!provider) return { ready: false, hint: resolve(UNAVAILABLE_HINT) }; if (provider.status !== "available") { return { ready: false, hint: sourceControlInstallHintText(provider.installHint, resolve) }; } if (provider.auth.status === "unauthenticated") { return { ready: false, hint: Option.getOrNull(provider.auth.detail) ?? resolve( msg( "{provider} is not authenticated. Open Source Control settings for setup guidance.", { provider: provider.label }, ), ), }; } return READY; }; } export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { const trimmed = baseDirectory?.trim() ?? ""; if (trimmed.length === 0) return "~/"; // A bare relative setting such as `Desktop/dev` means a folder under home. The browser // navigates `~/` but not `~\` home paths. const isAnchored = trimmed === "~" || isAbsolutePath(trimmed) || trimmed.startsWith("~/") || isExplicitRelativePath(trimmed); return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`); } export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string { const trimmed = (repositoryOrRemoteUrl ?? "").trim(); // Local paths keep both delimiters. SCP paths keep a literal # in the repository name. const isLocalPath = !trimmed.includes("://") && (isHostPath(trimmed) || isExplicitRelativePath(trimmed)); const withoutQuery = isLocalPath ? trimmed : trimmed.split(isScpLikeCloneUrl(trimmed) ? "?" : /[?#]/, 1)[0]!; const schemeIndex = withoutQuery.indexOf("://"); const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery); const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery; const segments = pathPart.split(/[/\\:]+/).filter((segment) => segment.trim().length > 0); if (hasHost && segments.length < 2) { return ""; } const lastSegment = segments.at(-1)?.trim() ?? ""; if (hasHost && segments.length === 2 && /^\d+$/.test(lastSegment)) { return ""; } return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment; } /** The folder a clone gets below its base: ``, or `//` like ghq. */ export function getCloneDirectoryPath( remoteUrl: string, ghqCloneLayout: boolean, repository = remoteUrl, ): string { return ( (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository) ); } /** The clone's own folder, which folder browsing keeps at the end of the destination. */ export function getCloneDirectoryLeafName( remoteUrl: string, ghqCloneLayout: boolean, repository = remoteUrl, ): string { return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? ""; } export function getCloneDestinationPath( directoryPath: string, directoryName: string | null | undefined, ): string { const name = directoryName?.trim() ?? ""; if (name.length === 0) { return directoryPath; } const base = ensureBrowseDirectoryPath(directoryPath); return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`; } export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string { return getCloneDestinationPath(newProjectsRoot, newProjectFolderName(name)); } export interface NewProjectPublishTarget { readonly definition: SourceControlDefinition; readonly owner: string | null; } export function getNewProjectPublishTargets( discovery: SourceControlDiscoveryResult | null, offered: OfferedSourceControlProviders | undefined, ): ReadonlyArray { const readiness = buildAddProjectRemoteSourceReadiness(discovery); return sourceControlClients.definitions.flatMap((definition) => { if (!isSourceControlProviderOffered(offered, definition.kind)) return []; if (!readiness(definition.kind).ready) return []; const provider = discovery?.sourceControlProviders.find( (candidate) => candidate.kind === definition.kind, ); const placement = definition.newRepositoryOwner( provider ? Option.getOrNull(provider.auth.account) : null, ); return placement === null ? [] : [{ definition, owner: placement.owner }]; }); } export function getNewProjectPublishTarget( targets: ReadonlyArray, kind: SourceControlProviderKind | null, ): NewProjectPublishTarget | null { return targets.find((target) => target.definition.kind === kind) ?? targets[0] ?? null; } export function getNewProjectRepository( target: Pick, workspaceRoot: string, ): string { const folderName = workspaceRoot.split(/[\\/]/).filter(Boolean).at(-1) ?? ""; return target.owner ? `${target.owner}/${folderName}` : folderName; } export function getCloneDestinationBrowsePath(input: { readonly browseDirectoryPath: string; readonly selectedDirectoryName: string; readonly cloneDirectoryName: string; readonly caseSensitive: boolean; }): string { const selectedDirectoryPath = appendBrowsePathSegment( input.browseDirectoryPath, input.selectedDirectoryName, ); const selectedDirectoryMatches = input.caseSensitive ? input.selectedDirectoryName === input.cloneDirectoryName : input.selectedDirectoryName.toLowerCase() === input.cloneDirectoryName.toLowerCase(); return selectedDirectoryMatches ? selectedDirectoryPath : getCloneDestinationPath(selectedDirectoryPath, input.cloneDirectoryName); } // The native picker returns a full path, not a name under the browsed directory. // Split it and reuse the in-app rules so a folder already named after the // repository stays that folder instead of becoming repo/repo. export function getCloneDestinationForPickedFolder(input: { readonly pickedPath: string; readonly cloneDirectoryName: string; readonly caseSensitive: boolean; }): string { const parentPath = getBrowseParentPath(input.pickedPath); if (parentPath === null) { return getCloneDestinationPath(input.pickedPath, input.cloneDirectoryName); } return getCloneDestinationBrowsePath({ browseDirectoryPath: parentPath, selectedDirectoryName: inferProjectTitleFromPath(input.pickedPath), cloneDirectoryName: input.cloneDirectoryName, caseSensitive: input.caseSensitive, }); } export function resolveAddProjectPath( input: { readonly rawPath: string; readonly currentProjectCwd?: string | null; readonly platform: string; }, resolve: MFunctionType = mFallback, ): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly error: string } { const rawPath = input.rawPath.trim(); if (rawPath.length === 0) { return { ok: false, error: resolve(msg("Enter a project path.")) }; } if (isUnsupportedWindowsProjectPath(rawPath, input.platform)) { return { ok: false, error: resolve(msg("Windows-style paths are only supported on Windows environments.")), }; } if (isExplicitRelativeProjectPath(rawPath) && !input.currentProjectCwd) { return { ok: false, error: resolve(msg("Relative paths require an active project in this environment.")), }; } const path = resolveProjectPathForDispatch(rawPath, input.currentProjectCwd); return path.length === 0 ? { ok: false, error: resolve(msg("Enter a project path.")) } : { ok: true, path }; } export function findExistingAddProject(input: { readonly projects: ReadonlyArray; readonly environmentId: EnvironmentId; readonly path: string; }): EnvironmentProject | null { return ( findProjectByPath( input.projects.filter((project) => project.environmentId === input.environmentId), input.path, ) ?? null ); } export function buildProjectCreateCommand(input: { readonly commandId: CommandId; readonly projectId: ProjectId; readonly workspaceRoot: string; readonly trackedFolders?: ReadonlyArray; }): Extract { return { type: "project.create", commandId: input.commandId, projectId: input.projectId, title: inferProjectTitleFromPath(input.workspaceRoot), workspaceRoot: input.workspaceRoot, createWorkspaceRootIfMissing: true, defaultModelSelection: null, ...(input.trackedFolders === undefined || input.trackedFolders.length === 0 ? {} : { trackedFolders: input.trackedFolders }), }; }