From 2a996acd631f5675907d7c6ec2e03ffeaeb2681e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:51:13 +0000 Subject: [PATCH] prebuilt: buf format runs dx buf_diff as its PATH diff (part of #13154) The quality runner's PATH shims now take leading args, so buf format's `diff` is a shim for `dx buf_diff` instead of a separate rust_binary. The standalone //core/quality/tools/diff binary is deleted; its lib gains run_process and joins the dx multicall. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xut2hwaXeBgTTdhK337xLR --- cli/cli/BUILD.bazel | 1 + cli/cli/src/main.rs | 1 + cli/cli/src/multicall.rs | 5 + core/quality/families/generation.bzl | 10 +- core/quality/real_core.bzl | 9 +- core/quality/runner/src/entry.rs | 5 +- core/quality/runner/src/matrix_harness.rs | 16 ++- core/quality/runner/src/real.rs | 112 +++++++++++++----- core/quality/runner/src/real/config_tools.rs | 4 +- core/quality/runner/src/real/helm.rs | 4 +- core/quality/runner/src/real/scripting.rs | 4 +- core/quality/runner/src/real_delegated.rs | 20 ++-- core/quality/runner/src/real_helm.rs | 9 +- core/quality/runner/src/request.rs | 33 ++++-- .../testdata/runner_matrix_structured.bzl | 6 +- core/quality/testdata/runner_matrix_tests.bzl | 6 + core/quality/tools/diff/BUILD.bazel | 14 +-- core/quality/tools/diff/src/lib.rs | 17 +++ core/quality/tools/diff/src/main.rs | 21 ---- 19 files changed, 196 insertions(+), 101 deletions(-) delete mode 100644 core/quality/tools/diff/src/main.rs diff --git a/cli/cli/BUILD.bazel b/cli/cli/BUILD.bazel index a1d88aecab..c1c82e52c2 100644 --- a/cli/cli/BUILD.bazel +++ b/cli/cli/BUILD.bazel @@ -184,6 +184,7 @@ rust_binary( "//core/quality/markdown:quality_markdown_lib", "//core/quality/notebook:quality_notebook_lib", "//core/quality/runner:quality_runner_lib", + "//core/quality/tools/diff:diff_lib", "//deploy/private:dx_deploy_tools", "//deploy/private/release:dx_release_tools", "//qt/private/tools/rust:qt_rust_bridge", diff --git a/cli/cli/src/main.rs b/cli/cli/src/main.rs index 617f8d7916..546567b3a8 100644 --- a/cli/cli/src/main.rs +++ b/cli/cli/src/main.rs @@ -228,6 +228,7 @@ fn run_as_tool() -> Option { Tool::SiteAggregate => dx_site_aggregate::run_process(&lossy(args)), Tool::SiteBuild => dx_site_build::run_process(&lossy(args)), Tool::SiteCheck => dx_site_check::run_process(&lossy(args)), + Tool::BufDiff => unified_diff::run_process(&args.collect::>()), Tool::Archiver => dx_deploy_tools::entry::archiver(&named("archiver", args)), Tool::Hasher => dx_deploy_tools::entry::hasher(&named("hasher", args)), Tool::SizeChecker => dx_deploy_tools::entry::size_checker(&named("size_checker", args)), diff --git a/cli/cli/src/multicall.rs b/cli/cli/src/multicall.rs index 8644067f5e..3dc466ada2 100644 --- a/cli/cli/src/multicall.rs +++ b/cli/cli/src/multicall.rs @@ -57,6 +57,7 @@ pub enum Tool { SiteAggregate, SiteBuild, SiteCheck, + BufDiff, } /// The tool `dx` was started as, judged by the file stem of argv[0] so `.exe` does not matter. @@ -120,6 +121,7 @@ pub fn subcommand_for(arg1: &OsStr) -> Option { "site_aggregate" => Some(Tool::SiteAggregate), "site_build" => Some(Tool::SiteBuild), "site_check" => Some(Tool::SiteCheck), + "buf_diff" => Some(Tool::BufDiff), _ => None, } } @@ -226,6 +228,7 @@ mod tests { ("site_aggregate", Tool::SiteAggregate), ("site_build", Tool::SiteBuild), ("site_check", Tool::SiteCheck), + ("buf_diff", Tool::BufDiff), ] { assert_eq!(subcommand_for(OsStr::new(name)), Some(tool), "{name}"); } @@ -273,6 +276,8 @@ mod tests { "site_aggregate", "site_build", "site_check", + "buf_diff", + "diff", ] { assert_eq!(tool_for(OsStr::new(name)), None, "{name}"); } diff --git a/core/quality/families/generation.bzl b/core/quality/families/generation.bzl index 950dc9448e..fc086a1e4a 100644 --- a/core/quality/families/generation.bzl +++ b/core/quality/families/generation.bzl @@ -3,9 +3,9 @@ load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//avro/private:providers.bzl", "AvroInfo") load("//capnproto/private:providers.bzl", "CapnprotoInfo") -load("//flatbuffers:defs.bzl", "FlatBuffersInfo") load("//core/quality:family_hooks.bzl", "upstream_files") load("//core/quality:real_core.bzl", "real_config", "real_context", "real_make_aspect", "real_make_probe_aspect") +load("//flatbuffers:defs.bzl", "FlatBuffersInfo") load("//thrift:defs.bzl", "ThriftInfo") visibility(["//core/...", "//tools/..."]) @@ -48,7 +48,7 @@ TOOLS = { } _BUF_FORMAT_ATTRS = { - "_buf_diff": attr.label(default = "//core/quality/tools/diff", executable = True, cfg = "exec", doc = "The diff buf format runs from PATH."), + "_dx": attr.label(default = "@dx_prebuilt//:dx", executable = True, cfg = "exec", doc = "The dx whose buf_diff subcommand buf format runs as diff."), } SHARD_SPECS = { @@ -149,12 +149,12 @@ def _closure_hook(tool): return _hook def _buf_format_context(ctx, capability): - """Returns the inputs and options that put the pinned diff on buf format's PATH.""" + """Returns the inputs and options that put `dx buf_diff` on buf format's PATH as diff.""" if capability != "format": return {} return { - "inputs": [ctx.executable._buf_diff], - "options": {"path_tools": [("diff", ctx.executable._buf_diff)]}, + "inputs": [ctx.executable._dx], + "options": {"path_tools": [("diff", ctx.executable._dx, ["buf_diff"])]}, } def _buf_hook(target, ctx, _resolved, capability, _what, _shared): diff --git a/core/quality/real_core.bzl b/core/quality/real_core.bzl index c1bd53a706..e4beea3919 100644 --- a/core/quality/real_core.bzl +++ b/core/quality/real_core.bzl @@ -214,6 +214,13 @@ def _staged_line(f): return None return rel + "\t" + f.path +def _path_tool(helper): + """Returns the request entry of a (name, file) or (name, file, leading args) path tool.""" + entry = {"binary": helper[1].path, "name": helper[0]} + if len(helper) > 2: + entry["args"] = helper[2] + return entry + def _staged_file_list(ctx, name, staged): """Writes one `relexec path` line per staged file without flattening the depsets.""" out = ctx.actions.declare_file(name) @@ -542,7 +549,7 @@ def _real_pipeline_action(cfg, target, ctx, capability, allowed_tools, output_su env = tool_env_entries.get(tool, []), upstream = [f.path for f in (found.upstream if found != None else [])], search_paths = [f.path for f in options.get("search_paths", [])], - path_tools = [{"binary": f.path, "name": name} for (name, f) in options.get("path_tools", [])], + path_tools = [_path_tool(helper) for helper in options.get("path_tools", [])], ) doc = real_request_doc( diff --git a/core/quality/runner/src/entry.rs b/core/quality/runner/src/entry.rs index 0385989139..02188053c1 100644 --- a/core/quality/runner/src/entry.rs +++ b/core/quality/runner/src/entry.rs @@ -141,7 +141,10 @@ fn real_tool( path_tools: entry .path_tools .iter() - .map(|(name, binary)| (name.clone(), absolute(cwd, binary.clone()))) + .map(|helper| crate::real::PathTool { + binary: absolute(cwd, helper.binary.clone()), + ..helper.clone() + }) .collect(), search_paths: entry .search_paths diff --git a/core/quality/runner/src/matrix_harness.rs b/core/quality/runner/src/matrix_harness.rs index 6756337fad..a084c8b498 100644 --- a/core/quality/runner/src/matrix_harness.rs +++ b/core/quality/runner/src/matrix_harness.rs @@ -120,6 +120,8 @@ pub struct ManifestTool { pub struct ManifestPathTool { pub name: String, pub binary_key: String, + #[serde(default)] + pub args: Vec, } #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] @@ -159,7 +161,8 @@ pub struct ResolvedTool { pub binary: Option, pub files: Vec<(String, PathBuf)>, pub upstream: Vec, - pub path_tools: Vec<(String, PathBuf)>, + /// Name, binary and leading args of each helper on the tool's `PATH`. + pub path_tools: Vec<(String, PathBuf, Vec)>, } fn lookup(resolver: &Resolver, key: &str) -> Result { @@ -233,7 +236,11 @@ pub fn resolve_manifest(resolver: &Resolver, manifest: Manifest) -> Result, } #[derive(serde::Serialize)] @@ -389,9 +398,10 @@ pub fn build_request( .map(|paths| paths.path_tools.as_slice()) .unwrap_or_default() .iter() - .map(|(name, path)| RequestPathTool { + .map(|(name, path, args)| RequestPathTool { name: name.clone(), binary: display(path), + args: args.clone(), }) .collect(), }, diff --git a/core/quality/runner/src/real.rs b/core/quality/runner/src/real.rs index 44c83b96c9..f29a48274c 100644 --- a/core/quality/runner/src/real.rs +++ b/core/quality/runner/src/real.rs @@ -70,8 +70,17 @@ pub struct RealTool { pub tool_files: Vec<(String, Vec)>, pub upstream_diagnostics: Vec, pub search_paths: Vec, - /// Helper executables placed on the child's `PATH` as shims: `(name, binary)`. - pub path_tools: Vec<(String, PathBuf)>, + /// Helper executables placed on the child's `PATH` as shims. + pub path_tools: Vec, +} + +/// One helper the tool finds by name on its `PATH`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PathTool { + pub name: String, + pub binary: PathBuf, + /// Arguments the shim passes before the caller's, such as a dx subcommand. + pub args: Vec, } pub type SpawnFn = fn(&[OsString], &Path, &[(OsString, OsString)]) -> io::Result; @@ -185,8 +194,8 @@ fn launcher_env(tool_id: &str, binary: &Path) -> Vec<(OsString, OsString)> { Vec::new() } -/// A `/bin/sh` shim that sets the launcher's env, then execs its absolute path. -fn unix_shim(binary: &str, env: &[(String, String)]) -> String { +/// A `/bin/sh` shim that sets the launcher's env, then execs its absolute path with `args` first. +fn unix_shim(binary: &str, args: &[String], env: &[(String, String)]) -> String { use dx_process::shell::quote; let mut out = String::from("#!/bin/sh\n"); for (key, value) in env { @@ -194,12 +203,16 @@ fn unix_shim(binary: &str, env: &[(String, String)]) -> String { } // The child PATH is only the shim dir. out.push_str("unset PATH\n"); - out.push_str(&format!("exec {} \"$@\"\n", quote(binary))); + out.push_str(&format!("exec {}", quote(binary))); + for arg in args { + out.push_str(&format!(" {}", quote(arg))); + } + out.push_str(" \"$@\"\n"); out } /// A `.cmd` shim with CRLF endings. Characters `cmd.exe` would reinterpret are refused. -fn windows_shim(binary: &str, env: &[(String, String)]) -> Result { +fn windows_shim(binary: &str, args: &[String], env: &[(String, String)]) -> Result { let bad = |text: &str| { text.chars() .any(|c| matches!(c, '%' | '"' | '^' | '!' | '\n' | '\r')) @@ -215,16 +228,24 @@ fn windows_shim(binary: &str, env: &[(String, String)]) -> Result Result<(), String> { + let name = tool.name.as_str(); let env: Vec<(String, String)> = env .iter() .map(|(key, value)| { @@ -234,13 +255,14 @@ fn write_path_shim( ) }) .collect(); - let binary = binary.to_string_lossy(); + let binary = tool.binary.to_string_lossy(); if cfg!(windows) { - let body = windows_shim(&binary, &env)?; + let body = windows_shim(&binary, &tool.args, &env)?; std::fs::write(dir.join(format!("{name}.cmd")), body).map_err(|err| err.to_string()) } else { let path = dir.join(name); - std::fs::write(&path, unix_shim(&binary, &env)).map_err(|err| err.to_string())?; + std::fs::write(&path, unix_shim(&binary, &tool.args, &env)) + .map_err(|err| err.to_string())?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; @@ -543,10 +565,10 @@ fn base_env( let dir = scratch.root().join(PATH_TOOLS_DIR_REL); std::fs::create_dir_all(&dir) .map_err(|err| execution(tool_id, format!("path tools dir: {err}")))?; - for (name, binary) in &tool.path_tools { - let shim_env = launcher_env(name, binary); - write_path_shim(&dir, name, binary, &shim_env) - .map_err(|err| execution(tool_id, format!("path tool {name}: {err}")))?; + for helper in &tool.path_tools { + let shim_env = launcher_env(&helper.name, &helper.binary); + write_path_shim(&dir, helper, &shim_env) + .map_err(|err| execution(tool_id, format!("path tool {}: {err}", helper.name)))?; } env.retain(|(key, _)| !key.to_string_lossy().eq_ignore_ascii_case("PATH")); env.push((OsString::from("PATH"), dir.into_os_string())); @@ -601,7 +623,7 @@ fn tool_specific_env( || tool .path_tools .iter() - .any(|(name, binary)| name == "bicep" && bicep_argv0 == Some(binary.as_path())); + .any(|helper| helper.name == "bicep" && bicep_argv0 == Some(helper.binary.as_path())); if runs_bicep { let home = scratch.root().join(BICEP_HOME_REL); std::fs::create_dir_all(&home) @@ -1041,6 +1063,7 @@ mod tests { fn unix_shims_export_env_then_exec_the_quoted_launcher() { let body = super::unix_shim( "/w/it's/bin", + &[], &[("RUNFILES_MANIFEST_FILE".to_owned(), "/w/m".to_owned())], ); assert_eq!( @@ -1049,16 +1072,40 @@ mod tests { ); } + #[test] + fn unix_shims_pass_quoted_leading_args_before_the_callers() { + let body = super::unix_shim("/w/dx", &["buf_diff".to_owned(), "a b".to_owned()], &[]); + assert_eq!( + body, + "#!/bin/sh\nunset PATH\nexec '/w/dx' 'buf_diff' 'a b' \"$@\"\n" + ); + } + #[test] fn windows_shims_use_crlf_and_refuse_cmd_metacharacters() { - let body = super::windows_shim("C:\\t\\bin.bat", &[("K".to_owned(), "V".to_owned())]) + let body = super::windows_shim("C:\\t\\bin.bat", &[], &[("K".to_owned(), "V".to_owned())]) .expect("shim"); assert_eq!( body, "@echo off\r\nset \"K=V\"\r\nset \"PATH=\"\r\n\"C:\\t\\bin.bat\" %*\r\n" ); for bad in ["a%b", "a\"b", "a^b", "a!b", "a\nb"] { - assert!(super::windows_shim(bad, &[]).is_err(), "{bad}"); + assert!(super::windows_shim(bad, &[], &[]).is_err(), "{bad}"); + } + } + + #[test] + fn windows_shims_pass_leading_args_and_refuse_ones_cmd_would_split() { + let body = super::windows_shim("C:\\dx.exe", &["buf_diff".to_owned()], &[]).expect("shim"); + assert_eq!( + body, + "@echo off\r\nset \"PATH=\"\r\n\"C:\\dx.exe\" buf_diff %*\r\n" + ); + for bad in ["a b", "", "a%b", "a\tb"] { + assert!( + super::windows_shim("C:\\dx.exe", &[bad.to_owned()], &[]).is_err(), + "{bad:?}" + ); } } @@ -1070,18 +1117,24 @@ mod tests { let launcher = dir.path().join("fake"); std::fs::write(&launcher, "#!/bin/sh\necho \"$1:$K\"\n").expect("write"); std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).expect("mode"); - super::write_path_shim( - dir.path(), - "rst2html", - &launcher, - &[(OsString::from("K"), OsString::from("v"))], - ) - .expect("shim"); + let helper = |name: &str, args: &[&str]| super::PathTool { + name: name.to_owned(), + binary: launcher.clone(), + args: args.iter().map(|arg| (*arg).to_owned()).collect(), + }; + let env = [(OsString::from("K"), OsString::from("v"))]; + super::write_path_shim(dir.path(), &helper("rst2html", &[]), &env).expect("shim"); let out = std::process::Command::new(dir.path().join("rst2html")) .arg("arg") .output() .expect("run"); assert_eq!(String::from_utf8_lossy(&out.stdout), "arg:v\n"); + super::write_path_shim(dir.path(), &helper("diff", &["buf_diff"]), &env).expect("shim"); + let out = std::process::Command::new(dir.path().join("diff")) + .arg("arg") + .output() + .expect("run"); + assert_eq!(String::from_utf8_lossy(&out.stdout), "buf_diff:v\n"); } #[cfg(unix)] @@ -1092,7 +1145,12 @@ mod tests { let launcher = dir.path().join("fake"); std::fs::write(&launcher, "#!/usr/bin/env sh\necho ok\n").expect("write"); std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).expect("mode"); - super::write_path_shim(dir.path(), "tool", &launcher, &[]).expect("shim"); + let helper = super::PathTool { + name: "tool".to_owned(), + binary: launcher, + args: Vec::new(), + }; + super::write_path_shim(dir.path(), &helper, &[]).expect("shim"); let body = std::fs::read_to_string(dir.path().join("tool")).expect("read"); assert!(body.contains("unset PATH\n"), "{body}"); let out = std::process::Command::new(dir.path().join("tool")) diff --git a/core/quality/runner/src/real/config_tools.rs b/core/quality/runner/src/real/config_tools.rs index abe9fd4c49..49d4c1f238 100644 --- a/core/quality/runner/src/real/config_tools.rs +++ b/core/quality/runner/src/real/config_tools.rs @@ -279,8 +279,8 @@ pub(super) const TOOLS: &[ToolDef] = &[ if let Some(chart_root) = helm_chart_root(tool) { return scan_chart(backend, call, &cache, &severities, &chart_root); } - if let Some((_, bicep)) = tool.path_tools.iter().find(|(name, _)| name == "bicep") { - return scan_bicep(backend, call, &cache, &severities, bicep); + if let Some(bicep) = tool.path_tools.iter().find(|helper| helper.name == "bicep") { + return scan_bicep(backend, call, &cache, &severities, &bicep.binary); } let (_, names) = super::single_run::paths(call); let mut findings = Vec::new(); diff --git a/core/quality/runner/src/real/helm.rs b/core/quality/runner/src/real/helm.rs index 7bfe9bc25d..3eed5b4f61 100644 --- a/core/quality/runner/src/real/helm.rs +++ b/core/quality/runner/src/real/helm.rs @@ -168,8 +168,8 @@ fn kube_inputs( let binary = tool .path_tools .iter() - .find(|(name, _)| name == "kubeconform") - .map(|(_, binary)| binary.clone()) + .find(|helper| helper.name == "kubeconform") + .map(|helper| helper.binary.clone()) .ok_or_else(|| { execution( tool_id, diff --git a/core/quality/runner/src/real/scripting.rs b/core/quality/runner/src/real/scripting.rs index d002a63cb6..3db3accfdc 100644 --- a/core/quality/runner/src/real/scripting.rs +++ b/core/quality/runner/src/real/scripting.rs @@ -266,8 +266,8 @@ fn pkl_lsp(backend: &RealBackend, call: &CheckCall<'_>) -> Result = [ + ("java", "/fake/jdk/bin/java"), + ("pkl-lsp.jar", "/fake/pkl-lsp.jar"), + ("pkl-lsp-natives.jar", "/fake/natives.jar"), + ] + .into_iter() + .map(|(name, binary)| PathTool { + name: name.to_owned(), + binary: PathBuf::from(binary), + args: Vec::new(), + }) + .collect(); let tool = RealTool { path_tools: companions.clone(), ..plain_tool() diff --git a/core/quality/runner/src/real_helm.rs b/core/quality/runner/src/real_helm.rs index a5aab5c345..6c6dd4947a 100644 --- a/core/quality/runner/src/real_helm.rs +++ b/core/quality/runner/src/real_helm.rs @@ -115,10 +115,11 @@ fn helm_tool(context: Option<&str>, companion: bool) -> RealTool { config_rel: Some(CONFIG_REL.to_owned()), tool_files, path_tools: if companion { - vec![( - "kubeconform".to_owned(), - PathBuf::from("/fake/bin/kubeconform"), - )] + vec![PathTool { + name: "kubeconform".to_owned(), + binary: PathBuf::from("/fake/bin/kubeconform"), + args: Vec::new(), + }] } else { Vec::new() }, diff --git a/core/quality/runner/src/request.rs b/core/quality/runner/src/request.rs index dfe5fe9644..3c693b9683 100644 --- a/core/quality/runner/src/request.rs +++ b/core/quality/runner/src/request.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use serde::Deserialize; use crate::StageSpec; -use crate::real::REAL_TOOLS; +use crate::real::{PathTool, REAL_TOOLS}; pub const REQUEST_SCHEMA_VERSION: u32 = 1; @@ -22,8 +22,8 @@ pub struct RequestTool { pub env: Vec<(String, String)>, pub upstream: Vec, pub search_paths: Vec, - /// Helper executables the tool finds by name on its own `PATH`: `(name, binary)`. - pub path_tools: Vec<(String, PathBuf)>, + /// Helper executables the tool finds by name on its own `PATH`. + pub path_tools: Vec, } /// Helper names each tool may be given on its `PATH`. One row per tool that shells out. @@ -157,6 +157,8 @@ struct ToolDoc { struct PathToolDoc { name: String, binary: String, + #[serde(default)] + args: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] @@ -242,8 +244,8 @@ fn non_empty_paths( Ok(out) } -fn check_path_tools(tool_id: &str, doc: &ToolDoc) -> Result, RequestError> { - let mut path_tools: Vec<(String, PathBuf)> = Vec::with_capacity(doc.path_tools.len()); +fn check_path_tools(tool_id: &str, doc: &ToolDoc) -> Result, RequestError> { + let mut path_tools: Vec = Vec::with_capacity(doc.path_tools.len()); for helper in &doc.path_tools { let allowed = PATH_TOOL_ALLOWLIST .iter() @@ -260,13 +262,17 @@ fn check_path_tools(tool_id: &str, doc: &ToolDoc) -> Result Result { Ok(DIFFERENT) } +/// Runs `dx buf_diff -u OLD NEW` and returns the process exit code. +pub fn run_process(args: &[OsString]) -> i32 { + let mut stdout = std::io::stdout().lock(); + match run(args, &mut stdout).and_then(|code| { + stdout + .flush() + .map(|()| code) + .map_err(|error| format!("stdout: {error}")) + }) { + Ok(code) => code, + Err(message) => { + eprintln!("diff: {message}"); + TROUBLE + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/core/quality/tools/diff/src/main.rs b/core/quality/tools/diff/src/main.rs deleted file mode 100644 index 25b8a74bd3..0000000000 --- a/core/quality/tools/diff/src/main.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![deny(clippy::indexing_slicing, clippy::string_slice)] - -use std::io::Write; - -fn main() { - let args: Vec = std::env::args_os().skip(1).collect(); - let mut stdout = std::io::stdout().lock(); - let code = match unified_diff::run(&args, &mut stdout).and_then(|code| { - stdout - .flush() - .map(|()| code) - .map_err(|error| format!("stdout: {error}")) - }) { - Ok(code) => code, - Err(message) => { - eprintln!("diff: {message}"); - unified_diff::TROUBLE - } - }; - std::process::exit(code); -}