Source src/render/paths.rs
1//! Stable report names with safely encoded workspace source paths.2use crate::{diagnostic::model::Report, source::SourceFile};3use std::{4 collections::BTreeMap,5 path::{Path, PathBuf},6};7pub struct PageMap { warning: clippy::struct_field_names8 pub category_pages: BTreeMap<String, PathBuf>, warning: clippy::struct_field_names9 pub lint_pages: BTreeMap<String, PathBuf>, warning: clippy::struct_field_names10 pub source_pages: BTreeMap<PathBuf, PathBuf>, warning: clippy::struct_field_names11} warning: clippy::struct_field_names12pub fn category_key(finding: &crate::diagnostic::model::Finding) -> Option<&str> {13 (finding.origin == "Clippy").then(|| {14 finding15 .category16 .as_deref()17 .filter(|c| crate::lint::metadata::CATEGORIES.contains(c))18 .unwrap_or("unknown")19 })20}21fn assigned_paths<K: Ord>(22 candidates: BTreeMap<K, PathBuf>,23 digest: impl Fn(&K) -> String,24) -> BTreeMap<K, PathBuf> {25 let collision_key = |path: &Path| {26 path.to_string_lossy()27 .replace('\\', "/")28 .to_lowercase()29 .to_uppercase()30 };31 let mut used: std::collections::BTreeSet<_> =32 candidates.values().map(|p| collision_key(p)).collect();33 let mut assigned = std::collections::BTreeSet::new();34 candidates35 .into_iter()36 .map(|(key, mut path)| {37 // Conservatively group Windows Unicode case aliases before writing.38 if !assigned.insert(collision_key(&path)) {39 let digest = digest(&key);40 let stem = path41 .file_stem()42 .unwrap_or_default()43 .to_string_lossy()44 .into_owned();45 let mut suffix = 0;46 loop {47 let extra = if suffix == 0 {48 String::new()49 } else {50 format!("-{suffix}")51 };52 path.set_file_name(format!(53 "{stem}-{}{extra}.html",54 digest.get(..16).unwrap_or(&digest)55 ));56 if used.insert(collision_key(&path)) {57 break;58 }59 suffix += 1;60 }61 }62 (key, path)63 })64 .collect()65}66pub fn group_key(f: &crate::diagnostic::model::Finding) -> String {67 format!("{}:{}", f.origin, f.code.as_deref().unwrap_or("general"))68}69fn safe_component(text: &str, directory: bool) -> String {70 let mut name = String::new();71 for ch in text.chars() {72 if ch.is_alphanumeric() || matches!(ch, '_' | '-' | '.') {73 name.push(ch);74 } else {75 for byte in ch.to_string().bytes() {76 name.push_str(&format!("~{byte:02X}")); warning: clippy::format_push_string77 }78 }79 }80 let stem = name81 .split('.')82 .next()83 .unwrap_or_default()84 .to_ascii_uppercase();85 if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")86 || ["COM", "LPT"].iter().any(|prefix| {87 stem.strip_prefix(prefix).is_some_and(|n| {88 matches!(89 n,90 "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"91 )92 })93 })94 {95 name.insert_str(0, "~00");96 }97 if name.is_empty() || name == "." || name == ".." {98 name = name.replace('.', "~2E");99 name.insert_str(0, "~00");100 }101 if directory && name.to_ascii_lowercase().ends_with(".html") {102 let dot = name.len() - 5;103 name.replace_range(dot..dot + 1, "~2E"); warning: clippy::range_plus_one104 }105 while name.ends_with('.') {106 name.pop();107 name.push_str("~2E");108 }109 // Keep single filenames well below common filesystem component limits.110 if name.len() > 120 {111 let hash = blake3::hash(text.as_bytes()).to_hex();112 let mut end = 80;113 while !name.is_char_boundary(end) {114 end -= 1;115 }116 name = format!("{}-{}", &name[..end], &hash[..16]);117 }118 name119}120fn source_candidate(root: &Path, path: &Path) -> PathBuf {121 if let Ok(relative) = path.strip_prefix(root)122 && relative123 .components()124 .all(|c| matches!(c, std::path::Component::Normal(_)))125 && relative.file_name().is_some()126 {127 let relative = if relative.components().count() > 1 {128 relative.strip_prefix("src").unwrap_or(relative)129 } else {130 relative131 };132 let parts: Vec<_> = relative.components().collect();133 let mut output = PathBuf::from("src");134 for (i, part) in parts.iter().enumerate() {135 let last = i + 1 == parts.len();136 let name = safe_component(&part.as_os_str().to_string_lossy(), !last);137 output.push(if last { format!("{name}.html") } else { name });138 }139 output140 } else {141 let name = safe_component(142 &path.file_name().unwrap_or_default().to_string_lossy(),143 false,144 );145 let digest = blake3::hash(path.as_os_str().as_encoded_bytes()).to_hex();146 PathBuf::from(format!("src/~external/{name}-{}.html", &digest[..16]))147 }148}149pub fn build_page_map(report: &Report, sources: &BTreeMap<PathBuf, SourceFile>) -> PageMap {150 let lint_candidates = report151 .findings152 .iter()153 .map(|finding| {154 let path = if let Some(code) = finding.code.as_deref() {155 let (namespace, name) = if finding.origin == "Clippy" {156 ("clippy", code.strip_prefix("clippy::").unwrap_or(code))157 } else {158 ("rustc", code)159 };160 PathBuf::from(format!(161 "lint/{namespace}/{}.html",162 safe_component(name, false)163 ))164 } else {165 PathBuf::from("lint/general.html")166 };167 (group_key(finding), path)168 })169 .collect();170 let lint_pages = assigned_paths(lint_candidates, |key| {171 blake3::hash(key.as_bytes()).to_hex().to_string()172 });173 let candidates: BTreeMap<_, _> = sources174 .keys()175 .map(|key| {176 (177 key.clone(),178 source_candidate(&report.project.workspace_root, key),179 )180 })181 .collect();182 let source_pages = assigned_paths(candidates, |key| {183 blake3::hash(key.as_os_str().as_encoded_bytes())184 .to_hex()185 .to_string()186 });187 PageMap {188 category_pages: report189 .findings190 .iter()191 .filter_map(category_key)192 .map(|name| {193 (194 name.to_owned(),195 PathBuf::from(format!("category/{name}.html")),196 )197 })198 .collect(),199 lint_pages,200 source_pages,201 }202}203pub fn relative_href(from: &Path, to: &Path, anchor: Option<&str>) -> String {204 let depth = from.parent().map_or(0, |p| p.components().count());205 let mut result = format!(206 "{}{}",207 "../".repeat(depth),208 to.to_string_lossy()209 .replace('\\', "/")210 .bytes()211 .map(|b| {212 if b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~') {213 char::from(b).to_string()214 } else {215 format!("%{b:02X}")216 }217 })218 .collect::<String>()219 );220 if let Some(id) = anchor {221 result.push('#');222 result.push_str(id);223 }224 result225}226#[cfg(test)]227mod tests {228 use super::*;229 #[test]230 fn lint_urls_keep_names_namespaces_and_distinct_safe_paths() {231 use crate::diagnostic::model::*;232 let cargo_metadata::Message::CompilerMessage(message) =233 serde_json::from_value(crate::diagnostic::sample()).unwrap()234 else {235 panic!()236 };237 let finding = crate::diagnostic::normalize::normalize(&message, Path::new("/demo"));238 let codes = [239 Some("clippy::clone_on_copy"),240 Some("E0308"),241 Some("unused_variables"),242 None,243 Some("clone_on_copy"),244 Some("clippy::CON"),245 Some("clippy::../a #%.rs"),246 Some("clippy::σ"),247 Some("clippy::ς"),248 Some("clippy::Foo"),249 Some("clippy::foo"),250 ];251 let mut report = Report {252 category_metadata: None,253 project: ProjectInfo {254 workspace_root: "/demo".into(),255 target_dir: "/demo/target".into(),256 build_dir: None,257 packages: vec![],258 },259 execution: Execution {260 code: Some(0),261 complete: true,262 requested_args: vec![],263 observed_packages: vec![],264 observed_targets: vec![],265 stderr: String::new(),266 stderr_truncated: false,267 text_stdout: String::new(),268 stdout_truncated: false,269 issues: vec![],270 },271 raw_count: codes.len(),272 findings: codes273 .into_iter()274 .map(|code| {275 let mut f = finding.clone();276 f.code = code.map(str::to_owned);277 f.origin = if code.is_some_and(|c| c.starts_with("clippy::")) {278 "Clippy"279 } else if code.is_some() {280 "Rust compiler"281 } else {282 "General"283 }284 .into();285 f286 })287 .collect(),288 };289 let pages = build_page_map(&report, &BTreeMap::new()).lint_pages;290 assert_eq!(291 pages["Clippy:clippy::clone_on_copy"],292 PathBuf::from("lint/clippy/clone_on_copy.html")293 );294 assert_eq!(295 pages["Rust compiler:E0308"],296 PathBuf::from("lint/rustc/E0308.html")297 );298 assert_eq!(299 pages["Rust compiler:unused_variables"],300 PathBuf::from("lint/rustc/unused_variables.html")301 );302 assert_eq!(pages["General:general"], PathBuf::from("lint/general.html"));303 assert_eq!(304 pages["Rust compiler:clone_on_copy"],305 PathBuf::from("lint/rustc/clone_on_copy.html")306 );307 assert_eq!(308 pages["Clippy:clippy::CON"],309 PathBuf::from("lint/clippy/~00CON.html")310 );311 let unique: std::collections::BTreeSet<_> = pages312 .values()313 .map(|p| p.to_string_lossy().to_lowercase().to_uppercase())314 .collect();315 assert_eq!(unique.len(), codes.len());316 for path in pages.values() {317 assert!(path.starts_with("lint"));318 assert!(319 path.components()320 .all(|c| matches!(c, std::path::Component::Normal(_)))321 );322 }323 report.findings.reverse();324 assert_eq!(pages, build_page_map(&report, &BTreeMap::new()).lint_pages);325 }326 #[test]327 fn source_names_preserve_hierarchy_without_unsafe_or_colliding_paths() {328 use crate::diagnostic::model::*;329 let report = Report {330 category_metadata: None,331 project: ProjectInfo {332 workspace_root: "/demo".into(),333 target_dir: "/demo/target".into(),334 build_dir: None,335 packages: vec![],336 },337 execution: Execution {338 code: Some(0),339 complete: true,340 requested_args: vec![],341 observed_packages: vec![],342 observed_targets: vec![],343 stderr: String::new(),344 stderr_truncated: false,345 text_stdout: String::new(),346 stdout_truncated: false,347 issues: vec![],348 },349 raw_count: 0,350 findings: vec![],351 };352 let keys = [353 "/demo/src/diagnostic/한글.rs",354 "/demo/src/a #%.rs",355 "/demo/src/CON.rs",356 "/demo/src/Foo.rs",357 "/demo/src/foo.rs",358 "/demo/src/a.html/child.rs",359 "/demo/src/a",360 "/outside/lib.rs",361 "/demo/../escape.rs",362 "/demo/src/σ.rs",363 "/demo/src/ς.rs",364 ];365 let sources = keys366 .into_iter()367 .map(|key| {368 (369 PathBuf::from(key),370 SourceFile {371 display_path: key.into(),372 text: None,373 reason: None,374 },375 )376 })377 .collect();378 let pages = build_page_map(&report, &sources).source_pages;379 assert_eq!(380 pages[Path::new(keys[0])],381 PathBuf::from("src/diagnostic/한글.rs.html")382 );383 assert_eq!(384 pages[Path::new(keys[1])],385 PathBuf::from("src/a~20~23~25.rs.html")386 );387 let names: std::collections::BTreeSet<_> = pages388 .values()389 .map(|p| p.to_string_lossy().to_lowercase())390 .collect();391 assert_eq!(names.len(), keys.len());392 assert_ne!(393 pages[Path::new(keys[9])].to_string_lossy().to_uppercase(),394 pages[Path::new(keys[10])].to_string_lossy().to_uppercase(),395 "Windows aliases sigma and final sigma; their output files must differ"396 );397 assert!(398 !pages[Path::new(keys[2])]399 .file_name()400 .unwrap()401 .to_string_lossy()402 .to_uppercase()403 .starts_with("CON.")404 );405 for page in pages.values() {406 assert!(page.starts_with("src"));407 assert!(408 page.components()409 .all(|c| matches!(c, std::path::Component::Normal(_)))410 );411 assert!(412 !pages413 .values()414 .any(|other| other != page && other.starts_with(page))415 );416 }417 assert_eq!(418 relative_href(419 Path::new("lint/a.html"),420 Path::new("src/한글.rs.html"),421 None422 ),423 "../src/%ED%95%9C%EA%B8%80.rs.html"424 );425 }426 #[test]427 fn relative_navigation_stays_portable() {428 assert_eq!(429 relative_href(430 Path::new("lint/a.html"),431 Path::new("src/b.html"),432 Some("L42")433 ),434 "../src/b.html#L42"435 );436 assert_eq!(437 relative_href(Path::new("index.html"), Path::new("lint/a.html"), None),438 "lint/a.html"439 );440 }441 #[test]442 fn colliding_names_are_distinct_and_order_independent() {443 let names = assigned_paths(444 BTreeMap::from([445 ("b", "lint/same.html".into()),446 ("a", "lint/same.html".into()),447 ("c", "lint/same-collision.html".into()),448 ]),449 |_| "collision".into(),450 );451 assert_ne!(names["a"], names["b"]);452 assert_eq!(names["b"], PathBuf::from("lint/same-collision-1.html"));453 assert_eq!(names["c"], PathBuf::from("lint/same-collision.html"));454 assert_eq!(455 names,456 assigned_paths(457 BTreeMap::from([458 ("a", "lint/same.html".into()),459 ("c", "lint/same-collision.html".into()),460 ("b", "lint/same.html".into())461 ]),462 |_| "collision".into()463 )464 );465 }466}467Findings in this file§
warning clippy::struct_field_names §
warning clippy::struct_field_names §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/paths.rs:7:1
help: remove the postfixes
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#struct_field_names
Rendered diagnostic (text)
warning: all fields have the same postfix: `pages`
--> src/render/paths.rs:7:1
|
7 | / pub struct PageMap {
8 | | pub category_pages: BTreeMap<String, PathBuf>,
9 | | pub lint_pages: BTreeMap<String, PathBuf>,
10 | | pub source_pages: BTreeMap<PathBuf, PathBuf>,
11 | | }
| |_^
|
= help: remove the postfixes
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#struct_field_names
warning clippy::format_push_string §
warning clippy::format_push_string §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/paths.rs:76:17
note: you may need to import the `std::fmt::Write` trait
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#format_push_string
note: `-W clippy::format-push-string` implied by `-W clippy::pedantic`
help: to override `-W clippy::pedantic` add `#[allow(clippy::format_push_string)]`
help: consider using `write!` to avoid the extra allocation
Suggestion: consider using `write!` to avoid the extra allocation
--- "a/src/render/paths.rs"
+++ "b/src/render/paths.rs"
@@ -73,7 +73,7 @@
name.push(ch);
} else {
for byte in ch.to_string().bytes() {
- name.push_str(&format!("~{byte:02X}"));
+ let _ = write!(name, "~{byte:02X}");
}
}
}
Rendered diagnostic (text)
warning: `format!(..)` appended to existing `String`
--> src/render/paths.rs:76:17
|
76 | name.push_str(&format!("~{byte:02X}"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: you may need to import the `std::fmt::Write` trait
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#format_push_string
= note: `-W clippy::format-push-string` implied by `-W clippy::pedantic`
= help: to override `-W clippy::pedantic` add `#[allow(clippy::format_push_string)]`
help: consider using `write!` to avoid the extra allocation
|
76 - name.push_str(&format!("~{byte:02X}"));
76 + let _ = write!(name, "~{byte:02X}");
|
warning clippy::range_plus_one §
warning clippy::range_plus_one §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/paths.rs:103:28
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#range_plus_one
note: `-W clippy::range-plus-one` implied by `-W clippy::pedantic`
help: to override `-W clippy::pedantic` add `#[allow(clippy::range_plus_one)]`
help: use
Suggestion: use
--- "a/src/render/paths.rs"
+++ "b/src/render/paths.rs"
@@ -100,7 +100,7 @@
}
if directory && name.to_ascii_lowercase().ends_with(".html") {
let dot = name.len() - 5;
- name.replace_range(dot..dot + 1, "~2E");
+ name.replace_range(dot..=dot, "~2E");
}
while name.ends_with('.') {
name.pop();
Rendered diagnostic (text)
warning: an inclusive range would be more readable
--> src/render/paths.rs:103:28
|
103 | name.replace_range(dot..dot + 1, "~2E");
| ^^^^^^^^^^^^ help: use: `dot..=dot`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#range_plus_one
= note: `-W clippy::range-plus-one` implied by `-W clippy::pedantic`
= help: to override `-W clippy::pedantic` add `#[allow(clippy::range_plus_one)]`