// glossary-ignore-file: перенос кода проекта делает администратор из командной строки // PEP-4: moving a project's repo to another Gitea namespace (an organization, usually) and // fixing everything that depends on its address: the project row, `origin` of the working // copy, the CI runner, the Actions secret and the webhook. Every step is safe to repeat. import { m } from "@peppa/shared/i18n"; import { existsSync } from "node:fs"; import { eq } from "drizzle-orm"; import { GiteaError, giteaForBot, logEvent, PeppaError, type Project } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { ensureBranchProtection } from "./branch-protection.ts"; import { setupCi } from "./ci.ts"; import { git } from "./git.ts"; import { forgetRepoInfo } from "./share.ts"; export interface TransferResult { project: Project; from: string; to: string; /** False when the repo was already there (a repeated run): only Peppa's side was fixed. */ moved: boolean; /** CI could not be set up at the new address (the transfer itself is done). */ ciError: string | null; } /** Moves the project's repo to `newOwner` as peppa-bot (CLI on Peppa's machine: no owner check). */ export async function transferProject(db: Db, project: Project, newOwner: string, o: { log?: (step: string) => void } = {}): Promise { const log = o.log ?? (() => {}); const target = newOwner.trim(); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(target)) throw new PeppaError(m("Пространство «{owner}»: логин пользователя или организации Gitea", { owner: newOwner })); const bot = giteaForBot(); const repoName = project.giteaRepo; const from = `${project.giteaOwner}/${repoName}`; const to = `${target}/${repoName}`; let dest = await bot.getRepo(target, repoName); // After a transfer the old address redirects to the new one: the same repo id means "already moved". const src = project.giteaOwner === target ? dest : await bot.getRepo(project.giteaOwner, repoName); let moved = false; if (dest && dest.owner.login.toLowerCase() !== target.toLowerCase()) dest = null; // a redirect left by an older move if (dest && src && src.id !== dest.id) throw new PeppaError(m("Репозиторий {repo} уже существует", { repo: to })); if (!dest) { if (!src) throw new PeppaError(m("Репозиторий {repo} не найден в Gitea", { repo: from })); const me = await bot.me(); if (!(await bot.canCreateIn(me.login, target))) throw new PeppaError(m("Пространство {owner} не найдено или у {login} нет прав создавать в нём репозитории", { owner: target, login: me.login })); log("transfer"); try { await bot.transferRepo(project.giteaOwner, repoName, target); } catch (e) { const status = e instanceof GiteaError ? e.status : 0; if (status === 422 || status === 409) throw new PeppaError(m("Репозиторий {repo} уже существует", { repo: to })); if (status === 403) throw new PeppaError(m("Нет прав администратора на {repo} — переносит владелец репозитория", { repo: from })); throw e; } dest = await bot.getRepo(target, repoName); if (!dest || dest.owner.login.toLowerCase() !== target.toLowerCase()) throw new PeppaError(m("Перенос {from} → {to} ждёт подтверждения в Gitea", { from, to })); moved = true; } const changed = project.giteaOwner !== dest.owner.login; if (changed) { log("project"); await db.update(projects).set({ giteaOwner: dest.owner.login }).where(eq(projects.id, project.id)); } const updated: Project = { ...project, giteaOwner: dest.owner.login }; forgetRepoInfo(project.id); if (existsSync(project.workspacePath)) { log("origin"); await git(project.workspacePath, "remote", "set-url", "origin", dest.clone_url); } log("protect branch"); await ensureBranchProtection(db, updated, { clients: [bot], log }); log("ci"); const ciError = await setupCi(db, updated).then( () => null, (e: Error) => e.message, ); if (moved || changed) await logEvent(db, { projectId: project.id, type: "repo_transferred", payload: { from, to } }); return { project: updated, from, to, moved, ciError }; }