cli 教程
本教程介绍如何在 MoonBit 之外用 build-index 命令度量一个注册表:把几个包的发布记录写入 JSON 文件,运行命令,然后像索引构建器那样用 jq 和 Python 读取报告。你需要本仓库的检出、MoonBit 工具链、Node.js 20.16、22.3 或更高版本,以及用于 shell 示例的 jq。所有命令都在仓库根目录下运行。
| 我想要 | 使用 |
|---|---|
| 构建该命令 | moon build src/cli --target js --release |
| 度量一个注册表 | node _build/js/release/build/cli/cli.js build-index --input <file> --output <file> |
| 列出排名 | 对 .packages[].snapshot 使用 jq |
| 解释一个分数 | 该包的 .signals、.signals_30d_ago 和 .snapshot.breakdown |
| 列出一个包的依赖方 | 带有该 target 的 .edges[] |
| 从另一种语言调用它 | 写入输入文件,运行命令,检查退出状态,读取输出文件 |
快速开始
构建可执行程序:
moon build src/cli --target js --release
把四个包的发布版本、它们当前的下载量,以及大约 30 天前的一个下载量快照写入 input.json:
cat > input.json <<'JSON'
{
"now": "2026-10-01T00:00:00Z",
"releases": [
{"name": "alice/json", "version": "0.1.0", "created_at": "2025-11-02T08:00:00Z", "deps": [], "yanked": false},
{"name": "alice/json", "version": "0.2.0", "created_at": "2026-09-10T08:00:00Z", "deps": [], "yanked": false},
{"name": "alice/http", "version": "1.0.0", "created_at": "2026-06-01T12:00:00Z", "deps": ["alice/json"], "yanked": false},
{"name": "bob/web", "version": "0.3.0", "created_at": "2026-09-25T09:30:00Z", "deps": ["alice/http", "alice/json"], "yanked": false},
{"name": "carol/cli", "version": "1.0.0", "created_at": "2025-03-01T00:00:00Z", "deps": ["alice/json"], "yanked": false}
],
"downloads": {"alice/json": 1200, "alice/http": 300, "bob/web": 40, "carol/cli": 15},
"download_history": [
{"taken_at": "2026-09-02T00:00:00Z", "counts": {"alice/json": 900, "alice/http": 280, "carol/cli": 15}}
]
}
JSON
运行命令,查看报告的摘要:
CLI=_build/js/release/build/cli/cli.js
node $CLI build-index --input input.json --output report.json
jq '{computed_at, population, download_history_used, top_score, rank_counts, momentum_counts}' report.json
{
"computed_at": "2026-10-01T00:00:00.000Z",
"population": 4,
"download_history_used": true,
"top_score": 249.40610439873305,
"rank_counts": {
"B": 1,
"S": 1,
"C": 1,
"D": 1
},
"momentum_counts": {
"Rising": 2,
"New": 1,
"Stable": 1
}
}
9 月 2 日的下载量快照与 now 之前 30 天的 9 月 1 日相差不到 7 天,因此 download_history_used 为 true。不带 --output 时,命令会把同样的报告以一行打印到标准输出。
日常任务
下面的示例读取快速开始中的 report.json。
列出排名
每个包都带有其分数快照。按 rank_position 排序即可得到排名:
jq -r '.packages | sort_by(.snapshot.rank_position)[]
| [.snapshot.rank_position, .snapshot.rank_label, .name,
(.snapshot.score | floor), .snapshot.momentum_label] | @tsv' report.json
1 S alice/json 249 Rising
2 B alice/http 179 Rising
3 C bob/web 91 New
4 D carol/cli 53 Stable
标签按在总体中所占的比例划分:有四个包时,每个名次占总体的 25 %,因此名次 2 就已经是 B。score 教程用 MoonBit 展示了这一规则。
解释一个分数
signals 存放现在度量的结果,signals_30d_ago 存放 30 天前度量的结果,snapshot.breakdown 存放分数的三项和发布乘数:
jq '.packages[] | select(.name == "alice/json")
| {signals, signals_30d_ago, breakdown: .snapshot.breakdown}' report.json
{
"signals": {
"external_dependents": 2,
"self_dependents": 1,
"recent_external_dependents": 1,
"recent_self_dependents": 1,
"downloads": 1200,
"days_since_release": 20
},
"signals_30d_ago": {
"external_dependents": 1,
"self_dependents": 1,
"recent_external_dependents": 0,
"recent_self_dependents": 1,
"downloads": 900,
"days_since_release": 302
},
"breakdown": {
"dependents": 44.78888986098256,
"recent_dependents": 21.895115837840876,
"downloads": 156.00001608575963,
"multiplier": 1.12
}
}
30 天前 bob/web 还不存在,因此 alice/json 少一个外部依赖方;它的下载量取自快照;它的最新发布是 0.1.0,已有 302 天。分数为 。
列出一个包的依赖方
edges 中每条当前依赖只出现一次,并带有它首次出现的日期:
jq -r '.edges[] | select(.target == "alice/json")
| "\(.source)\t\(if .same_owner then "same owner" else "external" end)\t\(.first_seen_at // "unknown")"' report.json
alice/http same owner 2026-06-01T12:00:00.000Z
bob/web external 2026-09-25T09:30:00.000Z
carol/cli external 2025-03-01T00:00:00.000Z
carol/cli 在 180 多天前就加入了该依赖,因此它不是近期依赖方之一。alice/http 属于同一所有者,在分数中按四分之一计。
跟踪 30 天的变化
score_30d_ago 和 momentum_label 显示每个包的变化:
jq -r '.packages[] | "\(.name)\t\(.snapshot.score_30d_ago | floor) -> \(.snapshot.score | floor)\t\(.snapshot.momentum_label)"' report.json
alice/http 133 -> 179 Rising
alice/json 172 -> 249 Rising
bob/web 0 -> 91 New
carol/cli 53 -> 53 Stable
值未知的键不会出现在报告中,而 jq 把不存在的键读作 null。bob/web 在 30 天前没有发布,因此没有 signals_30d_ago;它也不在下载量快照中,因此没有 downloads_30d_ago:
jq -r '.packages[] | select(has("signals_30d_ago") | not) | .name' report.json
bob/web
从 Python 调用
索引构建器把输入写入一个临时文件,用 --output 运行命令,再把报告读回来。一个最简版本:
import json
import subprocess
import tempfile
from pathlib import Path
CLI = Path("_build/js/release/build/cli/cli.js")
def build_index(payload: dict) -> dict:
with tempfile.TemporaryDirectory() as tmp:
input_path = Path(tmp) / "input.json"
output_path = Path(tmp) / "report.json"
input_path.write_text(json.dumps(payload), encoding="utf-8")
done = subprocess.run(
["node", str(CLI), "build-index",
"--input", str(input_path), "--output", str(output_path)],
capture_output=True, text=True,
)
if done.returncode != 0:
raise RuntimeError(f"build-index failed: {done.stdout}{done.stderr}")
return json.loads(output_path.read_text(encoding="utf-8"))
def release(name, version, created_at=None, deps=(), yanked=False):
record = {"name": name, "version": version, "deps": list(deps), "yanked": yanked}
if created_at is not None: # an unknown date is an absent key, not null
record["created_at"] = created_at
return record
report = build_index({
"now": "2026-10-01T00:00:00Z",
"releases": [
release("alice/json", "0.2.0", "2026-09-10T08:00:00Z"),
release("bob/web", "0.3.0", deps=["alice/json"]),
],
"downloads": {"alice/json": 1200},
"download_history": [],
})
for package in report["packages"]:
snapshot = package["snapshot"]
print(package["name"], snapshot["rank_label"], round(snapshot["score"], 2))
alice/json S 204.22
bob/web D 0
bob/web 没有发布日期,也没有下载量;它对 alice/json 的依赖仍然计数,但不算近期,因为其日期未知。从文件而不是标准输出读取报告,可以让大型报告不经过管道,而退出状态可以区分成功和失败。
处理错误
错误会输出一个带 error 键的 JSON 对象,并以状态 1 退出。只有日期、没有时间和时区的值不是 RFC 3339:
echo '{"now": "2026-10-01", "releases": [], "downloads": {}, "download_history": []}' > bad-now.json
node $CLI build-index --input bad-now.json; echo "status $?"
{"error":"invalid timestamp for now: 2026-10-01"}
status 1
未知的发布日期写成了 null,而不是省略该键:
cat > null-date.json <<'JSON'
{"now": "2026-10-01T00:00:00Z",
"releases": [{"name": "a/lib", "version": "1.0.0", "created_at": null, "deps": [], "yanked": false}],
"downloads": {}, "download_history": []}
JSON
node $CLI build-index --input null-date.json; echo "status $?"
{"error":"JsonDecodeError((/releases/0/created_at, String::from_json: expected string))"}
status 1
输入路径不存在或无法读取时,会打印 JSON 错误并以状态 1 退出:
node $CLI build-index --input missing.json; echo "status $?"
{"error":"Failed to read input: missing.json"}
status 1
使用输出前请检查退出状态。无法写入的输出路径仍由 Node.js 报告,并可能向标准错误打印堆栈跟踪。
进阶
- 度量真实的注册表。
python3 scripts/build_index.py读取~/.moon/registry/index/user下的本地注册表索引,获取下载量,在data/download_history.json中保留 45 天的下载量历史,运行一次build-index,并把报告写入 Web 应用的 SQLite 数据库。--now固定时间点;架构指南描述了完整的管道。 - 改在 MoonBit 中处理。 在 MoonBit 程序内部,直接调用
@metrics.compute,如 metrics 教程所示;该命令只是额外加上了文件读取和 JSON。 - 精确规则。 metrics API 列出了每条计数规则;cli API 列出了输入和输出约定。
常见陷阱
- 用
null表示未知值。 应省略该键。输入中只有created_at是可选的;其他每个键都是必填的。 - 参数顺序错误。
build-index必须是脚本之后的第一个参数;--input input.json build-index会输出用法错误。 - 构建过期。 修改
src/score或src/metrics之后要重新构建,否则报告仍按旧规则计算。索引构建器每次运行前都会重新构建;手动运行的node命令则不会。 - 带
--output时读取标准输出。 带--output时,命令成功后什么也不打印;请读取文件。 - 比较来自不同输入的报告。 等级是在输入总体中所占的比例。由少数几个包构建的报告只在它们之间排名,而不是与整个注册表比较。
下一步
- cli API:精确的输入、输出和错误约定。
- cli 设计:为何这座桥是基于文件的命令。
- metrics API:每个报告字段的含义。
- score API:分数、等级和势头标签。