(dirPath: string, name?: string)
| 132 | * 打开文件夹作为工作区 |
| 133 | */ |
| 134 | export async function openFolderAsWorkspace(dirPath: string, name?: string): Promise<Workspace> { |
| 135 | const { workspace } = stores |
| 136 | |
| 137 | await persistence.database.approveWorkspacePath(dirPath) |
| 138 | |
| 139 | // 验证路径 |
| 140 | const validation = await validateWorkspacePath(dirPath) |
| 141 | |
| 142 | if (!validation.valid) { |
| 143 | throw new Error(validation.error || 'Invalid workspace path') |
| 144 | } |
| 145 | |
| 146 | if (validation.lockedByAccountId) { |
| 147 | throw new Error(`This folder is already used by another account`) |
| 148 | } |
| 149 | |
| 150 | if (validation.repairable) { |
| 151 | throw new WorkspaceRepairRequiredError(dirPath, validation) |
| 152 | } |
| 153 | |
| 154 | // 使用目录名作为默认名称 |
| 155 | const workspaceName = name || dirPath.split(/[/\\]/).pop() || 'Workspace' |
| 156 | |
| 157 | // 如果已经是工作区且属于当前账户,直接切换 |
| 158 | if (validation.isWorkspace && validation.workspaceId) { |
| 159 | const existing = await workspace.getById(validation.workspaceId) |
| 160 | if (existing) { |
| 161 | await switchWorkspace(existing.id) |
| 162 | return existing |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | // 创建/初始化自定义工作区 |
| 167 | const newWorkspace = await workspace.openCustomWorkspace(dirPath, workspaceName) |
| 168 | |
| 169 | await runSwitchTransaction('workspace', newWorkspace.name, async () => { |
| 170 | await workspace.setCurrentWorkspaceId(newWorkspace.id) |
| 171 | await commitWorkspaceContext(newWorkspace.accountId, newWorkspace.path, [dirPath]) |
| 172 | await cleanupWorkspaceTempAttachments() |
| 173 | resetWorkspaceStores() |
| 174 | await initWorkspaceStores() |
| 175 | }) |
| 176 | |
| 177 | return newWorkspace |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * 验证目录是否可作为工作区 |
no test coverage detected