Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,22 @@ jobs:
# 插件 manifest 检查以最近的 v* 标签为基准
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
with:
# 插件版本检查按插件后端的 WASM 目标解析依赖(cargo tree)
targets: wasm32-wasip2
- uses: Swatinem/rust-cache@v2
with:
key: xtask
- name: Scan conventions
run: cargo xtask check rules
# 已发布的在线插件改了输入却没有递增版本,合入 dev 后发布必然失败:在 PR 里就报出来。
# 基准是 merge-base,只看本 PR 带来的改动;修复方式见失败输出(手动改版本或 --fix)
- name: Published plugins bump their version
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
BASE_REF: ${{ github.base_ref }}
run: cargo xtask plugin versions --base "$(git merge-base "origin/$BASE_REF" HEAD)"
- name: Lint shell scripts
run: shellcheck scripts/*.sh

Expand Down
94 changes: 10 additions & 84 deletions .github/workflows/plugins.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ jobs:
echo '::error::Cannot read COS catalog through COSCLI; first publication requires a bootstrap run'; exit 1
fi
python3 - <<'PY'
import hashlib, json, os, pathlib, re, subprocess, tomllib
import hashlib, json, os, pathlib, re, subprocess
root = pathlib.Path('dist/plugins')
assets = {a['name'] for a in json.loads((root / 'previous-release.json').read_text())['assets']}
prior_path = pathlib.Path(os.environ['RUNNER_TEMP']) / 'prior-catalog.json'
Expand All @@ -114,90 +114,16 @@ jobs:
if target.stat().st_size != item['size'] or hashlib.sha256(target.read_bytes()).hexdigest() != item['sha256']:
raise SystemExit('Cannot recover verified historical COS bytes')
assets.add(name)
# Compare only packages reachable from each WASM backend. Native App-only lock
# updates must not force every online plugin to publish a new version.
cargo_changed = set()
manifests = {}
if prior:
changed = subprocess.check_output(['git', 'diff', '--name-only', prior['sourceCommit'], 'HEAD', '--', 'Cargo.lock'], text=True)
if changed.strip():
old_lock = tomllib.loads(subprocess.check_output(['git', 'show', prior['sourceCommit'] + ':Cargo.lock'], text=True))
new_lock = tomllib.loads(pathlib.Path('Cargo.lock').read_text())
key = lambda p: (p['name'], p.get('source'))
old_packages = {key(p): p for p in old_lock['package']}
new_packages = {key(p): p for p in new_lock['package']}
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'wasm32-wasip2'], text=True))
packages = {p['id']: p for p in metadata['packages']}
nodes = {n['id']: n for n in metadata['resolve']['nodes']}
manifests = {str(pathlib.Path(p['manifest_path']).resolve()): p['id'] for p in metadata['packages']}
for ident, package in packages.items():
entry = key(package)
old, new = old_packages.get(entry), new_packages.get(entry)
if old is None or new is None:
cargo_changed.add(ident)
continue
# Local path crates carry release metadata versions: a
# version-only bump does not change compiled plugin bytes.
# A crates.io release is always a real input change.
if package.get('source') is None:
drop = {'version'}
old = {field: value for field, value in old.items() if field not in drop}
new = {field: value for field, value in new.items() if field not in drop}
if old != new:
cargo_changed.add(ident)
# SDK changes listed in .github/plugin-sdk-host-only.txt only affect the host;
# when every commit touching the SDK since the last publication is listed,
# those paths do not count as inputs of already published plugins.
sdk_paths = ['packages/plugin-ui-sdk', 'packages/plugin-build', 'crates/tf-plugin-api', 'crates/tf-plugin-guest', 'wit']
host_only = set()
ack = pathlib.Path('.github/plugin-sdk-host-only.txt')
for line in ack.read_text().splitlines() if ack.exists() else []:
line = line.strip()
if not line or line.startswith('#'):
continue
sha = line.split()[0]
if not re.fullmatch(r'[a-f0-9]{40}', sha):
raise SystemExit(f'Invalid commit in {ack}: {sha}')
host_only.add(sha)
sdk_host_only = False
if prior:
sdk_commits = subprocess.check_output(['git', 'log', '--format=%H', f"{prior['sourceCommit']}..HEAD", '--', *sdk_paths], text=True).split()
sdk_host_only = bool(sdk_commits) and set(sdk_commits) <= host_only
if sdk_host_only:
print(f'SDK changes since the last publication are host-only: {len(sdk_commits)} commit(s)')
pending = []
for path in sorted(pathlib.Path('market').glob('*/manifest.json')):
manifest = json.loads(path.read_text())
slug = path.parent.name
if not slug.replace('-', '').isalnum():
raise SystemExit('Unsafe plugin slug')
name = f"{manifest['id']}-{manifest['version']}.tfp"
if name not in assets:
pending.append(slug)
elif prior:
watched = [str(path.parent)] + ([] if sdk_host_only else sdk_paths)
changed = subprocess.check_output(['git', 'diff', '--name-only', prior['sourceCommit'], 'HEAD', '--', *watched], text=True)
# pnpm-lock.yaml is deliberately absent: shared UI dependencies
# load from the host bundle (window.__TF_SHARED__) and never
# enter plugin bytes, so one plugin's dependency additions must
# not force every published plugin to re-version.
inputs = [line for line in changed.splitlines() if line not in ('crates/tf-plugin-api/Cargo.toml', 'crates/tf-plugin-guest/Cargo.toml')]
dependency_changed = False
if cargo_changed:
manifest_path = str((path.parent / 'backend' / 'Cargo.toml').resolve())
frontier = [manifests[manifest_path]]
seen = set()
while frontier:
ident = frontier.pop()
if ident in seen:
continue
seen.add(ident)
frontier.extend(dep['pkg'] for dep in nodes[ident]['deps'])
dependency_changed = bool(seen & cargo_changed)
if inputs or dependency_changed:
raise SystemExit(f'{slug}: published plugin inputs changed without a version bump')
(root / 'pending.txt').write_text(''.join(slug + '\n' for slug in pending))
PY
# Same check authors run locally and PR CI runs against the merge-base.
# Without a prior catalog (bootstrap) HEAD is the base: only pending is computed.
base=HEAD
if [[ -f $RUNNER_TEMP/prior-catalog.json ]]; then
base=$(jq -r .sourceCommit "$RUNNER_TEMP/prior-catalog.json")
fi
target/release/xtask plugin versions --base "$base" \
--published dist/plugins/previous-release.json --published dist/plugins/previous \
--pending dist/plugins/pending.txt
- name: Build unsigned candidates without signing credentials
run: |
mkdir -p dist/unsigned
Expand Down
22 changes: 21 additions & 1 deletion crates/xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod interfaces;
mod manifests;
mod notes;
mod plugin;
mod plugin_versions;
mod release_dates;
mod rules;
mod sidecar;
Expand Down Expand Up @@ -36,6 +37,10 @@ Commands:
plugin sign <file> --out <dir> [--key-id id]\n Sign a prebuilt unsigned candidate without running child processes\n plugin verify <dir> Verify every .tfp has a trusted official signature\n plugin index <dir> <stats-base-url> --source-commit <sha> --generation <n>\n [--merge <registry.json>] [--merge-catalog <catalog.json>]
Write <dir>/registry.json listing the .tfp packages in <dir>,
keeping other plugins from an existing index when --merge is given
plugin versions [--base <rev>] [--published <release.json|dir>]... [--pending <file>] [--fix]
Fail when a published online plugin changed (its directory, the plugin
SDK or the crates its backend compiles) without a version bump since
<rev> (default: the last publication); --fix bumps every such plugin
help Show this message
";

Expand Down Expand Up @@ -123,6 +128,21 @@ fn main() -> ExitCode {
}
None => Err(format!("missing base url\n\n{HELP}")),
},
(Some("versions"), _) => plugin_versions::run(
&check::workspace_root(),
&plugin_versions::Options {
base: flag("--base"),
published: args
.iter()
.enumerate()
.filter(|(_, a)| *a == "--published")
.filter_map(|(i, _)| args.get(i + 1))
.map(std::path::PathBuf::from)
.collect(),
pending: flag("--pending").map(std::path::PathBuf::from),
fix: args.iter().any(|a| a == "--fix"),
},
),
(Some("pack"), Some(slug)) => {
let root = check::workspace_root();
plugin::pack(
Expand All @@ -139,7 +159,7 @@ fn main() -> ExitCode {
.map(|_| ())
}
_ => Err(format!(
"usage: cargo xtask plugin keygen <file> | pack <slug>\n\n{HELP}"
"usage: cargo xtask plugin keygen <file> | pack <slug> | versions\n\n{HELP}"
)),
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/xtask/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub fn keygen(out: &Path) -> Result<(), String> {
/// 与 xtask 同一工具链的 cargo。显式指定同目录的 rustc:cargo 默认经 PATH 中的 rustup 代理
/// 调用 rustc,代理会读取依赖包自带的 rust-toolchain.toml(如 pic-scale 指定 nightly),
/// 在没有设置 RUSTUP_TOOLCHAIN 的环境(CI)里换成别的工具链
fn cargo() -> Command {
pub(crate) fn cargo() -> Command {
let cargo = Path::new(env!("CARGO"));
let mut command = Command::new(cargo);
let rustc = cargo.with_file_name(if cfg!(windows) { "rustc.exe" } else { "rustc" });
Expand All @@ -72,7 +72,7 @@ fn run(command: &mut Command) -> Result<(), String> {
}
}

fn crate_name(backend: &Path) -> Result<String, String> {
pub(crate) fn crate_name(backend: &Path) -> Result<String, String> {
let toml = std::fs::read_to_string(backend.join("Cargo.toml")).map_err(|e| e.to_string())?;
toml.lines()
.find_map(|l| {
Expand Down
Loading
Loading