Author SHA1 Message Date
cflmy 0bbaac86e4 ci: add protected component publish workflow and immutable release helpers
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Vendor the root component-release helpers, add source packaging plus
release-evidence, and split publish (tag/manual) from notify (release event).
2026-11-27 19:23:05 +08:00
marqdo-ci a1a223f53f ci: notify the root reconcile on a completed release
ci/woodpecker/push/ci Pipeline is pending
ci/woodpecker/push/main Pipeline is pending
ci/woodpecker/pr/ci Pipeline is pending
ci/woodpecker/pr/main Pipeline is pending
ci/woodpecker/manual/ci Pipeline was successful
Release event fast path: validate the secret is present, then ask the root
manual `reconcile` workflow to check the authoritative Gitea release. The call
is only a hint; correctness and lost-notification recovery stay in the root
reconcile cron/script.
2026-11-27 14:18:04 +08:00
marqdo-ci 917c12e760 ci: consume the shared Rust CI image
ci/woodpecker/push/ci Pipeline is pending
ci/woodpecker/push/main Pipeline is pending
ci/woodpecker/pr/ci Pipeline is pending
ci/woodpecker/pr/main Pipeline is pending
Replaces per-run rustup/apt/CLI setup with the published marqdo-ci-rust image
(pinned toolchain, rustfmt/clippy, warm cargo cache and released CLI/Bundle).
2026-11-27 14:15:02 +08:00
marqdo-norms 6e88100089 docs: adopt the ecosystem repository development conventions
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
Add the repository AGENTS.md boundary and anti-bloat rules required by
marqdo docs/REPOSITORY-CONVENTIONS.md, with the marker and canonical link so
scripts/check-repo-conventions.py can enforce it.
2026-11-27 11:36:14 +08:00
marqdo-knowledge d8fa201b28 docs(release): record 0.1.0-beta.3 publication evidence
ci/woodpecker/push/main Pipeline was successful
CI / fmt + clippy + workspace tests (push) Canceled after 0s
CI / MSRV check (1.89) (push) Canceled after 0s
CI / real Analysis integration (pinned core CLI) (push) Canceled after 0s
CI / beta release archive (push) Canceled after 0s
- add docs/evidence/2026-11-26-beta.3-release.md: tag/source commit, Gitea
  release URL and assets, published archive SHA-256, CI tag pipeline #11
  success and its archive SHA, local 139-test gate results, withdrawn beta.2
  tag, and the explicit secret-injection limitation with the reviewed local
  publish path
- link the release/evidence from docs/STATUS.md, the beta.3 release notes and
  docs/ci.md; keep the NOT RUN inventory unchanged
- record the local release/CI bookkeeping in the git-ignored .secrets notes
2026-11-26 09:59:32 +08:00
15 changed files with 1099 additions and 195 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@
# Python tooling cache # Python tooling cache
__pycache__/ __pycache__/
*.pyc *.pyc
dist/
+23
View File
@@ -0,0 +1,23 @@
# Unified Woodpecker CI for a Rust Marqdo Tool.
#
# One published `marqdo-ci-rust` image contains the pinned toolchain and the
# released CLI/Bundle (`MARQDO_BIN`, `MARQDO_STDLIB_DIR` preset); the lane only
# runs this repository's own checks. No per-run rustup/apt/CLI download.
when:
event: [push, pull_request, manual]
steps:
test:
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
environment:
MARQDO_BIN: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo
MARQDO_STDLIB_DIR: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/stdlib
MARQDO_TEST_BIN: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo
MARQDO_TOOL_HOME: /tmp/marqdo-tool-home
commands:
- python3 tools/ci/test_release_metadata.py
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets --locked -- -D warnings
- cargo test --workspace --locked
- cargo build --release --locked
- target/release/marqdo-knowledge --help
+40
View File
@@ -0,0 +1,40 @@
when:
- event: [tag, manual]
steps:
publish:
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
environment:
GITEA_PUBLISH_TOKEN:
from_secret: gitea_publish_token
WOODPECKER_NOTIFY_TOKEN:
from_secret: woodpecker_notify_token
commands:
- |
set -eu
test -n "${GITEA_PUBLISH_TOKEN:?}"
test -n "${CI_COMMIT_TAG:?}"
export SOURCE_SHA="${CI_COMMIT_SHA}"
export VERSION="${CI_COMMIT_TAG#v}"
scripts/ci.sh
scripts/package-release.sh
# Attach release-evidence then publish immutably.
ARCHIVE=$(ls dist/marqdo-knowledge-*.tar.gz | head -1)
python3 scripts/release/write_evidence.py \
--component-id knowledge \
--repository cflmy/marqdo-knowledge \
--tag "${CI_COMMIT_TAG}" \
--source-sha "${SOURCE_SHA}" \
--asset "$ARCHIVE" \
--asset "${ARCHIVE}.sha256" \
--out dist/release-evidence.json
python3 scripts/release/publish_gitea.py \
--repo cflmy/marqdo-knowledge \
--tag "${CI_COMMIT_TAG}" \
--target "${SOURCE_SHA}" \
--prerelease \
--body-file "docs/releases/${VERSION}.md" \
--asset "$ARCHIVE" \
--asset "${ARCHIVE}.sha256" \
--asset dist/release-evidence.json \
--evidence-out dist/gitea-publish-result.json
+16
View File
@@ -0,0 +1,16 @@
when:
event: [release]
steps:
notify:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment:
WOODPECKER_NOTIFY_TOKEN:
from_secret: woodpecker_notify_token
commands:
- |
set -eu
test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
python3 scripts/release/notify_root.py \
--hint-component "knowledge" \
--hint-tag "${CI_COMMIT_TAG:-}"
+37
View File
@@ -0,0 +1,37 @@
<!-- marqdo:repo-conventions v1 -->
# AGENTS.md — knowledge
全局规范唯一来源:[marqdo 仓库开发规范](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md)。本文件只写本仓边界,不复制全局规范或合同正文。
## 1. 本仓定位与唯一权威
- catalog ID:`knowledge`;父级:根;角色:tool;状态:active。
- 职责/本仓拥有:确定性离线知识编译/检索与文档投影
- 本仓不拥有:Markdown/语言 parser、CLI 核心、其它业务实现
- 权威输入/合同:CLI 公开 Analysis 3;`MARQDO_BIN` 与项目输入
## 2. 必做 / 禁止
| 必做 | 禁止 |
| --- | --- |
| 只在本仓职责内修改,先开本仓工单 | 实现其它仓库功能,复制 parser/实现/合同 |
| 用真实 CLI/制品与独立期望测试 | mock、字符串检查或原型冒充真实验收/PASS |
| 依赖使用固定 SHA/摘要与显式输入 | 依赖父仓 checkout、兄弟仓相对路径、浮动分支 |
| 未运行写 `UNVERIFIED` | 伪造 entry/版本/CI 徽章/gitlink/发布资产 |
| 记录 SHA、制品摘要、平台、命令、退出码 | 提交密钥、凭证、构建产物或本地绝对路径 |
| 跨仓变更走 C2 → B2 → A2 晋升 | 自动 tag/release/合并,或直接改父仓/兄弟仓 |
- 不新增第二 catalog/manifest/lock/版本表/发布流程;不为单功能拆仓或建空壳仓。
- 不在本仓登记其它仓库后代路径;治理树最多两级 gitlink。
## 3. 构建、测试与证据
- CI/验收入口:`scripts/ci.sh`(非交互、失败非零、不打印秘密、只写声明输出;构建与发布权限分离)。
- 输入与依赖:CLI 公开 Analysis 3;`MARQDO_BIN` 与项目输入
- 交付:Tool bundle + `tool.json` 与知识投影验收证据
- 证据:候选 SHA、依赖/制品 SHA-256、平台/工具链、命令与退出码、日志位置、测试范围;FAIL/UNVERIFIED 不得写成 PASS。
## 4. 工单路由
- 公共协议/字段缺失 → `marqdo-cli`;检索/投影语义 → 本仓。
- 不把知识检索做成第二套文档 parser。
+10 -2
View File
@@ -7,7 +7,14 @@ must not be claimed as passing.
## Release state ## Release state
- Channel: **beta** (`0.1.0-beta.3`), Linux x86_64. Not a stable claim. - Channel: **beta** (`0.1.0-beta.3`), Linux x86_64. Not a stable claim.
- Release notes: [`releases/0.1.0-beta.3.md`](releases/0.1.0-beta.3.md). - Release: <https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
(prerelease; tag commit `3edad237cfa92fc59822cfa13dd5480c3fac6532`; published
archive SHA-256
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`).
- Release notes: [`releases/0.1.0-beta.3.md`](releases/0.1.0-beta.3.md);
release evidence: [`evidence/2026-11-26-beta.3-release.md`](evidence/2026-11-26-beta.3-release.md).
- `v0.1.0-beta.2` was withdrawn (release lane failed before packaging); its tag
was deleted.
- CI/CD: [`.woodpecker/main.yml`](../.woodpecker/main.yml), - CI/CD: [`.woodpecker/main.yml`](../.woodpecker/main.yml),
[`.github/workflows/ci.yml`](../.github/workflows/ci.yml) and [`.github/workflows/ci.yml`](../.github/workflows/ci.yml) and
[`scripts/ci.sh`](../scripts/ci.sh); procedure in [`ci.md`](ci.md) and [`scripts/ci.sh`](../scripts/ci.sh); procedure in [`ci.md`](ci.md) and
@@ -58,7 +65,8 @@ must not be claimed as passing.
| Windows/macOS native testing | Release candidate platform is Linux x86_64 only. | | Windows/macOS native testing | Release candidate platform is Linux x86_64 only. |
| Upstream batch `--documents` Analysis interface (U01) | Current upstream exposes per-entry `check --emit`; this tool invokes it per `.mq.md` entry and merges contexts, as the specification permits for the development stage. | | Upstream batch `--documents` Analysis interface (U01) | Current upstream exposes per-entry `check --emit`; this tool invokes it per `.mq.md` entry and merges contexts, as the specification permits for the development stage. |
| Release archive native install on other platforms | Archive was built and cold-installed on Linux x86_64 only. | | Release archive native install on other platforms | Archive was built and cold-installed on Linux x86_64 only. |
| CI provider run URL for this beta | The pipeline configuration is committed; no external Woodpecker/GitHub run URL is recorded in this workspace. Local lanes were executed on the release SHA. | | Automatic CI publication of the Gitea release | The Woodpecker instance did not inject the repository token into tag pipelines; the tag lane records build/smoke evidence and a publish-skipped notice, and the prerelease was published from the same tagged SHA by a reviewed local invocation. |
| GitHub Actions run for this beta | The GitHub workflow is committed but this workspace has no GitHub remote/run; the Woodpecker lane is the executed CI evidence. |
| Version-freeze reproducibility of `RELEASE_INFO.json` | It contains build metadata (`built_at_utc`, rustc/cargo versions); the archive SHA is recorded by the pipeline, not reproducible byte-for-byte from the same commit. | | Version-freeze reproducibility of `RELEASE_INFO.json` | It contains build metadata (`built_at_utc`, rustc/cargo versions); the archive SHA is recorded by the pipeline, not reproducible byte-for-byte from the same commit. |
| Incremental write-granularity benchmark | Incremental compiles reuse facts (no re-analysis for plain-only edits) but rewrite the projection inside one transaction; the specification's write-count benchmark has not been run. | | Incremental write-granularity benchmark | Incremental compiles reuse facts (no re-analysis for plain-only edits) but rewrite the projection inside one transaction; the specification's write-count benchmark has not been run. |
+11
View File
@@ -43,6 +43,17 @@ recording a new Analysis fixture artifact.
| release build | `cargo build --release --locked` | | release build | `cargo build --release --locked` |
| deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` | | deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` |
## Forge publication from the tag lane
The tag-only release lane builds and smoke-tests the deterministic archive and
then invokes `tools/release/publish-gitea.py` when `GITEA_TOKEN` is present in
the step environment. If the Woodpecker instance does not inject repository
secrets into tag pipelines, the lane prints a `publish: skipped` notice, keeps
the build/smoke evidence, and the prerelease is published from the same tagged
SHA by a reviewed local invocation with the token read from a local-only
environment file. Never put the token in the repository, pipeline config, logs
or documentation.
## Not gated by CI (explicit non-claims) ## Not gated by CI (explicit non-claims)
- Real-model semantic quality benchmark (§8.3/§16) — needs a pinned model and - Real-model semantic quality benchmark (§8.3/§16) — needs a pinned model and
+107
View File
@@ -0,0 +1,107 @@
# Evidence: 0.1.0-beta.3 beta release
Date: 2026-11-26 (Asia/Shanghai)
Release channel: **beta** (not a stable-version claim)
Platform: Linux x86_64
Tool version: `0.1.0-beta.3`
Source/tag commit: `3edad237cfa92fc59822cfa13dd5480c3fac6532`
Tag: `v0.1.0-beta.3` (annotated)
Core CLI baseline: `cflmy/marqdo-cli` `3.0.0-rc.4`
(`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`), Analysis revision 3.
Contracts: `marqdo.cli-tool` revision 1, tool API revision 1, consumed Analysis
revision 3, SQLite schema revision 1, result/error envelope schema_version 1,
OKF 0.3.
## Published release
- Release URL:
<https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
- Gitea release id: 76, `prerelease: true`, `draft: false`
- Assets uploaded and verified through the Gitea API:
- `marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz` (3,838,786 bytes)
- `marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz.sha256`
- `RELEASE_INFO.json`
- `FILES.sha256`
- `smoke-evidence.json`
- Published archive SHA-256:
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`
- Published archive `source_sha`: `3edad237cfa92fc59822cfa13dd5480c3fac6532`
## CI/CD evidence
Tag-only Woodpecker pipeline **#11**: **success** on commit `3edad237`.
- Pipeline: <https://ci.cflmy.cn/repos/4/pipeline/11>
- Lanes: `test` (metadata consistency, fmt, clippy `-D warnings`, locked
workspace tests), `minimum-rust` (1.89 check), `core-analysis` (builds the
pinned core CLI and runs the real Analysis integration tests), `release`
(locked release build, deterministic package, cold-install smoke).
- CI-produced archive SHA-256 (same source commit, CI build environment):
`358acbb2279740b35dd800764ac649b7a122e4940c7209ad99c306c12e55642c`
- CI smoke result: `smoke: OK`; packaged example compile 5 documents, query
4 hits, check database current with 0 errors.
Local gates on the same source commit:
- `python3 tools/ci/test_release_metadata.py`: PASS.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --workspace --all-targets --locked -- -D warnings`: clean.
- `cargo test --workspace --locked` with the real rc.4 core binary:
139 passed / 0 failed.
- `cargo build --release --locked`: clean.
- Local deterministic package and `tools/release/smoke.py` against the real
core CLI: `smoke: OK` (checksum/manifest/version, install, help, compile,
query, check, remove).
The CI archive and the published local archive are different byte streams
because they were built in different build environments, but both record the
same `SOURCE_SHA` and the same tool/contract versions. The published asset and
its checksum are the authoritative artifact for this release; the CI archive SHA
is recorded for traceability only.
## Publication path and known infrastructure limitation
This Woodpecker instance (3.20.1) did not inject the repository `GITEA_TOKEN`
secret into tag pipelines, neither as an implicit repo secret nor through an
explicit `environment.from_secret` mapping. The tag lane therefore keeps the
deterministic package and cold-install smoke as its CI evidence and records a
`publish: skipped` notice instead of failing. The Gitea prerelease was published
from the same tagged source commit by a reviewed local invocation of
`tools/release/publish-gitea.py`; the token was read from the local-only
`.secrets/release.env` (git-ignored) and never printed or committed.
The pipeline is configured to publish automatically when the secret injection
becomes available; no source or release change is required for that.
## Withdrawn tag
`v0.1.0-beta.2` was withdrawn and its remote tag deleted. Its tag-only release
lane failed before packaging because the lane did not build the tool release
binary; no archive or Gitea release was produced for it. Do not use that tag.
## Reproduction
```sh
# From the tagged commit, with a compatible core CLI:
python3 tools/ci/test_release_metadata.py
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --locked -- -D warnings
MARQDO_TEST_BIN=/path/to/marqdo cargo test --workspace --locked
cargo build --release --locked
python3 tools/release/package.py \
--source-sha "$(git rev-parse HEAD)" \
--version "$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"
MARQDO_BIN=/path/to/marqdo python3 tools/release/smoke.py \
--archive "dist/marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz"
```
## Not evidence for
- Real-model semantic retrieval quality (protocol mock only).
- Specification §16 retrieval/performance gates, latency/RSS/build-time or
incremental write-volume benchmarks.
- Windows/macOS platform support.
- Upstream batch Analysis interface (per-entry `check --emit` is used).
- Byte-identical archive reproducibility across different build environments.
+19 -6
View File
@@ -30,7 +30,7 @@ Contract versions (unchanged from beta.1):
traceback when the release binary is absent. traceback when the release binary is absent.
- No tool behaviour, CLI surface, contract or schema change. - No tool behaviour, CLI surface, contract or schema change.
Release evidence produced by the pipeline on this SHA: Release evidence produced for this SHA:
- metadata consistency gate PASS; - metadata consistency gate PASS;
- fmt/clippy/tests (including the real rc.4 Analysis integration) PASS; - fmt/clippy/tests (including the real rc.4 Analysis integration) PASS;
@@ -39,8 +39,8 @@ Release evidence produced by the pipeline on this SHA:
- cold-install smoke through the real core CLI: archive checksum/manifest/ - cold-install smoke through the real core CLI: archive checksum/manifest/
version verified, install -> help -> compile packaged example -> query -> version verified, install -> help -> compile packaged example -> query ->
check (current, 0 errors) -> remove; check (current, 0 errors) -> remove;
- Gitea prerelease for the tag with the archive and evidence assets attached - Gitea prerelease for the tag with the archive and evidence assets attached;
(recorded in `dist/gitea-release-evidence.json` by the release lane). see the Evidence section below for URLs and checksums.
## What is complete in this beta ## What is complete in this beta
@@ -129,6 +129,19 @@ Diagnostics never include source text, credentials or absolute paths.
integration and local cold install. integration and local cold install.
- `docs/STATUS.md` — implemented/tested vs NOT RUN matrix. - `docs/STATUS.md` — implemented/tested vs NOT RUN matrix.
- `docs/ci.md`, `docs/releasing.md` — gates, non-gates and frozen-SHA procedure. - `docs/ci.md`, `docs/releasing.md` — gates, non-gates and frozen-SHA procedure.
- Pipeline run, archive checksum, `FILES.sha256`, `RELEASE_INFO.json`, - Gitea prerelease:
`dist/smoke-evidence.json` and the Gitea prerelease record the same release <https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
SHA. (release id 76, `prerelease: true`) with the archive, sidecar checksum,
`RELEASE_INFO.json`, `FILES.sha256` and `smoke-evidence.json` attached.
- Source/tag commit `3edad237cfa92fc59822cfa13dd5480c3fac6532`; published
archive SHA-256
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`.
- CI tag pipeline #11 success:
<https://ci.cflmy.cn/repos/4/pipeline/11>; CI archive SHA-256
`358acbb2279740b35dd800764ac649b7a122e4940c7209ad99c306c12e55642c`
(different build environment, same `SOURCE_SHA`).
- Full record: [`docs/evidence/2026-11-26-beta.3-release.md`](../evidence/2026-11-26-beta.3-release.md).
- Note: this Woodpecker instance does not inject repository secrets into tag
pipelines, so the tag lane records build/smoke evidence and a
`publish: skipped` notice; the prerelease was published from the same tagged
SHA by a reviewed local invocation of `tools/release/publish-gitea.py`.
+9
View File
@@ -0,0 +1,9 @@
# Vendored from marqdo scripts/component-release
#
# Do not edit in place across repositories. Change the root copy, re-test,
# then re-run install-vendor.sh and record the hashes below.
#
# package_source.py sha256=cb18c2f7fbe807f55d49e2cf77720f0d3e57d355177d2b127ac09e119f90c6ae
# write_evidence.py sha256=bb194bfd251e39308bc1dd53f46fd9efac181082ea43f668484b067d9e54acfc
# publish_gitea.py sha256=a21a84146d9ea826eb8d0632a18a991b0c39f17005d83bd988c92fc608f67523
# notify_root.py sha256=8eee83eb2bb31b99d93981f2a97fc2f0f9a486cc3c5c072f7dc12cfb63baf025
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Ask the root Marqdo reconcile workflow to scan after a release.
The payload is only a hint. Correctness comes from the root
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
Lost notifications are recovered by the root `release-reconcile` cron.
"""
from __future__ import annotations
import argparse
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
class NotifyError(Exception):
pass
def token() -> str:
value = (
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
or os.environ.get("WOODPECKER_TOKEN")
or os.environ.get("woodpecker_token")
)
if not value:
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
return value
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
payload = json.dumps(body).encode()
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
request = urllib.request.Request(
url,
data=payload,
method="POST",
headers={
"Authorization": f"Bearer {token_value}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
raw = response.read()
decoded = json.loads(raw) if raw else {}
return {
"status": "triggered",
"http_status": response.status,
"pipeline_id": decoded.get("id"),
"pipeline_number": decoded.get("number"),
"attempt": attempt,
}
except urllib.error.HTTPError as error:
# Auth/permission failures must not retry forever.
if error.code in (401, 403, 404):
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
last_error = error
except urllib.error.URLError as error:
last_error = error
if attempt < attempts:
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
time.sleep(delay)
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
parser.add_argument("--branch", default="main")
parser.add_argument("--workflow", default="reconcile")
parser.add_argument("--hint-component", default="")
parser.add_argument("--hint-tag", default="")
parser.add_argument("--attempts", type=int, default=3)
args = parser.parse_args(argv)
body = {"branch": args.branch, "workflow": args.workflow}
# Hints are informational only; the root reconcile never trusts them as commands.
if args.hint_component or args.hint_tag:
body["variables"] = {
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
}
try:
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
except NotifyError as error:
print(f"notify_root: FAIL: {error}", file=sys.stderr)
return 1
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Build a deterministic source archive for a Marqdo component release.
Only allowlisted relative paths are included. The archive uses fixed mtime,
uid/gid, and sorted member names so the same tree always yields the same
sha256. Output is written under an isolated directory (default: dist/).
"""
from __future__ import annotations
import argparse
import hashlib
import io
import os
import sys
import tarfile
from pathlib import Path
DEFAULT_ALLOWLIST = (
"modules",
"index.mq.md",
"marqdo.yaml",
"LICENSE",
"README.md",
)
FIXED_MTIME = 0
EVIDENCE_NAME = "release-evidence.json"
class PackageError(Exception):
pass
def fail(message: str) -> None:
raise PackageError(message)
def is_safe_relative(path: str) -> bool:
if not path or path.startswith("/") or path.startswith("\\"):
return False
parts = Path(path).parts
return not any(part in (".", "..") for part in parts)
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
selected: dict[str, Path] = {}
for entry in allowlist:
if not is_safe_relative(entry):
fail(f"unsafe allowlist entry: {entry!r}")
target = root / entry
if not target.exists():
continue
if target.is_file():
selected[entry.replace("\\", "/")] = target
continue
if not target.is_dir():
fail(f"allowlist entry is not a regular file or directory: {entry}")
for path in sorted(target.rglob("*")):
if not path.is_file():
continue
if path.is_symlink():
fail(f"symlinks are not publishable: {path.relative_to(root)}")
relative = path.relative_to(root).as_posix()
if not is_safe_relative(relative):
fail(f"unsafe relative path: {relative}")
selected[relative] = path
if not selected:
fail("allowlist matched no files")
return sorted(selected.items(), key=lambda item: item[0])
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
for relative, path in files:
data = path.read_bytes()
info = tarfile.TarInfo(name=relative)
info.size = len(data)
info.mtime = FIXED_MTIME
info.uid = 0
info.gid = 0
info.uname = ""
info.gname = ""
info.mode = 0o644
archive.addfile(info, io.BytesIO(data))
return buffer.getvalue()
def write_outputs(
root: Path,
out_dir: Path,
component_id: str,
version: str,
allowlist: list[str],
) -> dict:
files = collect_files(root, allowlist)
payload = archive_bytes(files)
digest = hashlib.sha256(payload).hexdigest()
out_dir.mkdir(parents=True, exist_ok=True)
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
archive_path = out_dir / archive_name
sha_path = out_dir / f"{archive_name}.sha256"
archive_path.write_bytes(payload)
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
return {
"archive": str(archive_path),
"sha256_file": str(sha_path),
"name": archive_name,
"size": len(payload),
"sha256": digest,
"files": [relative for relative, _ in files],
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", default=".", help="component repository root")
parser.add_argument("--component-id", required=True)
parser.add_argument("--version", required=True, help="version without leading v")
parser.add_argument("--out-dir", default="dist")
parser.add_argument(
"--allow",
action="append",
default=[],
help="relative allowlist entry (repeatable); defaults applied when omitted",
)
args = parser.parse_args(argv)
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
root = Path(args.root).resolve()
out_dir = Path(args.out_dir)
if not out_dir.is_absolute():
out_dir = root / out_dir
try:
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
except PackageError as error:
print(f"package_source: FAIL: {error}", file=sys.stderr)
return 1
print(result["archive"])
print(result["sha256_file"])
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env python3
"""Publish a Gitea release with a draft transaction and immutable public assets.
Order (issue #10 §4.2):
create/reuse draft → upload non-index assets → upload release-evidence.json last
→ re-read and verify → mark non-draft → re-confirm.
Never deletes or replaces assets on an already-published (non-draft) release.
Identical published identity is treated as idempotent success.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import mimetypes
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
DEFAULT_API = "https://git.cflmy.cn/api/v1"
INDEX_NAME = "release-evidence.json"
class PublishError(Exception):
pass
def token() -> str:
value = (
os.environ.get("GITEA_PUBLISH_TOKEN")
or os.environ.get("GITEA_TOKEN")
or os.environ.get("gitea_token")
)
if not value:
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
return value
def request(
api: str,
method: str,
path: str,
token_value: str,
payload: dict | None = None,
raw: bytes | None = None,
content_type: str = "application/json",
) -> tuple[int, bytes]:
url = f"{api}{path}"
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = content_type
elif raw is not None:
data = raw
headers["Content-Type"] = content_type
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=120) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def decode(body: bytes) -> object:
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
status, body = request(
api,
"GET",
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
token_value,
)
if status == 404:
return None
if status != 200:
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
release = decode(body)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("release lookup response malformed")
return release
def create_draft(
api: str,
repo: str,
tag: str,
body: str,
token_value: str,
*,
prerelease: bool,
target: str,
) -> dict:
payload = {
"tag_name": tag,
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
}
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
if status not in (200, 201):
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("draft create response malformed")
return release
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
status, response = request(
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
)
if status != 200:
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
release = decode(response)
if not isinstance(release, dict):
raise PublishError("release patch response malformed")
return release
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
status, response = request(
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
)
if status != 200:
raise PublishError(f"listing assets failed with HTTP {status}")
assets = decode(response)
if not isinstance(assets, list):
raise PublishError("asset list malformed")
return assets
def upload_asset(
api: str, repo: str, release_id: int, path: Path, token_value: str
) -> dict:
name = path.name
if not name or "/" in name or name in (".", ".."):
raise PublishError(f"unsafe asset name: {name!r}")
existing = list_assets(api, repo, release_id, token_value)
for asset in existing:
if asset.get("name") == name:
raise PublishError(
f"asset {name} already exists on draft/release {release_id}; "
"refusing to overwrite"
)
boundary = f"----marqdo{uuid.uuid4().hex}"
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
body = bytearray()
body.extend(f"--{boundary}\r\n".encode())
body.extend(
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
)
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
body.extend(path.read_bytes())
body.extend(f"\r\n--{boundary}--\r\n".encode())
status, response = request(
api,
"POST",
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
token_value,
raw=bytes(body),
content_type=f"multipart/form-data; boundary={boundary}",
)
if status not in (200, 201):
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
result = decode(response)
if not isinstance(result, dict):
raise PublishError(f"upload response for {name} malformed")
return result
def asset_identity(path: Path) -> dict:
return {
"name": path.name,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
def published_matches(release: dict, expected: list[dict]) -> bool:
remote = {
asset.get("name"): int(asset.get("size") or -1)
for asset in (release.get("assets") or [])
}
if set(remote) != {item["name"] for item in expected}:
return False
for item in expected:
if remote.get(item["name"]) != item["size"]:
return False
return True
def publish(
*,
api: str,
repo: str,
tag: str,
body: str,
target: str,
assets: list[Path],
prerelease: bool,
token_value: str,
) -> dict:
if not assets:
raise PublishError("no assets to publish")
index_assets = [path for path in assets if path.name == INDEX_NAME]
other_assets = [path for path in assets if path.name != INDEX_NAME]
if len(index_assets) != 1:
raise PublishError("exactly one release-evidence.json is required")
ordered = other_assets + index_assets
expected = [asset_identity(path) for path in ordered]
existing = get_release_by_tag(api, repo, tag, token_value)
if existing and not existing.get("draft"):
if published_matches(existing, expected):
return {
"status": "idempotent",
"release_id": existing["id"],
"html_url": existing.get("html_url"),
"tag": tag,
"assets": expected,
}
raise PublishError(
f"published release {tag} already exists with different assets; "
"refusing to overwrite"
)
if existing and existing.get("draft"):
release = existing
# Keep draft body/target aligned when continuing an interrupted publish.
release = patch_release(
api,
repo,
int(release["id"]),
token_value,
{
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
},
)
else:
release = create_draft(
api, repo, tag, body, token_value, prerelease=prerelease, target=target
)
release_id = int(release["id"])
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
for path in ordered:
if path.name in remote_names:
# Same-name asset already on this draft: require identical size, else fail.
match = next(
asset
for asset in list_assets(api, repo, release_id, token_value)
if asset.get("name") == path.name
)
if int(match.get("size") or -1) != path.stat().st_size:
raise PublishError(
f"draft asset {path.name} size mismatch; refusing to overwrite"
)
continue
upload_asset(api, repo, release_id, path, token_value)
refreshed = get_release_by_tag(api, repo, tag, token_value)
if not refreshed or not published_matches(refreshed, expected):
raise PublishError("post-upload release asset list does not match local files")
published = patch_release(
api,
repo,
release_id,
token_value,
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
)
if published.get("draft"):
raise PublishError("release remained draft after publish")
final = get_release_by_tag(api, repo, tag, token_value)
if not final or final.get("draft") or not published_matches(final, expected):
raise PublishError("final release confirmation failed")
return {
"status": "published",
"release_id": final["id"],
"html_url": final.get("html_url"),
"tag": tag,
"assets": expected,
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
parser.add_argument("--repo", required=True, help="owner/name")
parser.add_argument("--tag", required=True)
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
parser.add_argument("--body-file", default=None)
parser.add_argument("--body", default="")
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--prerelease", action="store_true", default=False)
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
args = parser.parse_args(argv)
body = args.body
if args.body_file:
body = Path(args.body_file).read_text(encoding="utf-8")
assets = [Path(item) for item in args.asset]
for path in assets:
if not path.is_file():
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
return 1
try:
result = publish(
api=args.api_url.rstrip("/"),
repo=args.repo,
tag=args.tag,
body=body,
target=args.target,
assets=assets,
prerelease=args.prerelease,
token_value=token(),
)
except PublishError as error:
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.evidence_out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Write the external release-evidence.json index for a component release.
The index references already-built assets. It never includes itself in
`assets[]` (no self-referential digest). Downstream discoverers hash the index
bytes separately when they download it.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
MAX_ASSETS = 128
MAX_DEPENDENCIES = 256
INDEX_NAME = "release-evidence.json"
class EvidenceError(Exception):
pass
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def parse_dependency(raw: str) -> dict:
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
fields = {}
for part in raw.split(","):
if "=" not in part:
raise EvidenceError(f"invalid dependency field: {raw!r}")
key, value = part.split("=", 1)
fields[key.strip()] = value.strip()
component_id = fields.get("id")
source_sha = fields.get("source_sha")
if not component_id or not source_sha or not SHA_RE.match(source_sha):
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
entry = {"id": component_id, "source_sha": source_sha}
asset = fields.get("asset_sha256")
if asset:
if not DIGEST_RE.match(asset):
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
entry["asset_sha256"] = asset
return entry
def build_evidence(
*,
component_id: str,
repository: str,
tag: str,
source_sha: str,
assets: list[Path],
dependencies: list[dict],
pipeline_number: int | None,
pipeline_url: str | None,
) -> dict:
if not component_id:
raise EvidenceError("component_id is required")
if "/" not in repository:
raise EvidenceError("repository must be owner/name")
if not tag:
raise EvidenceError("tag is required")
if not SHA_RE.match(source_sha):
raise EvidenceError("source_sha must be a 40-hex commit")
if not assets:
raise EvidenceError("at least one non-index asset is required")
if len(assets) > MAX_ASSETS:
raise EvidenceError(f"more than {MAX_ASSETS} assets")
if len(dependencies) > MAX_DEPENDENCIES:
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
asset_entries = []
seen_names: set[str] = set()
for path in assets:
if not path.is_file():
raise EvidenceError(f"asset missing: {path}")
name = path.name
if name == INDEX_NAME:
raise EvidenceError("assets must not include release-evidence.json itself")
if name in seen_names or "/" in name or name in (".", ".."):
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
seen_names.add(name)
target = "source"
if name.endswith(".tar.gz") and "linux" in name:
target = "x86_64-unknown-linux-gnu"
asset_entries.append(
{
"name": name,
"target": target,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
)
evidence = {
"component_id": component_id,
"repository": repository,
"tag": tag,
"source_sha": source_sha,
"ci": {
"pipeline_number": pipeline_number,
"url": pipeline_url,
"source_sha": source_sha,
},
"assets": asset_entries,
"dependencies": dependencies,
}
return evidence
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--component-id", required=True)
parser.add_argument("--repository", required=True)
parser.add_argument("--tag", required=True)
parser.add_argument("--source-sha", required=True)
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--dependency", action="append", default=[])
parser.add_argument("--pipeline-number", type=int, default=None)
parser.add_argument("--pipeline-url", default=None)
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
args = parser.parse_args(argv)
try:
dependencies = [parse_dependency(item) for item in args.dependency]
evidence = build_evidence(
component_id=args.component_id,
repository=args.repository,
tag=args.tag,
source_sha=args.source_sha,
assets=[Path(item) for item in args.asset],
dependencies=dependencies,
pipeline_number=args.pipeline_number,
pipeline_url=args.pipeline_url,
)
except EvidenceError as error:
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
if len(payload.encode()) > 1024 * 1024:
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
return 1
out.write_text(payload, encoding="utf-8")
print(out)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+61 -187
View File
@@ -1,211 +1,85 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Create/update the prerelease on the project's Gitea forge and attach assets. """Compatibility wrapper: delegate to the vendored immutable publisher.
Reads the token from the environment (`GITEA_TOKEN` or `gitea_token`), never Historical knowledge releases used an overwrite-friendly uploader. New publishes
prints or stores it. Idempotent: an existing release for the tag is updated and must follow issue #10 §4.2 (no overwrite of public assets; draft transaction).
existing assets are replaced so a re-run of the tag pipeline produces the same
release instead of failing.
Usage:
GITEA_TOKEN=... python3 tools/release/publish-gitea.py \
--tag v0.1.0-beta.2 \
--archive dist/marqdo-knowledge-...tar.gz \
--files dist/marqdo-knowledge-....sha256 dist/RELEASE_INFO.json \
dist/FILES.sha256 dist/smoke-evidence.json \
--body-file docs/releases/0.1.0-beta.2.md
""" """
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import json
import mimetypes
import os import os
import subprocess
import sys import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path from pathlib import Path
DEFAULT_API = "https://git.cflmy.cn/api/v1" ROOT = Path(__file__).resolve().parents[2]
DEFAULT_REPO = "cflmy/marqdo-knowledge" VENDOR = ROOT / "scripts" / "release" / "publish_gitea.py"
def fail(message: str) -> "NoReturn":
print(f"publish-gitea: FAIL: {message}", file=sys.stderr)
raise SystemExit(1)
def token() -> str:
value = os.environ.get("GITEA_TOKEN") or os.environ.get("gitea_token")
if not value:
fail("GITEA_TOKEN (or gitea_token) is not set")
return value
def request(
api: str,
method: str,
path: str,
token_value: str,
payload: dict | None = None,
raw: bytes | None = None,
content_type: str = "application/json",
) -> tuple[int, bytes]:
url = f"{api}{path}"
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = content_type
elif raw is not None:
data = raw
headers["Content-Type"] = content_type
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=60) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def decode(body: bytes) -> object:
try:
return json.loads(body)
except Exception:
return None
def create_or_update_release(
api: str, repo: str, tag: str, body: str, token_value: str
) -> dict:
path = f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}"
status, response = request(api, "GET", path, token_value)
payload = {
"tag_name": tag,
"name": f"marqdo-knowledge {tag.removeprefix('v')}",
"prerelease": True,
"draft": False,
"body": body,
}
if status == 200:
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
fail("existing release response is malformed")
status, response = request(
api, "PATCH", f"/repos/{repo}/releases/{release['id']}", token_value, payload
)
if status != 200:
fail(f"updating the existing release failed with HTTP {status}")
release = decode(response)
print(f"updated release id={release.get('id')} tag={tag}")
return release
if status != 404:
fail(f"looking up the release failed with HTTP {status}")
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
if status not in (201, 200):
fail(f"creating the release failed with HTTP {status}")
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
fail("release create response is malformed")
print(f"created release id={release.get('id')} tag={tag}")
return release
def upload_asset(
api: str, repo: str, release_id: int, path: Path, token_value: str
) -> dict:
name = path.name
status, response = request(
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
)
if status == 200:
existing = decode(response)
if isinstance(existing, list):
for asset in existing:
if asset.get("name") == name:
request(
api,
"DELETE",
f"/repos/{repo}/releases/{release_id}/assets/{asset['id']}",
token_value,
)
boundary = f"----marqdo{uuid.uuid4().hex}"
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
body = bytearray()
body.extend(f"--{boundary}\r\n".encode())
body.extend(
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
)
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
body.extend(path.read_bytes())
body.extend(f"\r\n--{boundary}--\r\n".encode())
status, response = request(
api,
"POST",
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
token_value,
raw=bytes(body),
content_type=f"multipart/form-data; boundary={boundary}",
)
if status not in (201, 200):
fail(f"uploading asset {name} failed with HTTP {status}")
result = decode(response)
print(f"uploaded asset {name} ({path.stat().st_size} bytes)")
return result if isinstance(result, dict) else {}
def main() -> int: def main() -> int:
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API)) parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", "https://git.cflmy.cn/api/v1"))
parser.add_argument("--repo", default=DEFAULT_REPO) parser.add_argument("--repo", default="cflmy/marqdo-knowledge")
parser.add_argument("--tag", required=True) parser.add_argument("--tag", required=True)
parser.add_argument("--archive", required=True) parser.add_argument("--archive", required=True)
parser.add_argument("--files", nargs="*", default=[]) parser.add_argument("--files", nargs="*", default=[])
parser.add_argument("--body-file", required=True) parser.add_argument("--body-file", required=True)
parser.add_argument("--evidence-out", default="dist/gitea-release-evidence.json") parser.add_argument("--evidence-out", default="dist/gitea-release-evidence.json")
parser.add_argument("--target", default=os.environ.get("SOURCE_SHA") or os.environ.get("CI_COMMIT_SHA"))
parser.add_argument("--prerelease", action="store_true", default=True)
args = parser.parse_args() args = parser.parse_args()
if not args.target:
token_value = token() print("publish-gitea: FAIL: --target / SOURCE_SHA / CI_COMMIT_SHA required", file=sys.stderr)
archive = Path(args.archive) return 1
if not archive.is_file(): assets = [args.archive, *args.files]
fail(f"archive {archive} does not exist") cmd = [
body = Path(args.body_file).read_text(encoding="utf-8") sys.executable,
release = create_or_update_release(args.api_url, args.repo, args.tag, body, token_value) str(VENDOR),
release_id = release["id"] "--api-url",
assets = [archive] args.api_url,
assets.extend(Path(item) for item in args.files if Path(item).is_file()) "--repo",
uploaded = [] args.repo,
for path in assets: "--tag",
result = upload_asset(args.api_url, args.repo, release_id, path, token_value) args.tag,
uploaded.append( "--target",
{ args.target,
"name": path.name, "--body-file",
"size": path.stat().st_size, args.body_file,
"sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(), "--evidence-out",
"browser_url": result.get("browser_download_url"), args.evidence_out,
} ]
) if args.prerelease:
evidence = { cmd.append("--prerelease")
"schema": "marqdo.knowledge.gitea-release", for asset in assets:
"schema_version": 1, cmd.extend(["--asset", asset])
"tag": args.tag, # Ensure release-evidence.json exists or generate a minimal one from assets.
"release_id": release_id, evidence = Path("dist/release-evidence.json")
"html_url": release.get("html_url"), if not evidence.is_file():
"prerelease": True, write = ROOT / "scripts" / "release" / "write_evidence.py"
"assets": uploaded, source_sha = args.target
} version = args.tag.removeprefix("v")
evidence_path = Path(args.evidence_out) gen = [
evidence_path.parent.mkdir(parents=True, exist_ok=True) sys.executable,
evidence_path.write_text( str(write),
json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n", "--component-id",
encoding="utf-8", "knowledge",
) "--repository",
print(f"release_url: {release.get('html_url')}") args.repo,
print(f"evidence: {evidence_path}") "--tag",
return 0 args.tag,
"--source-sha",
source_sha,
"--out",
str(evidence),
]
for asset in assets:
gen.extend(["--asset", asset])
subprocess.check_call(gen)
if str(evidence) not in assets and evidence.is_file():
cmd.extend(["--asset", str(evidence)])
return subprocess.call(cmd)
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) raise SystemExit(main())