Skip to main content

Source src/render/search.rs

1//! Build a report-local classic-script index from existing pages and diagnostics.2use super::paths::{PageMap, category_key, group_key, relative_href};3use crate::{diagnostic::model::*, source::SourceFile}; warning: clippy::wildcard_imports4use serde::{Deserialize, Serialize};5use std::{6    collections::BTreeMap,7    path::{Path, PathBuf},8};910const PREFIX: &str = "globalThis.CLIPPY_HTML_SEARCH_DATA=";11#[derive(Serialize, Deserialize)]12struct Entry {13    kind: String,14    name: String,15    context: String,16    description: String,17    href: String,18}1920fn notes_text(notes: &[Note], output: &mut String) {21    for note in notes {22        output.push('\n');23        output.push_str(&note.message);24        notes_text(&note.children, output);25    }26}27fn script(entries: &[Entry]) -> Result<String, String> {28    let json = serde_json::to_string(entries).map_err(|e| e.to_string())?;29    let json = json30        .replace('&', "\\u0026")31        .replace('<', "\\u003c")32        .replace('>', "\\u003e")33        .replace('\u{2028}', "\\u2028")34        .replace('\u{2029}', "\\u2029");35    Ok(format!("{PREFIX}{json};\n"))36}37pub(super) fn write_index( warning: clippy::too_many_lines38    report: &Report, warning: clippy::too_many_lines39    sources: &BTreeMap<PathBuf, SourceFile>, warning: clippy::too_many_lines40    pages: &PageMap, warning: clippy::too_many_lines41    destination: &Path, warning: clippy::too_many_lines42) -> Result<(), String> { warning: clippy::too_many_lines43    let from = Path::new("index.html");44    let mut entries = vec![];45    for (key, path) in &pages.lint_pages {46        let findings: Vec<_> = report47            .findings48            .iter()49            .filter(|f| group_key(f) == *key)50            .collect();51        let Some(first) = findings.first() else {52            continue;53        };54        entries.push(Entry {55            kind: "lint".into(),56            name: first57                .code58                .clone()59                .unwrap_or_else(|| "General diagnostics".into()),60            context: first.origin.clone(),61            description: format!("{} findings", findings.len()),62            href: relative_href(from, path, None),63        });64    }65    for (key, path) in &pages.source_pages {66        entries.push(Entry {67            kind: "file".into(),68            name: sources[key].display_path.clone(),69            context: String::new(),70            description: sources[key].reason.clone().unwrap_or_default(),71            href: relative_href(from, path, None),72        });73    }74    for finding in &report.findings {75        let mut context = vec![76            finding77                .code78                .as_deref()79                .unwrap_or("General diagnostics")80                .to_owned(),81            finding.level.clone(),82        ];83        if let Some(package) = report84            .project85            .packages86            .iter()87            .find(|p| p.id == finding.package_id)88        {89            context.push(package.name.clone());90        }91        if let Some(category) = category_key(finding) {92            context.push(category.into());93        }94        if let Some(span) = finding95            .spans96            .iter()97            .find(|s| s.primary)98            .or_else(|| finding.spans.first())99        {100            let name = sources warning: clippy::map_unwrap_or101                .get(&span.path) warning: clippy::map_unwrap_or102                .map(|s| s.display_path.clone()) warning: clippy::map_unwrap_or103                .unwrap_or_else(|| span.path.to_string_lossy().replace('\\', "/")); warning: clippy::map_unwrap_or104            context.push(format!("{name}:{}:{}", span.line_start, span.column_start));105        }106        let mut description = context.join(" · ");107        notes_text(&finding.children, &mut description);108        for suggestion in &finding.suggestions {109            description.push('\n');110            description.push_str(&suggestion.message);111        }112        entries.push(Entry {113            kind: "finding".into(),114            name: finding.message.clone(),115            context: context.join(" "),116            description,117            href: relative_href(118                from,119                &pages.lint_pages[&group_key(finding)],120                Some(&format!("finding-{}", finding.id)),121            ),122        });123    }124    for (key, path) in &pages.category_pages {125        entries.push(Entry {126            kind: "category".into(),127            name: if key == "unknown" {128                "Unknown".into()129            } else {130                key.clone()131            },132            context: String::new(),133            description: format!(134                "{} findings",135                report136                    .findings137                    .iter()138                    .filter(|f| category_key(f) == Some(key.as_str()))139                    .count()140            ),141            href: relative_href(from, path, None),142        });143    }144    std::fs::write(145        destination.join("static.files/search-index.js"),146        script(&entries)?,147    )148    .map_err(|e| e.to_string())149}150pub(super) fn read_hrefs(root: &Path) -> Result<Vec<String>, String> {151    let script = match std::fs::read_to_string(root.join("static.files/search-index.js")) {152        Ok(script) => script,153        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),154        Err(e) => return Err(e.to_string()),155    };156    let json = script157        .strip_prefix(PREFIX)158        .and_then(|s| s.trim_end().strip_suffix(';'))159        .ok_or("Invalid search index script")?;160    let entries: Vec<Entry> = serde_json::from_str(json).map_err(|e| e.to_string())?;161    Ok(entries.into_iter().map(|entry| entry.href).collect())162}163164#[cfg(test)]165mod tests {166    use super::*;167    #[test]168    fn script_roundtrips_untrusted_text_without_html_or_line_separators() {169        let text = "</script><script>alert('x')</script>&\u{2028}\u{2029}한글";170        let encoded = script(&[Entry {171            kind: "finding".into(),172            name: text.into(),173            context: "".into(), warning: clippy::manual_string_new174            description: "".into(), warning: clippy::manual_string_new175            href: "index.html".into(),176        }])177        .unwrap();178        assert!(!encoded.contains(['<', '>', '&', '\u{2028}', '\u{2029}']));179        let entries: Vec<Entry> = serde_json::from_str(180            encoded181                .strip_prefix(PREFIX)182                .unwrap()183                .trim_end()184                .strip_suffix(';')185                .unwrap(),186        )187        .unwrap();188        assert_eq!(entries[0].name, text);189    }190}191

Findings in this file§

warning clippy::wildcard_imports §

usage of wildcard import

src/render/search.rs:3:13

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

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

Primary: src/render/search.rs:3:13

use crate::{diagnostic::model::*, source::SourceFile};

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

help: try

Suggestion: try

MachineApplicable

--- "a/src/render/search.rs"
+++ "b/src/render/search.rs"
@@ -1,6 +1,6 @@
 //! Build a report-local classic-script index from existing pages and diagnostics.
 use super::paths::{PageMap, category_key, group_key, relative_href};
-use crate::{diagnostic::model::*, source::SourceFile};
+use crate::{diagnostic::model::{Note, Report}, source::SourceFile};
 use serde::{Deserialize, Serialize};
 use std::{
     collections::BTreeMap,
Rendered diagnostic (text)
warning: usage of wildcard import
 --> src/render/search.rs:3:13
  |
3 | use crate::{diagnostic::model::*, source::SourceFile};
  |             ^^^^^^^^^^^^^^^^^^^^ help: try: `diagnostic::model::{Note, Report}`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#wildcard_imports

warning clippy::too_many_lines §

this function has too many lines (106/100)

src/render/search.rs:37:1

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

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

Primary: src/render/search.rs:37:1

pub(super) fn write_index(
    report: &Report,
    sources: &BTreeMap<PathBuf, SourceFile>,
    pages: &PageMap,
    destination: &Path,
) -> Result<(), String> {

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 (106/100)
  --> src/render/search.rs:37:1
   |
37 | / pub(super) fn write_index(
38 | |     report: &Report,
39 | |     sources: &BTreeMap<PathBuf, SourceFile>,
40 | |     pages: &PageMap,
41 | |     destination: &Path,
42 | | ) -> 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::map_unwrap_or §

called `map(<f>).unwrap_or_else(<g>)` on an `Option` value

src/render/search.rs:100:24

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

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

Primary: src/render/search.rs:100:24

            let name = sources
                .get(&span.path)
                .map(|s| s.display_path.clone())
                .unwrap_or_else(|| span.path.to_string_lossy().replace('\\', "/"));

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

note: `-W clippy::map-unwrap-or` implied by `-W clippy::pedantic`

help: to override `-W clippy::pedantic` add `#[allow(clippy::map_unwrap_or)]`

help: try

Suggestion: try

MachineApplicable

--- "a/src/render/search.rs"
+++ "b/src/render/search.rs"
@@ -98,9 +98,7 @@
             .or_else(|| finding.spans.first())
         {
             let name = sources
-                .get(&span.path)
-                .map(|s| s.display_path.clone())
-                .unwrap_or_else(|| span.path.to_string_lossy().replace('\\', "/"));
+                .get(&span.path).map_or_else(|| span.path.to_string_lossy().replace('\\', "/"), |s| s.display_path.clone());
             context.push(format!("{name}:{}:{}", span.line_start, span.column_start));
         }
         let mut description = context.join(" · ");
Rendered diagnostic (text)
warning: called `map(<f>).unwrap_or_else(<g>)` on an `Option` value
   --> src/render/search.rs:100:24
    |
100 |               let name = sources
    |  ________________________^
101 | |                 .get(&span.path)
102 | |                 .map(|s| s.display_path.clone())
103 | |                 .unwrap_or_else(|| span.path.to_string_lossy().replace('\\', "/"));
    | |__________________________________________________________________________________^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#map_unwrap_or
    = note: `-W clippy::map-unwrap-or` implied by `-W clippy::pedantic`
    = help: to override `-W clippy::pedantic` add `#[allow(clippy::map_unwrap_or)]`
help: try
    |
100 ~             let name = sources
101 ~                 .get(&span.path).map_or_else(|| span.path.to_string_lossy().replace('\\', "/"), |s| s.display_path.clone());
    |

warning clippy::manual_string_new §

empty String is being created manually

src/render/search.rs:173:22

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

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

Primary: src/render/search.rs:173:22

            context: "".into(),

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

note: `-W clippy::manual-string-new` implied by `-W clippy::pedantic`

help: to override `-W clippy::pedantic` add `#[allow(clippy::manual_string_new)]`

help: consider using

Suggestion: consider using

MachineApplicable

--- "a/src/render/search.rs"
+++ "b/src/render/search.rs"
@@ -170,7 +170,7 @@
         let encoded = script(&[Entry {
             kind: "finding".into(),
             name: text.into(),
-            context: "".into(),
+            context: String::new(),
             description: "".into(),
             href: "index.html".into(),
         }])
Rendered diagnostic (text)
warning: empty String is being created manually
   --> src/render/search.rs:173:22
    |
173 |             context: "".into(),
    |                      ^^^^^^^^^ help: consider using: `String::new()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#manual_string_new
    = note: `-W clippy::manual-string-new` implied by `-W clippy::pedantic`
    = help: to override `-W clippy::pedantic` add `#[allow(clippy::manual_string_new)]`

warning clippy::manual_string_new §

empty String is being created manually

src/render/search.rs:174:26

Clippy · Category: pedantic · cargo-clippy-html

Official Clippy documentation

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

Primary: src/render/search.rs:174:26

            description: "".into(),

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

help: consider using

Suggestion: consider using

MachineApplicable

--- "a/src/render/search.rs"
+++ "b/src/render/search.rs"
@@ -171,7 +171,7 @@
             kind: "finding".into(),
             name: text.into(),
             context: "".into(),
-            description: "".into(),
+            description: String::new(),
             href: "index.html".into(),
         }])
         .unwrap();
Rendered diagnostic (text)
warning: empty String is being created manually
   --> src/render/search.rs:174:26
    |
174 |             description: "".into(),
    |                          ^^^^^^^^^ help: consider using: `String::new()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#manual_string_new