PEP-4: peppa project transfer — move a project's repo to another Gitea namespace (origin, CI runner, secret, webhook)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
6a0cb9c7c3
commit
748216eef2
2
openspec/changes/pep-4-gitea-org/.openspec.yaml
Normal file
2
openspec/changes/pep-4-gitea-org/.openspec.yaml
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-14
|
||||||
80
openspec/changes/pep-4-gitea-org/design.md
Normal file
80
openspec/changes/pep-4-gitea-org/design.md
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
# Design
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Мотивация — в proposal.md. Что есть сейчас (проверено 2026-11-14, Gitea 1.22.6):
|
||||||
|
|
||||||
|
- Организации `peppa` нет, имя свободно (ни пользователя, ни организации). `peppa-bot` не админ
|
||||||
|
Gitea и не состоит ни в одной организации; может ли он создавать организации — видно только
|
||||||
|
по ответу на `POST /orgs`.
|
||||||
|
- В пространстве `peppa-bot` 12 репозиториев: `peppa`, `template` (приватный, шаблон) и 10
|
||||||
|
проектов пользователей. В БД у всех 11 проектов `gitea_owner = peppa-bot`.
|
||||||
|
- Раннер CI зарегистрирован на уровне пользователя `peppa-bot`; `setupCi` для проекта с другим
|
||||||
|
владельцем сам регистрирует раннер на репозиторий (метка `repo-<owner>--<repo>`).
|
||||||
|
- Адрес `peppa-bot/peppa` вшит в `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`;
|
||||||
|
шаблон — `GITEA_TEMPLATE_REPO` (env, умолчание в `env.ts`, `push-template.sh`, `.env.example`).
|
||||||
|
- Открыт PR #79 (`task/pep-87`), идут сессии PEP — работа параллельными волнами.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- `peppa/peppa` и `peppa/template` работают как раньше: CI, вебхуки, превью, правила агентов.
|
||||||
|
- Перенос повторяем и проверяем кодом (команда + тест на `mock-gitea`), а не разовым curl.
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- Перенос проектов пользователей из `peppa-bot`; смена пространства для новых проектов (PEP-68).
|
||||||
|
- Команды и права внутри организации сверх Owners; официальный прод (PEP-18).
|
||||||
|
- UI/MCP для переноса — только CLI администратора (как `project visibility`).
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **Организацию создаёт `peppa-bot` (`POST /orgs`, visibility public)**, если Gitea разрешит;
|
||||||
|
403 — просим PM создать её админом и добавить `peppa-bot` в Owners. Давать боту права админа
|
||||||
|
Gitea не нужно и не хочется: ему достаточно быть владельцем одной организации.
|
||||||
|
Вторым владельцем добавляем учётку PM в Gitea — организация не должна держаться на одном боте.
|
||||||
|
2. **Перенос — операция `transferProject` в runner + `peppa project transfer`**, а не ручные
|
||||||
|
шаги. Порядок: проверить пространство и отсутствие `<owner>/<repo>` → `POST
|
||||||
|
/repos/{o}/{r}/transfer` (владелец организации переносит сразу, без подтверждения) → обновить
|
||||||
|
`projects.gitea_owner` → `git remote set-url origin` в рабочей копии (worktree делят конфиг) →
|
||||||
|
`setupCi` (раннер на репозиторий, секрет, вебхук) → событие `repo_transferred`. Каждый шаг
|
||||||
|
идемпотентен: если репозиторий уже на новом месте, шаг Gitea пропускается.
|
||||||
|
Альтернатива — UPDATE в БД руками — не оставляет следа в журнале и забывает раннер.
|
||||||
|
3. **Раннер — на репозиторий** (существующий путь `setupCi`), не на организацию: раннер с
|
||||||
|
docker.sock хоста не должен автоматически обслуживать любой будущий репозиторий организации.
|
||||||
|
4. **`GITEA_PLATFORM_REPO`** (env, умолчание `peppa/peppa`) вместо трёх вшитых строк. Брать адрес
|
||||||
|
из проекта `PEPPA_PLATFORM_KEY` в БД нельзя: скрипты релиза и `ci.sh` работают без БД.
|
||||||
|
5. **Шаблон** — не проект Пеппы, переносится тем же вызовом клиента из задачи разово
|
||||||
|
(`peppa project transfer` его не знает); затем `GITEA_TEMPLATE_REPO=peppa/template` в `.env`,
|
||||||
|
`scripts/push-template.sh` и проверка `get_rules`. Остаётся приватным и `template: true`.
|
||||||
|
6. **Порядок на живой системе**: сначала мерж кода (умолчания новые, но `.env` ещё держит
|
||||||
|
старые адреса — ничего не ломается), затем перенос одной командой, сразу `.env` и рестарт
|
||||||
|
сервисов. Редиректы Gitea покрывают окно между шагами и чужие клоны.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- [Редирект не действует на API-запросы Пеппы по старому адресу] → адрес проекта в БД меняется
|
||||||
|
в той же команде, сразу после переноса; окно — секунды.
|
||||||
|
- [Живые сессии PEP и PR #79 в момент переноса] → git идёт через редирект; `origin` общей
|
||||||
|
рабочей копии и worktree обновляются командой. Контейнерные сессии (релей git пускает только
|
||||||
|
`owner/repo` проекта) — на PEP сейчас не используются; проверить перед переносом.
|
||||||
|
- [Секрет Actions и вебхук могут не пережить перенос] → `setupCi` ставит их заново в любом случае.
|
||||||
|
- [Раннер уровня `peppa-bot` перестаёт видеть `peppa/peppa`] → регистрация на репозиторий — часть
|
||||||
|
команды; проверка — зелёный прогон CI на PR этой стори после переноса.
|
||||||
|
- [Кто-то создаст `peppa-bot/peppa` заново и сломает редирект] → не создавать; записать в память.
|
||||||
|
- [Bare-клон будущего прода `~/peppa/repo.git`] → `PEPPA_RELEASE_REMOTE` по умолчанию от
|
||||||
|
`GITEA_PLATFORM_REPO`; существующему клону — `git remote set-url`.
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
1. PR с кодом и тестами — зелёный CI на старом адресе, мерж.
|
||||||
|
2. Организация `peppa` (бот или PM), `peppa-bot` и PM — Owners.
|
||||||
|
3. `peppa db backup`, `peppa project transfer PEP peppa`; перенос `template`.
|
||||||
|
4. `.env`: `GITEA_TEMPLATE_REPO=peppa/template`; рестарт web/bot/watchdog; `peppa status`.
|
||||||
|
5. Проверки: `git fetch` в рабочей копии, `get_rules`, пробный PR/пуш → проверки `peppa/*`
|
||||||
|
зелёные и видны на карточке, футер ведёт на `peppa/peppa`.
|
||||||
|
|
||||||
|
Откат: `peppa project transfer PEP peppa-bot`, обратный перенос `template`, прежний `.env`.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
- Логин PM в Gitea для второго владельца организации — нужен только на шаге 2, на код не влияет.
|
||||||
46
openspec/changes/pep-4-gitea-org/proposal.md
Normal file
46
openspec/changes/pep-4-gitea-org/proposal.md
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# Proposal
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Репозитории платформы (`peppa-bot/peppa`, `peppa-bot/template`) лежат в личном пространстве
|
||||||
|
служебной учётки `peppa-bot` вперемешку с проектами пользователей без Gitea (PEP-68). Платформа
|
||||||
|
мультипользовательская (эпик #2): её код и шаблон должны принадлежать организации `peppa`, где
|
||||||
|
владельцев несколько и права задаются командами, а не паролем одного бота.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- В Gitea создаётся организация `peppa` (публичная); `peppa-bot` — в команде Owners.
|
||||||
|
- `peppa-bot/peppa` → `peppa/peppa`, `peppa-bot/template` → `peppa/template` (перенос Gitea:
|
||||||
|
история, PR, issues, вебхуки и секреты Actions сохраняются, старые адреса редиректят).
|
||||||
|
- Новая команда `peppa project transfer <KEY> <owner>` — переносит репозиторий проекта в другое
|
||||||
|
пространство Gitea и чинит всё, что от адреса зависит: запись проекта, `origin` рабочей копии,
|
||||||
|
раннер CI, секрет и вебхук. Перенос `peppa` делается ею же; повторный запуск безопасен.
|
||||||
|
- `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; адрес репозитория платформы перестаёт быть
|
||||||
|
вшитым (`peppa-bot/peppa` в футере, `scripts/ci.sh`, `scripts/peppa-release.sh`) — одна
|
||||||
|
настройка `GITEA_PLATFORM_REPO` (по умолчанию `peppa/peppa`).
|
||||||
|
- Живая система: `.env`, `origin` рабочей копии, раннер CI на `peppa/peppa`, документация.
|
||||||
|
- Проекты пользователей в пространстве `peppa-bot` **не переносятся** (вне scope).
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
Нет.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
- `project-provisioning`: новое требование — перенос репозитория проекта в другое пространство
|
||||||
|
Gitea командой CLI.
|
||||||
|
- `peppa-ci`: репозиторий платформы в требованиях — `peppa/peppa` вместо `peppa-bot/peppa`.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- Gitea: новая организация, перенос двух репозиториев (обратим обратным переносом, но адреса
|
||||||
|
меняются для всех клонов); нужно право `peppa-bot` создавать организации **или** организация,
|
||||||
|
созданная админом Gitea с `peppa-bot` в Owners.
|
||||||
|
- Код: `packages/core/src/gitea.ts` (перенос), `packages/runner` (новая операция, `ci.ts`),
|
||||||
|
`packages/cli`, `packages/shared/src/env.ts`, `apps/web/components/Footer.tsx`, `scripts/ci.sh`,
|
||||||
|
`scripts/peppa-release.sh`, `scripts/push-template.sh`, `.env.example`, `mock-gitea`.
|
||||||
|
- Данные: `projects.gitea_owner` проекта PEP (`peppa-bot` → `peppa`), без миграций схемы.
|
||||||
|
- CI: раннер уровня пользователя `peppa-bot` перестаёт покрывать `peppa/peppa` — регистрация на
|
||||||
|
репозиторий. Открытые PR (сейчас #79) и живые сессии PEP продолжают работать через редирект.
|
||||||
|
- Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help`.
|
||||||
48
openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
Normal file
48
openspec/changes/pep-4-gitea-org/specs/peppa-ci/spec.md
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
# Spec Delta
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Статус проверки в PR
|
||||||
|
`scripts/ci.sh --pr <N>` (запасной путь, если раннер недоступен) SHALL проверять голову PR N репозитория платформы
|
||||||
|
(`GITEA_PLATFORM_REPO`, по умолчанию `peppa/peppa`) в отдельном
|
||||||
|
временном worktree и выставлять коммиту статус `peppa/ci`: `pending` на старте, затем
|
||||||
|
`success` или `failure` с описанием; рабочая копия, из которой запущен скрипт, не меняется.
|
||||||
|
|
||||||
|
#### Scenario: Зелёный PR
|
||||||
|
- **GIVEN** открыт PR 15, его голова проходит все проверки
|
||||||
|
- **WHEN** запускается `scripts/ci.sh --pr 15`
|
||||||
|
- **THEN** у головного коммита PR статус `peppa/ci` = `success` с описанием «passed in <N> min»
|
||||||
|
- **AND** лог прогона лежит в `~/.peppa/ci/<sha>.log`, временный worktree удалён
|
||||||
|
|
||||||
|
#### Scenario: Красный PR
|
||||||
|
- **GIVEN** открыт PR 16, в его голове падает e2e
|
||||||
|
- **WHEN** запускается `scripts/ci.sh --pr 16`
|
||||||
|
- **THEN** статус `peppa/ci` = `failure`, в описании упавший шаг «FAIL e2e 1/1» и путь к логу
|
||||||
|
- **AND** код выхода 1
|
||||||
|
|
||||||
|
#### Scenario: Нет такого PR
|
||||||
|
- **GIVEN** в репозитории нет PR 999
|
||||||
|
- **WHEN** запускается `scripts/ci.sh --pr 999`
|
||||||
|
- **THEN** выводится «PR 999 not found», статусы не выставляются, код выхода 2
|
||||||
|
|
||||||
|
### Requirement: Проверки на каждый PR в Gitea Actions
|
||||||
|
Workflow `.gitea/workflows/ci.yml` репозитория `peppa/peppa` SHALL на каждый PR из ветки этого
|
||||||
|
репозитория и на push в `main` запускать `scripts/ci.sh` на раннере Пеппы `peppa-trusted` (PEP-57),
|
||||||
|
с тестовой БД `peppa_test_ci_r<run_id>` на Postgres хоста, и выставлять статус коммита
|
||||||
|
`peppa-ci / ci (pull_request)`; PR из форков не запускаются.
|
||||||
|
|
||||||
|
#### Scenario: PR зелёный
|
||||||
|
- **GIVEN** PR из ветки `task/PEP-22`, все проверки проходят
|
||||||
|
- **WHEN** ветка пушится
|
||||||
|
- **THEN** у головного коммита статус `peppa-ci / ci (pull_request)` = `success` («Successful in <N>m<S>s»)
|
||||||
|
- **AND** БД `peppa_test_ci_r<run_id>` после job не существует
|
||||||
|
|
||||||
|
#### Scenario: PR красный
|
||||||
|
- **GIVEN** в голове PR падает один e2e-тест
|
||||||
|
- **WHEN** job доходит до шага `ci`
|
||||||
|
- **THEN** статус = `failure` («Failing after <N>m<S>s»), в логе job строка «ci: FAIL e2e 1/1» и имя упавшего теста
|
||||||
|
|
||||||
|
#### Scenario: PR из форка
|
||||||
|
- **GIVEN** PR открыт из форка репозитория
|
||||||
|
- **WHEN** Gitea обрабатывает событие `pull_request`
|
||||||
|
- **THEN** job пропускается и на раннере с docker.sock хоста чужой код не выполняется
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
# Spec Delta
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Перенос репозитория проекта в другое пространство
|
||||||
|
Команда `peppa project transfer <KEY> <owner>` SHALL переносить репозиторий проекта в пространство
|
||||||
|
`<owner>` (организация или пользователь Gitea) и приводить проект в рабочее состояние по новому
|
||||||
|
адресу: адрес проекта в Пеппе, `origin` рабочей копии, раннер CI, секрет и вебхук. Повторный запуск
|
||||||
|
после частичного сбоя SHALL доводить перенос до конца без ошибки.
|
||||||
|
|
||||||
|
#### Scenario: Перенос в организацию
|
||||||
|
- **GIVEN** проект `DEMO` с репозиторием `peppa-bot/demo` и организация `acme`, где `peppa-bot` — владелец
|
||||||
|
- **WHEN** выполняется `peppa project transfer DEMO acme`
|
||||||
|
- **THEN** репозиторий доступен как `acme/demo`, вывод — «DEMO: peppa-bot/demo → acme/demo»
|
||||||
|
- **AND** страница проекта в вебе ссылается на `acme/demo`
|
||||||
|
- **AND** `git remote get-url origin` в рабочей копии оканчивается на `/acme/demo.git`
|
||||||
|
- **AND** в журнале проекта есть событие «репозиторий перенесён» со старым и новым адресом
|
||||||
|
|
||||||
|
#### Scenario: CI после переноса
|
||||||
|
- **GIVEN** проект `DEMO` с подключённым CI перенесён из `peppa-bot/demo` в `acme/demo`
|
||||||
|
- **WHEN** в `acme/demo` открывается PR
|
||||||
|
- **THEN** проверки `peppa/*` выполняются на раннере Пеппы и их отчёты приходят на карточку стори
|
||||||
|
|
||||||
|
#### Scenario: Повторный запуск
|
||||||
|
- **GIVEN** репозиторий проекта `DEMO` уже находится в `acme/demo`, а в Пеппе записан `peppa-bot/demo`
|
||||||
|
- **WHEN** выполняется `peppa project transfer DEMO acme`
|
||||||
|
- **THEN** перенос в Gitea не запрашивается, адрес проекта и `origin` становятся `acme/demo`, код выхода 0
|
||||||
|
|
||||||
|
#### Scenario: Пространства нет или нет прав
|
||||||
|
- **GIVEN** организации `nope` в Gitea нет
|
||||||
|
- **WHEN** выполняется `peppa project transfer DEMO nope`
|
||||||
|
- **THEN** выводится «Пространство nope не найдено или у peppa-bot нет прав создавать в нём репозитории», код выхода 1
|
||||||
|
- **AND** репозиторий остаётся `peppa-bot/demo`, адрес проекта в Пеппе не меняется
|
||||||
|
|
||||||
|
#### Scenario: В пространстве уже есть такой репозиторий
|
||||||
|
- **GIVEN** в организации `acme` уже есть другой репозиторий `demo`
|
||||||
|
- **WHEN** выполняется `peppa project transfer DEMO acme`
|
||||||
|
- **THEN** выводится «Репозиторий acme/demo уже существует», код выхода 1, ничего не меняется
|
||||||
27
openspec/changes/pep-4-gitea-org/tasks.md
Normal file
27
openspec/changes/pep-4-gitea-org/tasks.md
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
## 1. Перенос репозитория проекта (код)
|
||||||
|
|
||||||
|
- [x] 1.1 `GiteaClient`: `transferRepo(owner, repo, newOwner)` и проверка пространства (организация/пользователь, право создавать репозитории); `mock-gitea` — `POST /repos/{o}/{r}/transfer` (404 пространства, 409 занятое имя, редирект старого адреса) — проверка: юнит-вызовы мока в новом тесте
|
||||||
|
- [x] 1.2 `transferProject` в `packages/runner` (перенос → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` → событие `repo_transferred` через `logEvent`), идемпотентно — проверка: `project-transfer.test.ts`, сценарии «Перенос в организацию», «CI после переноса», «Повторный запуск»
|
||||||
|
- [x] 1.3 CLI `peppa project transfer <KEY> <owner>` (админ, строка в справке) и ошибки «Пространства нет или нет прав», «В пространстве уже есть такой репозиторий» — проверка: те же тесты по сценариям, код выхода 1 и неизменный проект
|
||||||
|
- [x] 1.4 Текст события «репозиторий перенесён» в журнале/чате проекта (`EVENT_TEXT`) — проверка: сценарий «Перенос в организацию» видит событие
|
||||||
|
|
||||||
|
## 2. Адреса платформы без вшитых строк
|
||||||
|
|
||||||
|
- [ ] 2.1 `GITEA_PLATFORM_REPO` в `packages/shared/src/env.ts` (умолчание `peppa/peppa`), `GITEA_TEMPLATE_REPO` по умолчанию `peppa/template`; `.env.example` — проверка: `pnpm typecheck`
|
||||||
|
- [ ] 2.2 `Footer.tsx`, `scripts/ci.sh`, `scripts/peppa-release.sh`, `scripts/push-template.sh` берут адрес из env — проверка: `git grep 'peppa-bot/peppa\|peppa-bot/template'` вне архива пуст, `bash -n` скриптов
|
||||||
|
- [ ] 2.3 Документация: `AGENTS.md`, `docs/HANDOFF.md`, `/help` (где репозиторий платформы, команда переноса) — проверка: вычитка, ссылки на `peppa/peppa`
|
||||||
|
- [ ] 2.4 Локальные проверки `bash .gitea/peppa-check.sh install|typecheck|build|test` зелёные, PR, мерж после зелёного CI
|
||||||
|
|
||||||
|
## 3. Перенос на живой системе (после одобрения PM и мержа кода)
|
||||||
|
|
||||||
|
- [ ] 3.1 Организация `peppa` (публичная): `POST /orgs` от `peppa-bot`; при 403 — `ask_pm` создать и добавить `peppa-bot` в Owners; PM — второй владелец — проверка: `GET /orgs/peppa` 200, `peppa-bot` в Owners
|
||||||
|
- [ ] 3.2 `peppa db backup`; убедиться, что контейнерных сессий PEP нет; `peppa project transfer PEP peppa` — проверка: `GET /repos/peppa/peppa` 200, `git fetch` в рабочей копии, проект PEP в вебе ссылается на `peppa/peppa`
|
||||||
|
- [ ] 3.3 Перенос `peppa-bot/template` → `peppa/template`, `GITEA_TEMPLATE_REPO=peppa/template` в `.env`, рестарт web/bot/watchdog — проверка: `peppa status` зелёный, MCP `get_rules` отдаёт свежий RULES.md, `scripts/push-template.sh` проходит
|
||||||
|
- [ ] 3.4 Сквозная проверка: пуш в ветку стори → проверки `peppa/*` на `peppa/peppa` зелёные и видны на карточке; PR #79 и другие открытые PR на месте; футер ведёт на `peppa/peppa`
|
||||||
|
- [ ] 3.5 Память проекта (`remember`): адреса `peppa/peppa`, `peppa/template`, не создавать `peppa-bot/peppa` заново (сломает редирект)
|
||||||
|
|
||||||
|
## Workflow follow-up
|
||||||
|
|
||||||
|
- `openspec archive pep-4-gitea-org`, PR, `update_task(status: review)`.
|
||||||
@ -74,7 +74,7 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner
|
|||||||
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
||||||
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||||
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
@ -87,6 +87,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
|||||||
peppa project autonomy <KEY> [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes)
|
peppa project autonomy <KEY> [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes)
|
||||||
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit)
|
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit)
|
||||||
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
|
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
|
||||||
|
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
|
||||||
peppa project import-issues <KEY> (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
|
peppa project import-issues <KEY> (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
|
||||||
peppa project list
|
peppa project list
|
||||||
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
|
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
|
||||||
@ -319,6 +320,18 @@ async function main(): Promise<void> {
|
|||||||
if (failed) process.exitCode = 1;
|
if (failed) process.exitCode = 1;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "project transfer": {
|
||||||
|
const [key, owner] = args;
|
||||||
|
if (!key || !owner) throw new PeppaError("usage: peppa project transfer <KEY> <owner>");
|
||||||
|
const p = await getProject(db, key);
|
||||||
|
const r = await transferProject(db, p, owner, { log: (step) => console.log(`… ${step}`) });
|
||||||
|
console.log(`${p.key}: ${r.from} → ${r.to}${r.moved ? "" : " (репозиторий уже там)"}`);
|
||||||
|
if (r.ciError) {
|
||||||
|
console.log(`CI: ${r.ciError} — повторите: peppa ci connect ${p.key}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "project autonomy": {
|
case "project autonomy": {
|
||||||
// PEP-23: peppa project autonomy <KEY> [manual|assisted|auto] [key=value…]
|
// PEP-23: peppa project autonomy <KEY> [manual|assisted|auto] [key=value…]
|
||||||
const [key, ...rest] = args;
|
const [key, ...rest] = args;
|
||||||
|
|||||||
@ -274,6 +274,8 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
|||||||
},
|
},
|
||||||
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
||||||
pm_comment: () => null, // handled separately: a person's message
|
pm_comment: () => null, // handled separately: a person's message
|
||||||
|
// PEP-4: the project's repo moved to another Gitea namespace.
|
||||||
|
repo_transferred: (p) => ({ text: `📦 Репозиторий перенесён: ${s(p.from)} → ${s(p.to)}`, important: true }),
|
||||||
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
||||||
intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
|
intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
|
||||||
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
|
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
|
||||||
|
|||||||
@ -151,6 +151,26 @@ export class GiteaClient {
|
|||||||
return this.request<GiteaRepo>("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate });
|
return this.request<GiteaRepo>("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves a repo to another namespace (PEP-4). Gitea moves it at once only when the token owner
|
||||||
|
* may create repos there; otherwise the transfer stays pending — check where the repo is after.
|
||||||
|
*/
|
||||||
|
transferRepo(owner: string, name: string, newOwner: string) {
|
||||||
|
return this.request<GiteaRepo>("POST", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/transfer`, { new_owner: newOwner });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if the token owner `login` may create repos in `namespace` (own account or an org with that right). */
|
||||||
|
async canCreateIn(login: string, namespace: string): Promise<boolean> {
|
||||||
|
if (namespace.toLowerCase() === login.toLowerCase()) return true;
|
||||||
|
try {
|
||||||
|
const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(namespace)}/permissions`);
|
||||||
|
return !!p?.can_create_repository;
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof GiteaError && (e.status === 404 || e.status === 403)) return false;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** True if `name` is an organization (false for a user account). */
|
/** True if `name` is an organization (false for a user account). */
|
||||||
async isOrg(name: string): Promise<boolean> {
|
async isOrg(name: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -12,6 +12,7 @@ export * from "./share.ts";
|
|||||||
export * from "./limits.ts";
|
export * from "./limits.ts";
|
||||||
export * from "./monitor.ts";
|
export * from "./monitor.ts";
|
||||||
export * from "./ci.ts";
|
export * from "./ci.ts";
|
||||||
|
export * from "./transfer.ts";
|
||||||
export * from "./incidents.ts";
|
export * from "./incidents.ts";
|
||||||
export * from "./triage.ts";
|
export * from "./triage.ts";
|
||||||
export * from "./ci-feedback.ts";
|
export * from "./ci-feedback.ts";
|
||||||
|
|||||||
@ -157,6 +157,9 @@ const DESCRIBE_CACHE_MS = 60_000;
|
|||||||
// The project page refreshes every few seconds; Gitea is asked at most once a minute per project.
|
// The project page refreshes every few seconds; Gitea is asked at most once a minute per project.
|
||||||
const describeCache = new Map<number, { at: number; info: RepoInfo }>();
|
const describeCache = new Map<number, { at: number; info: RepoInfo }>();
|
||||||
|
|
||||||
|
/** Drops the cached repo info (the repo moved or changed outside this module). */
|
||||||
|
export const forgetRepoInfo = (projectId: number) => void describeCache.delete(projectId);
|
||||||
|
|
||||||
/** Where the project's repo is and who can see it, asked from Gitea (owner's client, then peppa-bot). */
|
/** Where the project's repo is and who can see it, asked from Gitea (owner's client, then peppa-bot). */
|
||||||
export async function describeRepo(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<RepoInfo> {
|
export async function describeRepo(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<RepoInfo> {
|
||||||
const hit = describeCache.get(project.id);
|
const hit = describeCache.get(project.id);
|
||||||
|
|||||||
74
packages/runner/src/transfer.ts
Normal file
74
packages/runner/src/transfer.ts
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
// 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 { 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 { 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<TransferResult> {
|
||||||
|
const log = o.log ?? (() => {});
|
||||||
|
const target = newOwner.trim();
|
||||||
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(target)) throw new PeppaError(`Пространство «${newOwner}»: логин пользователя или организации Gitea`);
|
||||||
|
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(`Репозиторий ${to} уже существует`);
|
||||||
|
if (!dest) {
|
||||||
|
if (!src) throw new PeppaError(`Репозиторий ${from} не найден в Gitea`);
|
||||||
|
const me = await bot.me();
|
||||||
|
if (!(await bot.canCreateIn(me.login, target))) throw new PeppaError(`Пространство ${target} не найдено или у ${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(`Репозиторий ${to} уже существует`);
|
||||||
|
if (status === 403) throw new PeppaError(`Нет прав администратора на ${from} — переносит владелец репозитория`);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
dest = await bot.getRepo(target, repoName);
|
||||||
|
if (!dest || dest.owner.login.toLowerCase() !== target.toLowerCase()) throw new PeppaError(`Перенос ${from} → ${to} ждёт подтверждения в Gitea`);
|
||||||
|
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("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 };
|
||||||
|
}
|
||||||
@ -4,7 +4,7 @@
|
|||||||
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
|
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
import { createHmac } from "node:crypto";
|
import { createHmac } from "node:crypto";
|
||||||
import { mkdirSync, mkdtempSync } from "node:fs";
|
import { mkdirSync, mkdtempSync, renameSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { createServer, type Server } from "node:http";
|
import { createServer, type Server } from "node:http";
|
||||||
import type { AddressInfo } from "node:net";
|
import type { AddressInfo } from "node:net";
|
||||||
@ -59,6 +59,8 @@ export class MockGitea {
|
|||||||
readonly users = new Map<string, MockGiteaUser>();
|
readonly users = new Map<string, MockGiteaUser>();
|
||||||
readonly oauthCodes = new Map<string, string>(); // code → token
|
readonly oauthCodes = new Map<string, string>(); // code → token
|
||||||
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
|
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
|
||||||
|
/** PEP-4: old `owner/name` → current one, like Gitea's redirects after a transfer. */
|
||||||
|
readonly redirects = new Map<string, string>();
|
||||||
private seq = 1;
|
private seq = 1;
|
||||||
private server: Server | null = null;
|
private server: Server | null = null;
|
||||||
url = "";
|
url = "";
|
||||||
@ -98,6 +100,10 @@ export class MockGitea {
|
|||||||
return new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
return new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private isOrg(name: string) {
|
||||||
|
return [...this.users.values()].some((u) => u.orgs?.includes(name));
|
||||||
|
}
|
||||||
|
|
||||||
addUser(u: MockGiteaUser) {
|
addUser(u: MockGiteaUser) {
|
||||||
this.users.set(u.token, u);
|
this.users.set(u.token, u);
|
||||||
return u;
|
return u;
|
||||||
@ -300,12 +306,12 @@ export class MockGitea {
|
|||||||
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } };
|
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } };
|
||||||
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
|
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
|
||||||
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {
|
||||||
|
if (!this.isOrg(decodeURIComponent(m[2]!))) return { status: 404, body: { message: "org does not exist" } };
|
||||||
return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } };
|
return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } };
|
||||||
}
|
}
|
||||||
if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) {
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) {
|
||||||
const name = decodeURIComponent(m[1]!);
|
const name = decodeURIComponent(m[1]!);
|
||||||
const isOrg = [...this.users.values()].some((u) => u.orgs?.includes(name));
|
return this.isOrg(name) ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } };
|
||||||
return isOrg ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } };
|
|
||||||
}
|
}
|
||||||
if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) {
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) {
|
||||||
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
||||||
@ -322,6 +328,29 @@ export class MockGitea {
|
|||||||
this.runnerTokens.push({ scope: `user:${me.login}`, token });
|
this.runnerTokens.push({ scope: `user:${me.login}`, token });
|
||||||
return { status: 200, body: { token } };
|
return { status: 200, body: { token } };
|
||||||
}
|
}
|
||||||
|
if (method === "POST" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/transfer$/))) {
|
||||||
|
// Gitea: repo admin only; unknown namespace → 404; name taken there → 422; the doer may
|
||||||
|
// create repos in the target → moved at once (202), otherwise the transfer stays pending (201).
|
||||||
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
||||||
|
if (!r) return { status: 404, body: { message: "not found" } };
|
||||||
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
|
||||||
|
const to = String(body.new_owner ?? "");
|
||||||
|
const users = [...this.users.values()];
|
||||||
|
if (!this.isOrg(to) && !users.some((u) => u.login === to)) return { status: 404, body: { message: "new owner does not exist" } };
|
||||||
|
if (this.repos.has(`${to}/${r.name}`)) return { status: 422, body: { message: "The repository with the same name already exists." } };
|
||||||
|
if (!(to === me.login || (me.orgs ?? []).includes(to))) return { status: 201, body: this.json(r, me) };
|
||||||
|
const old = `${r.owner}/${r.name}`;
|
||||||
|
const path2 = join(this.dir, to, `${r.name}.git`);
|
||||||
|
mkdirSync(join(this.dir, to), { recursive: true });
|
||||||
|
renameSync(r.path, path2);
|
||||||
|
this.repos.delete(old);
|
||||||
|
Object.assign(r, { owner: to, path: path2, admins: new Set([to, ...users.filter((u) => u.orgs?.includes(to)).map((u) => u.login)]) });
|
||||||
|
this.repos.set(`${to}/${r.name}`, r);
|
||||||
|
for (const [k, v] of this.redirects) if (v === old) this.redirects.set(k, `${to}/${r.name}`);
|
||||||
|
this.redirects.delete(`${to}/${r.name}`);
|
||||||
|
this.redirects.set(old, `${to}/${r.name}`);
|
||||||
|
return { status: 202, body: this.json(r, me) };
|
||||||
|
}
|
||||||
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) {
|
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) {
|
||||||
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
||||||
if (!r) return { status: 404, body: { message: "not found" } };
|
if (!r) return { status: 404, body: { message: "not found" } };
|
||||||
@ -329,7 +358,9 @@ export class MockGitea {
|
|||||||
if (res) return res;
|
if (res) return res;
|
||||||
}
|
}
|
||||||
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) {
|
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) {
|
||||||
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
const full = `${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`;
|
||||||
|
// A moved repo answers GET by its old address too (Gitea redirects, fetch follows).
|
||||||
|
const r = this.repos.get(full) ?? (method === "GET" ? this.repos.get(this.redirects.get(full) ?? "") : undefined);
|
||||||
if (!r) return { status: 404, body: { message: "not found" } };
|
if (!r) return { status: 404, body: { message: "not found" } };
|
||||||
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
|
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
|
||||||
if (method === "PATCH") {
|
if (method === "PATCH") {
|
||||||
|
|||||||
141
packages/testkit/test/project-transfer.test.ts
Normal file
141
packages/testkit/test/project-transfer.test.ts
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
// PEP-4: `peppa project transfer <KEY> <owner>` — the project's repo moves to another Gitea
|
||||||
|
// namespace and the project keeps working there (address, origin, CI runner, secret, webhook).
|
||||||
|
// Tests are named after the scenarios of openspec/specs/project-provisioning.
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { execFile, execFileSync } from "node:child_process";
|
||||||
|
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
import { after, before, describe, test } from "node:test";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { events, projects } from "@peppa/db";
|
||||||
|
import { core, db, runner, teardown } from "./helpers.ts";
|
||||||
|
import { MockGitea } from "../src/mock-gitea.ts";
|
||||||
|
|
||||||
|
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||||
|
const TMP = mkdtempSync(join(tmpdir(), "peppa-transfer-"));
|
||||||
|
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||||
|
|
||||||
|
const gitea = new MockGitea(join(TMP, "gitea"));
|
||||||
|
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-transfer-bot", orgs: ["mock-acme"] };
|
||||||
|
const ORG = "mock-acme";
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await gitea.start();
|
||||||
|
process.env.GITEA_URL = gitea.url;
|
||||||
|
process.env.GITEA_TOKEN = BOT.token;
|
||||||
|
gitea.addUser(BOT);
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await gitea.stop();
|
||||||
|
await teardown();
|
||||||
|
});
|
||||||
|
|
||||||
|
/** A project with a repo in peppa-bot's namespace and a cloned working copy. */
|
||||||
|
async function project(slug: string, key: string) {
|
||||||
|
const repo = gitea.addRepo(BOT.login, slug, { files: { "README.md": `# ${slug}\n` } });
|
||||||
|
const ws = join(TMP, "ws", slug);
|
||||||
|
execFileSync("git", ["clone", "-q", repo.path, ws]);
|
||||||
|
return core.createProject(db, { slug, key, name: key, giteaOwner: BOT.login, workspacePath: ws, ownerId: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cli(...a: string[]) {
|
||||||
|
try {
|
||||||
|
const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "transfer", ...a], { encoding: "utf8", env: process.env });
|
||||||
|
return { code: 0, out: r.stdout + r.stderr };
|
||||||
|
} catch (e) {
|
||||||
|
const x = e as { code?: number; stdout?: string; stderr?: string };
|
||||||
|
return { code: x.code ?? 1, out: `${x.stdout ?? ""}${x.stderr ?? ""}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const origin = (ws: string) => execFileSync("git", ["-C", ws, "remote", "get-url", "origin"], { encoding: "utf8" }).trim();
|
||||||
|
const reload = async (id: number) => (await db.select().from(projects).where(eq(projects.id, id)))[0]!;
|
||||||
|
const registrations = () => {
|
||||||
|
const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl");
|
||||||
|
return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string }) : [];
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("project transfer (PEP-4)", () => {
|
||||||
|
let demoId = 0;
|
||||||
|
|
||||||
|
test("Перенос в организацию", async () => {
|
||||||
|
const p = await project("mock-demo", "MTDEMO");
|
||||||
|
demoId = p.id;
|
||||||
|
const r = await cli("MTDEMO", ORG);
|
||||||
|
assert.equal(r.code, 0, r.out);
|
||||||
|
assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo\n/);
|
||||||
|
assert.ok(gitea.repos.has(`${ORG}/mock-demo`));
|
||||||
|
assert.ok(!gitea.repos.has("peppa-bot/mock-demo"));
|
||||||
|
const now = await reload(p.id);
|
||||||
|
assert.equal(now.giteaOwner, ORG);
|
||||||
|
const repo = await runner.describeRepo(db, now, { fresh: true });
|
||||||
|
assert.equal(repo.fullName, `${ORG}/mock-demo`); // what the project page links to
|
||||||
|
assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`), origin(p.workspacePath));
|
||||||
|
execFileSync("git", ["-C", p.workspacePath, "fetch", "-q", "origin"]);
|
||||||
|
const ev = (await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred");
|
||||||
|
assert.equal(ev.length, 1);
|
||||||
|
assert.deepEqual(ev[0]!.payload, { from: "peppa-bot/mock-demo", to: `${ORG}/mock-demo` });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("CI после переноса", async () => {
|
||||||
|
// The bot-level runner no longer covers the repo: it gets its own, plus the report secret and the webhook.
|
||||||
|
const repo = gitea.repo(ORG, "mock-demo");
|
||||||
|
assert.ok(registrations().some((x) => x.name === `repo-${ORG}--mock-demo`), JSON.stringify(registrations()));
|
||||||
|
assert.equal(repo.secrets[runner.CI_SECRET_NAME], core.projectHookSecret(demoId));
|
||||||
|
assert.equal(repo.hooks.length, 1);
|
||||||
|
assert.equal(repo.hooks[0]!.url, runner.giteaHookUrl());
|
||||||
|
assert.deepEqual(repo.hooks[0]!.events, runner.GITEA_HOOK_EVENTS);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Повторный запуск", async () => {
|
||||||
|
// Peppa's side lost: the repo is already in the org, the project and origin still point to the old place.
|
||||||
|
const p = await reload(demoId);
|
||||||
|
await db.update(projects).set({ giteaOwner: BOT.login }).where(eq(projects.id, demoId));
|
||||||
|
execFileSync("git", ["-C", p.workspacePath, "remote", "set-url", "origin", join(TMP, "gone", "peppa-bot", "mock-demo.git")]);
|
||||||
|
const id = gitea.repo(ORG, "mock-demo").id;
|
||||||
|
const r = await cli("MTDEMO", ORG);
|
||||||
|
assert.equal(r.code, 0, r.out);
|
||||||
|
assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo \(репозиторий уже там\)/);
|
||||||
|
assert.equal(gitea.repo(ORG, "mock-demo").id, id);
|
||||||
|
assert.equal((await reload(demoId)).giteaOwner, ORG);
|
||||||
|
assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`));
|
||||||
|
// …and once more, with nothing left to fix.
|
||||||
|
const again = await cli("MTDEMO", ORG);
|
||||||
|
assert.equal(again.code, 0, again.out);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Пространства нет или нет прав", async () => {
|
||||||
|
const p = await project("mock-stay", "MTSTAY");
|
||||||
|
const before = origin(p.workspacePath);
|
||||||
|
const r = await cli("MTSTAY", "mock-nope");
|
||||||
|
assert.equal(r.code, 1, r.out);
|
||||||
|
assert.match(r.out, /Пространство mock-nope не найдено или у peppa-bot нет прав создавать в нём репозитории/);
|
||||||
|
assert.ok(gitea.repos.has("peppa-bot/mock-stay"));
|
||||||
|
assert.equal((await reload(p.id)).giteaOwner, BOT.login);
|
||||||
|
assert.equal(origin(p.workspacePath), before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("В пространстве уже есть такой репозиторий", async () => {
|
||||||
|
const p = await project("mock-twin", "MTTWIN");
|
||||||
|
gitea.addRepo(ORG, "mock-twin", { files: { "README.md": "# other\n" } });
|
||||||
|
const r = await cli("MTTWIN", ORG);
|
||||||
|
assert.equal(r.code, 1, r.out);
|
||||||
|
assert.match(r.out, /Репозиторий mock-acme\/mock-twin уже существует/);
|
||||||
|
assert.ok(gitea.repos.has("peppa-bot/mock-twin"));
|
||||||
|
assert.equal((await reload(p.id)).giteaOwner, BOT.login);
|
||||||
|
assert.equal((await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred").length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("mock-gitea: перенос без права создавать в пространстве остаётся ожидающим", async () => {
|
||||||
|
gitea.addUser({ id: 72, login: "mock-other", token: "mock-token-transfer-other" });
|
||||||
|
gitea.addRepo(BOT.login, "mock-pending", { files: { "README.md": "# x\n" } });
|
||||||
|
const bot = core.giteaForBot();
|
||||||
|
await bot.transferRepo(BOT.login, "mock-pending", "mock-other");
|
||||||
|
assert.ok(gitea.repos.has("peppa-bot/mock-pending"));
|
||||||
|
assert.equal(await bot.getRepo("mock-other", "mock-pending"), null);
|
||||||
|
await assert.rejects(bot.transferRepo(BOT.login, "mock-pending", "mock-nobody"), /404/);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user