//! `cargo xtask lints-selftest`: proves that the workspace lint table rejects //! panicking code in shipped code and accepts it in tests. //! //! The check builds two scratch crates under `target/xtask/lints-selftest/` //! that copy `[workspace.lints]` and `clippy.toml` from the repository: one //! calls `unwrap()` in a public function and must fail clippy, the other calls //! it only inside `#[cfg(test)]` and must pass. use std::fs; use std::path::Path; use std::process::Command; use crate::util::{TaskResult, repo_root}; /// Source of the scratch crate whose shipped code unwraps. const SHIPPED_SRC: &str = "//! Probe.\n\n/// Probe.\npub fn probe(v: Option) -> u8 {\n v.unwrap()\n}\n"; /// Source of the scratch crate that unwraps only in a test. const TESTED_SRC: &str = r#"//! Probe. /// Probe. pub fn probe(v: Option) -> u8 { v.unwrap_or(0) } #[cfg(test)] mod tests { #[test] fn probe_returns_value() { let v: Option = "1".parse().ok(); assert_eq!(super::probe(v), v.unwrap()); } } "#; /// Runs the self-test. /// /// # Errors /// Fails if the shipped probe passes clippy, if the test probe fails it, or /// if the scratch crates cannot be written or checked. pub fn selftest() -> TaskResult { let root = repo_root()?; let lints = lints_section(&fs::read_to_string(root.join("Cargo.toml")).map_err(|e| e.to_string())?)?; let clippy = fs::read_to_string(root.join("clippy.toml")).map_err(|e| e.to_string())?; let base = root.join("target").join("xtask").join("lints-selftest"); let shipped = probe(&base, "shipped", SHIPPED_SRC, &lints, &clippy)?; if shipped.0 { return Err("lints-selftest: unwrap() in shipped code passed clippy".into()); } if !shipped.1.contains("unwrap_used") { return Err(format!( "lints-selftest: shipped probe failed for another reason:\n{}", shipped.1 )); } let tested = probe(&base, "tested", TESTED_SRC, &lints, &clippy)?; if !tested.0 { return Err(format!( "lints-selftest: unwrap() in a test was rejected:\n{}", tested.1 )); } println!("lints-selftest: shipped unwrap() rejected, test unwrap() accepted"); Ok(()) } /// Converts the `[workspace.lints]` table of the root manifest into the /// `[lints.*]` sections of a standalone manifest. /// /// # Errors /// Fails if the manifest is not valid TOML or has no `[workspace.lints]`. pub fn lints_section(manifest: &str) -> TaskResult { let doc: toml::Table = manifest.parse().map_err(|e| format!("Cargo.toml: {e}"))?; let lints = doc .get("workspace") .and_then(|w| w.get("lints")) .and_then(toml::Value::as_table) .ok_or("Cargo.toml has no [workspace.lints]")?; let mut out = String::new(); for (group, table) in lints { out.push_str(&format!("[lints.{group}]\n")); if let Some(table) = table.as_table() { for (name, level) in table { out.push_str(&format!("{name} = {level}\n")); } } out.push('\n'); } Ok(out) } /// Writes one scratch crate and runs clippy on all its targets. /// /// Returns whether clippy passed and its combined output. /// /// # Errors /// Fails if the files cannot be written or cargo cannot be started. fn probe( base: &Path, name: &str, src: &str, lints: &str, clippy: &str, ) -> TaskResult<(bool, String)> { let dir = base.join(name); fs::create_dir_all(dir.join("src")).map_err(|e| e.to_string())?; let manifest = format!( "[package]\nname = \"lint-probe-{name}\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n[workspace]\n\n{lints}" ); fs::write(dir.join("Cargo.toml"), manifest).map_err(|e| e.to_string())?; fs::write(dir.join("clippy.toml"), clippy).map_err(|e| e.to_string())?; fs::write(dir.join("src").join("lib.rs"), src).map_err(|e| e.to_string())?; let output = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into())) .args(["clippy", "--quiet", "--all-targets", "--", "-D", "warnings"]) .current_dir(&dir) .env("CARGO_TARGET_DIR", base.join("target")) .output() .map_err(|e| format!("cannot start cargo: {e}"))?; let text = format!( "{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) ); Ok((output.status.success(), text)) } #[cfg(test)] mod tests { use super::lints_section; #[test] fn copies_lint_groups() { let manifest = "[workspace.lints.rust]\nmissing_docs = \"deny\"\n[workspace.lints.clippy]\nunwrap_used = \"deny\"\n"; let out = lints_section(manifest).unwrap(); assert!(out.contains("[lints.rust]\nmissing_docs = \"deny\"")); assert!(out.contains("[lints.clippy]\nunwrap_used = \"deny\"")); } #[test] fn rejects_manifest_without_lints() { assert!(lints_section("[workspace]\n").is_err()); } }