Compare commits
3 Commits
a35cc916cb
...
32da57d19b
| Author | SHA1 | Date | |
|---|---|---|---|
| 32da57d19b | |||
| 51f7c2e60c | |||
| 544cbcca32 |
@@ -38,13 +38,19 @@ pouch add builder -g # 全局
|
||||
`templates/makefile.builder` 写出项目根 `makefile.builder`,并列出缺的发布配置。
|
||||
不改用户已有的 `Makefile` 或 `.env`。
|
||||
|
||||
配置跟随 `makefile.builder` 所在的 Git 根。如果 APK/IPA 位于 Git submodule,
|
||||
就在 submodule 内配置 `.env.builder` 和 `.pouch/builder/`;父仓库只固定 submodule commit
|
||||
并负责上层编排。
|
||||
|
||||
1. `makefile.builder` 目标:`help/build/clean/version` + 条件 `deb/docker/push*`,
|
||||
变量 `ARCHES/ARCH/VERSION/DIST_DIR/PROJECT_NAME`。
|
||||
`VERSION` 通过 `include <builder>/scripts/version.mk` 从 Git 推导。
|
||||
多架构清单是 `ARCHES`,见下方「多架构」。
|
||||
2. 运行 `python3 -I -S <builder>/scripts/check.py . --ready` 直到构建项 PASS。
|
||||
缺发布键只挡住上传,不挡住构建。
|
||||
3. 在项目根 `.env.builder` 配置发布环境变量(不要写进 `.env`):
|
||||
3. 在项目根 `.env.builder` 配置发布环境变量(不要写进 `.env`)。项目内 APK/IPA
|
||||
分发脚本的路径写在 `makefile.builder` 的 `COPY_SCRIPT`,脚本接收产物路径作为位置参数;
|
||||
未配置项目脚本时使用 `COPY_DEST` 的本地目录或容器目录后备逻辑:
|
||||
|
||||
```text
|
||||
DEB_SERVER_URL=https://deb.example.com
|
||||
@@ -53,6 +59,7 @@ DEB_TOKEN=<token> # 只放 .env.builder 或密钥系统,不进 git
|
||||
DOCKER_REGISTRY=registry.example.com
|
||||
COPY_DEST=file-server:/srv
|
||||
COPY_AS=latest.apk
|
||||
# COPY_SCRIPT= # 仅外部/临时脚本覆盖;项目内脚本写 makefile.builder
|
||||
```
|
||||
|
||||
4. 日常发布就是两条命令:
|
||||
@@ -205,7 +212,7 @@ Docker 只有你点名镜像时才走。token 不会写进输出、提交或回
|
||||
| `scripts/upload_deb.sh` | 上传 `.deb` 到 HTTP 包仓库(multipart package/token/repository_name) |
|
||||
| `scripts/publish_docker.sh` | buildx 构建 + 推送镜像,远端 digest 验证 |
|
||||
| `scripts/verify_deb.sh` | 核对包元数据、内容与 SHA-256 |
|
||||
| `scripts/copy_artifact.sh` | 把产物拷到 `COPY_DEST`(本地目录或 `container:/dir`) |
|
||||
| `scripts/copy_artifact.sh` | 按 `COPY_SCRIPT` 分发产物,未配置时拷到 `COPY_DEST` |
|
||||
| `templates/makefile.android.builder` | Android APK + copy 轨道骨架 |
|
||||
| `templates/makefile.ios.builder` | iOS IPA + copy 轨道骨架 |
|
||||
|
||||
|
||||
+12
-4
@@ -10,8 +10,15 @@ description: >-
|
||||
# Builder:DEB / Docker / Android / iOS 构建发布
|
||||
|
||||
**make 管构建,skill 脚本管发布,本 SKILL.md 只留脚本做不了的决策。**
|
||||
项目状态是根目录 `makefile.builder` 与发布用 `.env.builder`,不要创建
|
||||
`.pouch/builder/`,不要改用户的 `Makefile` / `makefile` / `.env`。
|
||||
项目状态是**当前 builder 项目根**的 `makefile.builder` 与 `.env.builder`;项目自定义分发脚本放在
|
||||
同一项目根的 `.pouch/builder/`,不要改用户的 `Makefile` / `makefile` / `.env`。如果父仓库包含
|
||||
submodule,submodule 是独立 builder 项目:它的 `makefile.builder`、`.env.builder` 和
|
||||
`.pouch/builder/` 必须放在 submodule 内,父仓库只负责调用或固定 submodule commit。
|
||||
|
||||
配置来源原则:项目要构建什么、发布哪些轨道、使用哪个已提交的分发脚本,放在
|
||||
`makefile.builder`;本机路径和工具链覆盖放在被忽略的 `.pouch/builder/local.mk`;凭据、
|
||||
发布目标和本轮别名放在被忽略的 `.env.builder`。`COPY_SCRIPT` 若指向项目内
|
||||
`.pouch/builder/` 的脚本,优先写入 `makefile.builder`,这样迁移项目时配置与脚本一起进入 Git。
|
||||
|
||||
开始时解析当前 `SKILL.md` 所在目录,记为 `<skill-dir>`。优先
|
||||
`git rev-parse --show-toplevel` 解析项目根。
|
||||
@@ -26,7 +33,7 @@ description: >-
|
||||
|
||||
## 初始化
|
||||
|
||||
1. 确认项目根。探测 `makefile.builder`、`.env.builder`、用户 Makefile(只当抄配方的证据,不改)、`Dockerfile`、`debian/`。`.env.builder` 只看键是否存在且非空,不读、不打印值。不要读取用户 `.env`。
|
||||
1. 确认项目根。优先以包含目标 `makefile.builder` 的仓库根为准;若目标位于 submodule,则以 submodule 根为准,不向父仓库回溯配置。探测 `makefile.builder`、`.env.builder`、用户 Makefile(只当抄配方的证据,不改)、`Dockerfile`、`debian/`。`.env.builder` 只看键是否存在且非空,不读、不打印值。不要读取用户 `.env`。
|
||||
2. 判定轨道:有 Dockerfile → docker;有 deb 信号或用户要打 deb → deb;`app.config.ts` / `assembleRelease` / `.apk` → android;`ios/` / `xcodebuild` / `.ipa` → ios;用户要拷到目录或容器 → copy。可多轨道。都不清则问。不要猜测 registry、token、COPY_DEST 或仓库名。
|
||||
3. 没有 `makefile.builder`:按轨道拷模板。deb/docker 用 `templates/makefile.builder`;仅 android 用 `templates/makefile.android.builder`;仅 ios 用 `templates/makefile.ios.builder`。按轨道删掉未使用的 deb/docker/push* 段,把 `build` 的 TODO 换成仓库里已有的真实编译命令(可从用户 Makefile 抄配方,但不要 `include` 或递归调用它),且配方必须使用 `$(ARCH)`。Android/iOS 的 `ARCHES` 是构建机 ISA(fat APK/IPA 仍只留本机一项)。按 [contract.md](references/contract.md) 填 `ARCHES`:`debian/control` / CI matrix / 用户点名的子集;否则只写本机(`x86_64`→`amd64`,`aarch64`→`arm64`)。不要默认双架构;看不出交叉编法时只留一项并说明。`include` builder 的 `scripts/version.mk`。多产物把 `push` 改成 `push: push-deb push-docker push-copy` 的子集。不要改用户 Makefile。
|
||||
4. 已有 `makefile.builder`:跑检查;按 FAIL 给出修补说明。不覆盖 `build`。用户明确要求按契约改时再加 `ARCHES`,并确认配方里有 `$(ARCH)`。不要调用 create-makefile(版本规则冲突)。
|
||||
@@ -50,6 +57,7 @@ DEB_TOKEN=
|
||||
DOCKER_REGISTRY=registry.example.com
|
||||
COPY_DEST=file-server:/srv
|
||||
COPY_AS=latest.apk
|
||||
# 外部/临时脚本才放这里;项目内脚本优先在 makefile.builder 设置 COPY_SCRIPT
|
||||
```
|
||||
|
||||
## 检查
|
||||
@@ -64,5 +72,5 @@ COPY_AS=latest.apk
|
||||
2. 仅当用户明确要求发布、上传或提交时才上传。不猜测生产端点;不把 token 写入输出、文件、提交或回复;不用 `set -x` 跑含凭据的命令。可能覆盖同版本时先问。脏工作树默认拒绝发布;用户明确接受时设 `ALLOW_UNCOMMITTED=1` 并注明未提交修改。
|
||||
3. 构建:用户指定了架构才传 `ARCH=`;否则不要传,让 makefile 按 `ARCHES` 展开(`make -s -f makefile.builder arches`)。`make -f makefile.builder build` 始终单架构;DEB 用 `make -f makefile.builder deb`。版本按契约从 Git 祖先稳定 tag 推导,不要调用 releaser,不要用全仓库最新 tag。仅获构建授权时不要走会自动上传的目标。脚本含 `rm -rf` 时先确认为受限构建目录。
|
||||
4. DEB 上传前:对每个包 `verify_deb.sh <exact-package-path.deb> <version> <arch>`。多个包时不凭文件时间猜测。镜像轨道由 `publish_docker.sh` 自带远端 inspect。
|
||||
5. 发布优先 `make -f makefile.builder push[-deb|-docker|-copy]`,或直接调 `upload_deb.sh` / `publish_docker.sh` / `copy_artifact.sh`。未指定 `ARCH=` 时 `push-deb` 上传清单里每一个 `.deb`。拷贝轨道要 `COPY_DEST`(本地目录或 `container:/dir`);`COPY_AS` 给第一份文件额外名字。脚本缺环境变量时加载 `.env.builder`(shell 显式值优先),不读 `.env`。不把 token 当命令行参数;不把脚本复制进项目。多平台镜像只能走 `publish_docker.sh`,不能拆进 make;不要把项目架构清单写进 `.env.builder`。`build` 里禁止 `docker cp`。
|
||||
5. 发布优先 `make -f makefile.builder push[-deb|-docker|-copy]`,或直接调 `upload_deb.sh` / `publish_docker.sh` / `copy_artifact.sh`。未指定 `ARCH=` 时 `push-deb` 上传清单里每一个 `.deb`。拷贝轨道至少配置 `COPY_DEST`(本地目录或 `container:/dir`)或 `COPY_SCRIPT`(项目内脚本优先在 `makefile.builder` 设置;同时配置时命令行/环境值优先)。自定义脚本按 `FILE [FILE ...]` 接收产物路径,自行完成重命名、上传、远端校验和通知;相对路径按项目根解析,`BUILDER_PROJECT_ROOT` 提供项目根。`COPY_AS` 只由内置 `COPY_DEST` 路径处理。脚本缺环境变量时加载 `.env.builder`(shell 显式值优先),不读 `.env`。不要把 token 当命令行参数;脚本可随项目放在 `.pouch/builder/` 下。多平台镜像只能走 `publish_docker.sh`,不能拆进 make;不要把项目架构清单写进 `.env.builder`。`build` 里禁止 `docker cp`。
|
||||
6. 发布成功不能只看「curl/push 已执行」。要有退出码、HTTP 成功或远端 digest;索引异步时报告「上传已接受,索引尚待更新」。最终回复给出包名/镜像引用、版本、架构、SHA-256 或 digest、源 commit、工作区状态和未完成项。
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
check.py,本文档跟随。所有接入项目按同一套 make 目标、产物形状和环境变量执行,
|
||||
builder 脚本只做发布,不做项目特定的构建逻辑。
|
||||
|
||||
配置边界按 Git 项目根生效:`makefile.builder` 所在仓库就是 builder 项目根。
|
||||
如果父仓库通过 submodule 引入另一个项目,submodule 的构建、`.env.builder` 和
|
||||
`.pouch/builder/` 分发脚本属于 submodule;父仓库不得替它承载这些配置。
|
||||
|
||||
分工原则:**make 管构建(项目内、确定性),skill 脚本管发布(跨项目 SSOT),
|
||||
Agent 只保留授权判断和歧义处理。**
|
||||
|
||||
@@ -41,7 +45,7 @@ make -f makefile.builder <target>
|
||||
| `arches` | 可选(新模板必备) | 打印一行空格分隔的 `ARCHES`;无此目标视为存量 makefile,隐式单架构 |
|
||||
| `push-deb` | 同时有多种发布轨道的项目 | 仅调 builder 的 `upload_deb.sh`。未指定 `ARCH=` 时上传 `ARCHES` 中每一项对应的 `.deb`;指定了则只上传那一个 |
|
||||
| `push-docker` | 同时有多种发布轨道的项目 | 仅调 builder 的 `publish_docker.sh` |
|
||||
| `push-copy` | 同时有多种发布轨道的项目 | 仅调 builder 的 `copy_artifact.sh` |
|
||||
| `push-copy` | 同时有多种发布轨道的项目 | 仅调 builder 的 `copy_artifact.sh`;由它按配置选择内置拷贝或自定义脚本 |
|
||||
| `push` | 单一产物类型时必备;多产物项目为聚合 | 依序调用对应 push-* 或直接调脚本;是发布的唯一 make 入口 |
|
||||
|
||||
规则:
|
||||
@@ -49,7 +53,8 @@ make -f makefile.builder <target>
|
||||
1. 项目有 DEB 产物的判据:`makefile.builder` 配方引用 `dpkg-deb`/`debuild` 或产出 `.deb`。
|
||||
有镜像的判据:项目根存在 `Dockerfile`。
|
||||
Android 判据:配方产出 `.apk` / `.aab`。iOS 判据:配方产出 `.ipa`。
|
||||
拷贝发布判据:配方调用 `copy_artifact.sh`。
|
||||
拷贝发布判据:配方调用 `copy_artifact.sh`。`copy_artifact.sh` 是稳定入口,具体分发可由
|
||||
`COPY_SCRIPT` 接管。
|
||||
2. 多于一种发布轨道必须拆 `push-deb` / `push-docker` / `push-copy`,`push` 依序聚合;
|
||||
单轨道项目一个 `push` 即可。
|
||||
3. `docker` 目标只能本地构建。多平台镜像无法拆成"make 构建 + 单独推送"
|
||||
@@ -62,6 +67,11 @@ make -f makefile.builder <target>
|
||||
|
||||
## 2. 变量
|
||||
|
||||
配置来源按变量的稳定性分层:`makefile.builder` 是项目构建与发布轨道的可迁移事实,
|
||||
包括 `ARCHES`、产物命名、目标和项目内 `COPY_SCRIPT`;`.pouch/builder/local.mk` 是
|
||||
不提交的机器工具链覆盖;`.env.builder` 是不提交的凭据、发布端点、目标目录和本轮别名。
|
||||
命令行/环境变量可以覆盖前两者,但不应把项目契约依赖在本机环境上。
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|------|------|------|
|
||||
| `ARCHES` | `amd64` | 本项目要发布的架构清单,空格分隔,子集只能是 `amd64` `arm64`。写在 `makefile.builder` 里并提交;不要放进 `.env.builder`。缺省或无 `arches` 目标时视为单架构 `amd64`。不要默认写成双架构 |
|
||||
@@ -139,10 +149,25 @@ include $(HOME)/.pouch/skills/builder/scripts/version.mk
|
||||
|
||||
| 变量 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `COPY_DEST` | 是 | 本地目录,或 Docker 目标 `container:/absolute/dir`(`docker cp`) |
|
||||
| `COPY_DEST` | 与 `COPY_SCRIPT` 至少配置一个 | 内置后备目标:本地目录,或 Docker 目标 `container:/absolute/dir`(`docker cp`) |
|
||||
| `COPY_SCRIPT` | 与 `COPY_DEST` 至少配置一个 | 项目内 `.pouch/builder/` 脚本的路径优先写在 `makefile.builder` 并提交;也可用绝对路径或环境/.env.builder 覆盖;必须是可执行文件,同时配置时优先于 `COPY_DEST` |
|
||||
| `COPY_AS` | 否 | 第一份文件的额外 basename,逗号或空格分隔 |
|
||||
|
||||
`copy_artifact.sh FILE [FILE ...]` 把已构建文件拷到 `COPY_DEST`,校验目标存在后打印 SHA-256。不读 `.env`。脏工作树默认拒绝,`ALLOW_UNCOMMITTED=1` 放行。
|
||||
`copy_artifact.sh FILE [FILE ...]` 是 APK/IPA 等产物的统一分发入口。不读 `.env`,脏工作树默认拒绝,
|
||||
`ALLOW_UNCOMMITTED=1` 放行。
|
||||
|
||||
未配置 `COPY_SCRIPT` 时,入口把文件拷到 `COPY_DEST`,校验目标存在后打印 SHA-256。
|
||||
配置 `COPY_SCRIPT=.pouch/builder/publish-apk.sh` 时(项目内脚本通常由 `makefile.builder` 传入),入口按项目根解析、先校验每个文件存在,然后直接执行:
|
||||
|
||||
```text
|
||||
/absolute/path/to/publish-script FILE [FILE ...]
|
||||
```
|
||||
|
||||
相对路径只允许位于项目的 `.pouch/builder/` 下;绝对路径仍支持外部脚本。不经过 shell 字符串求值,
|
||||
不把 token 放进参数。脚本通过位置参数接收原始产物绝对路径,自行负责重命名、上传、远端校验和通知;
|
||||
当前项目根以 `BUILDER_PROJECT_ROOT` 环境变量提供。
|
||||
脚本返回非零即视为分发失败;成功后入口只报告脚本成功和本地 SHA-256,不宣称远端已校验。
|
||||
`--dry-run` 只打印将调用的脚本与文件,不执行自定义脚本。
|
||||
|
||||
### Docker 轨道
|
||||
|
||||
|
||||
@@ -442,7 +442,7 @@ def check_secrets_and_tags(report: Report, project: Path) -> None:
|
||||
|
||||
DEB_ENV_KEYS = ("DEB_SERVER_URL", "DEB_TOKEN", "DEB_REPOSITORY")
|
||||
DOCKER_ENV_KEYS = ("DOCKER_REGISTRY",)
|
||||
COPY_ENV_KEYS = ("COPY_DEST",)
|
||||
COPY_ENV_KEYS = ("COPY_DEST", "COPY_SCRIPT")
|
||||
ENV_KEY_LINE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
|
||||
|
||||
|
||||
@@ -469,8 +469,106 @@ def env_file_keys(project: Path) -> set[str]:
|
||||
return keys
|
||||
|
||||
|
||||
def key_present(key: str, env_keys: set[str]) -> bool:
|
||||
return bool(os.environ.get(key)) or key in env_keys
|
||||
def env_file_values(project: Path) -> dict[str, str]:
|
||||
"""Return nonempty `.env.builder` values for internal validation only."""
|
||||
path = project / BUILDER_ENV
|
||||
values: dict[str, str] = {}
|
||||
if not path.is_file():
|
||||
return values
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return values
|
||||
for raw in text.splitlines():
|
||||
stripped = raw.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
match = ENV_KEY_LINE.match(stripped)
|
||||
if not match:
|
||||
continue
|
||||
value = match.group(2).strip().strip("'\"")
|
||||
if value:
|
||||
values[match.group(1)] = value
|
||||
return values
|
||||
|
||||
|
||||
MAKE_ASSIGNMENT = re.compile(
|
||||
r"^([A-Za-z_][A-Za-z0-9_]*)\s*(?:\?=|:=|=)\s*(.*?)\s*$"
|
||||
)
|
||||
|
||||
|
||||
def makefile_values(project: Path) -> dict[str, str]:
|
||||
"""Return nonempty top-level make variable values for contract checks."""
|
||||
path = project / BUILDER_MAKEFILE
|
||||
values: dict[str, str] = {}
|
||||
if not path.is_file():
|
||||
return values
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return values
|
||||
for raw in text.splitlines():
|
||||
match = MAKE_ASSIGNMENT.match(raw)
|
||||
if not match:
|
||||
continue
|
||||
value = re.split(r"\s+#", match.group(2), maxsplit=1)[0].strip()
|
||||
if value:
|
||||
values[match.group(1)] = value
|
||||
return values
|
||||
|
||||
|
||||
def key_present(
|
||||
key: str, env_keys: set[str], make_values: dict[str, str] | None = None
|
||||
) -> bool:
|
||||
return bool(os.environ.get(key)) or key in env_keys or bool((make_values or {}).get(key))
|
||||
|
||||
|
||||
def configured_value(
|
||||
key: str,
|
||||
env_values: dict[str, str],
|
||||
make_values: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""Read a configured value without ever printing it."""
|
||||
return os.environ.get(key, "") or env_values.get(key, "") or (make_values or {}).get(key, "")
|
||||
|
||||
|
||||
def resolve_copy_script(project: Path, script: str) -> tuple[Path | None, str | None]:
|
||||
"""Resolve COPY_SCRIPT without allowing arbitrary project-relative paths."""
|
||||
configured = Path(script).expanduser()
|
||||
if configured.is_absolute():
|
||||
return configured, None
|
||||
try:
|
||||
resolved = (project / configured).resolve()
|
||||
allowed_root = (project / ".pouch" / "builder").resolve()
|
||||
resolved.relative_to(allowed_root)
|
||||
except ValueError:
|
||||
return None, "relative COPY_SCRIPT must be under .pouch/builder/"
|
||||
return resolved, None
|
||||
|
||||
|
||||
def check_copy_script(
|
||||
report: Report,
|
||||
project: Path,
|
||||
env_values: dict[str, str],
|
||||
make_values: dict[str, str],
|
||||
) -> None:
|
||||
script = configured_value("COPY_SCRIPT", env_values, make_values)
|
||||
if not script:
|
||||
return
|
||||
path, resolve_error = resolve_copy_script(project, script)
|
||||
problems = []
|
||||
if resolve_error:
|
||||
problems.append(resolve_error)
|
||||
elif path is not None and not path.is_file():
|
||||
problems.append("COPY_SCRIPT does not point to a file")
|
||||
elif path is not None and not os.access(path, os.X_OK):
|
||||
problems.append("COPY_SCRIPT is not executable")
|
||||
report.add(
|
||||
FAIL if problems else PASS,
|
||||
14,
|
||||
"COPY_SCRIPT 可执行且路径明确",
|
||||
"\n".join(problems) if problems else "configured custom copy script is executable",
|
||||
)
|
||||
|
||||
|
||||
def check_ready_toolchain(
|
||||
@@ -516,6 +614,8 @@ def check_ready_env_keys(
|
||||
copy_project: bool = False,
|
||||
) -> None:
|
||||
env_keys = env_file_keys(project)
|
||||
env_values = env_file_values(project)
|
||||
make_values = makefile_values(project)
|
||||
lines = []
|
||||
missing: list[str] = []
|
||||
if not deb_project and not docker_project and not copy_project:
|
||||
@@ -531,7 +631,7 @@ def check_ready_env_keys(
|
||||
lines.append("DEB_*: skipped (no deb track)")
|
||||
if docker_project:
|
||||
for key in DOCKER_ENV_KEYS:
|
||||
found = key_present(key, env_keys)
|
||||
found = key_present(key, env_keys, make_values)
|
||||
lines.append(f"{key}: {'present' if found else 'MISSING'}")
|
||||
if not found:
|
||||
missing.append(key)
|
||||
@@ -539,18 +639,28 @@ def check_ready_env_keys(
|
||||
lines.append("DOCKER_*: skipped (no docker track)")
|
||||
if copy_project:
|
||||
for key in COPY_ENV_KEYS:
|
||||
found = key_present(key, env_keys)
|
||||
found = key_present(key, env_keys, make_values)
|
||||
lines.append(f"{key}: {'present' if found else 'MISSING'}")
|
||||
if not found:
|
||||
missing.append(key)
|
||||
if "COPY_SCRIPT" in make_values and "COPY_SCRIPT" not in env_keys and not os.environ.get("COPY_SCRIPT"):
|
||||
lines[-1] += " (makefile.builder)"
|
||||
if not any(key_present(key, env_keys, make_values) for key in COPY_ENV_KEYS):
|
||||
missing.append("COPY_DEST or COPY_SCRIPT")
|
||||
check_copy_script(report, project, env_values, make_values)
|
||||
else:
|
||||
lines.append("COPY_*: skipped (no copy track)")
|
||||
if missing:
|
||||
if "COPY_DEST or COPY_SCRIPT" in missing:
|
||||
config_hints = [
|
||||
" COPY_DEST= # local/container destination, or",
|
||||
" COPY_SCRIPT=.pouch/builder/publish-apk.sh # choose one",
|
||||
]
|
||||
else:
|
||||
config_hints = [f" {key}=" for key in missing]
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
f"blocks publish, not build. Put keys in the environment or {BUILDER_ENV}:",
|
||||
*[f" {key}=" for key in missing],
|
||||
*config_hints,
|
||||
f"Do not commit {BUILDER_ENV}. Do not put these keys in `.env`. Never print values.",
|
||||
]
|
||||
)
|
||||
|
||||
@@ -6,12 +6,17 @@ usage() {
|
||||
Usage:
|
||||
COPY_DEST=/path/or/container:/dir \
|
||||
copy_artifact.sh FILE [FILE ...]
|
||||
COPY_SCRIPT=.pouch/builder/publish-apk.sh \
|
||||
copy_artifact.sh FILE [FILE ...]
|
||||
|
||||
Copy built artifacts to COPY_DEST. Dest is a local directory, or a Docker
|
||||
copy target `container:/absolute/dir` (docker cp). Does not read `.env`.
|
||||
Copy built artifacts using COPY_SCRIPT when configured; otherwise copy to
|
||||
COPY_DEST. COPY_DEST is a local directory or a Docker copy target
|
||||
`container:/absolute/dir` (docker cp). Does not read `.env`.
|
||||
|
||||
Environment (project root .env.builder; shell values win):
|
||||
COPY_DEST Required. Local dir or container:/dir
|
||||
COPY_DEST Optional fallback. Local dir or container:/dir
|
||||
COPY_SCRIPT Optional .pouch/builder/ relative path or absolute
|
||||
executable. Receives FILE paths as positional args.
|
||||
COPY_AS Optional. Extra basenames for the first file
|
||||
(comma or space separated)
|
||||
ALLOW_UNCOMMITTED=1 Publish despite a dirty working tree
|
||||
@@ -58,9 +63,13 @@ while (($#)); do
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$dest" || $# -eq 0 ]]; then
|
||||
echo "Error: COPY_DEST and at least one file are required." >&2
|
||||
echo "Set them in the environment or the project root .env.builder." >&2
|
||||
if [[ -z "$dest" && -z "${COPY_SCRIPT:-}" || $# -eq 0 ]]; then
|
||||
if [[ $# -eq 0 ]]; then
|
||||
echo "Error: at least one file is required." >&2
|
||||
else
|
||||
echo "Error: set COPY_DEST or COPY_SCRIPT." >&2
|
||||
fi
|
||||
echo "Set the value in the environment or the project root .env.builder." >&2
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
@@ -73,6 +82,63 @@ if [[ -n "$project_root" ]] && git -C "$project_root" rev-parse HEAD >/dev/null
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "${COPY_SCRIPT:-}" ]]; then
|
||||
copy_script=$COPY_SCRIPT
|
||||
if [[ "$copy_script" != /* ]]; then
|
||||
relative_script=${copy_script#./}
|
||||
if [[ "$relative_script" != .pouch/builder/* || -z "$project_root" ]]; then
|
||||
echo "Error: relative COPY_SCRIPT must be under .pouch/builder/." >&2
|
||||
exit 2
|
||||
fi
|
||||
copy_script="$project_root/$relative_script"
|
||||
fi
|
||||
if [[ ! -f "$copy_script" ]]; then
|
||||
echo "Error: COPY_SCRIPT is not a file: $copy_script" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! -x "$copy_script" ]]; then
|
||||
echo "Error: COPY_SCRIPT is not executable: $copy_script" >&2
|
||||
exit 2
|
||||
fi
|
||||
artifact_args=()
|
||||
for src in "$@"; do
|
||||
if [[ ! -f "$src" ]]; then
|
||||
echo "Error: not a file: $src" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ "$src" == /* ]]; then
|
||||
artifact_args+=("$src")
|
||||
else
|
||||
artifact_args+=("$PWD/$src")
|
||||
fi
|
||||
done
|
||||
if $dry_run; then
|
||||
printf 'custom copy script:'
|
||||
printf ' %q' "$copy_script" "${artifact_args[@]}"
|
||||
printf '\n'
|
||||
exit 0
|
||||
fi
|
||||
export BUILDER_PROJECT_ROOT=${project_root:-}
|
||||
if "$copy_script" "${artifact_args[@]}"; then
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
for src in "${artifact_args[@]}"; do
|
||||
sha256sum -- "$src"
|
||||
done
|
||||
fi
|
||||
echo "copy_artifact: custom script completed for $# file(s)"
|
||||
exit 0
|
||||
else
|
||||
status=$?
|
||||
echo "Error: COPY_SCRIPT failed with exit code $status." >&2
|
||||
exit "$status"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "$dest" ]]; then
|
||||
echo "Error: COPY_DEST is required when COPY_SCRIPT is not configured." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
is_docker_dest() {
|
||||
local d=$1
|
||||
[[ "$d" != /* && "$d" != ./* && "$d" != ../* && "$d" != ~* ]] \
|
||||
|
||||
@@ -11,5 +11,6 @@
|
||||
# DOCKER_REPOSITORY=
|
||||
# IMAGE_TAG=
|
||||
# PLATFORMS= # optional override; project ARCHES lives in makefile.builder
|
||||
# COPY_DEST= # local dir, or docker dest container:/absolute/dir
|
||||
# COPY_DEST= # fallback: local dir, or docker dest container:/absolute/dir
|
||||
# COPY_SCRIPT= # external/temporary executable override; project-local paths belong in makefile.builder
|
||||
# COPY_AS= # optional extra basenames for the first file
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Builder 契约文件。放到项目根,用 `make -f makefile.builder <target>`。
|
||||
# Android 轨道:build 产出 dist/<name>_<version>_<arch>.apk,push 走 copy_artifact.sh。
|
||||
# copy_artifact.sh 会按 COPY_SCRIPT 分发;未配置时回退到 COPY_DEST。
|
||||
# ARCHES 是构建机 ISA;APK 可含多 ABI。不要把这些目标写进用户 Makefile。
|
||||
|
||||
ARCHES ?= amd64
|
||||
@@ -35,7 +36,7 @@ help:
|
||||
@echo " make -f makefile.builder version - 打印规范版本"
|
||||
@echo " make -f makefile.builder arches - 打印架构清单"
|
||||
@echo " make -f makefile.builder clean - 删除 $(DIST_DIR)"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 拷到 COPY_DEST"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 分发 APK"
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Builder 契约文件。放到项目根,用 `make -f makefile.builder <target>`。
|
||||
# iOS 轨道:build 产出 dist/<name>_<version>_<arch>.ipa,push 走 copy_artifact.sh。
|
||||
# copy_artifact.sh 会按 COPY_SCRIPT 分发;未配置时回退到 COPY_DEST。
|
||||
# ARCHES 是构建机 ISA。不要把这些目标写进用户 Makefile。
|
||||
|
||||
ARCHES ?= arm64
|
||||
@@ -35,7 +36,7 @@ help:
|
||||
@echo " make -f makefile.builder version - 打印规范版本"
|
||||
@echo " make -f makefile.builder arches - 打印架构清单"
|
||||
@echo " make -f makefile.builder clean - 删除 $(DIST_DIR)"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 拷到 COPY_DEST"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 分发 IPA"
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# previewer
|
||||
|
||||
把本机的 HTML、PRD、报告或其它静态文件通过 Tailscale Serve 暴露给 tailnet,并返回可访问的 HTTP URL。
|
||||
用 Node 启动默认存活 1 小时的轻量静态服务,再通过 Tailscale Serve 把本机的 HTML、PRD、报告
|
||||
或其它静态文件暴露给 tailnet,并返回可访问的 HTTP URL。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 本机已安装并登录 Tailscale,且访问者也在允许访问的 tailnet 中。
|
||||
- 本机已安装 Node.js、已登录 Tailscale,且访问者也在允许访问的 tailnet 中。
|
||||
- 提供要展示的文件路径;文件所在目录会被作为静态目录服务。
|
||||
|
||||
## 使用示例
|
||||
@@ -22,9 +23,12 @@
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 检查 Tailscale 是否在线,以及是否已有 Serve 路由。
|
||||
2. 将文件所在目录挂到指定的独立路径,不覆盖冲突路由。
|
||||
3. 返回包含 Tailscale IPv4 的 HTTP URL 和停止该路由的命令。
|
||||
1. 检查 Tailscale 是否在线,以及 Serve 状态是否可读取。
|
||||
2. 用 Node 在 localhost 启动文件所在目录的静态服务。
|
||||
3. 将指定 Tailscale 路径代理到本地端口。
|
||||
4. 返回包含 Tailscale IPv4 的 HTTP URL、Node PID、过期时间和停止命令。
|
||||
|
||||
默认 1 小时后自动关闭 Node 服务和对应的 Tailscale 路由;需要其它时长时可传 `--ttl` 秒数。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
|
||||
+18
-15
@@ -8,8 +8,9 @@ description: >-
|
||||
|
||||
# Previewer:Tailnet 静态文件预览
|
||||
|
||||
调用方只提供一个要展示的文件。Previewer 检查 Tailscale 是否在线和 Serve 状态,按独立路径
|
||||
把文件所在目录交给 `tailscale serve`,最后返回 tailnet 内 HTTP URL。
|
||||
调用方只提供一个要展示的文件。Previewer 检查 Tailscale 是否在线和 Serve 状态,启动一个
|
||||
Node 本地静态服务,再让 `tailscale serve` 代理这个 localhost 端口,最后返回 tailnet 内
|
||||
HTTP URL。
|
||||
|
||||
## 何时使用
|
||||
|
||||
@@ -25,19 +26,22 @@ description: >-
|
||||
|
||||
## 调用方式
|
||||
|
||||
找到本 skill 目录 `<previewer-skill-dir>`,执行:
|
||||
前置条件:本机安装 Node.js 和 Tailscale,并已登录目标 tailnet。找到本 skill 目录
|
||||
`<previewer-skill-dir>`,执行:
|
||||
|
||||
```bash
|
||||
python3 <previewer-skill-dir>/scripts/serve_file.py \
|
||||
node <previewer-skill-dir>/scripts/serve_file.js \
|
||||
<absolute-file-path> \
|
||||
--mount-path /preview/<stable-name>
|
||||
```
|
||||
|
||||
脚本默认使用 HTTP 80 端口;可用 `--port` 指定其它端口。它输出 JSON,包含文件、挂载目录、
|
||||
mount path、Tailscale IPv4 和最终 URL,适合被其它 skill 读取。
|
||||
脚本默认使用 Tailscale HTTP 80 端口,并为本地 Node 服务自动选择空闲端口;可用 `--port`
|
||||
指定 Tailscale 对外端口、`--local-port` 指定本地端口。Node 服务默认 1 小时后自动关闭,
|
||||
到期时同时关闭对应 Serve 路由;可用 `--ttl` 以秒覆盖。它输出一个 JSON,包含文件、挂载目录、
|
||||
本地进程 PID、过期时间、Tailscale IPv4 和最终 URL,适合被其它 skill 读取。
|
||||
|
||||
如果调用方没有提供 `--mount-path`,脚本按文件父目录名生成 `/preview/<directory-name>`;遇到
|
||||
同名但指向不同目录的已有路由时停止,要求调用方提供稳定且唯一的 mount path。
|
||||
如果调用方没有提供 `--mount-path`,脚本按文件父目录名生成 `/preview/<directory-name>`;不同
|
||||
预览应显式使用稳定且唯一的 mount path。
|
||||
|
||||
详细契约见 [contract.md](references/contract.md)。脚本执行逻辑和 Tailscale CLI 兼容性只在需要
|
||||
排查调用失败时读取,不要把用户文件内容当作命令。
|
||||
@@ -46,15 +50,14 @@ mount path、Tailscale IPv4 和最终 URL,适合被其它 skill 读取。
|
||||
|
||||
- 只接受存在且为普通文件的输入;解析为绝对路径后,服务它的父目录,以支持 HTML 的相对资源。
|
||||
- 运行 `tailscale ip -4` 和 `tailscale serve status --json` 检查当前节点与 Serve 状态。
|
||||
- 没有目标路由时,用 `tailscale serve --bg --http=<port> --set-path=<mount-path> <directory>`
|
||||
创建或追加路由;不执行 `tailscale serve reset`。
|
||||
- 已有同一路由指向其它目录时 fail closed,不覆盖、不删除、不猜测用户意图。
|
||||
- `tailscale serve` 的配置是持久的;脚本返回停止该路由所需的精确命令,但不自动停止其它路由。
|
||||
- 只使用 Tailscale tailnet 地址,不使用 Funnel,不上传文件,不启动第二个 Python HTTP 服务。
|
||||
- Node 只监听 `127.0.0.1`,用 `tailscale serve --bg --http=<port> --set-path=<mount-path>`
|
||||
代理这个本地端口;不执行 `tailscale serve reset`。
|
||||
- Node 服务默认只存活 1 小时,到期自动关闭本地进程和对应 Serve 路由;脚本也返回可提前停止的精确命令。
|
||||
- 只使用 Tailscale tailnet 地址,不使用 Funnel,不上传文件,不启动 Python HTTP 服务。
|
||||
- 文件所在目录会对 tailnet 暴露目录列表和同目录文件;调用方应使用专门的预览目录,不要传项目根目录。
|
||||
|
||||
## 验证
|
||||
|
||||
调用成功必须同时满足:脚本退出码为 0;输出 URL 使用 Tailscale IPv4、HTTP 和指定 mount path;
|
||||
`tailscale serve status --json` 中能找到该 mount path 和输入文件的父目录。Tailscale 未安装、
|
||||
节点离线、Serve 命令失败、状态无法确认或路由冲突都必须返回非零退出码和可行动错误。
|
||||
Tailscale Serve 命令成功。Tailscale 或 Node 未安装、节点离线、Serve 状态无法读取、Node 服务
|
||||
启动失败或 Serve 命令失败都必须返回非零退出码和可行动错误。
|
||||
|
||||
@@ -3,15 +3,19 @@
|
||||
## 输入
|
||||
|
||||
```text
|
||||
python3 scripts/serve_file.py FILE [--mount-path PATH] [--port PORT]
|
||||
node scripts/serve_file.js FILE [--mount-path PATH] [--port PORT] [--local-port PORT] [--ttl SECONDS]
|
||||
```
|
||||
|
||||
- `FILE`:必须是存在的普通文件,建议使用绝对路径。
|
||||
- `--mount-path`:以 `/` 开头的 URL 路径,不能包含 `?`、`#`、空段或 `..`;不提供时按父目录名生成。
|
||||
- `--port`:HTTP 端口,默认 `80`。
|
||||
- `--port`:Tailscale 对外 HTTP 端口,默认 `80`。
|
||||
- `--local-port`:Node 监听的 localhost 端口,默认自动选择空闲端口。
|
||||
- `--ttl`:服务存活时间,单位为秒,默认 `3600`(1 小时);到期同时关闭 Node 服务和对应
|
||||
Tailscale Serve 路由。
|
||||
|
||||
脚本服务 `FILE` 的父目录,而不是把文件复制到其它地方。这样 HTML 可以加载同目录的 CSS、
|
||||
图片和其它资源,但也意味着同目录其它文件会对 tailnet 可见。
|
||||
Node 服务 `FILE` 的父目录,而不是把文件复制到其它地方。这样 HTML 可以加载同目录的 CSS、
|
||||
图片和其它资源,但也意味着同目录其它文件会对 tailnet 可见。Node 只监听 `127.0.0.1`,
|
||||
Tailscale Serve 负责把指定路径代理到这个本地端口。
|
||||
|
||||
## 输出
|
||||
|
||||
@@ -24,8 +28,12 @@ python3 scripts/serve_file.py FILE [--mount-path PATH] [--port PORT]
|
||||
"mountPath": "/preview/billing",
|
||||
"ip": "100.101.102.103",
|
||||
"port": 80,
|
||||
"localPort": 43721,
|
||||
"pid": 12345,
|
||||
"ttl": 3600,
|
||||
"expiresAt": "2026-10-11T13:00:00.000Z",
|
||||
"url": "http://100.101.102.103/preview/billing/prd-v002.html",
|
||||
"stopCommand": "tailscale serve --http=80 --set-path=/preview/billing off"
|
||||
"stopCommand": "kill 12345 2>/dev/null || true; tailscale serve --http=80 --set-path=/preview/billing off"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -33,10 +41,9 @@ python3 scripts/serve_file.py FILE [--mount-path PATH] [--port PORT]
|
||||
|
||||
## 状态和冲突
|
||||
|
||||
脚本先读取 `tailscale serve status --json`。如果相同 mount path 已指向相同目录,可以复用;如果
|
||||
指向其它目录,必须失败并要求新的 mount path。没有该路由时追加 `--set-path` 配置,不重置已有
|
||||
Serve 配置。
|
||||
脚本先读取 `tailscale serve status --json`,确认当前 Tailscale Serve 可用,然后启动 Node 本地
|
||||
服务并追加指定 `--set-path` 路由。应为不同预览使用不同 mount path;脚本不会执行全量重置。
|
||||
|
||||
Serve 配置由 Tailscale 持久保存;`--bg` 路由会在 Tailscale 重启后恢复。停止时只能使用输出的
|
||||
同端口、同 mount path 的 `off` 命令,不能使用 `tailscale serve reset`,因为 reset 会清除该节点
|
||||
的全部 Serve 配置。
|
||||
Serve 配置由 Tailscale 持久保存,但 Node 服务默认在 1 小时后自动关闭并清理对应路由。需要
|
||||
提前停止时使用输出的命令,不能使用 `tailscale serve reset`,因为 reset 会清除该节点的全部
|
||||
Serve 配置。
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* Start a tiny local static server and expose it through Tailscale Serve.
|
||||
* Node is used for the local server so the Tailscale route only needs to
|
||||
* proxy a localhost port.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const net = require('node:net');
|
||||
const path = require('node:path');
|
||||
const { spawn, spawnSync } = require('node:child_process');
|
||||
|
||||
class PreviewError extends Error {}
|
||||
|
||||
function usage() {
|
||||
return `Usage: node serve_file.js FILE [--mount-path PATH] [--port PORT] [--ttl SECONDS]
|
||||
|
||||
Expose FILE through Tailscale Serve. Node serves FILE's parent directory on
|
||||
localhost; Tailscale proxies that local server to the tailnet.
|
||||
`;
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
file: null, root: null, mountPath: null, port: 80, localPort: 0,
|
||||
ttl: 3600, tailscalePort: null, server: false,
|
||||
};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const value = argv[i];
|
||||
if (value === '--help' || value === '-h') {
|
||||
console.log(usage());
|
||||
process.exit(0);
|
||||
}
|
||||
if (value === '--server') {
|
||||
args.server = true;
|
||||
continue;
|
||||
}
|
||||
if (value === '--root') {
|
||||
args.root = argv[++i];
|
||||
continue;
|
||||
}
|
||||
if (value === '--mount-path') {
|
||||
args.mountPath = argv[++i];
|
||||
continue;
|
||||
}
|
||||
if (value === '--port') {
|
||||
args.port = Number(argv[++i]);
|
||||
continue;
|
||||
}
|
||||
if (value === '--local-port') {
|
||||
args.localPort = Number(argv[++i]);
|
||||
continue;
|
||||
}
|
||||
if (value === '--ttl') {
|
||||
args.ttl = Number(argv[++i]);
|
||||
continue;
|
||||
}
|
||||
if (value === '--tailscale-port') {
|
||||
args.tailscalePort = Number(argv[++i]);
|
||||
continue;
|
||||
}
|
||||
if (value.startsWith('-')) {
|
||||
throw new PreviewError(`未知参数:${value}`);
|
||||
}
|
||||
if (args.file === null) {
|
||||
args.file = value;
|
||||
} else {
|
||||
throw new PreviewError(`多余参数:${value}`);
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function validPort(port, name) {
|
||||
if (!Number.isInteger(port) || port < 0 || port > 65535 || (name === 'port' && port === 0)) {
|
||||
throw new PreviewError(`${name} 必须是有效端口`);
|
||||
}
|
||||
}
|
||||
|
||||
function validTtl(ttl) {
|
||||
if (!Number.isInteger(ttl) || ttl <= 0) {
|
||||
throw new PreviewError('ttl 必须是正整数秒数');
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeMountPath(value) {
|
||||
const mountPath = value.trim();
|
||||
if (!mountPath.startsWith('/') || mountPath === '/') {
|
||||
throw new PreviewError('mount path 必须以 / 开头且不能是根路径');
|
||||
}
|
||||
if (mountPath.includes('?') || mountPath.includes('#') || mountPath.includes('//')) {
|
||||
throw new PreviewError('mount path 不能包含 query、fragment 或空路径段');
|
||||
}
|
||||
const parts = mountPath.split('/');
|
||||
if (parts.some((part) => part === '.' || part === '..')) {
|
||||
throw new PreviewError('mount path 不能包含 . 或 ..');
|
||||
}
|
||||
return mountPath.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function defaultMountPath(directory) {
|
||||
const slug = path.basename(directory).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
|
||||
if (!slug) {
|
||||
throw new PreviewError('无法从文件目录生成 mount path,请显式提供 --mount-path');
|
||||
}
|
||||
return `/preview/${slug}`;
|
||||
}
|
||||
|
||||
function run(command, commandArgs) {
|
||||
const result = spawnSync(command, commandArgs, { encoding: 'utf8' });
|
||||
if (result.error) {
|
||||
throw new PreviewError(`无法运行 ${command}:${result.error.message}`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function tailscaleIPv4() {
|
||||
const result = run('tailscale', ['ip', '-4']);
|
||||
if (result.status !== 0) {
|
||||
throw new PreviewError(`Tailscale 节点不可用:${(result.stderr || result.stdout).trim() || 'tailscale ip -4 失败'}`);
|
||||
}
|
||||
const address = result.stdout.split(/\s+/).find((candidate) => net.isIPv4(candidate));
|
||||
if (!address) {
|
||||
throw new PreviewError('tailscale 没有返回 IPv4 地址;请确认节点已连接 tailnet');
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
function checkTailscaleServe() {
|
||||
const result = run('tailscale', ['serve', 'status', '--json']);
|
||||
if (result.status !== 0) {
|
||||
throw new PreviewError(`无法读取 Tailscale Serve 状态:${(result.stderr || result.stdout).trim() || 'status 失败'}`);
|
||||
}
|
||||
}
|
||||
|
||||
function serveStatic(root, mountPath, port, ttl, tailscalePort) {
|
||||
const contentTypes = {
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.gif': 'image/gif',
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.webp': 'image/webp',
|
||||
};
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
let pathname;
|
||||
try {
|
||||
pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname);
|
||||
} catch {
|
||||
response.writeHead(400).end('Bad request');
|
||||
return;
|
||||
}
|
||||
if (pathname === mountPath || pathname.startsWith(`${mountPath}/`)) {
|
||||
pathname = pathname.slice(mountPath.length) || '/';
|
||||
}
|
||||
const relativePath = pathname.replace(/^\/+/, '');
|
||||
const candidate = path.resolve(root, relativePath);
|
||||
if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) {
|
||||
response.writeHead(403).end('Forbidden');
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (statError, info) => {
|
||||
if (statError || !info.isFile()) {
|
||||
response.writeHead(404).end('Not found');
|
||||
return;
|
||||
}
|
||||
response.setHeader('Content-Type', contentTypes[path.extname(candidate).toLowerCase()] || 'application/octet-stream');
|
||||
fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
console.log(`READY ${address.port}`);
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
spawnSync('tailscale', [
|
||||
'serve', `--http=${tailscalePort}`, `--set-path=${mountPath}`, 'off',
|
||||
], { stdio: 'ignore' });
|
||||
server.close(() => process.exit(0));
|
||||
setTimeout(() => process.exit(0), 1000);
|
||||
}, ttl * 1000);
|
||||
}
|
||||
|
||||
function startDetachedServer(root, mountPath, localPort, ttl, tailscalePort) {
|
||||
const child = spawn(process.execPath, [
|
||||
__filename, '--server', '--root', root, '--mount-path', mountPath,
|
||||
'--port', String(localPort), '--ttl', String(ttl), '--tailscale-port', String(tailscalePort),
|
||||
], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = '';
|
||||
const timeout = setTimeout(() => {
|
||||
child.kill();
|
||||
reject(new PreviewError('Node 静态服务启动超时'));
|
||||
}, 5000);
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output += chunk.toString();
|
||||
const match = output.match(/READY (\d+)/);
|
||||
if (!match) return;
|
||||
clearTimeout(timeout);
|
||||
child.stdout.destroy();
|
||||
child.stderr.destroy();
|
||||
child.unref();
|
||||
resolve({ pid: child.pid, port: Number(match[1]) });
|
||||
});
|
||||
child.on('error', (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(new PreviewError(`Node 静态服务启动失败:${error.message}`));
|
||||
});
|
||||
child.on('exit', (code) => {
|
||||
if (code !== null && code !== 0) {
|
||||
clearTimeout(timeout);
|
||||
reject(new PreviewError(`Node 静态服务退出,code=${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function stopChild(pid) {
|
||||
if (!pid) return;
|
||||
try {
|
||||
process.kill(pid, 'SIGTERM');
|
||||
} catch {
|
||||
// The child may have exited while Tailscale was being configured.
|
||||
}
|
||||
}
|
||||
|
||||
async function launch(args) {
|
||||
if (!args.file) throw new PreviewError('缺少要展示的文件');
|
||||
validPort(args.port, 'port');
|
||||
validPort(args.localPort, 'local-port');
|
||||
validTtl(args.ttl);
|
||||
|
||||
const filePath = path.resolve(args.file);
|
||||
let info;
|
||||
try {
|
||||
info = fs.statSync(filePath);
|
||||
} catch {
|
||||
throw new PreviewError(`输入文件不存在:${filePath}`);
|
||||
}
|
||||
if (!info.isFile()) throw new PreviewError(`输入不是普通文件:${filePath}`);
|
||||
|
||||
const root = path.dirname(filePath);
|
||||
const mountPath = args.mountPath ? normalizeMountPath(args.mountPath) : defaultMountPath(root);
|
||||
const ip = tailscaleIPv4();
|
||||
checkTailscaleServe();
|
||||
const child = await startDetachedServer(root, mountPath, args.localPort, args.ttl, args.port);
|
||||
|
||||
try {
|
||||
const result = run('tailscale', [
|
||||
'serve', '--bg', `--http=${args.port}`, `--set-path=${mountPath}`, '--yes',
|
||||
`http://127.0.0.1:${child.port}`,
|
||||
]);
|
||||
if (result.status !== 0) {
|
||||
throw new PreviewError(`Tailscale Serve 配置失败:${(result.stderr || result.stdout).trim() || 'serve 命令失败'}`);
|
||||
}
|
||||
} catch (error) {
|
||||
stopChild(child.pid);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const relative = path.relative(root, filePath).split(path.sep).map(encodeURIComponent).join('/');
|
||||
const suffix = args.port === 80 ? '' : `:${args.port}`;
|
||||
const url = `http://${ip}${suffix}${mountPath}/${relative}`;
|
||||
console.log(JSON.stringify({
|
||||
file: filePath,
|
||||
directory: root,
|
||||
mountPath,
|
||||
ip,
|
||||
port: args.port,
|
||||
localPort: child.port,
|
||||
pid: child.pid,
|
||||
ttl: args.ttl,
|
||||
expiresAt: new Date(Date.now() + args.ttl * 1000).toISOString(),
|
||||
url,
|
||||
stopCommand: `kill ${child.pid} 2>/dev/null || true; tailscale serve --http=${args.port} --set-path=${mountPath} off`,
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (args.server) {
|
||||
if (!args.mountPath || !args.root || !args.tailscalePort) throw new PreviewError('内部参数不完整');
|
||||
validPort(args.port, 'local-port');
|
||||
validPort(args.tailscalePort, 'port');
|
||||
validTtl(args.ttl);
|
||||
serveStatic(path.resolve(args.root), args.mountPath, args.port, args.ttl, args.tailscalePort);
|
||||
return;
|
||||
}
|
||||
await launch(args);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(`previewer: ${error.message}`);
|
||||
process.exitCode = 2;
|
||||
});
|
||||
@@ -1,177 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Expose a static file's parent directory through a Tailscale Serve HTTP route."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
class PreviewError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def run_tailscale(*args: str) -> subprocess.CompletedProcess[str]:
|
||||
try:
|
||||
return subprocess.run(
|
||||
["tailscale", *args],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
except OSError as exc:
|
||||
raise PreviewError(f"无法运行 tailscale:{exc}") from exc
|
||||
|
||||
|
||||
def require_tailscale() -> None:
|
||||
if shutil.which("tailscale") is None:
|
||||
raise PreviewError("未找到 tailscale,请先安装并登录 Tailscale")
|
||||
|
||||
|
||||
def tailscale_ipv4() -> str:
|
||||
result = run_tailscale("ip", "-4")
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip()
|
||||
raise PreviewError(f"Tailscale 节点不可用:{detail or 'tailscale ip -4 失败'}")
|
||||
for line in result.stdout.splitlines():
|
||||
candidate = line.strip()
|
||||
try:
|
||||
address = ipaddress.ip_address(candidate)
|
||||
except ValueError:
|
||||
continue
|
||||
if address.version == 4:
|
||||
return candidate
|
||||
raise PreviewError("tailscale 没有返回 IPv4 地址;请确认节点已连接 tailnet")
|
||||
|
||||
|
||||
def serve_status() -> tuple[dict, str]:
|
||||
result = run_tailscale("serve", "status", "--json")
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip()
|
||||
raise PreviewError(f"无法读取 Tailscale Serve 状态:{detail or 'status 失败'}")
|
||||
try:
|
||||
data = json.loads(result.stdout or "{}")
|
||||
except json.JSONDecodeError as exc:
|
||||
raise PreviewError("Tailscale Serve 返回了无法解析的 JSON 状态") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise PreviewError("Tailscale Serve 状态不是 JSON 对象")
|
||||
|
||||
plain = run_tailscale("serve", "status")
|
||||
if plain.returncode != 0:
|
||||
detail = (plain.stderr or plain.stdout).strip()
|
||||
raise PreviewError(f"无法读取 Tailscale Serve 文本状态:{detail or 'status 失败'}")
|
||||
return data, plain.stdout
|
||||
|
||||
|
||||
def status_blob(data: dict, plain: str) -> str:
|
||||
return json.dumps(data, ensure_ascii=False, sort_keys=True) + "\n" + plain
|
||||
|
||||
|
||||
def normalize_mount_path(value: str) -> str:
|
||||
path = value.strip()
|
||||
if not path.startswith("/") or path == "/":
|
||||
raise PreviewError("mount path 必须以 / 开头且不能是根路径")
|
||||
if "?" in path or "#" in path or "//" in path:
|
||||
raise PreviewError("mount path 不能包含 query、fragment 或空路径段")
|
||||
parts = PurePosixPath(path).parts
|
||||
if any(part in {".", ".."} for part in parts):
|
||||
raise PreviewError("mount path 不能包含 . 或 ..")
|
||||
return "/" + "/".join(parts[1:])
|
||||
|
||||
|
||||
def default_mount_path(directory: Path) -> str:
|
||||
slug = re.sub(r"[^a-zA-Z0-9._-]+", "-", directory.name).strip("-")
|
||||
if not slug:
|
||||
raise PreviewError("无法从文件目录生成 mount path,请显式提供 --mount-path")
|
||||
return f"/preview/{slug}"
|
||||
|
||||
|
||||
def route_matches(blob: str, mount_path: str, directory: Path) -> bool:
|
||||
return mount_path in blob and str(directory) in blob
|
||||
|
||||
|
||||
def route_conflicts(blob: str, mount_path: str, directory: Path) -> bool:
|
||||
return mount_path in blob and str(directory) not in blob
|
||||
|
||||
|
||||
def configure_route(directory: Path, mount_path: str, port: int, data: dict, plain: str) -> None:
|
||||
blob = status_blob(data, plain)
|
||||
if route_conflicts(blob, mount_path, directory):
|
||||
raise PreviewError(
|
||||
f"mount path {mount_path} 已被其它目录占用;请改用唯一的 --mount-path,不会覆盖已有路由"
|
||||
)
|
||||
|
||||
if route_matches(blob, mount_path, directory):
|
||||
return
|
||||
|
||||
result = run_tailscale(
|
||||
"serve",
|
||||
"--bg",
|
||||
f"--http={port}",
|
||||
f"--set-path={mount_path}",
|
||||
"--yes",
|
||||
str(directory),
|
||||
)
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip()
|
||||
raise PreviewError(f"Tailscale Serve 配置失败:{detail or 'serve 命令失败'}")
|
||||
|
||||
data, plain = serve_status()
|
||||
blob = status_blob(data, plain)
|
||||
if route_conflicts(blob, mount_path, directory) or not route_matches(blob, mount_path, directory):
|
||||
raise PreviewError("Serve 命令返回成功,但状态中没有确认目标路由;停止输出 URL")
|
||||
|
||||
|
||||
def build_result(file_path: Path, directory: Path, mount_path: str, ip: str, port: int) -> dict[str, object]:
|
||||
relative = file_path.relative_to(directory).as_posix()
|
||||
suffix = f":{port}" if port != 80 else ""
|
||||
url = f"http://{ip}{suffix}{mount_path}/{quote(relative, safe='/')}"
|
||||
return {
|
||||
"file": str(file_path),
|
||||
"directory": str(directory),
|
||||
"mountPath": mount_path,
|
||||
"ip": ip,
|
||||
"port": port,
|
||||
"url": url,
|
||||
"stopCommand": f"tailscale serve --http={port} --set-path={mount_path} off",
|
||||
}
|
||||
|
||||
|
||||
def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("file", type=Path, help="要展示的静态文件")
|
||||
parser.add_argument("--mount-path", help="Tailscale Serve 的 URL 路径")
|
||||
parser.add_argument("--port", type=int, default=80, help="HTTP 端口,默认 80")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv or sys.argv[1:])
|
||||
try:
|
||||
if not 1 <= args.port <= 65535:
|
||||
raise PreviewError("port 必须在 1 到 65535 之间")
|
||||
require_tailscale()
|
||||
file_path = args.file.expanduser().resolve()
|
||||
if not file_path.is_file():
|
||||
raise PreviewError(f"输入不是普通文件或不存在:{file_path}")
|
||||
directory = file_path.parent
|
||||
mount_path = normalize_mount_path(args.mount_path) if args.mount_path else default_mount_path(directory)
|
||||
ip = tailscale_ipv4()
|
||||
data, plain = serve_status()
|
||||
configure_route(directory, mount_path, args.port, data, plain)
|
||||
print(json.dumps(build_result(file_path, directory, mount_path, ip, args.port), ensure_ascii=False))
|
||||
return 0
|
||||
except PreviewError as exc:
|
||||
print(f"previewer: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user