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