diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs
index b61723b488..e517292e73 100644
--- a/xtask/src/test_lint.rs
+++ b/xtask/src/test_lint.rs
@@ -99,8 +99,9 @@
use std::cell::{OnceCell, RefCell};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
+use std::io::Write;
use std::path::Path;
-use std::process::Command;
+use std::process::{Command, Stdio};
/// Test files that read Rust source on purpose: they audit the source tree.
pub const SOURCE_AUDITS: &[&str] = &[
@@ -350,7 +351,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
// Files that load a module through `#[path]`, found with `git grep` (untracked files included)
// instead of reading the tree, and the target roots beside a shared `tests/
/mod.rs`.
let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files);
- let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE));
+ let base_sizes = base_blob_sizes(root, &base);
+ let read_base = cached_read(|p| read_base_blob(root, &base, p, MAX_FILE, base_sizes.as_ref()));
// The base's target roots come from the base tree: a root the change deleted still loaded the
// shared module beside it.
let base_overrides =
@@ -643,6 +645,74 @@ fn git(root: &Path, args: &[&str]) -> Result {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
+/// The file `path` as it is at `rev`, or `None` when it is missing there or its blob is larger
+/// than `limit` bytes. `size` and `show` take the `rev:path` object name and give the blob's
+/// size and text; a blob over the limit is never passed to `show`.
+fn read_blob(rev: &str, path: &str, limit: u64, size: impl Fn(&str) -> Option, show: impl Fn(&str) -> Option) -> Option {
+ let spec = format!("{rev}:{path}");
+ if size(&spec)? > limit {
+ return None;
+ }
+ show(&spec)
+}
+
+/// [`read_blob`] through Git in `root`.
+fn read_git_blob(root: &Path, rev: &str, path: &str, limit: u64) -> Option {
+ let size = |spec: &str| git(root, &["cat-file", "-s", spec]).ok()?.parse().ok();
+ read_blob(rev, path, limit, size, |spec| git(root, &["show", spec]).ok())
+}
+
+fn read_base_blob(root: &Path, rev: &str, path: &str, limit: u64, sizes: Option<&HashMap>) -> Option {
+ match sizes.and_then(|sizes| sizes.get(path)).copied() {
+ Some(size) => read_blob(rev, path, limit, |_| Some(size), |spec| git(root, &["show", spec]).ok()),
+ None => read_git_blob(root, rev, path, limit),
+ }
+}
+
+/// The size of each `.rs` blob in the tree at `rev`, or `None` when either Git command fails.
+fn base_blob_sizes(root: &Path, rev: &str) -> Option> {
+ let list = git(root, &["ls-tree", "-r", "-z", "--name-only", rev, "--", "crates", "apps", "xtask"]).ok()?;
+ // Each batch request is one line; paths with newlines use read_git_blob instead.
+ let paths: Vec<&str> = list.split('\0').filter(|path| is_scanned(path) && !path.contains('\n')).collect();
+ let input: String = paths.iter().map(|path| format!("{rev}:{path}\n")).collect();
+ let mut child = Command::new("git")
+ .current_dir(root)
+ .arg("cat-file")
+ .arg("--batch-check=%(objectsize)")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .ok()?;
+ let mut stdin = child.stdin.take()?;
+ let output = std::thread::scope(|scope| {
+ let writer = match std::thread::Builder::new().spawn_scoped(scope, move || stdin.write_all(input.as_bytes())) {
+ Ok(writer) => writer,
+ Err(_) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ };
+ let output = child.wait_with_output().ok();
+ writer.join().ok()?.ok()?;
+ output
+ })?;
+ if !output.status.success() {
+ return None;
+ }
+ let output = String::from_utf8_lossy(&output.stdout);
+ let mut lines = output.lines();
+ let mut sizes = HashMap::new();
+ for path in paths {
+ let size = lines.next()?;
+ if !size.ends_with("missing") {
+ sizes.insert(path.to_owned(), size.parse().ok()?);
+ }
+ }
+ Some(sizes)
+}
+
fn resolve_base(root: &Path, explicit: Option) -> Result {
if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) {
return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")])
@@ -9146,6 +9216,43 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
+ #[test]
+ fn base_blobs_over_the_limit_are_not_read() {
+ let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let root = std::env::temp_dir().join(format!("test-lint-blob-{}-{unique}", std::process::id()));
+ std::fs::create_dir_all(root.join("crates/x/src")).unwrap();
+ git(&root, &["init", "--quiet"]).unwrap();
+ // 1 byte of text and 40 of trailing whitespace: the blob is 41 bytes.
+ std::fs::write(root.join("crates/x/src/padded.rs"), format!("x{}", " \n".repeat(20))).unwrap();
+ std::fs::write(root.join("crates/x/src/small.rs"), "fn f() {}\n").unwrap();
+ std::fs::write(root.join("crates/x/src/other.txt"), "other\n").unwrap();
+ git(&root, &["add", "."]).unwrap();
+ let base = git(&root, &["write-tree"]).unwrap();
+ assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 8), None, "the blob's size counts, not its trimmed text");
+ assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 41).as_deref(), Some("x"));
+ assert_eq!(read_git_blob(&root, &base, "crates/x/src/small.rs", 10).as_deref(), Some("fn f() {}"));
+ assert_eq!(read_git_blob(&root, &base, "crates/x/src/missing.rs", 10), None);
+ let sizes = base_blob_sizes(&root, &base).unwrap();
+ assert_eq!(sizes.get("crates/x/src/padded.rs"), Some(&41));
+ assert!(!sizes.contains_key("crates/x/src/other.txt"));
+ assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 6, Some(&sizes)).as_deref(), Some("other"));
+ assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 5, Some(&sizes)), None);
+ assert_eq!(read_base_blob(&root, &base, "crates/x/src/padded.rs", 8, Some(&sizes)), None);
+ assert!(base_blob_sizes(&root, "missing-revision").is_none());
+ // A blob over the limit is not read at all.
+ let shown = RefCell::new(vec![]);
+ let show = |spec: &str| {
+ shown.borrow_mut().push(spec.to_owned());
+ Some(String::new())
+ };
+ assert_eq!(read_blob("r", "big.rs", 8, |_| Some(9), show), None);
+ assert_eq!(read_blob("r", "fits.rs", 8, |_| Some(8), show).as_deref(), Some(""));
+ assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 8, |_| sizes.get("crates/x/src/padded.rs").copied(), show), None);
+ assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 41, |_| sizes.get("crates/x/src/padded.rs").copied(), show).as_deref(), Some(""));
+ assert_eq!(*shown.borrow(), ["r:fits.rs".to_owned(), format!("{base}:crates/x/src/padded.rs")]);
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
fn base_root_routes_come_from_the_base_tree() {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();