rustdoc/
externalfiles.rs

1use std::path::Path;
2use std::{fs, str};
3
4use rustc_errors::DiagCtxtHandle;
5use rustc_span::edition::Edition;
6use serde::Serialize;
7
8use crate::html::markdown::{ErrorCodes, HeadingOffset, IdMap, Markdown, Playground};
9
10#[derive(Clone, Debug, Serialize)]
11pub(crate) struct ExternalHtml {
12    /// Content that will be included inline in the `<head>` section of a
13    /// rendered Markdown file or generated documentation
14    pub(crate) in_header: String,
15    /// Content that will be included inline between `<body>` and the content of
16    /// a rendered Markdown file or generated documentation
17    pub(crate) before_content: String,
18    /// Content that will be included inline between the content and `</body>` of
19    /// a rendered Markdown file or generated documentation
20    pub(crate) after_content: String,
21}
22
23impl ExternalHtml {
24    pub(crate) fn load(
25        in_header: &[String],
26        before_content: &[String],
27        after_content: &[String],
28        md_before_content: &[String],
29        md_after_content: &[String],
30        nightly_build: bool,
31        dcx: DiagCtxtHandle<'_>,
32        id_map: &mut IdMap,
33        edition: Edition,
34        playground: &Option<Playground>,
35    ) -> Option<ExternalHtml> {
36        let codes = ErrorCodes::from(nightly_build);
37        let ih = load_external_files(in_header, dcx)?;
38        let bc = load_external_files(before_content, dcx)?;
39        let m_bc = load_external_files(md_before_content, dcx)?;
40        let bc = format!(
41            "{bc}{}",
42            Markdown {
43                content: &m_bc,
44                links: &[],
45                ids: id_map,
46                error_codes: codes,
47                edition,
48                playground,
49                heading_offset: HeadingOffset::H2,
50            }
51            .into_string()
52        );
53        let ac = load_external_files(after_content, dcx)?;
54        let m_ac = load_external_files(md_after_content, dcx)?;
55        let ac = format!(
56            "{ac}{}",
57            Markdown {
58                content: &m_ac,
59                links: &[],
60                ids: id_map,
61                error_codes: codes,
62                edition,
63                playground,
64                heading_offset: HeadingOffset::H2,
65            }
66            .into_string()
67        );
68        Some(ExternalHtml { in_header: ih, before_content: bc, after_content: ac })
69    }
70}
71
72pub(crate) enum LoadStringError {
73    ReadFail,
74    BadUtf8,
75}
76
77pub(crate) fn load_string<P: AsRef<Path>>(
78    file_path: P,
79    dcx: DiagCtxtHandle<'_>,
80) -> Result<String, LoadStringError> {
81    let file_path = file_path.as_ref();
82    let contents = match fs::read(file_path) {
83        Ok(bytes) => bytes,
84        Err(e) => {
85            dcx.struct_err(format!(
86                "error reading `{file_path}`: {e}",
87                file_path = file_path.display()
88            ))
89            .emit();
90            return Err(LoadStringError::ReadFail);
91        }
92    };
93    match str::from_utf8(&contents) {
94        Ok(s) => Ok(s.to_string()),
95        Err(_) => {
96            dcx.err(format!("error reading `{}`: not UTF-8", file_path.display()));
97            Err(LoadStringError::BadUtf8)
98        }
99    }
100}
101
102fn load_external_files(names: &[String], dcx: DiagCtxtHandle<'_>) -> Option<String> {
103    let mut out = String::new();
104    for name in names {
105        let Ok(s) = load_string(name, dcx) else { return None };
106        out.push_str(&s);
107        out.push('\n');
108    }
109    Some(out)
110}