PEP-314: помощник шаблона ставит Go и временную PostgreSQL для проверок без docker

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-27 10:06:52 +00:00
parent 88d6ce4921
commit a7f992dae2
3 changed files with 293 additions and 2 deletions

View File

@ -3,8 +3,8 @@
- [x] 1.2 Дымовой тест `scripts/runner-image.sh` проверяет go, psql, initdb; тест на моке
## 2. Проверки
- [ ] 2.1 `template/.gitea/peppa-tools.sh` (go, postgres)
- [ ] 2.2 Тест помощника на моках (скачивание Go из file://, кластер из мок-бинарей, повтор)
- [x] 2.1 `template/.gitea/peppa-tools.sh` (go, postgres)
- [x] 2.2 Тест помощника на моках (скачивание Go из file://, кластер из мок-бинарей, повтор)
## 3. Шаблон выкладки
- [ ] 3.1 `template/deploy/Dockerfile.go`, `template/deploy/compose.postgres.yml`

View File

@ -0,0 +1,153 @@
// PEP-314, spec peppa-ci «Go и временная база для проверок без нового образа»: the template's
// .gitea/peppa-tools.sh runs for real — Go comes from a file:// "go.dev/dl" with a mock archive,
// PostgreSQL from mock initdb/pg_ctl/createdb (mock-pg-*), no docker anywhere.
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, test } from "node:test";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TOOLS = join(ROOT, "template/.gitea/peppa-tools.sh");
const TMP = mkdtempSync(join(tmpdir(), "peppa-stack-tools-"));
const ARCH = ({ x64: "amd64", arm64: "arm64" } as Record<string, string>)[process.arch] ?? process.arch;
const SYS_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
function exe(path: string, body: string) {
writeFileSync(path, `#!/usr/bin/env bash\n${body}\n`);
chmodSync(path, 0o755);
}
/** A mock go.dev/dl: go<ver>.linux-<arch>.tar.gz with go/bin/go answering `go version`. */
function mockGoDl(version: string): string {
const dl = mkdtempSync(join(TMP, "mock-go-dl-"));
const src = join(dl, "src");
mkdirSync(join(src, "go/bin"), { recursive: true });
exe(join(src, "go/bin/go"), `echo "go version go${version} linux/${ARCH}"`);
execFileSync("tar", ["-czf", join(dl, `go${version}.linux-${ARCH}.tar.gz`), "-C", src, "go"]);
return dl;
}
/** Mock PostgreSQL binaries: initdb makes data/, pg_ctl start/status/stop, createdb; all log to calls.log. */
function mockPgBin(): string {
const bin = mkdtempSync(join(TMP, "mock-pg-"));
exe(join(bin, "initdb"), `echo "initdb $*" >> "${bin}/calls.log"; while [ $# -gt 0 ]; do [ "$1" = -D ] && mkdir -p "$2" && echo 18 > "$2/PG_VERSION"; shift; done`);
exe(
join(bin, "pg_ctl"),
`echo "pg_ctl $*" >> "${bin}/calls.log"; d=""; cmd=""; for a in "$@"; do [ "$prev" = -D ] && d="$a"; prev="$a"; cmd="$a"; done
case "$cmd" in
start) touch "$d/running" ;;
status) [ -f "$d/running" ] ;;
stop) rm -f "$d/running" ;;
esac`,
);
exe(join(bin, "createdb"), `echo "createdb $*" >> "${bin}/calls.log"`);
return bin;
}
/** `source peppa-tools.sh <args>` in a fresh bash; prints PATH, DATABASE_URL and `command -v go`. */
function source(args: string[], env: Record<string, string>, cwd = TMP) {
const script = `source "${TOOLS}" ${args.join(" ")}; code=$?; echo "CODE=$code"; echo "URL=\${DATABASE_URL:-}"; echo "GO=$(command -v go)"; exit 0`;
const r = spawnSync("bash", ["-c", script], { cwd, encoding: "utf8", env: { HOME: TMP, TMPDIR: TMP, PATH: SYS_PATH, ...env } });
const line = (k: string) => (r.stdout.match(new RegExp(`^${k}=(.*)$`, "m")) ?? [])[1] ?? "";
return { code: Number(line("CODE")), url: line("URL"), go: line("GO"), err: r.stderr };
}
describe("Go для проверок", () => {
test("Scenario: Задание проверок без Go", () => {
const dl = mockGoDl("1.27.0");
const work = mkdtempSync(join(TMP, "work-"));
writeFileSync(join(work, "go.mod"), "module example.com/shop\n\ngo 1.27\n");
const ghPath = join(work, "github_path");
const cache = join(work, "cache");
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: cache, GITHUB_PATH: ghPath }, work);
assert.equal(r.code, 0, r.err);
assert.match(r.err, new RegExp(`скачиваю go1\\.27\\.0\\.linux-${ARCH}\\.tar\\.gz`));
assert.equal(r.go, join(cache, "go/1.27.0/go/bin/go"));
assert.equal(readFileSync(ghPath, "utf8").trim(), join(cache, "go/1.27.0/go/bin"));
// the second call takes the cache, nothing is downloaded
const again = source(["go"], { PEPPA_GO_DL_BASE: "file:///nonexistent", PEPPA_TOOLS_CACHE: cache }, work);
assert.equal(again.code, 0, again.err);
assert.doesNotMatch(again.err, /скачиваю/);
});
test("Scenario: Go уже есть (песочница агента)", () => {
const bin = mkdtempSync(join(TMP, "image-bin-"));
exe(join(bin, "go"), 'echo "go version go1.27.3 linux/amd64"');
const r = source(["go"], { PATH: `${bin}:${SYS_PATH}`, PEPPA_GO_DL_BASE: "file:///nonexistent" });
assert.equal(r.code, 0, r.err);
assert.equal(r.go, join(bin, "go"));
assert.doesNotMatch(r.err, /скачиваю/);
});
test("go.mod с полной версией и строкой toolchain — качается версия строки go", () => {
const dl = mockGoDl("1.27.2");
const work = mkdtempSync(join(TMP, "work-"));
writeFileSync(join(work, "go.mod"), "module m\n\ngo 1.27.2\n\ntoolchain go1.27.4\n");
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: join(work, "c") }, work);
assert.equal(r.code, 0, r.err);
assert.match(r.go, /go\/1\.27\.2\/go\/bin\/go$/);
});
test("Go не скачался — ошибка, а не тишина", () => {
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${TMP}/no-such-dl`, PEPPA_TOOLS_CACHE: join(TMP, "c-fail") });
assert.equal(r.code, 1);
assert.match(r.err, /не удалось скачать Go 1\.27\.0/);
assert.equal(r.go, "");
});
});
describe("Временная база для тестов", () => {
test("Scenario: Временная база для тестов", () => {
const bin = mockPgBin();
const dir = join(TMP, "pg-1");
const ghEnv = join(TMP, "github_env-1");
const env = { PEPPA_PG_BINDIR: bin, PEPPA_PG_DIR: dir, GITHUB_ENV: ghEnv };
const first = source(["postgres"], env);
assert.equal(first.code, 0, first.err);
const m = first.url.match(/^postgres:\/\/app@127\.0\.0\.1:(\d+)\/app\?sslmode=disable$/);
assert.ok(m, first.url);
assert.ok(Number(m[1]) >= 18432);
assert.equal(readFileSync(ghEnv, "utf8").trim(), `DATABASE_URL=${first.url}`);
const calls = readFileSync(join(bin, "calls.log"), "utf8");
assert.match(calls, /initdb -D .* -U app --auth=trust/);
assert.match(calls, new RegExp(`listen_addresses=127\\.0\\.0\\.1 -p ${m[1]}`));
assert.match(calls, new RegExp(`createdb -h 127\\.0\\.0\\.1 -p ${m[1]} -U app app`));
const second = source(["postgres"], env);
assert.equal(second.url, first.url);
assert.equal(readFileSync(join(bin, "calls.log"), "utf8").match(/^initdb /gm)?.length, 1, "no second cluster");
// stop removes the cluster; the next call makes a new one
spawnSync("bash", [TOOLS, "stop"], { env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
assert.ok(!existsSync(dir));
});
test("занятый порт пропускается", async () => {
const busy = createServer();
await new Promise<void>((r) => busy.listen(0, "127.0.0.1", r));
const port = (busy.address() as AddressInfo).port;
try {
const r = source(["postgres"], { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-2"), PEPPA_PG_PORT_FROM: String(port) });
assert.equal(r.code, 0, r.err);
assert.notEqual(r.url, `postgres://app@127.0.0.1:${port}/app?sslmode=disable`);
} finally {
busy.close();
}
});
test("Scenario: Нет PostgreSQL и нельзя поставить", { skip: process.getuid?.() === 0 }, () => {
const r = source(["postgres"], { PEPPA_PG_DIR: join(TMP, "pg-3") });
assert.notEqual(r.code, 0);
assert.match(r.err, /PostgreSQL не найден/);
assert.equal(r.url, "");
});
test("запуск без source печатает export для eval", () => {
const env = { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-4") };
const out = execFileSync("bash", [TOOLS, "postgres"], { encoding: "utf8", env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
assert.match(out, /^export DATABASE_URL=postgres:\/\/app@127\.0\.0\.1:\d+\/app\\\?sslmode=disable$/m);
});
});

138
template/.gitea/peppa-tools.sh Executable file
View File

@ -0,0 +1,138 @@
#!/usr/bin/env bash
# Инструменты стандартного стека FORGE для проверок и для агента (PEP-314):
# source .gitea/peppa-tools.sh go — Go в PATH (нет — скачать версию из go.mod)
# source .gitea/peppa-tools.sh postgres — временная PostgreSQL на 127.0.0.1, DATABASE_URL
# source .gitea/peppa-tools.sh go postgres — оба
# bash .gitea/peppa-tools.sh stop — остановить временную базу
# Подключается через source: PATH и DATABASE_URL нужны той же оболочке. В задании проверок
# (Gitea Actions) значения ещё пишутся в $GITHUB_PATH / $GITHUB_ENV для следующих шагов.
# Docker не нужен: Go — архив с go.dev, база — initdb/pg_ctl (в образе агента они есть; в задании
# проверок под root пакет postgresql ставится через apt-get). Повторный вызов дешёвый: Go берётся
# из кэша, живая база переиспользуется — команды checks могут звать его каждая сама.
# Настройки: PEPPA_GO_VERSION (без go.mod; по умолчанию 1.27.0), PEPPA_TOOLS_CACHE (кэш),
# PEPPA_PG_DIR (каталог базы), PEPPA_PG_BINDIR (каталог initdb/pg_ctl).
_peppa_say() { echo "peppa-tools: $*" >&2; }
_peppa_go_version() {
local v=""
[[ -f go.mod ]] && v=$(sed -n -E 's/^go[[:space:]]+([0-9]+\.[0-9]+(\.[0-9]+)?).*/\1/p' go.mod | head -1)
v="${v:-${PEPPA_GO_VERSION:-1.27.0}}"
# С Go 1.21 первый выпуск ветки называется go1.N.0: «go 1.27» в go.mod — это 1.27.0.
[[ "$v" =~ ^[0-9]+\.[0-9]+$ ]] && v="$v.0"
printf '%s' "$v"
}
_peppa_go() {
if command -v go >/dev/null 2>&1; then
_peppa_say "Go уже есть: $(go version 2>/dev/null)"
return 0
fi
local v arch os cache dir url tgz
v=$(_peppa_go_version)
case "$(uname -m)" in x86_64|amd64) arch=amd64 ;; aarch64|arm64) arch=arm64 ;; *) arch=$(uname -m) ;; esac
os=$(uname -s | tr '[:upper:]' '[:lower:]')
cache="${PEPPA_TOOLS_CACHE:-${RUNNER_TOOL_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/peppa-tools}}"
dir="$cache/go/$v"
if [[ ! -x "$dir/go/bin/go" ]]; then
tgz="go$v.$os-$arch.tar.gz"
url="${PEPPA_GO_DL_BASE:-https://go.dev/dl}/$tgz"
_peppa_say "скачиваю $tgz"
mkdir -p "$dir" || return 1
if ! curl -fsSL --retry 3 "$url" | tar -xz -C "$dir"; then
_peppa_say "не удалось скачать Go $v ($url)"
rm -rf "$dir"
return 1
fi
fi
export PATH="$dir/go/bin:$PATH"
[[ -n "${GITHUB_PATH:-}" ]] && echo "$dir/go/bin" >> "$GITHUB_PATH"
_peppa_say "Go $v: $dir/go/bin"
}
_peppa_pg_bindir() {
if [[ -n "${PEPPA_PG_BINDIR:-}" ]]; then printf '%s' "$PEPPA_PG_BINDIR"; return 0; fi
if command -v initdb >/dev/null 2>&1; then dirname "$(command -v initdb)"; return 0; fi
local d
d=$(ls -d /usr/lib/postgresql/*/bin 2>/dev/null | sort -V | tail -1)
[[ -n "$d" && -x "$d/initdb" ]] && { printf '%s' "$d"; return 0; }
return 1
}
_peppa_pg_install() {
[[ $(id -u) == 0 ]] && command -v apt-get >/dev/null 2>&1 || return 1
_peppa_say "ставлю PostgreSQL (apt-get)"
mkdir -p /etc/postgresql-common/createcluster.d
echo "create_main_cluster = false" > /etc/postgresql-common/createcluster.d/peppa.conf
DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null &&
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends postgresql >/dev/null
}
_peppa_pg_dir() { printf '%s' "${PEPPA_PG_DIR:-${TMPDIR:-/tmp}/peppa-pg-$(id -u)}"; }
_peppa_postgres() {
local bin dir port url as=() lib
dir=$(_peppa_pg_dir)
bin=$(_peppa_pg_bindir) || { _peppa_pg_install && bin=$(_peppa_pg_bindir); } || {
_peppa_say "PostgreSQL не найден: нет initdb (в образе агента он есть; поставьте пакет postgresql)"
return 1
}
# initdb не работает от root: в задании проверок база идёт от пользователя postgres.
if [[ $(id -u) == 0 ]]; then as=(runuser -u postgres --); fi
if [[ -s "$dir/url" ]] && "${as[@]}" "$bin/pg_ctl" -D "$dir/data" status >/dev/null 2>&1; then
url=$(cat "$dir/url")
else
rm -rf "$dir"
mkdir -p "$dir" && chmod 700 "$dir" || return 1
((${#as[@]})) && chown postgres "$dir"
if ! "${as[@]}" "$bin/initdb" -D "$dir/data" -U app --auth=trust -E UTF8 --no-locale >"$dir/initdb.log" 2>&1; then
_peppa_say "initdb не удался:"; tail -n 20 "$dir/initdb.log" >&2; return 1
fi
# Порт — первый свободный от 18432 (правило портов FORGE: локальные проверки — от 18000).
port="${PEPPA_PG_PORT_FROM:-18432}"
while (echo >"/dev/tcp/127.0.0.1/$port") 2>/dev/null; do port=$((port + 1)); done
lib=""
[[ -f "$bin/../lib/pg_stat_statements.so" ]] && lib="-c shared_preload_libraries=pg_stat_statements"
if ! "${as[@]}" "$bin/pg_ctl" -D "$dir/data" -l "$dir/server.log" -w -t 60 \
-o "-c listen_addresses=127.0.0.1 -p $port -k $dir $lib" start >/dev/null; then
_peppa_say "PostgreSQL не запустился:"; tail -n 20 "$dir/server.log" >&2; return 1
fi
"${as[@]}" "$bin/createdb" -h 127.0.0.1 -p "$port" -U app app || { _peppa_say "createdb не удался"; return 1; }
url="postgres://app@127.0.0.1:$port/app?sslmode=disable"
printf '%s' "$url" > "$dir/url"
fi
export DATABASE_URL="$url"
[[ -n "${GITHUB_ENV:-}" ]] && echo "DATABASE_URL=$url" >> "$GITHUB_ENV"
_peppa_say "PostgreSQL: $url"
}
_peppa_stop() {
local bin dir as=()
dir=$(_peppa_pg_dir)
bin=$(_peppa_pg_bindir) || return 0
[[ $(id -u) == 0 ]] && as=(runuser -u postgres --)
[[ -d "$dir/data" ]] && "${as[@]}" "$bin/pg_ctl" -D "$dir/data" -m fast stop >/dev/null 2>&1
rm -rf "$dir"
}
_peppa_tools() {
local t
(($#)) || { _peppa_say "usage: source .gitea/peppa-tools.sh <go|postgres|stop>…"; return 2; }
for t in "$@"; do
case "$t" in
go) _peppa_go || return 1 ;;
postgres|pg) _peppa_postgres || return 1 ;;
stop) _peppa_stop ;;
*) _peppa_say "неизвестный инструмент: $t (go|postgres|stop)"; return 2 ;;
esac
done
}
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
# Запуск без source: переменные не дойдут до вызывающей оболочки — печатаем их для eval.
_peppa_tools "$@" || exit $?
[[ " $* " == *" go "* ]] && printf 'export PATH=%q\n' "$PATH"
[[ -n "${DATABASE_URL:-}" ]] && printf 'export DATABASE_URL=%q\n' "$DATABASE_URL"
exit 0
fi
_peppa_tools "$@"