Source src/render/pages.rs
1#[path = "categories.rs"]2mod categories;3use super::paths::PageMap;4use super::paths::{group_key, relative_href};5use crate::source::{all_spans, span_matches};6use crate::{diagnostic::model::*, source::SourceFile}; warning: clippy::wildcard_imports7use askama::Template;8use std::{9 collections::BTreeMap,10 path::{Path, PathBuf},11};12struct Link {13 href: String,14 text: String,15}16struct CountLink {17 link: Link,18 count: usize,19}20struct PackageRow {21 name: String,22 observed: &'static str,23}24struct CrateInfo {25 name: String,26 version: String,27}28#[derive(Template)]29#[template(path = "base.html")]30struct Page<'a> {31 title: &'a str,32 section: &'a str,33 root: String,34 sidebar: Vec<Link>,35 content: String,36 crate_context: String,37 crates: Vec<CrateInfo>,38 heading_kind: &'a str,39 source_page: bool, warning: clippy::struct_field_names40 standalone_page: bool, warning: clippy::struct_field_names41 generator_version: &'static str,42 source_tree: String,43}44#[derive(Template)]45#[template(path = "index.html")]46struct Index<'a> {47 categories: Vec<categories::CategoryRow>,48 category_metadata: Option<&'a CategoryMetadata>,49 workspace: String,50 status: &'static str,51 exit: String,52 collection: &'static str,53 count: usize,54 errors: usize,55 warnings: usize,56 raw_count: usize,57 args: String,58 issues: &'a [String],59 packages: Vec<PackageRow>,60 targets: Vec<String>,61 lints: Vec<CountLink>,62 files: Vec<Link>,63 stderr: &'a str,64 stderr_truncated: bool,65 stdout: &'a str,66 stdout_truncated: bool,67}68struct Location {69 kind: &'static str,70 href: String,71 label: String,72 note: String,73 snippet: String,74}75struct NoteView {76 level: String,77 message: String,78 link: Option<Link>,79}80fn note_view(note: &Note) -> NoteView {81 const PREFIX: &str = "for further information visit ";82 if let Some(text) = note.message.strip_prefix(PREFIX)83 && let Ok(url) = url::Url::parse(text)84 && url.scheme() == "https"85 && url.host_str().is_some()86 && url.username().is_empty()87 && url.password().is_none()88 {89 NoteView {90 level: note.level.clone(),91 message: PREFIX.into(),92 link: Some(Link {93 href: url.to_string(),94 text: text.into(),95 }),96 }97 } else {98 NoteView {99 level: note.level.clone(),100 message: note.message.clone(),101 link: None,102 }103 }104}105struct ReplacementView {106 location: String,107 applicability: String,108 text: String,109}110struct SuggestionView {111 message: String,112 replacements: Vec<ReplacementView>,113 applicability: String,114 patch: Option<PatchView>,115 reason: String,116}117struct PatchView {118 json: String,119 lines: Vec<PatchLine>,120}121struct PatchLine {122 class: &'static str,123 text: String,124}125struct FindingView {126 category_href: String,127 id: String,128 level: String,129 code: String,130 message: String,131 origin: String,132 category: String,133 package: String,134 docs: String,135 targets: Vec<String>,136 locations: Vec<Location>,137 summary_location: Option<Link>,138 notes: Vec<NoteView>,139 suggestions: Vec<SuggestionView>,140 fallback: String,141}142#[derive(Template)]143#[template(path = "lint.html")]144struct Lint {145 findings: Vec<FindingView>,146}147#[derive(Template)]148#[template(path = "licenses.html")]149struct Licenses;150#[derive(Template)]151#[template(path = "settings.html")]152struct Settings;153#[derive(Template)]154#[template(path = "help.html")]155struct Help {156 generator_version: &'static str,157}158struct SourceRow {159 number: usize,160 fragments: Vec<super::ranges::Fragment>,161 marked: bool,162 links: Vec<Link>,163}164#[derive(Template)]165#[template(path = "source.html")]166struct SourceView {167 reason: String,168 rows: Vec<SourceRow>,169 digits: usize,170}171172fn source_rows( warning: clippy::too_many_lines173 source: &SourceFile, warning: clippy::too_many_lines174 key: &Path, warning: clippy::too_many_lines175 path: &Path, warning: clippy::too_many_lines176 findings: &[&Finding], warning: clippy::too_many_lines177 pages: &PageMap, warning: clippy::too_many_lines178 validate: &impl Fn(&SourceFile, &Span) -> bool, warning: clippy::too_many_lines179) -> Vec<SourceRow> { warning: clippy::too_many_lines180 let Some(text) = source.text.as_deref() else {181 return vec![];182 };183 let lexical = super::highlight::lines(text);184 let lines: Vec<_> = text.split('\n').map(|s| s.trim_end_matches('\r')).collect();185 let mut annotations: Vec<Vec<super::ranges::Range>> =186 (0..lexical.len()).map(|_| vec![]).collect();187 let mut rows: Vec<_> = lexical188 .iter()189 .enumerate()190 .map(|(i, _)| SourceRow {191 number: i + 1,192 fragments: vec![],193 marked: false,194 links: vec![],195 })196 .collect();197 let mut assigned = std::collections::BTreeSet::new();198 for finding in findings {199 for span in display_spans(finding).iter().filter(|s| s.path == key) {200 if !validate(source, span) {201 continue;202 }203 let whitespace_only = text[span.byte_start..span.byte_end]204 .chars()205 .all(char::is_whitespace);206 for number in span.line_start..=span.line_end {207 let insertion = span.byte_start == span.byte_end;208 if !insertion209 && number == span.line_end210 && number > span.line_start211 && span.column_end == 1212 {213 continue;214 }215 let line = lines[number - 1];216 let offset = |column: usize| {217 let bom = if number == 1 && line.starts_with('\u{feff}') {218 3219 } else {220 0221 };222 line[bom..]223 .char_indices()224 .nth(column - 1)225 .map_or(line.len(), |(byte, _)| bom + byte)226 };227 let mut start = if number == span.line_start {228 offset(span.column_start)229 } else {230 0231 };232 let end = if number == span.line_end {233 offset(span.column_end)234 } else {235 line.len()236 };237 // Hide layout indentation only; literal/comment whitespace and238 // diagnostics explicitly targeting whitespace retain their range.239 if !whitespace_only240 && lexical[number - 1]241 .first()242 .is_some_and(|f| f.class.is_none())243 {244 let indent = line.len() - line.trim_start_matches([' ', '\t']).len();245 start = start.max(indent);246 }247 if start < end || insertion {248 let kind = if span.primary { "Primary" } else { "Secondary" };249 annotations[number - 1].push(super::ranges::Range {250 start,251 end,252 primary: span.primary,253 title: format!(254 "{kind} · {}{}{}",255 finding.code.as_deref().unwrap_or("diagnostic"),256 if span.label.is_some() { ": " } else { "" },257 span.label.as_deref().unwrap_or("")258 ),259 });260 }261 if let Some(row) = rows.get_mut(number - 1)262 && assigned.insert((number, &finding.id))263 {264 row.marked = true;265 row.links.push(Link {266 href: relative_href(267 path,268 &pages.lint_pages[&group_key(finding)],269 Some(&format!("finding-{}", finding.id)),270 ),271 text: format!(272 "{}: {}",273 finding.level,274 finding.code.as_deref().unwrap_or("diagnostic")275 ),276 });277 }278 }279 }280 }281 for ((row, fragments), ranges) in rows.iter_mut().zip(lexical).zip(annotations) {282 row.fragments = super::ranges::annotate(fragments, &ranges);283 }284 rows285}286fn render(t: &impl Template) -> Result<String, String> {287 t.render().map_err(|e| e.to_string())288}289fn write_page(destination: &Path, path: &Path, page: Page<'_>) -> Result<(), String> { warning: clippy::needless_pass_by_value290 if let Some(parent) = path.parent() {291 std::fs::create_dir_all(destination.join(parent)).map_err(|e| e.to_string())?;292 }293 std::fs::write(destination.join(path), render(&page)?).map_err(|e| e.to_string())294}295fn target_label(t: &TargetInfo) -> String {296 format!("{} ({})", t.name, t.kinds.join(", "))297}298fn crate_infos(report: &Report, findings: &[&Finding]) -> Vec<CrateInfo> {299 let mut crates: Vec<_> = report300 .project301 .packages302 .iter()303 .filter(|p| {304 p.workspace_member305 && (findings.is_empty() || findings.iter().any(|f| f.package_id == p.id))306 })307 .map(|p| CrateInfo {308 name: p.name.clone(),309 version: p.version.clone(),310 })311 .collect();312 crates.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));313 crates314}315fn crate_context(report: &Report, findings: &[&Finding]) -> String {316 let crates = crate_infos(report, findings);317 let names: Vec<_> = crates.iter().map(|c| c.name.as_str()).collect();318 if names.is_empty() {319 report320 .project321 .workspace_root322 .file_name()323 .unwrap_or_default()324 .to_string_lossy()325 .into_owned()326 } else {327 names.join(", ")328 }329}330fn display_spans(f: &Finding) -> Vec<Span> {331 let mut seen: BTreeMap<(PathBuf, usize, usize), usize> = BTreeMap::new();332 let mut result: Vec<Span> = vec![];333 for span in all_spans(f) {334 let key = (span.path.clone(), span.byte_start, span.byte_end);335 if let Some(&index) = seen.get(&key) {336 result[index].primary |= span.primary;337 if let Some(label) = &span.label {338 let existing = &mut result[index].label;339 if existing.as_deref() != Some(label) {340 *existing = Some(341 existing342 .as_ref()343 .map_or_else(|| label.clone(), |text| format!("{text}; {label}")),344 );345 }346 }347 } else {348 seen.insert(key, result.len());349 result.push(span.clone());350 }351 }352 result353}354fn views( warning: clippy::too_many_lines355 findings: &[&Finding], warning: clippy::too_many_lines356 from: &Path, warning: clippy::too_many_lines357 sources: &BTreeMap<PathBuf, SourceFile>, warning: clippy::too_many_lines358 pages: &PageMap, warning: clippy::too_many_lines359 packages: &[PackageInfo], warning: clippy::too_many_lines360 workspace_root: &Path, warning: clippy::too_many_lines361) -> Vec<FindingView> { warning: clippy::too_many_lines362 fn flatten(n: &Note, out: &mut Vec<NoteView>) {363 out.push(note_view(n));364 for c in &n.children {365 flatten(c, out);366 }367 }368 findings369 .iter()370 .map(|f| {371 let locations: Vec<Location> = display_spans(f)372 .into_iter()373 .map(|s| {374 let matched = sources375 .get(&s.path)376 .is_some_and(|src| span_matches(src, &s));377 let anchor = if matched {378 format!("L{}", s.line_start)379 } else {380 format!("finding-{}", f.id)381 };382 Location {383 kind: if s.primary { "Primary" } else { "Secondary" },384 href: relative_href(from, &pages.source_pages[&s.path], Some(&anchor)),385 label: format!(386 "{}:{}:{}",387 sources[&s.path].display_path, s.line_start, s.column_start388 ),389 note: format!(390 "{}{}",391 s.label.as_deref().unwrap_or(""),392 if matched {393 ""394 } else {395 " [Diagnostic snippet; full source unavailable or changed]"396 }397 ),398 snippet: s399 .text400 .iter()401 .map(|t| t.text.as_str())402 .collect::<Vec<_>>()403 .join("\n"),404 }405 })406 .collect();407 let mut notes = vec![];408 for n in &f.children {409 flatten(n, &mut notes);410 }411 let docs = f412 .code413 .as_deref()414 .and_then(|c| c.strip_prefix("clippy::"))415 .map(|name| {416 let mut url = url::Url::parse(417 "https://rust-lang.github.io/rust-clippy/master/index.html",418 )419 .expect("constant URL");420 url.set_fragment(Some(name));421 url.to_string()422 })423 .unwrap_or_default();424 FindingView {425 summary_location: locations426 .iter()427 .find(|loc| loc.kind == "Primary")428 .or_else(|| locations.first())429 .map(|loc| Link {430 href: loc.href.clone(),431 text: loc.label.clone(),432 }),433 id: f.id.clone(),434 level: f.level.clone(),435 code: f436 .code437 .clone()438 .unwrap_or_else(|| "General diagnostic".into()),439 message: f.message.clone(),440 origin: f.origin.clone(),441 category: super::paths::category_key(f).map_or_else(442 || "Category: not applicable".into(),443 |key| {444 format!(445 "Category: {}",446 if key == "unknown" { "Unknown" } else { key }447 )448 },449 ),450 category_href: super::paths::category_key(f)451 .and_then(|key| pages.category_pages.get(key))452 .map(|target| relative_href(from, target, None))453 .unwrap_or_default(),454 package: packages455 .iter()456 .find(|p| p.id == f.package_id)457 .map_or_else(|| f.package_id.clone(), |p| p.name.clone()),458 docs,459 targets: f.targets.iter().map(target_label).collect(),460 locations,461 notes,462 suggestions: f463 .suggestions464 .iter()465 .map(|s| {466 let (patch, reason) =467 match super::suggestions::build_patch(s, sources, workspace_root) {468 Ok(text) => (469 Some(PatchView {470 json: serde_json::to_string(&text)471 .expect("serialize patch string"),472 lines: text473 .split_inclusive('\n')474 .map(|line| PatchLine {475 class: if line.starts_with("--- ")476 || line.starts_with("+++ ")477 || line.starts_with("@@")478 {479 "diff-header"480 } else if line.starts_with('+') {481 "diff-add"482 } else if line.starts_with('-') {483 "diff-remove"484 } else {485 "diff-context"486 },487 text: line.into(),488 })489 .collect(),490 }),491 String::new(),492 ),493 Err(reason) => (None, reason),494 };495 SuggestionView {496 message: s.message.clone(),497 applicability: s498 .replacements499 .iter()500 .map(|r| r.applicability.as_str())501 .collect::<std::collections::BTreeSet<_>>()502 .into_iter()503 .collect::<Vec<_>>()504 .join(" · "),505 patch,506 reason,507 replacements: s508 .replacements509 .iter()510 .map(|r| ReplacementView {511 location: format!(512 "{}:{}:{}",513 r.span.path.display(),514 r.span.line_start,515 r.span.column_start516 ),517 applicability: r.applicability.clone(),518 text: r.text.clone(),519 })520 .collect(),521 }522 })523 .collect(),524 fallback: f.rendered.clone().unwrap_or_default(),525 }526 })527 .collect()528}529pub fn render_report( warning: clippy::too_many_lines530 report: &Report, warning: clippy::too_many_lines531 sources: &BTreeMap<PathBuf, SourceFile>, warning: clippy::too_many_lines532 pages: &PageMap, warning: clippy::too_many_lines533 destination: &Path, warning: clippy::too_many_lines534) -> Result<(), String> { warning: clippy::too_many_lines535 super::assets::write_assets(destination)?;536 super::search::write_index(report, sources, pages, destination)?;537 for dir in ["lint", "src"] {538 std::fs::create_dir_all(destination.join(dir)).map_err(|e| e.to_string())?;539 }540 let groups: BTreeMap<String, Vec<&Finding>> =541 report.findings.iter().fold(BTreeMap::new(), |mut map, f| {542 map.entry(group_key(f)).or_default().push(f);543 map544 });545 let index_path = Path::new("index.html");546 let lints = groups547 .iter()548 .map(|(key, fs)| CountLink {549 link: Link {550 href: relative_href(index_path, &pages.lint_pages[key], None),551 text: fs[0]552 .code553 .clone()554 .unwrap_or_else(|| "General diagnostics".into()),555 },556 count: fs.len(),557 })558 .collect();559 let files: Vec<_> = sources560 .iter()561 .map(|(key, s)| Link {562 href: relative_href(index_path, &pages.source_pages[key], None),563 text: s.display_path.clone(),564 })565 .collect();566 let index = Index {567 categories: categories::rows(report, pages, index_path),568 category_metadata: report.category_metadata.as_ref(),569 workspace: {570 let members: Vec<_> = report571 .project572 .packages573 .iter()574 .filter(|p| p.workspace_member)575 .collect();576 if members.len() == 1 {577 members[0].name.clone()578 } else {579 report580 .project581 .workspace_root582 .file_name()583 .unwrap_or_default()584 .to_string_lossy()585 .into_owned()586 }587 },588 status: if report.execution.code == Some(0) {589 "Succeeded"590 } else {591 "Failed"592 },593 exit: report594 .execution595 .code596 .map_or("unavailable".into(), |n| n.to_string()),597 collection: if report.execution.complete {598 "Complete"599 } else {600 "Incomplete — inspect collection issues"601 },602 count: report.findings.len(),603 errors: report604 .findings605 .iter()606 .filter(|f| f.level == "error")607 .count(),608 warnings: report609 .findings610 .iter()611 .filter(|f| f.level == "warning")612 .count(),613 raw_count: report.raw_count,614 args: report615 .execution616 .requested_args617 .iter()618 .map(|a| format!("{a:?}")) warning: clippy::unnecessary_debug_formatting619 .collect::<Vec<_>>()620 .join(" "),621 issues: &report.execution.issues,622 packages: report623 .project624 .packages625 .iter()626 .filter(|p| p.workspace_member)627 .map(|p| PackageRow {628 name: p.name.clone(),629 observed: if report.execution.observed_packages.contains(&p.id) {630 "Yes"631 } else {632 "Not observed; not inferred from warnings"633 },634 })635 .collect(),636 targets: report637 .execution638 .observed_targets639 .iter()640 .map(target_label)641 .collect(),642 lints,643 files,644 stderr: &report.execution.stderr,645 stderr_truncated: report.execution.stderr_truncated,646 stdout: &report.execution.text_stdout,647 stdout_truncated: report.execution.stdout_truncated,648 };649 let mut sidebar = vec![650 Link {651 href: "#packages".into(),652 text: "Workspace packages".into(),653 },654 Link {655 href: "#lints".into(),656 text: "Diagnostic kinds".into(),657 },658 ];659 if !index.categories.is_empty() {660 sidebar.push(Link {661 href: "#categories".into(),662 text: "Categories".into(),663 });664 }665 sidebar.push(Link {666 href: "#files".into(),667 text: "Source files".into(),668 });669 write_page(670 destination,671 index_path,672 Page {673 title: &index.workspace,674 section: "Overview",675 root: String::new(),676 sidebar,677 content: render(&index)?,678 crate_context: crate_context(report, &[]),679 crates: crate_infos(report, &[]),680 heading_kind: "Report",681 source_page: false,682 standalone_page: false,683 generator_version: env!("CARGO_PKG_VERSION"),684 source_tree: String::new(),685 },686 )?;687 write_page(688 destination,689 Path::new("licenses/index.html"),690 Page {691 title: "Licenses and third-party notices",692 section: "Licenses",693 root: "../".into(),694 sidebar: vec![695 Link {696 href: "#fonts".into(),697 text: "Fonts".into(),698 },699 Link {700 href: "#styles".into(),701 text: "Styles and notices".into(),702 },703 ],704 content: render(&Licenses)?,705 crate_context: crate_context(report, &[]),706 crates: crate_infos(report, &[]),707 heading_kind: "Report",708 source_page: false,709 standalone_page: false,710 generator_version: env!("CARGO_PKG_VERSION"),711 source_tree: String::new(),712 },713 )?;714 write_page(715 destination,716 Path::new("help.html"),717 Page {718 title: "Clippy HTML help",719 section: "Help",720 root: String::new(),721 sidebar: vec![],722 content: render(&Help {723 generator_version: env!("CARGO_PKG_VERSION"),724 })?,725 crate_context: crate_context(report, &[]),726 crates: crate_infos(report, &[]),727 heading_kind: "Report",728 source_page: false,729 standalone_page: true,730 generator_version: env!("CARGO_PKG_VERSION"),731 source_tree: String::new(),732 },733 )?;734 write_page(735 destination,736 Path::new("settings.html"),737 Page {738 title: "Clippy HTML settings",739 section: "Settings",740 root: String::new(),741 sidebar: vec![],742 content: render(&Settings)?,743 crate_context: crate_context(report, &[]),744 crates: crate_infos(report, &[]),745 heading_kind: "",746 source_page: false,747 standalone_page: true,748 generator_version: env!("CARGO_PKG_VERSION"),749 source_tree: String::new(),750 },751 )?;752 for (key, fs) in &groups {753 let path = &pages.lint_pages[key];754 let title = fs[0].code.as_deref().unwrap_or("General diagnostics");755 let sidebar = fs756 .iter()757 .map(|f| Link {758 href: format!("#finding-{}", f.id),759 text: format!(760 "{} · {}",761 f.level,762 f.spans763 .first()764 .map_or("No source location".into(), |s| format!(765 "{}:{}",766 sources[&s.path].display_path, s.line_start767 ))768 ),769 })770 .collect();771 write_page(772 destination,773 path,774 Page {775 title,776 section: "Occurrences",777 root: relative_href(path, Path::new(""), None),778 sidebar,779 content: render(&Lint {780 findings: views(781 fs,782 path,783 sources,784 pages,785 &report.project.packages,786 &report.project.workspace_root,787 ),788 })?,789 crate_context: crate_context(report, fs),790 crates: crate_infos(report, fs),791 heading_kind: "Lint",792 source_page: false,793 standalone_page: false,794 generator_version: env!("CARGO_PKG_VERSION"),795 source_tree: String::new(),796 },797 )?;798 }799 categories::write(report, pages, destination)?;800 let source_counts = super::navigation::source_counts(&report.findings);801 for (key, source) in sources {802 let path = &pages.source_pages[key];803 let fs: Vec<_> = report804 .findings805 .iter()806 .filter(|f| all_spans(f).iter().any(|s| &s.path == key))807 .collect();808 let rows = source_rows(source, key, path, &fs, pages, &span_matches);809 let mut content = render(&SourceView {810 reason: source.reason.clone().unwrap_or_default(),811 digits: rows.len().max(1).to_string().len(),812 rows,813 })?;814 content.push_str(&render(&Lint {815 findings: views(816 &fs,817 path,818 sources,819 pages,820 &report.project.packages,821 &report.project.workspace_root,822 ),823 })?);824 let sidebar = fs825 .iter()826 .map(|f| {827 let spans = display_spans(f);828 let span = spans829 .iter()830 .find(|s| s.path == *key && s.primary)831 .or_else(|| spans.iter().find(|s| s.path == *key));832 let href = span.filter(|s| span_matches(source, s)).map_or_else(833 || format!("#finding-{}", f.id),834 |s| format!("#L{}", s.line_start),835 );836 Link {837 href,838 text: format!(839 "{} · {}{}",840 f.level,841 f.code.as_deref().unwrap_or("diagnostic"),842 span.map_or_else(String::new, |s| format!(843 " · {}:{}",844 s.line_start, s.column_start845 ))846 ),847 }848 })849 .collect();850 write_page(851 destination,852 path,853 Page {854 title: &source.display_path,855 section: "File findings",856 root: relative_href(path, Path::new(""), None),857 sidebar,858 content,859 crate_context: crate_context(report, &fs),860 crates: crate_infos(report, &fs),861 heading_kind: "Source",862 source_page: true,863 standalone_page: false,864 generator_version: env!("CARGO_PKG_VERSION"),865 source_tree: super::navigation::source_tree(866 sources,867 pages,868 &source_counts,869 &report.project.workspace_root,870 key,871 path,872 )?,873 },874 )?;875 }876 Ok(())877}878879// Only inspect generated, double-quoted attributes. All variable text has already880// been escaped by Askama; HTML parser tests independently check this assumption.881fn attributes<'a>(html: &'a str, name: &str) -> Vec<&'a str> {882 let pattern = format!(" {name}=\"");883 html.split(&pattern)884 .skip(1)885 .filter_map(|s| s.split('"').next())886 .collect()887}888pub fn validate_report(destination: &Path) -> Result<(), String> {889 let root = destination.canonicalize().map_err(|e| e.to_string())?;890 let mut docs = BTreeMap::new();891 let mut directories = vec![root.clone()];892 while let Some(dir) = directories.pop() {893 for entry in std::fs::read_dir(dir).map_err(|e| e.to_string())? {894 let path = entry.map_err(|e| e.to_string())?.path();895 if path.is_dir() {896 directories.push(path);897 } else if path.extension().is_some_and(|x| x == "html") {898 let html = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;899 let ids = attributes(&html, "id");900 let unique: std::collections::BTreeSet<_> = ids.iter().collect();901 if ids.len() != unique.len() {902 return Err(format!("Duplicate anchor in {}", path.display()));903 }904 docs.insert(path, html);905 }906 }907 }908 if !docs.contains_key(&root.join("index.html")) {909 return Err("Missing report index".into());910 }911 for (path, html) in &docs {912 let base = url::Url::from_file_path(path).map_err(|_| "Invalid report URL")?; warning: clippy::ignored_unit_patterns913 let search_hrefs = if path == &root.join("index.html") {914 super::search::read_hrefs(&root)?915 } else {916 vec![]917 };918 let references = attributes(html, "href")919 .into_iter()920 .map(|s| (s, true))921 .chain(attributes(html, "src").into_iter().map(|s| (s, false)))922 .chain(search_hrefs.iter().map(|s| (s.as_str(), false)));923 for (href, external_allowed) in references {924 if external_allowed && href.starts_with("https://") {925 continue;926 }927 let linked = base.join(href).map_err(|e| e.to_string())?;928 let target = linked929 .to_file_path()930 .map_err(|_| "Nonlocal internal link")? warning: clippy::ignored_unit_patterns931 .canonicalize()932 .map_err(|e| format!("Broken report link {href}: {e}"))?;933 if !target.starts_with(&root) || !target.is_file() {934 return Err(format!("Broken report link: {href}"));935 }936 if let Some(id) = linked.fragment() {937 let content = docs.get(&target).ok_or("Anchor target is not HTML")?;938 if !attributes(content, "id").contains(&id) {939 return Err(format!("Missing anchor: {href}"));940 }941 }942 }943 }944 super::assets::validate_font_resources(&root)945}946#[cfg(test)]947mod tests {948 use super::*;949 fn positioned_finding(text: &str, positions: &[(usize, usize, usize, usize, bool)]) -> Finding {950 let cargo_metadata::Message::CompilerMessage(message) =951 serde_json::from_value(crate::diagnostic::sample()).unwrap()952 else {953 panic!()954 };955 let mut finding = crate::diagnostic::normalize::normalize(&message, Path::new("/demo"));956 finding.id = "range-test".into();957 let original = finding.spans[0].clone();958 let lines: Vec<_> = text.split('\n').collect();959 let offset = |line: usize, column: usize| {960 lines961 .iter()962 .take(line - 1)963 .map(|s| s.len() + 1)964 .sum::<usize>()965 + lines[line - 1]966 .trim_end_matches('\r')967 .char_indices()968 .nth(column - 1)969 .map_or(lines[line - 1].trim_end_matches('\r').len(), |(i, _)| i)970 };971 finding.spans = positions972 .iter()973 .map(974 |&(line_start, column_start, line_end, column_end, primary)| {975 let mut span = original.clone();976 span.line_start = line_start;977 span.line_end = line_end;978 span.column_start = column_start;979 span.column_end = column_end;980 span.byte_start = offset(line_start, column_start);981 span.byte_end = offset(line_end, column_end);982 span.primary = primary;983 span.text = lines[line_start - 1..line_end]984 .iter()985 .map(|s| SnippetLine {986 text: s.trim_end_matches('\r').into(),987 highlight_start: 1,988 highlight_end: 1,989 })990 .collect();991 span992 },993 )994 .collect();995 finding.children.clear();996 finding.suggestions.clear();997 finding998 }999 #[test]1000 fn source_ranges_project_multiline_crlf_unicode_tabs_and_eof() {1001 let text = "\t한글 + value\r\nnext(\"<&>\");\r\n";1002 let finding = positioned_finding(1003 text,1004 &[(1, 2, 2, 1, true), (2, 1, 2, 5, false), (3, 1, 3, 1, true)],1005 );1006 let key = &finding.spans[0].path;1007 let source = SourceFile {1008 display_path: "a.rs".into(),1009 text: Some(text.into()),1010 reason: None,1011 };1012 let pages = PageMap {1013 category_pages: BTreeMap::new(),1014 source_pages: BTreeMap::new(),1015 lint_pages: BTreeMap::from([(group_key(&finding), "lint/a.html".into())]),1016 };1017 let rows = source_rows(1018 &source,1019 key,1020 Path::new("src/a.rs.html"),1021 &[&finding],1022 &pages,1023 &span_matches,1024 );1025 let primary: String = rows[0]1026 .fragments1027 .iter()1028 .filter(|f| f.class.contains("primary"))1029 .map(|f| f.text.as_str())1030 .collect();1031 assert_eq!(primary, "한글 + value");1032 assert!(1033 !rows[1]1034 .fragments1035 .iter()1036 .any(|f| f.class.contains("primary")),1037 "end is exclusive at next-line column 1"1038 );1039 assert_eq!(1040 rows[1]1041 .fragments1042 .iter()1043 .filter(|f| f.class.contains("secondary"))1044 .map(|f| f.text.as_str())1045 .collect::<String>(),1046 "next"1047 );1048 assert_eq!(rows[2].fragments.iter().filter(|f| f.insertion).count(), 1);1049 assert_eq!(1050 rows.iter()1051 .map(|r| r1052 .fragments1053 .iter()1054 .map(|f| f.text.as_str())1055 .collect::<String>())1056 .collect::<Vec<_>>()1057 .join("\n"),1058 text.replace("\r\n", "\n")1059 );1060 assert!(rows.iter().all(|r| r.links.len() == 1));1061 }1062 #[test]1063 fn range_background_omits_layout_indent_but_preserves_whitespace_targets_and_literals() {1064 fn marked(text: &str, positions: &[(usize, usize, usize, usize, bool)]) -> Vec<String> {1065 let finding = positioned_finding(text, positions);1066 let source = SourceFile {1067 display_path: "a.rs".into(),1068 text: Some(text.into()),1069 reason: None,1070 };1071 let pages = PageMap {1072 category_pages: BTreeMap::new(),1073 source_pages: BTreeMap::new(),1074 lint_pages: BTreeMap::from([(group_key(&finding), "lint/a.html".into())]),1075 };1076 let rows = source_rows(1077 &source,1078 &finding.spans[0].path,1079 Path::new("src/a.rs.html"),1080 &[&finding],1081 &pages,1082 &span_matches,1083 );1084 assert_eq!(1085 rows.iter()1086 .map(|r| r1087 .fragments1088 .iter()1089 .map(|f| f.text.as_str())1090 .collect::<String>())1091 .collect::<Vec<_>>()1092 .join("\n"),1093 text.replace("\r\n", "\n")1094 );1095 rows.iter()1096 .map(|r| {1097 r.fragments1098 .iter()1099 .filter(|f| f.class.contains("primary"))1100 .map(|f| f.text.as_str())1101 .collect()1102 })1103 .collect()1104 }1105 assert_eq!(1106 marked("\t 한글\r\n next", &[(1, 1, 2, 9, true)]),1107 ["한글", "next"]1108 );1109 assert_eq!(marked("\t value", &[(1, 1, 1, 4, true)]), ["\t "]);1110 assert_eq!(1111 marked(1112 "let s = r#\"first\n literal\nlast\"#;",1113 &[(2, 1, 2, 10, true)]1114 ),1115 ["", " literal", ""]1116 );1117 assert_eq!(1118 marked("/* first\n comment\n*/", &[(2, 1, 2, 10, true)]),1119 ["", " comment", ""]1120 );1121 }1122 #[test]1123 fn repeated_location_promotes_primary_and_keeps_labels() {1124 let mut finding = positioned_finding("value", &[(1, 1, 1, 6, false), (1, 1, 1, 6, true)]);1125 finding.spans[0].label = Some("related".into());1126 finding.spans[1].label = Some("problem".into());1127 let spans = display_spans(&finding);1128 assert_eq!(spans.len(), 1);1129 assert!(spans[0].primary);1130 assert_eq!(spans[0].label.as_deref(), Some("related; problem"));1131 }1132 #[test]1133 fn changed_source_keeps_snippet_fallback_without_precise_annotations() {1134 let finding = positioned_finding("before", &[(1, 1, 1, 4, true)]);1135 let key = &finding.spans[0].path;1136 let source = SourceFile {1137 display_path: "a.rs".into(),1138 text: Some("after!".into()),1139 reason: None,1140 };1141 let pages = PageMap {1142 category_pages: BTreeMap::new(),1143 source_pages: BTreeMap::from([(key.clone(), "src/a.rs.html".into())]),1144 lint_pages: BTreeMap::from([(group_key(&finding), "lint/a.html".into())]),1145 };1146 let rows = source_rows(1147 &source,1148 key,1149 Path::new("src/a.rs.html"),1150 &[&finding],1151 &pages,1152 &span_matches,1153 );1154 assert!(1155 rows.iter()1156 .all(|r| !r.marked && r.fragments.iter().all(|f| f.title.is_empty()))1157 );1158 let sources = BTreeMap::from([(key.clone(), source)]);1159 let rendered = views(1160 &[&finding],1161 Path::new("lint/a.html"),1162 &sources,1163 &pages,1164 &[],1165 Path::new("/workspace"),1166 );1167 assert!(1168 rendered[0].locations[0]1169 .href1170 .ends_with("#finding-range-test")1171 );1172 assert!(1173 rendered[0].locations[0]1174 .note1175 .contains("source unavailable or changed")1176 );1177 assert_eq!(rendered[0].locations[0].snippet, "before");1178 }1179 #[test]1180 fn precise_range_markup_preserves_escaped_source_and_caret_labels() {1181 let text = "<script>한글";1182 let ranges = [1183 super::super::ranges::Range {1184 start: 0,1185 end: 8,1186 primary: true,1187 title: "Primary: <img onerror=bad>".into(),1188 },1189 super::super::ranges::Range {1190 start: 8,1191 end: text.len(),1192 primary: false,1193 title: "Secondary: related".into(),1194 },1195 super::super::ranges::Range {1196 start: text.len(),1197 end: text.len(),1198 primary: true,1199 title: "Primary: insert".into(),1200 },1201 ];1202 let fragments =1203 super::super::ranges::annotate(super::super::highlight::lines(text).remove(0), &ranges);1204 let html = render(&SourceView {1205 reason: String::new(),1206 digits: 1,1207 rows: vec![SourceRow {1208 number: 1,1209 fragments,1210 marked: true,1211 links: vec![],1212 }],1213 })1214 .unwrap();1215 let doc = scraper::Html::parse_fragment(&html);1216 let select = |s| scraper::Selector::parse(s).unwrap();1217 assert_eq!(1218 doc.select(&select(".line-text"))1219 .next()1220 .unwrap()1221 .text()1222 .collect::<String>(),1223 text1224 );1225 assert_eq!(doc.select(&select("script,img,[onerror]")).count(), 0);1226 assert_eq!(1227 doc.select(&select(".diagnostic-span.primary:not(.insertion)"))1228 .flat_map(|e| e.text())1229 .collect::<String>(),1230 "<script>"1231 );1232 assert_eq!(1233 doc.select(&select(".diagnostic-span.secondary"))1234 .flat_map(|e| e.text())1235 .collect::<String>(),1236 "한글"1237 );1238 let caret = doc.select(&select(".insertion[role=img]")).next().unwrap();1239 assert_eq!(caret.value().attr("aria-label"), Some("Primary: insert"));1240 assert_eq!(caret.value().attr("title"), None);1241 assert_eq!(doc.select(&select(".range-legend")).count(), 0);1242 }1243 #[test]1244 fn missing_or_nonlocal_search_scripts_are_rejected() {1245 let t = tempfile::tempdir().unwrap();1246 for src in [1247 "static.files/missing.js",1248 "https://example.com/search.js",1249 "../outside.js",1250 ] {1251 std::fs::write(1252 t.path().join("index.html"),1253 format!("<script src=\"{src}\"></script>"),1254 )1255 .unwrap();1256 assert!(validate_report(t.path()).is_err(), "must reject {src}");1257 }1258 }1259 #[test]1260 fn missing_search_destination_anchor_is_rejected() {1261 let t = tempfile::tempdir().unwrap();1262 std::fs::create_dir(t.path().join("static.files")).unwrap();1263 std::fs::write(1264 t.path().join("index.html"),1265 "<h1 id=\"existing\">Report</h1>",1266 )1267 .unwrap();1268 std::fs::write(t.path().join("static.files/search-index.js"),1269 "globalThis.CLIPPY_HTML_SEARCH_DATA=[{\"kind\":\"finding\",\"name\":\"message\",\"context\":\"\",\"description\":\"\",\"href\":\"index.html#absent\"}];\n").unwrap();1270 assert!(validate_report(t.path()).is_err());1271 }1272 #[test]1273 fn missing_css_font_resource_is_rejected() {1274 let t = tempfile::tempdir().unwrap();1275 std::fs::create_dir(t.path().join("static.files")).unwrap();1276 std::fs::write(1277 t.path().join("index.html"),1278 "<link href=\"static.files/fonts.css\">",1279 )1280 .unwrap();1281 std::fs::write(1282 t.path().join("static.files/fonts.css"),1283 "@font-face { src: url(\"missing.woff2\"); }",1284 )1285 .unwrap();1286 assert!(1287 validate_report(t.path()).is_err(),1288 "a report with missing font resources cannot be published"1289 );1290 }1291 #[test]1292 fn nonlocal_css_font_resources_are_rejected() {1293 let t = tempfile::tempdir().unwrap();1294 let root = t.path().join("report");1295 std::fs::create_dir_all(root.join("static.files")).unwrap();1296 std::fs::write(1297 root.join("index.html"),1298 "<link href=\"static.files/fonts.css\">",1299 )1300 .unwrap();1301 std::fs::write(t.path().join("outside.woff2"), b"wOF2").unwrap();1302 for reference in [1303 "../../outside.woff2",1304 "https://example.com/font.woff2",1305 "data:font/woff2;base64,d09GMg==",1306 ] {1307 std::fs::write(1308 root.join("static.files/fonts.css"),1309 format!("@font-face {{ src: url(\"{reference}\"); }}"),1310 )1311 .unwrap();1312 assert!(1313 validate_report(&root).is_err(),1314 "font resources must stay inside the report: {reference}"1315 );1316 }1317 }1318 #[test]1319 fn validates_links_inside_nested_source_pages() {1320 let t = tempfile::tempdir().unwrap();1321 std::fs::create_dir_all(t.path().join("src/one/src")).unwrap();1322 std::fs::write(t.path().join("index.html"), "<h1>Report</h1>").unwrap();1323 std::fs::write(1324 t.path().join("src/one/src/lib.rs.html"),1325 "<a href=\"#missing\">broken</a>",1326 )1327 .unwrap();1328 assert!(1329 validate_report(t.path())1330 .unwrap_err()1331 .contains("Missing anchor")1332 );1333 }1334 #[test]1335 fn diagnostic_document_links_keep_version_and_reject_unsafe_schemes() {1336 let make_note = |text: &str| Note {1337 level: "help".into(),1338 message: format!("for further information visit {text}"),1339 spans: vec![],1340 children: vec![],1341 };1342 let url = "https://rust-lang.github.io/rust-clippy/rust-1.97.0/index.html#clone_on_copy";1343 assert_eq!(note_view(&make_note(url)).link.unwrap().href, url);1344 for text in [1345 "javascript:alert(1)",1346 "file:///C:/secret.txt",1347 "https://user:password@example.com/",1348 "not a URL",1349 ] {1350 let note = make_note(text);1351 let view = note_view(¬e);1352 assert!(view.link.is_none());1353 assert_eq!(view.message, note.message);1354 }1355 }1356 #[test]1357 fn long_source_validates_each_span_once_and_marks_the_right_row() {1358 let cargo_metadata::Message::CompilerMessage(m) =1359 serde_json::from_value(crate::diagnostic::sample()).unwrap()1360 else {1361 panic!()1362 };1363 let mut f = crate::diagnostic::normalize::normalize(&m, Path::new("/demo"));1364 f.id = "one".into();1365 let source = SourceFile {1366 display_path: "src/lib.rs".into(),1367 text: Some("abc\n".repeat(1000)),1368 reason: None,1369 };1370 let pages = PageMap {1371 category_pages: BTreeMap::new(),1372 lint_pages: BTreeMap::from([(group_key(&f), PathBuf::from("lint/a.html"))]),1373 source_pages: BTreeMap::new(),1374 };1375 let calls = std::cell::Cell::new(0);1376 let rows = source_rows(1377 &source,1378 &f.spans[0].path,1379 Path::new("src/a.html"),1380 &[&f],1381 &pages,1382 &|src, span| {1383 calls.set(calls.get() + 1);1384 span_matches(src, span)1385 },1386 );1387 assert_eq!(rows.len(), 1001);1388 assert!(rows[0].marked);1389 assert_eq!(rows.iter().filter(|r| r.marked).count(), 1);1390 assert_eq!(1391 calls.get(),1392 1,1393 "source validation must not rescan the file for every output row"1394 );1395 }1396 #[test]1397 fn repeated_child_and_replacement_locations_are_presented_once() {1398 let mut raw = crate::diagnostic::sample();1399 let mut span = raw["message"]["spans"][0].clone();1400 span["suggested_replacement"] = "fixed".into();1401 span["suggestion_applicability"] = "MachineApplicable".into();1402 raw["message"]["children"] = serde_json::json!([{"level":"help","message":"replace it","spans":[span],"children":[],"code":null,"rendered":null}]);1403 let cargo_metadata::Message::CompilerMessage(m) = serde_json::from_value(raw).unwrap()1404 else {1405 panic!()1406 };1407 let f = crate::diagnostic::normalize::normalize(&m, Path::new("/demo"));1408 let sources = BTreeMap::from([(1409 f.spans[0].path.clone(),1410 SourceFile {1411 display_path: "src/lib.rs".into(),1412 text: None,1413 reason: Some("unavailable".into()),1414 },1415 )]);1416 let pages = PageMap {1417 category_pages: BTreeMap::new(),1418 lint_pages: BTreeMap::new(),1419 source_pages: BTreeMap::from([(f.spans[0].path.clone(), PathBuf::from("src/a.html"))]),1420 };1421 let result = views(1422 &[&f],1423 Path::new("lint/a.html"),1424 &sources,1425 &pages,1426 &[],1427 Path::new("/workspace"),1428 );1429 assert_eq!(result[0].locations.len(), 1);1430 assert_eq!(result[0].notes.len(), 1);1431 assert_eq!(result[0].suggestions.len(), 1);1432 assert_eq!(result[0].suggestions[0].replacements.len(), 1);1433 }1434 #[test]1435 fn empty_report_has_success_status_and_valid_license_links() {1436 let t = tempfile::tempdir().unwrap();1437 let report = Report {1438 category_metadata: None,1439 project: ProjectInfo {1440 workspace_root: PathBuf::from("/demo"),1441 target_dir: PathBuf::from("/demo/target"),1442 build_dir: None,1443 packages: vec![],1444 },1445 execution: Execution {1446 code: Some(0),1447 complete: true,1448 requested_args: vec![],1449 observed_packages: vec![],1450 observed_targets: vec![],1451 stderr: String::new(),1452 stderr_truncated: false,1453 text_stdout: String::new(),1454 stdout_truncated: false,1455 issues: vec![],1456 },1457 raw_count: 0,1458 findings: vec![],1459 };1460 let sources = BTreeMap::new();1461 let pages = super::super::paths::build_page_map(&report, &sources);1462 render_report(&report, &sources, &pages, t.path()).unwrap();1463 validate_report(t.path()).unwrap();1464 assert!(1465 std::fs::read_to_string(t.path().join("index.html"))1466 .unwrap()1467 .contains("Succeeded")1468 );1469 let doc = scraper::Html::parse_document(1470 &std::fs::read_to_string(t.path().join("index.html")).unwrap(),1471 );1472 assert_eq!(1473 doc.select(1474 &scraper::Selector::parse(1475 "main > .width-limiter > section#main-content > .main-heading"1476 )1477 .unwrap()1478 )1479 .count(),1480 11481 );1482 std::fs::remove_file(t.path().join("licenses/Fira-LICENSE.txt")).unwrap();1483 assert!(1484 validate_report(t.path())1485 .unwrap_err()1486 .contains("Fira-LICENSE.txt")1487 );1488 }1489 #[test]1490 fn hostile_text_and_multiple_findings_have_safe_unique_anchors() {1491 let t = tempfile::tempdir().unwrap();1492 let cargo_metadata::Message::CompilerMessage(m) =1493 serde_json::from_value(crate::diagnostic::sample()).unwrap()1494 else {1495 panic!()1496 };1497 let mut f = crate::diagnostic::normalize::normalize(&m, Path::new("/demo"));1498 f.message = "<script>alert('bad')</script> & \"quoted\"".into();1499 f.spans[0].path = PathBuf::from("/demo/src/<script>&#.rs");1500 let mut second = f.clone();1501 second.level = "error".into();1502 second.spans.push(second.spans[0].clone());1503 let report = Report {1504 category_metadata: None,1505 project: ProjectInfo {1506 workspace_root: PathBuf::from("/demo"),1507 target_dir: PathBuf::from("/demo/target"),1508 build_dir: None,1509 packages: vec![],1510 },1511 execution: Execution {1512 code: Some(101),1513 complete: true,1514 requested_args: vec![],1515 observed_packages: vec![],1516 observed_targets: vec![],1517 stderr: String::new(),1518 stderr_truncated: false,1519 text_stdout: String::new(),1520 stdout_truncated: false,1521 issues: vec![],1522 },1523 raw_count: 2,1524 findings: crate::diagnostic::dedup::merge_findings(vec![f, second]),1525 };1526 let sources = crate::source::load_sources(&report.project, &report.findings);1527 let pages = super::super::paths::build_page_map(&report, &sources);1528 render_report(&report, &sources, &pages, t.path()).unwrap();1529 validate_report(t.path()).unwrap();1530 let html =1531 std::fs::read_to_string(t.path().join(pages.lint_pages.values().next().unwrap()))1532 .unwrap();1533 let doc = scraper::Html::parse_document(&html);1534 assert_eq!(1535 doc.select(&scraper::Selector::parse("script:not([src]),[onclick],[onerror]").unwrap())1536 .count(),1537 01538 );1539 assert_eq!(1540 doc.select(&scraper::Selector::parse(".finding").unwrap())1541 .count(),1542 21543 );1544 assert!(1545 doc.root_element()1546 .text()1547 .collect::<String>()1548 .contains("<script>alert('bad')</script>")1549 );1550 let source =1551 std::fs::read_to_string(t.path().join(pages.source_pages.values().next().unwrap()))1552 .unwrap();1553 let doc = scraper::Html::parse_document(&source);1554 assert_eq!(1555 doc.select(&scraper::Selector::parse("script:not([src]),[onclick],[onerror]").unwrap())1556 .count(),1557 01558 );1559 let active = doc1560 .select(&scraper::Selector::parse(".source-tree [aria-current=\"page\"]").unwrap())1561 .next()1562 .unwrap();1563 assert!(active.text().collect::<String>().contains("<script>&#.rs"));1564 }1565}1566Findings in this file§
warning clippy::wildcard_imports §
warning clippy::wildcard_imports §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:6:13
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#wildcard_imports
help: try
Suggestion: try
--- "a/src/render/pages.rs"
+++ "b/src/render/pages.rs"
@@ -3,7 +3,7 @@
use super::paths::PageMap;
use super::paths::{group_key, relative_href};
use crate::source::{all_spans, span_matches};
-use crate::{diagnostic::model::*, source::SourceFile};
+use crate::{diagnostic::model::{Report, Finding, CategoryMetadata, Note, Span, TargetInfo, PackageInfo}, source::SourceFile};
use askama::Template;
use std::{
collections::BTreeMap,
Rendered diagnostic (text)
warning: usage of wildcard import
--> src/render/pages.rs:6:13
|
6 | use crate::{diagnostic::model::*, source::SourceFile};
| ^^^^^^^^^^^^^^^^^^^^ help: try: `diagnostic::model::{Report, Finding, CategoryMetadata, Note, Span, TargetInfo, PackageInfo}`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#wildcard_imports
warning clippy::struct_field_names §
warning clippy::struct_field_names §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:39:5
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#struct_field_names
note: `-W clippy::struct-field-names` implied by `-W clippy::pedantic`
help: to override `-W clippy::pedantic` add `#[allow(clippy::struct_field_names)]`
Rendered diagnostic (text)
warning: field name ends with the struct's name --> src/render/pages.rs:39:5 | 39 | source_page: bool, | ^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#struct_field_names = note: `-W clippy::struct-field-names` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::struct_field_names)]`
warning clippy::struct_field_names §
warning clippy::struct_field_names §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:40:5
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: field name ends with the struct's name --> src/render/pages.rs:40:5 | 40 | standalone_page: bool, | ^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#struct_field_names
warning clippy::too_many_lines §
warning clippy::too_many_lines §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:172:1
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
Rendered diagnostic (text)
warning: this function has too many lines (103/100)
--> src/render/pages.rs:172:1
|
172 | / fn source_rows(
173 | | source: &SourceFile,
174 | | key: &Path,
175 | | path: &Path,
... |
178 | | validate: &impl Fn(&SourceFile, &Span) -> bool,
179 | | ) -> Vec<SourceRow> {
| |___________________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
warning clippy::needless_pass_by_value §
warning clippy::needless_pass_by_value §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:289:54
Primary: src/render/pages.rs:289:54
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#needless_pass_by_value
help: consider taking a reference instead
Suggestion: consider taking a reference instead
--- "a/src/render/pages.rs"
+++ "b/src/render/pages.rs"
@@ -286,7 +286,7 @@
fn render(t: &impl Template) -> Result<String, String> {
t.render().map_err(|e| e.to_string())
}
-fn write_page(destination: &Path, path: &Path, page: Page<'_>) -> Result<(), String> {
+fn write_page(destination: &Path, path: &Path, page: &Page<'_>) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(destination.join(parent)).map_err(|e| e.to_string())?;
}
Rendered diagnostic (text)
warning: this argument is passed by value, but not consumed in the function body
--> src/render/pages.rs:289:54
|
289 | fn write_page(destination: &Path, path: &Path, page: Page<'_>) -> Result<(), String> {
| ^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#needless_pass_by_value
help: consider taking a reference instead
|
289 | fn write_page(destination: &Path, path: &Path, page: &Page<'_>) -> Result<(), String> {
| +
warning clippy::too_many_lines §
warning clippy::too_many_lines §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:354:1
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
Rendered diagnostic (text)
warning: this function has too many lines (166/100)
--> src/render/pages.rs:354:1
|
354 | / fn views(
355 | | findings: &[&Finding],
356 | | from: &Path,
357 | | sources: &BTreeMap<PathBuf, SourceFile>,
... |
360 | | workspace_root: &Path,
361 | | ) -> Vec<FindingView> {
| |_____________________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
warning clippy::too_many_lines §
warning clippy::too_many_lines §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:529:1
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
Rendered diagnostic (text)
warning: this function has too many lines (342/100)
--> src/render/pages.rs:529:1
|
529 | / pub fn render_report(
530 | | report: &Report,
531 | | sources: &BTreeMap<PathBuf, SourceFile>,
532 | | pages: &PageMap,
533 | | destination: &Path,
534 | | ) -> Result<(), String> {
| |_______________________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#too_many_lines
warning clippy::unnecessary_debug_formatting §
warning clippy::unnecessary_debug_formatting §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:618:32
help: use `Display` formatting and change this to `a.display()`
note: switching to `Display` formatting will change how the value is shown; escaped characters will no longer be escaped and surrounding quotes will be removed
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#unnecessary_debug_formatting
note: `-W clippy::unnecessary-debug-formatting` implied by `-W clippy::pedantic`
help: to override `-W clippy::pedantic` add `#[allow(clippy::unnecessary_debug_formatting)]`
Rendered diagnostic (text)
warning: unnecessary `Debug` formatting in `format!` args
--> src/render/pages.rs:618:32
|
618 | .map(|a| format!("{a:?}"))
| ^
|
= help: use `Display` formatting and change this to `a.display()`
= note: switching to `Display` formatting will change how the value is shown; escaped characters will no longer be escaped and surrounding quotes will be removed
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#unnecessary_debug_formatting
= note: `-W clippy::unnecessary-debug-formatting` implied by `-W clippy::pedantic`
= help: to override `-W clippy::pedantic` add `#[allow(clippy::unnecessary_debug_formatting)]`
warning clippy::ignored_unit_patterns §
warning clippy::ignored_unit_patterns §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:912:60
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#ignored_unit_patterns
help: use `()` instead of `_`
Suggestion: use `()` instead of `_`
--- "a/src/render/pages.rs"
+++ "b/src/render/pages.rs"
@@ -909,7 +909,7 @@
return Err("Missing report index".into());
}
for (path, html) in &docs {
- let base = url::Url::from_file_path(path).map_err(|_| "Invalid report URL")?;
+ let base = url::Url::from_file_path(path).map_err(|()| "Invalid report URL")?;
let search_hrefs = if path == &root.join("index.html") {
super::search::read_hrefs(&root)?
} else {
Rendered diagnostic (text)
warning: matching over `()` is more explicit
--> src/render/pages.rs:912:60
|
912 | let base = url::Url::from_file_path(path).map_err(|_| "Invalid report URL")?;
| ^ help: use `()` instead of `_`: `()`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#ignored_unit_patterns
warning clippy::ignored_unit_patterns §
warning clippy::ignored_unit_patterns §
Targets (1)
cargo-clippy-html (bin)
Primary: src/render/pages.rs:930:27
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#ignored_unit_patterns
help: use `()` instead of `_`
Suggestion: use `()` instead of `_`
--- "a/src/render/pages.rs"
+++ "b/src/render/pages.rs"
@@ -927,7 +927,7 @@
let linked = base.join(href).map_err(|e| e.to_string())?;
let target = linked
.to_file_path()
- .map_err(|_| "Nonlocal internal link")?
+ .map_err(|()| "Nonlocal internal link")?
.canonicalize()
.map_err(|e| format!("Broken report link {href}: {e}"))?;
if !target.starts_with(&root) || !target.is_file() {
Rendered diagnostic (text)
warning: matching over `()` is more explicit
--> src/render/pages.rs:930:27
|
930 | .map_err(|_| "Nonlocal internal link")?
| ^ help: use `()` instead of `_`: `()`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#ignored_unit_patterns