mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 9: Phase 9: One owner for creating and removing OpenCode worksp
This commit is contained in:
1 parent
8cd00e1a8a
commit
f402e8479a
3 files changed
+195
-15
No files matched your search
@@ -12,14 +12,13 @@ import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
import { handleOpenCodeError } from '../utils/route-helpers'
|
||||
import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/utils'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import path from 'path'
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
@@ -267,19 +266,13 @@ app.get('/', async (c) => {
|
||||
const body = await c.req.json().catch(() => null)
|
||||
const parsed = DeleteWorkspaceRequestSchema.safeParse(body)
|
||||
if (!parsed.success) return c.json({ error: 'directory is required' }, 400)
|
||||
const directory = parsed.data.directory
|
||||
|
||||
const siblings = await repoService.getSiblingRepos(database, id, gitAuthService.getGitEnvironment(), openCodeClient)
|
||||
const requestedDirectory = canonicalPathSync(path.resolve(directory))
|
||||
const worktree = siblings.find(
|
||||
(sibling) => isWorktreeSibling(sibling) && canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory,
|
||||
)
|
||||
if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400)
|
||||
|
||||
try {
|
||||
const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
await openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true })
|
||||
await repoService.removeRepoWorkspace(database, openCodeClient, gitAuthService.getGitEnvironment(), repo, parsed.data.directory)
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof repoService.RepoWorkspaceError) {
|
||||
return c.json({ error: error.message }, error.status)
|
||||
}
|
||||
if (isWorktreeError(error)) {
|
||||
return c.json({ error: error.data.message }, 409)
|
||||
}
|
||||
@@ -302,8 +295,7 @@ app.get('/', async (c) => {
|
||||
if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404)
|
||||
|
||||
try {
|
||||
const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
const worktree = await openCodeClient.api.worktree.create({ projectID })
|
||||
const worktree = await repoService.createRepoWorkspace(openCodeClient, repo)
|
||||
return c.json(worktree)
|
||||
} catch (error: unknown) {
|
||||
if (isWorktreeError(error)) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN } from '@opencode-manager/shared/utils'
|
||||
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, isWorktreeSibling, SCP_STYLE_URL_PATTERN } from '@opencode-manager/shared/utils'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import { isGitHubHttpsUrl } from '../utils/git-auth'
|
||||
import path from 'path'
|
||||
@@ -1263,3 +1263,44 @@ export async function getSiblingRepos(
|
||||
return repoSiblings
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoWorkspaceError extends Error {
|
||||
readonly status: 400 | 404
|
||||
|
||||
constructor(message: string, status: 400 | 404) {
|
||||
super(message)
|
||||
this.name = 'RepoWorkspaceError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(
|
||||
openCodeClient: OpenCodeClient,
|
||||
repo: Repo,
|
||||
options: { name?: string; ref?: string } = {},
|
||||
): Promise<{ directory: string }> {
|
||||
const projectID = await resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
return openCodeClient.api.worktree.create({
|
||||
projectID,
|
||||
...(options.name ? { name: options.name } : {}),
|
||||
...(options.ref ? { branch: options.ref } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function removeRepoWorkspace(
|
||||
database: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
gitEnv: Record<string, string>,
|
||||
repo: Repo,
|
||||
directory: string,
|
||||
): Promise<void> {
|
||||
const siblings = await getSiblingRepos(database, repo.id, gitEnv, openCodeClient)
|
||||
const requestedDirectory = canonicalPathSync(path.resolve(directory))
|
||||
const worktree = siblings.find(
|
||||
(sibling) => isWorktreeSibling(sibling) && canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory,
|
||||
)
|
||||
if (!worktree) throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400)
|
||||
|
||||
const projectID = await resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
await openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true })
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
|
||||
const executeCommand = vi.fn()
|
||||
const listRepos = vi.fn()
|
||||
const resolveProjectId = vi.fn()
|
||||
const isGitMainCheckout = vi.fn()
|
||||
const getSettings = vi.fn()
|
||||
const mkdirSafe = vi.fn()
|
||||
|
||||
vi.mock('../../src/utils/fs-safe', () => ({
|
||||
mkdirSafe,
|
||||
mkdirSyncSafe: vi.fn(),
|
||||
canonicalPathSync: (target: string) => target,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({ getSettings })),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/project-id-resolver', () => ({
|
||||
resolveProjectId,
|
||||
isGitMainCheckout,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({
|
||||
executeCommand,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
listRepos,
|
||||
}))
|
||||
|
||||
describe('repo workspace service', () => {
|
||||
type WorktreeEntry = { directory: string; strategy?: string }
|
||||
|
||||
let db: Database
|
||||
|
||||
function createRepoRow(id: number, localPath: string, overrides: Partial<Repo> = {}): Repo {
|
||||
return {
|
||||
id,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath,
|
||||
fullPath: path.join(getReposPath(), localPath),
|
||||
sourcePath: path.join(getReposPath(), localPath),
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createClient(worktrees: WorktreeEntry[], overrides: {
|
||||
create?: OpenCodeClient['api']['worktree']['create']
|
||||
remove?: OpenCodeClient['api']['worktree']['remove']
|
||||
} = {}): OpenCodeClient {
|
||||
return {
|
||||
api: {
|
||||
location: {
|
||||
get: async () => ({
|
||||
directory: path.join(getReposPath(), 'repo-a'),
|
||||
project: { id: 'commit-A', directory: path.join(getReposPath(), 'repo-a'), canonical: path.join(getReposPath(), 'repo-a') },
|
||||
}),
|
||||
},
|
||||
worktree: {
|
||||
list: async () => worktrees,
|
||||
create: overrides.create ?? (async () => ({ directory: '/worktrees/feature-x' })),
|
||||
remove: overrides.remove ?? (async () => undefined),
|
||||
},
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mkdirSafe.mockResolvedValue(undefined)
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() })
|
||||
resolveProjectId.mockResolvedValue('commit-A')
|
||||
isGitMainCheckout.mockResolvedValue(false)
|
||||
listRepos.mockReturnValue([createRepoRow(1, 'repo-a')])
|
||||
executeCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('HEAD') && !args.includes('--abbrev-ref')) {
|
||||
return 'abc123'
|
||||
}
|
||||
|
||||
if (args.includes('--abbrev-ref')) {
|
||||
return 'main'
|
||||
}
|
||||
|
||||
return ''
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('passes name and ref through to the worktree create call', async () => {
|
||||
const { createRepoWorkspace } = await import('../../src/services/repo')
|
||||
const create = vi.fn(async () => ({ directory: '/worktrees/feature-x' }))
|
||||
const client = createClient([], { create })
|
||||
|
||||
const result = await createRepoWorkspace(client, createRepoRow(1, 'repo-a'), { name: 'feature-x', ref: 'feature/x' })
|
||||
|
||||
expect(create).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'feature-x', branch: 'feature/x' })
|
||||
expect(result).toEqual({ directory: '/worktrees/feature-x' })
|
||||
})
|
||||
|
||||
it('creates a worktree without optional options', async () => {
|
||||
const { createRepoWorkspace } = await import('../../src/services/repo')
|
||||
const create = vi.fn(async () => ({ directory: '/worktrees/feature-x' }))
|
||||
const client = createClient([], { create })
|
||||
|
||||
await createRepoWorkspace(client, createRepoRow(1, 'repo-a'))
|
||||
|
||||
expect(create).toHaveBeenCalledWith({ projectID: 'commit-A' })
|
||||
})
|
||||
|
||||
it('rejects a directory that is not a worktree sibling of the repo', async () => {
|
||||
const { removeRepoWorkspace, RepoWorkspaceError } = await import('../../src/services/repo')
|
||||
const client = createClient([{ directory: '/worktrees/feature-x', strategy: 'git' }])
|
||||
|
||||
const error = await removeRepoWorkspace(db, client, {}, createRepoRow(1, 'repo-a'), '/worktrees/unknown').catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(RepoWorkspaceError)
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
})
|
||||
|
||||
it('removes a matching worktree sibling with force', async () => {
|
||||
const { removeRepoWorkspace } = await import('../../src/services/repo')
|
||||
const remove = vi.fn(async () => undefined)
|
||||
const client = createClient([{ directory: '/worktrees/feature-x', strategy: 'git' }], { remove })
|
||||
|
||||
await removeRepoWorkspace(db, client, {}, createRepoRow(1, 'repo-a'), '/worktrees/feature-x')
|
||||
|
||||
expect(remove).toHaveBeenCalledWith({ projectID: 'commit-A', directory: '/worktrees/feature-x', force: true })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user