mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
section 6: Phase 6: Project configuration schemas and personal action storage
This commit is contained in:
1 parent
c320e2ac7d
commit
e83b979730
10 files changed
+712
-6
No files matched your search
@@ -4,17 +4,13 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { logger } from '../utils/logger'
|
||||
import { parseGitError } from '../utils/git-errors'
|
||||
import { GitService } from '../services/git/GitService'
|
||||
import { createGitService } from '../services/git/GitService'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { CredentialProvider } from '../services/credential-provider'
|
||||
import type { GitStatusResponse } from '../types/git'
|
||||
|
||||
export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthService) {
|
||||
const app = new Hono()
|
||||
const settingsService = new SettingsService(database)
|
||||
const credentialProvider = new CredentialProvider(database)
|
||||
const git = new GitService(gitAuthService, settingsService, credentialProvider)
|
||||
const git = createGitService(database, gitAuthService)
|
||||
|
||||
app.get('/:id/git/status', async (c) => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import * as repoService from '../services/repo'
|
||||
import { resolveRepoWorkingDirectory } from '../services/repo'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import { ProjectConfigError, type ProjectConfigService } from '../services/project-config'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
|
||||
export interface RepoProjectConfigDeps {
|
||||
database: Database
|
||||
gitAuthService: GitAuthService
|
||||
openCodeClient: OpenCodeClient
|
||||
projectConfigService: ProjectConfigService
|
||||
terminalService: TerminalService
|
||||
}
|
||||
|
||||
function handleProjectConfigError(c: Context, error: unknown): Response {
|
||||
if (error instanceof ProjectConfigError) {
|
||||
return c.json(
|
||||
{ error: error.message, code: error.code, details: error.details },
|
||||
error.status as ContentfulStatusCode,
|
||||
)
|
||||
}
|
||||
logger.error('Project config request failed:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
|
||||
export function createRepoProjectConfigRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
projectConfigService: ProjectConfigService,
|
||||
terminalService: TerminalService,
|
||||
) {
|
||||
const deps: RepoProjectConfigDeps = {
|
||||
database,
|
||||
gitAuthService,
|
||||
openCodeClient,
|
||||
projectConfigService,
|
||||
terminalService,
|
||||
}
|
||||
const app = new Hono()
|
||||
|
||||
async function resolveRepoDirectory(
|
||||
c: Context,
|
||||
repoIdParam: string,
|
||||
directory: string | undefined,
|
||||
): Promise<{ repo: Repo; directory: string } | Response> {
|
||||
const id = Number.parseInt(repoIdParam, 10)
|
||||
if (Number.isNaN(id)) {
|
||||
return c.json({ error: 'Invalid repo id' }, 400)
|
||||
}
|
||||
|
||||
const repo = getRepoById(deps.database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
repoService.getSiblingRepos(
|
||||
deps.database,
|
||||
repo.id,
|
||||
deps.gitAuthService.getGitEnvironment(),
|
||||
deps.openCodeClient,
|
||||
),
|
||||
)
|
||||
|
||||
if (!resolved) {
|
||||
return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
}
|
||||
|
||||
return { repo, directory: resolved }
|
||||
}
|
||||
|
||||
app.get('/:id/project-config', async (c) => {
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/:id/project-config/actions', async (c) => {
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = UpdateProjectActionsRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo)
|
||||
deps.projectConfigService.setPersonalActions(projectRepo, parsed.data.actions)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/:id/project-config/worktree-setup', async (c) => {
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = UpdateWorktreeSetupRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
|
||||
if (resolved instanceof Response) return resolved
|
||||
|
||||
try {
|
||||
const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo)
|
||||
deps.projectConfigService.setPersonalSetup(projectRepo, parsed.data.commands)
|
||||
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
|
||||
} catch (error: unknown) {
|
||||
return handleProjectConfigError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -16,9 +16,12 @@ import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/u
|
||||
import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import { createRepoTerminalRoutes } from './repo-terminals'
|
||||
import { createRepoProjectConfigRoutes } from './repo-project-config'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import { ProjectConfigService } from '../services/project-config'
|
||||
import { createGitService } from '../services/git/GitService'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode'
|
||||
import path from 'path'
|
||||
@@ -51,8 +54,15 @@ export function createRepoRoutes(
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
const projectConfigService = new ProjectConfigService(
|
||||
database,
|
||||
createGitService(database, gitAuthService),
|
||||
gitAuthService,
|
||||
)
|
||||
|
||||
app.route('/', createRepoGitRoutes(database, gitAuthService))
|
||||
app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService))
|
||||
app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService))
|
||||
app.route('/:id/schedules', createScheduleRoutes(scheduleService))
|
||||
|
||||
app.post('/', async (c) => {
|
||||
|
||||
@@ -12,6 +12,10 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git'
|
||||
import path from 'path'
|
||||
|
||||
export function createGitService(database: Database, gitAuthService: GitAuthService): GitService {
|
||||
return new GitService(gitAuthService, new SettingsService(database), new CredentialProvider(database))
|
||||
}
|
||||
|
||||
export class GitService {
|
||||
constructor(
|
||||
private gitAuthService: GitAuthService,
|
||||
@@ -19,6 +23,16 @@ export class GitService {
|
||||
private credentialProvider: CredentialProvider
|
||||
) {}
|
||||
|
||||
async getMainCheckoutPath(directory: string): Promise<string> {
|
||||
const env = this.gitAuthService.getGitEnvironment()
|
||||
const output = await executeCommand(['git', '-C', directory, 'worktree', 'list', '--porcelain'], { env })
|
||||
const firstEntry = output.split('\n').find((line) => line.startsWith('worktree '))
|
||||
if (!firstEntry) {
|
||||
throw new Error(`Unable to resolve the main checkout for ${directory}`)
|
||||
}
|
||||
return firstEntry.slice('worktree '.length).trim()
|
||||
}
|
||||
|
||||
async getStatus(repoId: number, database: Database): Promise<GitStatusResponse> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import {
|
||||
ProjectActionSchema,
|
||||
WorktreeSetupCommandsSchema,
|
||||
type ProjectAction,
|
||||
type ProjectConfigResponse,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries'
|
||||
import type { GitService } from './git/GitService'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
|
||||
const PROJECT_ACTIONS_KEY = 'projectActions'
|
||||
const WORKTREE_SETUP_KEY = 'worktreeSetupCommands'
|
||||
const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
|
||||
|
||||
export class ProjectConfigError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
public code?: string,
|
||||
public details?: unknown,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ProjectConfigError'
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectConfigService {
|
||||
constructor(
|
||||
private readonly database: Database,
|
||||
private readonly git: GitService,
|
||||
private readonly gitAuthService: GitAuthService,
|
||||
) {}
|
||||
|
||||
async resolveProjectRepo(repo: Repo): Promise<Repo> {
|
||||
if (!repo.isWorktree) {
|
||||
return repo
|
||||
}
|
||||
const mainCheckout = await this.git.getMainCheckoutPath(repo.fullPath)
|
||||
return getRepoByDirectory(this.database, mainCheckout) ?? repo
|
||||
}
|
||||
|
||||
getPersonalActions(projectRepo: Repo): ProjectAction[] {
|
||||
return this.readStoredJson(projectRepo.id, PROJECT_ACTIONS_KEY, z.array(ProjectActionSchema)) ?? []
|
||||
}
|
||||
|
||||
setPersonalActions(projectRepo: Repo, actions: ProjectAction[]): void {
|
||||
const ids = new Set<string>()
|
||||
for (const action of actions) {
|
||||
if (ids.has(action.id)) {
|
||||
throw new ProjectConfigError(400, 'Duplicate action id')
|
||||
}
|
||||
ids.add(action.id)
|
||||
}
|
||||
setRepoSetting(this.database, projectRepo.id, PROJECT_ACTIONS_KEY, JSON.stringify(actions))
|
||||
}
|
||||
|
||||
getPersonalSetup(projectRepo: Repo): string[] {
|
||||
return this.readStoredJson(projectRepo.id, WORKTREE_SETUP_KEY, WorktreeSetupCommandsSchema) ?? []
|
||||
}
|
||||
|
||||
setPersonalSetup(projectRepo: Repo, commands: string[]): void {
|
||||
setRepoSetting(this.database, projectRepo.id, WORKTREE_SETUP_KEY, JSON.stringify(commands))
|
||||
}
|
||||
|
||||
async getConfig(repo: Repo, directory: string): Promise<ProjectConfigResponse> {
|
||||
const projectRepo = await this.resolveProjectRepo(repo)
|
||||
const actions = this.getPersonalActions(projectRepo).map((action) => ({ ...action, source: 'personal' as const }))
|
||||
const worktreeSetup = this.getPersonalSetup(projectRepo).map((command) => ({ command, source: 'personal' as const }))
|
||||
const hash: string | null = null
|
||||
void directory
|
||||
|
||||
return {
|
||||
actions,
|
||||
worktreeSetup,
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: false,
|
||||
trusted: hash !== null && hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY),
|
||||
hash,
|
||||
warnings: [],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
private readStoredJson<T>(repoId: number, key: string, schema: z.ZodType<T>): T | null {
|
||||
const raw = getRepoSetting(this.database, repoId, key)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const result = schema.safeParse(JSON.parse(raw))
|
||||
return result.success ? result.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user