diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 681a1e30..e94d4189 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/plugins.yml b/.github/workflows/plugins.yml index 774d7d3b..7cacfb79 100644 --- a/.github/workflows/plugins.yml +++ b/.github/workflows/plugins.yml @@ -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' @@ -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 diff --git a/crates/xtask/src/main.rs b/crates/xtask/src/main.rs index ab79f998..af2ac9a6 100644 --- a/crates/xtask/src/main.rs +++ b/crates/xtask/src/main.rs @@ -7,6 +7,7 @@ mod interfaces; mod manifests; mod notes; mod plugin; +mod plugin_versions; mod release_dates; mod rules; mod sidecar; @@ -36,6 +37,10 @@ Commands: plugin sign --out [--key-id id]\n Sign a prebuilt unsigned candidate without running child processes\n plugin verify Verify every .tfp has a trusted official signature\n plugin index --source-commit --generation \n [--merge ] [--merge-catalog ] Write /registry.json listing the .tfp packages in , keeping other plugins from an existing index when --merge is given + plugin versions [--base ] [--published ]... [--pending ] [--fix] + Fail when a published online plugin changed (its directory, the plugin + SDK or the crates its backend compiles) without a version bump since + (default: the last publication); --fix bumps every such plugin help Show this message "; @@ -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( @@ -139,7 +159,7 @@ fn main() -> ExitCode { .map(|_| ()) } _ => Err(format!( - "usage: cargo xtask plugin keygen | pack \n\n{HELP}" + "usage: cargo xtask plugin keygen | pack | versions\n\n{HELP}" )), } } diff --git a/crates/xtask/src/plugin.rs b/crates/xtask/src/plugin.rs index 072372d8..8fe585a3 100644 --- a/crates/xtask/src/plugin.rs +++ b/crates/xtask/src/plugin.rs @@ -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" }); @@ -72,7 +72,7 @@ fn run(command: &mut Command) -> Result<(), String> { } } -fn crate_name(backend: &Path) -> Result { +pub(crate) fn crate_name(backend: &Path) -> Result { let toml = std::fs::read_to_string(backend.join("Cargo.toml")).map_err(|e| e.to_string())?; toml.lines() .find_map(|l| { diff --git a/crates/xtask/src/plugin_versions.rs b/crates/xtask/src/plugin_versions.rs new file mode 100644 index 00000000..9566638e --- /dev/null +++ b/crates/xtask/src/plugin_versions.rs @@ -0,0 +1,616 @@ +//! 已发布在线插件的版本检查:插件的输入(插件目录、插件 SDK、实际编译进 WASM 的依赖) +//! 相对基准有变化,而当前 version 已经在 `plugins` 预发布中发布过,就必须递增 version。 +//! +//! PR CI(基准为 merge-base)、发布流程 plugins.yml(基准为上次发布的提交)和作者本地 +//! 共用这一实现,规则完全一致;`--fix` 会把需要递增的插件一次性递增好。 + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use regex::Regex; +use serde_json::Value; + +use crate::notes::git; +use crate::plugin::{cargo, crate_name}; + +/// 本地运行且没有 GITHUB_REPOSITORY 时读取的仓库 +const REPOSITORY: &str = "devlive-community/toolforge"; +const RELEASE_TAG: &str = "plugins"; +/// 插件 SDK:改动默认算作所有已发布插件的输入 +pub const SDK_PATHS: &[&str] = &[ + "packages/plugin-ui-sdk", + "packages/plugin-build", + "crates/tf-plugin-api", + "crates/tf-plugin-guest", + "wit", +]; +/// 只随发布递增版本号的 SDK 清单:不按路径比较,依赖改动由 cargo tree 比较发现 +const SDK_MANIFESTS: &[&str] = &[ + "crates/tf-plugin-api/Cargo.toml", + "crates/tf-plugin-guest/Cargo.toml", +]; +/// 这些文件有改动时才逐个比较插件实际编译的依赖 +const CARGO_INPUTS: &[&str] = &[ + "Cargo.lock", + "Cargo.toml", + "crates/tf-plugin-api/Cargo.toml", + "crates/tf-plugin-guest/Cargo.toml", +]; +/// 只影响宿主的 SDK 提交清单 +const HOST_ONLY: &str = ".github/plugin-sdk-host-only.txt"; +/// 版本号每段最大值,超过就进位(与 scripts/release.sh 的 VERSION_PART_MAX 一致) +const VERSION_PART_MAX: u64 = 10; + +pub struct Options { + /// 基准提交;缺省为上次成功发布(Plugins 工作流)的提交 + pub base: Option, + /// 已发布资产:release JSON 文件或 .tfp 所在目录;缺省从 GitHub 读取 + pub published: Vec, + /// 写出尚未发布、需要打包的插件 slug + pub pending: Option, + /// 直接递增需要递增的插件 + pub fix: bool, +} + +/// 输入变了却没有递增版本的已发布插件 +#[derive(Debug, PartialEq)] +pub struct Stale { + pub slug: String, + pub version: String, + pub next: String, + pub reasons: Vec, +} + +pub fn run(root: &Path, options: &Options) -> Result<(), String> { + let repository = std::env::var("GITHUB_REPOSITORY").unwrap_or_else(|_| REPOSITORY.to_owned()); + let published = if options.published.is_empty() { + fetch_published(root, &repository)? + } else { + let mut names = BTreeSet::new(); + for source in &options.published { + names.extend(load_published(source)?); + } + names + }; + let base = match &options.base { + Some(base) => base.clone(), + None => last_publication(root, &repository)?, + }; + let base = git( + root, + &["rev-parse", "--verify", &format!("{base}^{{commit}}")], + ) + .map_err(|_| { + format!( + "base commit {base} is not in this clone; fetch it first: \ + git fetch https://github.com/{repository}.git dev" + ) + })?; + println!(" base {base}, {} published packages", published.len()); + + let mut pending = Vec::new(); + let mut stale = Vec::new(); + let changes = Changes::read(root, &base)?; + let mut base_checkout: Option = None; + for (slug, manifest) in plugins(root)? { + let id = string_field(&manifest, "id", &slug)?; + let version = string_field(&manifest, "version", &slug)?; + if !published.contains(&package_name(&id, &version)) { + pending.push(slug); + continue; + } + let mut reasons: Vec = changes + .inputs(&slug) + .into_iter() + .map(|path| format!("changed {path}")) + .collect(); + if reasons.is_empty() && changes.cargo { + if base_checkout.is_none() { + base_checkout = Some(BaseCheckout::create(root, &base)?); + } + let checkout = base_checkout.as_ref().map(|c| c.path.as_path()); + let before = checkout.map_or(Ok(None), |c| build_inputs(c, &slug))?; + let after = build_inputs(root, &slug)?.unwrap_or_default(); + match before { + None => reasons.push("backend did not exist at the base commit".to_owned()), + Some(before) => reasons.extend(dependency_changes(&before, &after)), + } + } + if !reasons.is_empty() { + let next = next_version(&id, &version, &published)?; + stale.push(Stale { + slug, + version, + next, + reasons, + }); + } + } + drop(base_checkout); + + if options.fix { + for item in &stale { + bump(root, item)?; + pending.push(item.slug.clone()); + } + pending.sort(); + } + if let Some(path) = &options.pending { + for slug in &pending { + if !safe_slug(slug) { + return Err(format!("unsafe plugin slug: {slug}")); + } + } + std::fs::write( + path, + pending.iter().map(|s| format!("{s}\n")).collect::(), + ) + .map_err(|e| format!("{}: {e}", path.display()))?; + } + if stale.is_empty() { + println!(" every published plugin with changed inputs has a new version"); + return Ok(()); + } + if options.fix { + for item in &stale { + println!( + " bumped market/{} {} -> {}", + item.slug, item.version, item.next + ); + } + println!( + "\n Updated plugins must declare minAppVersion and their function interfaces: \ + run `cargo xtask check rules`." + ); + return Ok(()); + } + Err(report(&stale, &base)) +} + +/// 失败说明:逐个列出插件、建议版本和变化,并给出两种修复方式 +pub fn report(stale: &[Stale], base: &str) -> String { + let annotate = std::env::var("GITHUB_ACTIONS").is_ok_and(|v| v == "true"); + let mut out = format!( + "{} published plugin(s) changed without a version bump \ + (published plugin inputs changed without a version bump):\n", + stale.len() + ); + for item in stale { + if annotate { + println!( + "::error file=market/{}/manifest.json,title=Plugin version not bumped::\ + {} is already published and its inputs changed; bump version to {}", + item.slug, item.version, item.next + ); + } + out.push_str(&format!( + "\n market/{} {} -> {}\n", + item.slug, item.version, item.next + )); + for reason in &item.reasons { + out.push_str(&format!(" {reason}\n")); + } + } + out.push_str(&format!( + "\nFix either way, then run `cargo xtask check rules`:\n\ + \x20 - bump \"version\" in each manifest.json listed above, or\n\ + \x20 - run: cargo xtask plugin versions --base {base} --fix\n\ + SDK changes that only affect the host can be listed in {HOST_ONLY} instead.\n" + )); + out +} + +/// 基准与当前工作区之间的改动 +struct Changes { + /// market/ 与 SDK 下改动的文件(含未跟踪文件) + paths: Vec, + /// SDK 改动全部登记为只影响宿主 + sdk_host_only: bool, + /// Cargo 依赖相关文件有改动 + cargo: bool, +} + +impl Changes { + fn read(root: &Path, base: &str) -> Result { + let mut watched = vec!["market"]; + watched.extend(SDK_PATHS); + let mut paths = changed_paths(root, base, &watched)?; + paths.sort(); + paths.dedup(); + + let mut log = vec!["log", "--format=%H"]; + let range = format!("{base}..HEAD"); + log.push(&range); + log.push("--"); + log.extend(SDK_PATHS); + let commits: Vec = git(root, &log)? + .split_whitespace() + .map(str::to_owned) + .collect(); + // 未提交的 SDK 改动没有提交 SHA,不可能登记为只影响宿主 + let uncommitted = !changed_paths(root, "HEAD", SDK_PATHS)?.is_empty(); + let acknowledged = match std::fs::read_to_string(root.join(HOST_ONLY)) { + Ok(text) => parse_host_only(&text)?, + Err(_) => BTreeSet::new(), + }; + let sdk_host_only = + !commits.is_empty() && !uncommitted && commits.iter().all(|c| acknowledged.contains(c)); + if sdk_host_only { + println!( + " SDK changes since the base are host-only: {} commit(s)", + commits.len() + ); + } + let cargo = !changed_paths(root, base, CARGO_INPUTS)?.is_empty(); + Ok(Self { + paths, + sdk_host_only, + cargo, + }) + } + + /// 某个插件的输入中改动的文件 + fn inputs(&self, slug: &str) -> Vec { + let own = format!("market/{slug}/"); + self.paths + .iter() + .filter(|path| { + path.starts_with(&own) + || (!self.sdk_host_only + && !SDK_MANIFESTS.contains(&path.as_str()) + && SDK_PATHS + .iter() + .any(|sdk| path.starts_with(&format!("{sdk}/")))) + }) + .cloned() + .collect() + } +} + +/// `from` 与工作区相比改动过的文件,包含尚未跟踪的新文件 +fn changed_paths(root: &Path, from: &str, paths: &[&str]) -> Result, String> { + let mut diff = vec!["diff", "--name-only", from, "--"]; + diff.extend(paths); + let mut untracked = vec!["ls-files", "--others", "--exclude-standard", "--"]; + untracked.extend(paths); + let mut result: Vec = git(root, &diff)?.lines().map(str::to_owned).collect(); + result.extend(git(root, &untracked)?.lines().map(str::to_owned)); + result.retain(|line| !line.is_empty()); + Ok(result) +} + +/// 基准提交的临时工作区,用完即删 +struct BaseCheckout { + root: PathBuf, + path: PathBuf, +} + +impl BaseCheckout { + fn create(root: &Path, base: &str) -> Result { + let parent = std::env::var_os("RUNNER_TEMP").map_or_else(std::env::temp_dir, PathBuf::from); + let path = parent.join(format!("toolforge-plugin-base-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + let _ = git(root, &["worktree", "prune"]); + let target = path.to_string_lossy().into_owned(); + git( + root, + &["worktree", "add", "--force", "--detach", &target, base], + )?; + Ok(Self { + root: root.to_path_buf(), + path, + }) + } +} + +impl Drop for BaseCheckout { + fn drop(&mut self) { + let target = self.path.to_string_lossy().into_owned(); + let _ = git(&self.root, &["worktree", "remove", "--force", &target]); + } +} + +/// 插件实际编译的包与特性:与 `xtask plugin pack` 相同,单独构建这个后端, +/// 特性只在它自己的依赖图里合并;工作区级 Cargo.lock 会合并所有成员,不能直接比较 +fn build_inputs(checkout: &Path, slug: &str) -> Result>, String> { + let backend = checkout.join("market").join(slug).join("backend"); + if !backend.join("Cargo.toml").is_file() { + return Ok(None); + } + let name = crate_name(&backend)?; + let output = cargo() + .current_dir(checkout) + .args([ + "tree", + "--locked", + "-q", + "-p", + &name, + "--target", + "wasm32-wasip2", + "-e", + "normal,build", + "--prefix", + "none", + "-f", + "{p}|{f}", + ]) + .output() + .map_err(|e| format!("failed to run cargo tree: {e}"))?; + if !output.status.success() { + return Err(format!( + "cargo tree for {slug} failed in {}: {}", + checkout.display(), + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(Some(parse_tree(&String::from_utf8_lossy(&output.stdout)))) +} + +/// 解析 `cargo tree --prefix none -f '{p}|{f}'` 的输出 +pub fn parse_tree(output: &str) -> BTreeSet { + output + .lines() + .map(|line| line.trim().trim_end_matches(" (*)")) + .filter(|line| !line.is_empty()) + .map(|line| { + let (package, features) = line.rsplit_once('|').unwrap_or((line, "")); + format!("{} [{features}]", normalize_package(package)) + }) + .collect() +} + +/// 本地 path crate 只保留名字:它的版本号是发布元数据、路径随检出位置变化,都不改变编译出的字节; +/// 注册表与 git 依赖保留版本和来源,任何发布都是真实的输入变化 +pub fn normalize_package(package: &str) -> String { + let (package, proc_macro) = match package.strip_suffix(" (proc-macro)") { + Some(rest) => (rest, " (proc-macro)"), + None => (package, ""), + }; + if let Some((head, source)) = package.split_once(" (") { + let source = source.trim_end_matches(')'); + if !source.contains("://") && !source.starts_with("registry ") { + let name = head.split(' ').next().unwrap_or(head); + return format!("{name} (local){proc_macro}"); + } + } + format!("{package}{proc_macro}") +} + +/// 依赖差异,供失败说明使用 +pub fn dependency_changes(before: &BTreeSet, after: &BTreeSet) -> Vec { + let removed = before + .difference(after) + .map(|p| format!("dependency - {p}")); + let added = after + .difference(before) + .map(|p| format!("dependency + {p}")); + removed.chain(added).collect() +} + +/// 解析只影响宿主的 SDK 提交清单:每行「完整 SHA 空格 说明」,# 开头为注释 +pub fn parse_host_only(text: &str) -> Result, String> { + let sha = Regex::new("^[a-f0-9]{40}$").expect("valid regex"); + let mut commits = BTreeSet::new(); + for line in text.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + let commit = line.split_whitespace().next().unwrap_or_default(); + if !sha.is_match(commit) { + return Err(format!("invalid commit in {HOST_ONLY}: {commit}")); + } + commits.insert(commit.to_owned()); + } + Ok(commits) +} + +/// 下一个未发布过的版本:patch 递增,每段超过 VERSION_PART_MAX 时进位 +pub fn next_version( + id: &str, + version: &str, + published: &BTreeSet, +) -> Result { + let parts: Vec = version + .split('.') + .map(|p| p.parse().ok()) + .collect::>() + .filter(|p: &Vec| p.len() == 3) + .ok_or_else(|| format!("{id}: version {version} is not x.y.z"))?; + let (mut major, mut minor, mut patch) = (parts[0], parts[1], parts[2]); + loop { + patch += 1; + if patch > VERSION_PART_MAX { + patch = 0; + minor += 1; + if minor > VERSION_PART_MAX { + minor = 0; + major += 1; + } + } + let next = format!("{major}.{minor}.{patch}"); + if !published.contains(&package_name(id, &next)) { + return Ok(next); + } + } +} + +/// 只替换顶层 version 字段,保留 manifest 其余内容和格式 +pub fn set_version(text: &str, from: &str, to: &str) -> Result { + let pattern = Regex::new(&format!(r#""version"(\s*):(\s*)"{}""#, regex::escape(from))) + .expect("valid regex"); + let updated = pattern + .replacen(text, 1, format!(r#""version"${{1}}:${{2}}"{to}""#)) + .into_owned(); + let mut expected: Value = serde_json::from_str(text).map_err(|e| e.to_string())?; + expected["version"] = Value::String(to.to_owned()); + let actual: Value = serde_json::from_str(&updated).map_err(|e| e.to_string())?; + if actual != expected { + return Err(format!("cannot rewrite version {from} -> {to} in place")); + } + Ok(updated) +} + +fn bump(root: &Path, item: &Stale) -> Result<(), String> { + let path = root.join("market").join(&item.slug).join("manifest.json"); + let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let updated = set_version(&text, &item.version, &item.next) + .map_err(|e| format!("market/{}/manifest.json: {e}", item.slug))?; + std::fs::write(&path, updated).map_err(|e| format!("{}: {e}", path.display())) +} + +pub fn package_name(id: &str, version: &str) -> String { + format!("{id}-{version}.tfp") +} + +pub fn safe_slug(slug: &str) -> bool { + !slug.is_empty() + && slug + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// market/ 下的全部在线插件,按 slug 排序 +fn plugins(root: &Path) -> Result, String> { + let dir = root.join("market"); + let mut result = Vec::new(); + for entry in std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))? { + let entry = entry.map_err(|e| e.to_string())?; + let manifest = entry.path().join("manifest.json"); + if !manifest.is_file() { + continue; + } + let slug = entry.file_name().to_string_lossy().into_owned(); + let text = std::fs::read_to_string(&manifest) + .map_err(|e| format!("{}: {e}", manifest.display()))?; + let value = + serde_json::from_str(&text).map_err(|e| format!("market/{slug}/manifest.json: {e}"))?; + result.push((slug, value)); + } + result.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(result) +} + +fn string_field(manifest: &Value, field: &str, slug: &str) -> Result { + manifest + .get(field) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("market/{slug}/manifest.json has no {field}")) +} + +/// 已发布资产名:release JSON(`assets[].name`,可为分页数组)或存放 .tfp 的目录 +fn load_published(source: &Path) -> Result, String> { + if source.is_dir() { + let entries = + std::fs::read_dir(source).map_err(|e| format!("{}: {e}", source.display()))?; + return Ok(entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".tfp")) + .collect()); + } + let text = std::fs::read_to_string(source).map_err(|e| format!("{}: {e}", source.display()))?; + let value: Value = + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", source.display()))?; + Ok(published_names(&value)) +} + +/// 从 release JSON 中取出 .tfp 资产名 +pub fn published_names(value: &Value) -> BTreeSet { + let mut names = BTreeSet::new(); + let mut stack = vec![value.get("assets").unwrap_or(value)]; + while let Some(node) = stack.pop() { + match node { + Value::Array(items) => stack.extend(items), + Value::Object(asset) => { + if let Some(name) = asset.get("name").and_then(Value::as_str) + && name.ends_with(".tfp") + { + names.insert(name.to_owned()); + } + } + _ => {} + } + } + names +} + +fn gh(root: &Path, args: &[&str]) -> Result { + let output = Command::new("gh") + .args(args) + .current_dir(root) + .output() + .map_err(|e| { + format!("failed to run gh ({e}); install the GitHub CLI or pass --published") + })?; + if !output.status.success() { + return Err(format!( + "gh {}: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned()) +} + +fn fetch_published(root: &Path, repository: &str) -> Result, String> { + let id = gh( + root, + &[ + "api", + &format!("repos/{repository}/releases/tags/{RELEASE_TAG}"), + "--jq", + ".id", + ], + )?; + if !id.chars().all(|c| c.is_ascii_digit()) || id.is_empty() { + return Err(format!("invalid release id for {repository}: {id}")); + } + // 资产按页列出,历史较多时不能只读第一页 + let pages = gh( + root, + &[ + "api", + "--paginate", + "--slurp", + &format!("repos/{repository}/releases/{id}/assets"), + ], + )?; + let value: Value = serde_json::from_str(&pages).map_err(|e| e.to_string())?; + Ok(published_names(&value)) +} + +/// 上次成功发布的提交:Plugins 工作流在 dev 上最近一次成功运行的提交 +fn last_publication(root: &Path, repository: &str) -> Result { + let sha = gh( + root, + &[ + "run", + "list", + "-R", + repository, + "--workflow", + "plugins.yml", + "--branch", + "dev", + "--status", + "success", + "--limit", + "1", + "--json", + "headSha", + "--jq", + ".[0].headSha // empty", + ], + )?; + if sha.is_empty() { + return Err("no successful plugin publication found; pass --base".to_owned()); + } + Ok(sha) +} + +#[cfg(test)] +#[path = "plugin_versions_test.rs"] +mod tests; diff --git a/crates/xtask/src/plugin_versions_test.rs b/crates/xtask/src/plugin_versions_test.rs new file mode 100644 index 00000000..148d6950 --- /dev/null +++ b/crates/xtask/src/plugin_versions_test.rs @@ -0,0 +1,162 @@ +use std::collections::BTreeSet; + +use serde_json::json; + +use super::*; + +fn set(items: &[&str]) -> BTreeSet { + items.iter().map(|s| (*s).to_owned()).collect() +} + +#[test] +fn local_crates_drop_version_and_checkout_path() { + assert_eq!( + normalize_package("tfm-demo v0.1.2 (/home/runner/work/toolforge/market/demo/backend)"), + "tfm-demo (local)" + ); + assert_eq!( + normalize_package("tf-plugin-guest v0.2.0 (/tmp/base/crates/tf-plugin-guest)"), + "tf-plugin-guest (local)" + ); + assert_eq!( + normalize_package("tf-macros v0.1.0 (/repo/crates/tf-macros) (proc-macro)"), + "tf-macros (local) (proc-macro)" + ); +} + +#[test] +fn registry_and_git_crates_keep_version_and_source() { + assert_eq!(normalize_package("num-bigint v0.4.8"), "num-bigint v0.4.8"); + assert_eq!( + normalize_package("serde_derive v1.0.228 (proc-macro)"), + "serde_derive v1.0.228 (proc-macro)" + ); + let git = "foo v0.1.0 (https://github.com/acme/foo?rev=abc#abcdef12)"; + assert_eq!(normalize_package(git), git); + let registry = "bar v1.0.0 (registry `mirror`)"; + assert_eq!(normalize_package(registry), registry); +} + +#[test] +fn tree_output_ignores_checkout_location_and_repeats() { + let base = "tfm-demo v0.1.0 (/tmp/base/market/demo/backend)|\n\ + num-bigint v0.4.8|default,std\n\ + serde v1.0.228|default,std (*)\n"; + let head = "tfm-demo v0.1.1 (/repo/market/demo/backend)|\n\ + serde v1.0.228|default,std\n\ + num-bigint v0.4.8|default,std\n"; + assert_eq!(parse_tree(base), parse_tree(head)); +} + +#[test] +fn second_major_version_elsewhere_is_not_a_change() { + // 工作区新增 num-bigint 0.5 不影响仍编译 0.4.8 的插件:比较的是插件自己的依赖树 + let before = parse_tree("num-bigint v0.4.8|default,std\n"); + let after = parse_tree("num-bigint v0.4.8|default,std\n"); + assert!(dependency_changes(&before, &after).is_empty()); +} + +#[test] +fn version_and_feature_changes_are_reported() { + let before = parse_tree("num-bigint v0.4.8|default,std\nahash v0.8.12|std\n"); + let after = parse_tree("num-bigint v0.5.1|default,std\nahash v0.8.12|compile-time-rng,std\n"); + assert_eq!( + dependency_changes(&before, &after), + vec![ + "dependency - ahash v0.8.12 [std]", + "dependency - num-bigint v0.4.8 [default,std]", + "dependency + ahash v0.8.12 [compile-time-rng,std]", + "dependency + num-bigint v0.5.1 [default,std]", + ] + ); +} + +#[test] +fn next_version_skips_published_and_carries() { + let published = set(&["demo-0.1.1.tfp", "demo-0.1.2.tfp"]); + assert_eq!(next_version("demo", "0.1.0", &published).unwrap(), "0.1.3"); + assert_eq!(next_version("demo", "0.1.9", &set(&[])).unwrap(), "0.1.10"); + assert_eq!(next_version("demo", "0.1.10", &set(&[])).unwrap(), "0.2.0"); + assert_eq!(next_version("demo", "0.10.10", &set(&[])).unwrap(), "1.0.0"); + assert!(next_version("demo", "0.1", &set(&[])).is_err()); +} + +#[test] +fn set_version_only_touches_the_top_level_field() { + let text = "{\n \"id\": \"demo\",\n \"version\": \"0.1.0\",\n \"tags\": [\"a\", \"b\"],\n \ + \"deps\": { \"version\": \"0.1.0\" }\n}\n"; + let updated = set_version(text, "0.1.0", "0.1.1").unwrap(); + assert_eq!(updated, text.replacen("\"0.1.0\"", "\"0.1.1\"", 1)); + assert!(updated.contains("[\"a\", \"b\"]")); +} + +#[test] +fn set_version_refuses_when_first_match_is_nested() { + let text = r#"{ "deps": { "version": "0.1.0" }, "version": "0.1.0" }"#; + assert!(set_version(text, "0.1.0", "0.1.1").is_err()); +} + +#[test] +fn host_only_list_accepts_comments_and_rejects_short_shas() { + let sha = "88581a396841bfc98893458603be0f61d53a1994"; + let parsed = parse_host_only(&format!("# note\n\n{sha} reason here\n")).unwrap(); + assert_eq!(parsed, set(&[sha])); + assert!(parse_host_only("88581a3 reason\n").is_err()); +} + +#[test] +fn published_names_read_release_and_paginated_assets() { + let release = json!({ "assets": [{ "name": "demo-0.1.0.tfp" }, { "name": "registry.json" }] }); + assert_eq!(published_names(&release), set(&["demo-0.1.0.tfp"])); + let pages = json!([[{ "name": "a-0.1.0.tfp" }], [{ "name": "b-0.2.0.tfp" }]]); + assert_eq!( + published_names(&pages), + set(&["a-0.1.0.tfp", "b-0.2.0.tfp"]) + ); +} + +#[test] +fn changed_inputs_follow_plugin_dir_and_sdk_rules() { + let changes = |sdk_host_only| Changes { + paths: vec![ + "market/demo/ui/src/index.tsx".to_owned(), + "market/demo-extra/manifest.json".to_owned(), + "crates/tf-plugin-api/Cargo.toml".to_owned(), + "wit/plugin.wit".to_owned(), + ], + sdk_host_only, + cargo: false, + }; + assert_eq!( + changes(false).inputs("demo"), + vec!["market/demo/ui/src/index.tsx", "wit/plugin.wit"] + ); + assert_eq!( + changes(true).inputs("demo"), + vec!["market/demo/ui/src/index.tsx"] + ); + assert!(changes(true).inputs("other").is_empty()); +} + +#[test] +fn report_offers_manual_and_one_command_fixes() { + let stale = vec![Stale { + slug: "demo".to_owned(), + version: "0.1.0".to_owned(), + next: "0.1.1".to_owned(), + reasons: vec!["changed market/demo/manifest.json".to_owned()], + }]; + let text = report(&stale, "abc123"); + assert!(text.contains("market/demo 0.1.0 -> 0.1.1")); + assert!(text.contains("changed market/demo/manifest.json")); + assert!(text.contains("cargo xtask plugin versions --base abc123 --fix")); + assert!(text.contains("published plugin inputs changed without a version bump")); +} + +#[test] +fn slugs_are_restricted_to_safe_names() { + assert!(safe_slug("base-converter")); + assert!(!safe_slug("../etc")); + assert!(!safe_slug("")); + assert!(!safe_slug("Demo")); +} diff --git a/market/bingo-cards/manifest.json b/market/bingo-cards/manifest.json index 7d1fd8ec..3ebc978d 100644 --- a/market/bingo-cards/manifest.json +++ b/market/bingo-cards/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.bingo-cards", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/color/manifest.json b/market/color/manifest.json index dcc9528d..a9bfe2e9 100644 --- a/market/color/manifest.json +++ b/market/color/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.color", - "version": "0.1.3", + "version": "0.1.4", "name": "i18n:name", "description": "i18n:description", "category": "convert", diff --git a/market/invoice-assistant/manifest.json b/market/invoice-assistant/manifest.json index 71deb188..58edd2ad 100644 --- a/market/invoice-assistant/manifest.json +++ b/market/invoice-assistant/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.invoice-assistant", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/markdown-editor/manifest.json b/market/markdown-editor/manifest.json index a2bb83de..6d2937a7 100644 --- a/market/markdown-editor/manifest.json +++ b/market/markdown-editor/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.markdown-editor", - "version": "0.2.3", + "version": "0.2.4", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/paper-box-templates/manifest.json b/market/paper-box-templates/manifest.json index 671b9e51..ac866049 100644 --- a/market/paper-box-templates/manifest.json +++ b/market/paper-box-templates/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.paper-box-templates", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/physics-calculator/manifest.json b/market/physics-calculator/manifest.json index 139716f4..c5cd214c 100644 --- a/market/physics-calculator/manifest.json +++ b/market/physics-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.physics-calculator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/pour-over-coffee/manifest.json b/market/pour-over-coffee/manifest.json index 9988d186..28282de3 100644 --- a/market/pour-over-coffee/manifest.json +++ b/market/pour-over-coffee/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.pour-over-coffee", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/redirect-map/manifest.json b/market/redirect-map/manifest.json index 4e16a209..ba44c0a1 100644 --- a/market/redirect-map/manifest.json +++ b/market/redirect-map/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.redirect-map", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/robots-sitemap/manifest.json b/market/robots-sitemap/manifest.json index 9fee9d87..55f6874a 100644 --- a/market/robots-sitemap/manifest.json +++ b/market/robots-sitemap/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.robots-sitemap", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/scratch-calculator/manifest.json b/market/scratch-calculator/manifest.json index b124b51a..c34cf20a 100644 --- a/market/scratch-calculator/manifest.json +++ b/market/scratch-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.scratch-calculator", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/symmetry-drawing/manifest.json b/market/symmetry-drawing/manifest.json index 267d480a..36328b07 100644 --- a/market/symmetry-drawing/manifest.json +++ b/market/symmetry-drawing/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.symmetry-drawing", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/tangram-studio/manifest.json b/market/tangram-studio/manifest.json index 4eef9be1..89d8ebd0 100644 --- a/market/tangram-studio/manifest.json +++ b/market/tangram-studio/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.tangram-studio", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/text-diff/manifest.json b/market/text-diff/manifest.json index 97d3a307..33db24c6 100644 --- a/market/text-diff/manifest.json +++ b/market/text-diff/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.text-diff", - "version": "0.1.2", + "version": "0.1.3", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/undercover-host/manifest.json b/market/undercover-host/manifest.json index 234f063e..1ff8744e 100644 --- a/market/undercover-host/manifest.json +++ b/market/undercover-host/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.undercover-host", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/wardrobe-journal/manifest.json b/market/wardrobe-journal/manifest.json index 8a4f0b7c..dc19269a 100644 --- a/market/wardrobe-journal/manifest.json +++ b/market/wardrobe-journal/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.wardrobe-journal", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/weekly-menu/manifest.json b/market/weekly-menu/manifest.json index 88529f09..905de9b7 100644 --- a/market/weekly-menu/manifest.json +++ b/market/weekly-menu/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.weekly-menu", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life",