|
| 1 | +import fs from 'node:fs/promises'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +import { projectsDb } from '@/modules/database/index.js'; |
| 5 | +import { projectApiView, type ProjectApiView } from '@/modules/projects/services/project-management.service.js'; |
| 6 | +import { scoreWorkspaceCandidates, type WorkspaceCandidate, type WorkspaceScoringChild } from '@/modules/projects/services/workspace-target-scoring.js'; |
| 7 | +import type { ProjectRepositoryRow } from '@/shared/types.js'; |
| 8 | +import { AppError, normalizeProjectPath } from '@/shared/utils.js'; |
| 9 | + |
| 10 | +export type { WorkspaceCandidate }; |
| 11 | + |
| 12 | +export type ResolveWorkspaceTargetResult = { |
| 13 | + isWorkspace: boolean; |
| 14 | + candidates: WorkspaceCandidate[]; |
| 15 | +}; |
| 16 | + |
| 17 | +export type DescendIntoChildResult = { |
| 18 | + created: boolean; |
| 19 | + project: ProjectApiView; |
| 20 | +}; |
| 21 | + |
| 22 | +function unknownProject(projectId: string): AppError { |
| 23 | + return new AppError(`Unknown projectId: ${projectId}`, { code: 'PROJECT_NOT_FOUND', statusCode: 404 }); |
| 24 | +} |
| 25 | + |
| 26 | +async function hasGitEntry(directoryPath: string): Promise<boolean> { |
| 27 | + try { |
| 28 | + await fs.stat(path.join(directoryPath, '.git')); |
| 29 | + return true; |
| 30 | + } catch (error) { |
| 31 | + const failure = error as NodeJS.ErrnoException; |
| 32 | + if (failure.code === 'ENOENT') return false; |
| 33 | + throw failure; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function isCandidateDirName(name: string): boolean { |
| 38 | + return name !== 'node_modules' && !name.startsWith('.'); |
| 39 | +} |
| 40 | + |
| 41 | +async function readPackageName(directoryPath: string): Promise<string | null> { |
| 42 | + try { |
| 43 | + const manifestPath = path.join(directoryPath, 'package.json'); |
| 44 | + const stats = await fs.lstat(manifestPath); |
| 45 | + if (!stats.isFile() || stats.size > 64 * 1024) return null; |
| 46 | + const raw = await fs.readFile(manifestPath, 'utf8'); |
| 47 | + const parsed = JSON.parse(raw) as { name?: unknown }; |
| 48 | + const name = typeof parsed.name === 'string' ? parsed.name.trim() : ''; |
| 49 | + if (!name) return null; |
| 50 | + // Scoped packages (`@scope/name`) contribute only the unscoped segment. |
| 51 | + return name.startsWith('@') ? name.split('/').slice(1).join('/') || null : name; |
| 52 | + } catch { |
| 53 | + return null; |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Lists the immediate child directories of `dir` that are themselves git repositories |
| 59 | + * (contain a `.git` entry). Hidden directories and `node_modules` are never candidates. |
| 60 | + */ |
| 61 | +export async function listChildRepos(dir: string, options: { withPackageNames?: boolean } = {}): Promise<WorkspaceScoringChild[]> { |
| 62 | + let entries: import('node:fs').Dirent[]; |
| 63 | + try { |
| 64 | + entries = await fs.readdir(dir, { withFileTypes: true }); |
| 65 | + } catch (error) { |
| 66 | + const failure = error as NodeJS.ErrnoException; |
| 67 | + if (failure.code === 'ENOENT' || failure.code === 'ENOTDIR') return []; |
| 68 | + throw failure; |
| 69 | + } |
| 70 | + |
| 71 | + const children: WorkspaceScoringChild[] = []; |
| 72 | + for (const entry of entries) { |
| 73 | + if (!entry.isDirectory() || !isCandidateDirName(entry.name)) continue; |
| 74 | + const childPath = path.join(dir, entry.name); |
| 75 | + if (!(await hasGitEntry(childPath))) continue; |
| 76 | + let stats: import('node:fs').Stats; |
| 77 | + try { |
| 78 | + stats = await fs.stat(childPath); |
| 79 | + } catch (error) { |
| 80 | + const failure = error as NodeJS.ErrnoException; |
| 81 | + if (failure.code === 'ENOENT') continue; |
| 82 | + throw failure; |
| 83 | + } |
| 84 | + children.push({ |
| 85 | + path: childPath, |
| 86 | + name: entry.name, |
| 87 | + packageName: options.withPackageNames === false ? null : await readPackageName(childPath), |
| 88 | + mtimeMs: stats.mtimeMs, |
| 89 | + }); |
| 90 | + } |
| 91 | + return children; |
| 92 | +} |
| 93 | + |
| 94 | +async function workspaceChildren(projectPath: string, withPackageNames: boolean): Promise<WorkspaceScoringChild[] | null> { |
| 95 | + if (await hasGitEntry(projectPath)) return null; |
| 96 | + const children = await listChildRepos(projectPath, { withPackageNames }); |
| 97 | + return children.length ? children : null; |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * A workspace root is a directory that is not itself a git work tree, but that |
| 102 | + * contains at least one immediate child directory that is one. |
| 103 | + */ |
| 104 | +export async function isWorkspaceRoot(dir: string): Promise<boolean> { |
| 105 | + return (await workspaceChildren(dir, false)) !== null; |
| 106 | +} |
| 107 | + |
| 108 | +function projectRowOrThrow(projectId: string): ProjectRepositoryRow { |
| 109 | + const project = projectsDb.getProjectById(projectId); |
| 110 | + if (!project) throw unknownProject(projectId); |
| 111 | + return project; |
| 112 | +} |
| 113 | + |
| 114 | +export async function resolveWorkspaceTarget(projectId: string, text: string): Promise<ResolveWorkspaceTargetResult> { |
| 115 | + const project = projectRowOrThrow(projectId); |
| 116 | + const children = await workspaceChildren(project.project_path, true); |
| 117 | + if (!children) { |
| 118 | + return { isWorkspace: false, candidates: [] }; |
| 119 | + } |
| 120 | + return { isWorkspace: true, candidates: scoreWorkspaceCandidates(text, children) }; |
| 121 | +} |
| 122 | + |
| 123 | +function notWorkspaceChild(message: string): AppError { |
| 124 | + return new AppError(message, { code: 'NOT_WORKSPACE_CHILD', statusCode: 400 }); |
| 125 | +} |
| 126 | + |
| 127 | +export async function descendIntoChild(projectId: string, childPath: string): Promise<DescendIntoChildResult> { |
| 128 | + const project = projectRowOrThrow(projectId); |
| 129 | + const children = await workspaceChildren(project.project_path, false); |
| 130 | + if (!children) { |
| 131 | + throw notWorkspaceChild('Project is not a workspace root'); |
| 132 | + } |
| 133 | + const resolvedChildPath = normalizeProjectPath(path.resolve(childPath)); |
| 134 | + const matchedChild = children.find((child) => normalizeProjectPath(child.path) === resolvedChildPath); |
| 135 | + if (!matchedChild) { |
| 136 | + throw notWorkspaceChild('path is not an immediate child repository of the workspace project'); |
| 137 | + } |
| 138 | + |
| 139 | + // The user chose this repo to work in, so it becomes a sidebar project the |
| 140 | + // same way "Add a project" does: created or un-archived as 'explicit', and a |
| 141 | + // row the session indexer had only discovered ('auto'/'legacy') is promoted. |
| 142 | + const { outcome, project: child } = projectsDb.createProjectPath(matchedChild.path); |
| 143 | + if (!child) { |
| 144 | + throw new AppError('Failed to register project for workspace child', { code: 'PROJECT_CREATE_FAILED', statusCode: 500 }); |
| 145 | + } |
| 146 | + const row = outcome === 'active_conflict' && child.origin !== 'explicit' |
| 147 | + ? projectsDb.promoteProjectOriginById(child.project_id) ?? child |
| 148 | + : child; |
| 149 | + return { created: outcome === 'created', project: projectApiView(row) }; |
| 150 | +} |
0 commit comments