Skip to main content
1//! Stage complete reports and replace only owned output directories.2use crate::diagnostic::model::ProjectInfo;3use std::path::{Path, PathBuf};4pub struct OutputTarget {5    pub path: PathBuf,6}7pub struct PublishedReport {8    pub index: PathBuf,9    pub warnings: Vec<String>,10    // Keep cooperating writers out until related external outputs are published.11    _publication_lock: Lock,12}13use std::{14    fs,15    io::{self, Write},16};17const MARKER: &str = ".clippy-html-owned";18fn canonical_future(path: &Path) -> Result<PathBuf, String> {19    if let Ok(m) = fs::symlink_metadata(path) {20        #[cfg(windows)]21        {22            use std::os::windows::fs::MetadataExt;23            if m.file_attributes() & 0x400 != 0 {24                return Err(format!(25                    "Refusing reparse-point output path: {}",26                    path.display()27                ));28            }29        }30        if m.file_type().is_symlink() {31            return Err(format!("Refusing symlink output path: {}", path.display()));32        }33    }34    let parent = path.parent().filter(|p| !p.as_os_str().is_empty());35    if let Some(parent) = parent {36        let base = canonical_future(parent)?;37        let name = path38            .file_name()39            .ok_or("Output path must name a directory")?;40        if path.exists() {41            path.canonicalize().map_err(|e| e.to_string())42        } else {43            Ok(base.join(name))44        }45    } else {46        path.canonicalize().map_err(|e| e.to_string())47    }48}49pub(crate) fn resolve_path(requested: &Path) -> Result<PathBuf, String> {50    let absolute = if requested.is_absolute() {51        requested.to_owned()52    } else {53        std::env::current_dir()54            .map_err(|e| e.to_string())?55            .join(requested)56    };57    let mut cleaned = PathBuf::new();58    for component in absolute.components() {59        match component {60            std::path::Component::ParentDir => {61                cleaned.pop();62            }63            std::path::Component::CurDir => {}64            c => cleaned.push(c),65        }66    }67    canonical_future(&cleaned)68}69pub fn prepare_target(requested: &Path, project: &ProjectInfo) -> Result<OutputTarget, String> {70    let path = resolve_path(requested)?;71    let mut protected = vec![72        canonical_future(&project.workspace_root)?,73        canonical_future(&project.target_dir)?,74    ];75    if let Some(build) = &project.build_dir {76        protected.push(canonical_future(build)?);77    }78    protected.extend(79        project80            .packages81            .iter()82            .filter_map(|p| p.manifest.parent())83            .map(canonical_future)84            .collect::<Result<Vec<_>, _>>()?,85    );86    if protected.iter().any(|p| p.starts_with(&path)) {87        return Err("Output must not replace a project, package, target, or build root".into());88    }89    check_owned(&path)?;90    Ok(OutputTarget { path })91}92fn check_owned(path: &Path) -> Result<(), String> {93    if !path.exists() {94        return Ok(());95    }96    if !path.is_dir() || !fs::read_to_string(path.join(MARKER)).is_ok_and(|s| s == "1\n") {97        return Err(format!(98            "Refusing to overwrite non-report directory: {}",99            path.display()100        ));101    }102    Ok(())103}104struct Lock {105    path: PathBuf,106    _file: fs::File,107}108impl Drop for Lock {109    fn drop(&mut self) {110        let _ = fs::remove_file(&self.path);111    }112}113pub fn publish_report(114    target: &OutputTarget,115    build: impl FnOnce(&Path) -> Result<(), String>,116) -> Result<PublishedReport, String> {117    publish_with_rename(target, build, |from, to| fs::rename(from, to))118}119fn publish_with_rename(120    target: &OutputTarget,121    build: impl FnOnce(&Path) -> Result<(), String>,122    mut rename: impl FnMut(&Path, &Path) -> io::Result<()>,123) -> Result<PublishedReport, String> {124    let parent = target.path.parent().ok_or("Output has no parent")?;125    fs::create_dir_all(parent).map_err(|e| e.to_string())?;126    // Parent-scoped publication serializes case aliases without assuming that127    // every Windows directory uses the same case-sensitivity rules.128    let parent = parent.canonicalize().map_err(|e| e.to_string())?;129    let lock_path = parent.join(".clippy-html-publish.lock");130    let mut file=fs::OpenOptions::new().write(true).create_new(true).open(&lock_path).map_err(|e|format!("Cannot lock report output ({e}); if no generator is running, inspect and remove {}",lock_path.display()))?;131    writeln!(file, "{}", std::process::id()).map_err(|e| e.to_string())?;132    let lock = Lock {133        path: lock_path,134        _file: file,135    };136    // Recheck after acquiring the lock, before touching an existing report.137    let checked = canonical_future(&target.path)?;138    if checked != target.path {139        return Err("Output path changed during generation".into());140    }141    check_owned(&target.path)?;142    let backup = parent.join(format!(143        ".clippy-html-{}.backup",144        blake3::hash(target.path.to_string_lossy().as_bytes()).to_hex()145    ));146    if backup.exists() {147        return Err(format!(148            "Recovery backup already exists; inspect {}",149            backup.display()150        ));151    }152    let staging = tempfile::Builder::new()153        .prefix(".clippy-html-stage-")154        .tempdir_in(&parent)155        .map_err(|e| e.to_string())?;156    build(staging.path())?;157    crate::render::validate_report(staging.path())?;158    fs::write(staging.path().join(MARKER), "1\n").map_err(|e| e.to_string())?;159    // Rendering may take time: another application can create or replace the160    // destination after the initial check without using our publication lock.161    if canonical_future(&target.path)? != target.path {162        return Err("Output path changed during rendering".into());163    }164    check_owned(&target.path)?;165    let old = target.path.exists();166    if old {167        rename(&target.path, &backup)168            .map_err(|e| format!("Cannot preserve existing report: {e}"))?;169        if let Err(problem) = check_owned(&backup) {170            if !target.path.exists() && rename(&backup, &target.path).is_ok() {171                return Err(format!("Unexpected destination preserved: {problem}"));172            }173            return Err(format!(174                "Unexpected destination retained at {}: {problem}",175                backup.display()176            ));177        }178    }179    if let Err(e) = rename(staging.path(), &target.path) {180        if old && let Err(restore) = rename(&backup, &target.path) {181            return Err(format!(182                "Report replacement failed: {e}; restore failed: {restore}; preserved backup: {}",183                backup.display()184            ));185        }186        return Err(format!(187            "Report replacement failed; previous report restored: {e}"188        ));189    }190    let mut warnings = vec![];191    if old && let Err(e) = fs::remove_dir_all(&backup) {192        warnings.push(format!(193            "Report ready; backup cleanup failed ({e}): {}",194            backup.display()195        ));196    }197    Ok(PublishedReport {198        index: target.path.join("index.html"),199        warnings,200        _publication_lock: lock,201    })202}203#[cfg(test)]204mod tests {205    use super::*;206    fn tempdir() -> tempfile::TempDir {207        // macOS's default temp path goes through the /var symlink.208        let parent = std::env::temp_dir().canonicalize().unwrap();209        tempfile::tempdir_in(parent).unwrap()210    }211    fn project(root: &Path) -> ProjectInfo {212        ProjectInfo {213            workspace_root: root.into(),214            target_dir: root.join("target"),215            build_dir: None,216            packages: vec![],217        }218    }219    #[test]220    fn build_failure_keeps_old_report() {221        let t = tempdir();222        let path = t.path().join("report");223        std::fs::create_dir(&path).unwrap();224        std::fs::write(path.join(".clippy-html-owned"), "1\n").unwrap();225        std::fs::write(path.join("index.html"), "old").unwrap();226        let target = prepare_target(&path, &project(t.path())).unwrap();227        assert!(publish_report(&target, |_| Err("failed render".into())).is_err());228        assert_eq!(229            std::fs::read_to_string(path.join("index.html")).unwrap(),230            "old"231        );232    }233    #[test]234    fn missing_font_assets_keep_old_report() {235        let t = tempdir();236        let path = t.path().join("report");237        std::fs::create_dir(&path).unwrap();238        std::fs::write(path.join(".clippy-html-owned"), "1\n").unwrap();239        std::fs::write(path.join("index.html"), "old").unwrap();240        let target = prepare_target(&path, &project(t.path())).unwrap();241        let result = publish_report(&target, |staging| {242            simple_report(staging)?;243            std::fs::create_dir(staging.join("static.files")).map_err(|e| e.to_string())?;244            std::fs::write(245                staging.join("static.files/fonts.css"),246                "@font-face { src: url(\"missing.woff2\"); }",247            )248            .map_err(|e| e.to_string())?;249            std::fs::write(250                staging.join("index.html"),251                "<link href=\"static.files/fonts.css\">",252            )253            .map_err(|e| e.to_string())254        });255        assert!(matches!(result, Err(message) if message.contains("Missing font resource")));256        assert_eq!(257            std::fs::read_to_string(path.join("index.html")).unwrap(),258            "old"259        );260    }261    #[test]262    fn separate_build_root_is_protected_but_a_report_below_it_is_allowed() {263        let t = tempdir();264        let mut p = project(t.path());265        let build = t.path().join("generated-cache");266        p.build_dir = Some(build.clone());267        assert!(prepare_target(&build, &p).is_err());268        assert!(prepare_target(&build.join("report"), &p).is_ok());269    }270    #[test]271    fn refuses_unowned_or_project_directory() {272        let t = tempdir();273        let p = project(t.path());274        assert!(prepare_target(t.path(), &p).is_err());275        let other = t.path().join("notes");276        std::fs::create_dir(&other).unwrap();277        assert!(prepare_target(&other, &p).is_err());278        assert!(prepare_target(&t.path().join("new-report"), &p).is_ok());279    }280    fn simple_report(path: &Path) -> Result<(), String> {281        fs::create_dir(path.join("lint")).map_err(|e| e.to_string())?;282        fs::create_dir(path.join("src")).map_err(|e| e.to_string())?;283        fs::write(path.join("index.html"), "<!doctype html><title>new</title>")284            .map_err(|e| e.to_string())285    }286    #[test]287    fn rename_failure_restores_backup() {288        let t = tempdir();289        let path = t.path().join("report");290        fs::create_dir(&path).unwrap();291        fs::write(path.join(MARKER), "1\n").unwrap();292        fs::write(path.join("index.html"), "old").unwrap();293        let target = prepare_target(&path, &project(t.path())).unwrap();294        let mut count = 0;295        let result = publish_with_rename(&target, simple_report, |a, b| {296            count += 1;297            if count == 2 {298                Err(io::Error::other("injected publish failure"))299            } else {300                fs::rename(a, b)301            }302        });303        assert!(result.is_err());304        assert_eq!(fs::read_to_string(path.join("index.html")).unwrap(), "old");305    }306    #[test]307    fn rollback_failure_retains_backup() {308        let t = tempdir();309        let path = t.path().join("report");310        fs::create_dir(&path).unwrap();311        fs::write(path.join(MARKER), "1\n").unwrap();312        fs::write(path.join("index.html"), "old").unwrap();313        let target = prepare_target(&path, &project(t.path())).unwrap();314        let mut count = 0;315        let result = publish_with_rename(&target, simple_report, |a, b| {316            count += 1;317            if count >= 2 {318                Err(io::Error::other("injected rename failure"))319            } else {320                fs::rename(a, b)321            }322        });323        let e = result.err().unwrap();324        assert!(e.contains("preserved backup"));325        let backup = fs::read_dir(t.path())326            .unwrap()327            .map(|e| e.unwrap().path())328            .find(|p| p.extension().is_some_and(|s| s == "backup"))329            .unwrap();330        assert_eq!(331            fs::read_to_string(backup.join("index.html")).unwrap(),332            "old"333        );334    }335    #[test]336    fn concurrent_publish_has_one_owner() {337        let t = tempdir();338        let target = prepare_target(&t.path().join("report"), &project(t.path())).unwrap();339        let result = publish_report(&target, |dir| {340            assert!(publish_report(&target, simple_report).is_err());341            simple_report(dir)342        })343        .unwrap();344        assert!(result.index.is_file());345        assert!(result.warnings.is_empty()); warning: clippy::assert_is_empty346    }347    #[test]348    fn publication_lock_covers_external_metadata_and_is_released_with_the_receipt() {349        let t = tempdir();350        let target = prepare_target(&t.path().join("report"), &project(t.path())).unwrap();351        let metadata_path = t.path().join("navigation.json");352        let metadata = crate::metadata::MetadataTarget::prepare(&metadata_path, &target)353            .unwrap()354            .stage(b"snapshot A".to_vec())355            .unwrap();356        let published = publish_report(&target, simple_report).unwrap();357        let competing = publish_report(&target, |_| {358            panic!("a second publisher must not enter between HTML and external JSON publication")359        });360        assert!(competing.is_err());361        metadata.publish_external().unwrap();362        assert_eq!(fs::read(&metadata_path).unwrap(), b"snapshot A");363        assert!(364            publish_report(&target, |_| panic!(365                "publication receipt still owns the lock"366            ))367            .is_err()368        );369        drop(published);370        assert!(publish_report(&target, simple_report).is_ok());371    }372    #[test]373    fn unexpected_destination_created_during_render_is_preserved() {374        let t = tempdir();375        let path = t.path().join("report");376        let target = prepare_target(&path, &project(t.path())).unwrap();377        let result = publish_report(&target, |staging| {378            fs::create_dir(&path).unwrap();379            fs::write(path.join("important.txt"), "keep me").unwrap();380            simple_report(staging)381        });382        assert!(result.is_err());383        assert_eq!(384            fs::read_to_string(path.join("important.txt")).unwrap(),385            "keep me"386        );387    }388    #[test]389    fn unexpected_object_moved_to_backup_is_never_deleted() {390        let t = tempdir();391        let path = t.path().join("report");392        fs::create_dir(&path).unwrap();393        fs::write(path.join(MARKER), "1\n").unwrap();394        fs::write(path.join("index.html"), "old").unwrap();395        let target = prepare_target(&path, &project(t.path())).unwrap();396        let mut call = 0;397        let result = publish_with_rename(&target, simple_report, |from, to| {398            call += 1;399            if call == 1 {400                fs::rename(from, t.path().join("original"))?;401                fs::create_dir(from)?;402                fs::write(from.join("important.txt"), "keep me")?;403            }404            fs::rename(from, to)405        });406        assert!(result.is_err());407        assert!(408            fs::read_dir(t.path())409                .unwrap()410                .map(|e| e.unwrap().path())411                .any(|p| p.is_dir()412                    && fs::read_to_string(p.join("important.txt")).is_ok_and(|s| s == "keep me"))413        );414    }415    #[cfg(windows)]416    #[test]417    fn case_aliases_share_one_publication_lock() {418        let t = tempdir();419        fs::write(t.path().join("case-probe"), "probe").unwrap();420        if !t.path().join("CASE-PROBE").exists() {421            return;422        }423        let a = prepare_target(&t.path().join("Report"), &project(t.path())).unwrap();424        let b = prepare_target(&t.path().join("report"), &project(t.path())).unwrap();425        let entered = std::cell::Cell::new(false);426        publish_report(&a, |staging| {427            assert!(428                publish_report(&b, |_| {429                    entered.set(true);430                    Err("nested".into())431                })432                .is_err()433            );434            simple_report(staging)435        })436        .unwrap();437        assert!(438            !entered.get(),439            "case alias entered the protected publication section"440        );441    }442}443

Findings in this file§

warning clippy::assert_is_empty §

used `assert!` to check that a value is empty

src/output.rs:345:9

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

Targets (1)
  • cargo-clippy-html (bin)

Primary: src/output.rs:345:9

        assert!(result.warnings.is_empty());

Primary: src/output.rs:345:15

        assert!(result.warnings.is_empty());

Primary: src/output.rs:345:17

        assert!(result.warnings.is_empty());

help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#assert_is_empty

help: use `assert_eq!` to show the value on failure

Suggestion: use `assert_eq!` to show the value on failure

MachineApplicable

--- "a/src/output.rs"
+++ "b/src/output.rs"
@@ -342,7 +342,7 @@
         })
         .unwrap();
         assert!(result.index.is_file());
-        assert!(result.warnings.is_empty());
+        assert_eq!(result.warnings, [] as [std::string::String; 0]);
     }
     #[test]
     fn publication_lock_covers_external_metadata_and_is_released_with_the_receipt() {
Rendered diagnostic (text)
warning: used `assert!` to check that a value is empty
   --> src/output.rs:345:9
    |
345 |         assert!(result.warnings.is_empty());
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#assert_is_empty
help: use `assert_eq!` to show the value on failure
    |
345 -         assert!(result.warnings.is_empty());
345 +         assert_eq!(result.warnings, [] as [std::string::String; 0]);
    |