]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Rollup merge of #86165 - m-ou-se:proc-macro-span-shrink, r=dtolnay
[rust.git] / src / librustdoc / markdown.rs
1 use std::fs::{create_dir_all, read_to_string, File};
2 use std::io::prelude::*;
3 use std::path::Path;
4
5 use rustc_span::edition::Edition;
6 use rustc_span::source_map::DUMMY_SP;
7 use rustc_span::Symbol;
8
9 use crate::config::{Options, RenderOptions};
10 use crate::doctest::{Collector, TestOptions};
11 use crate::html::escape::Escape;
12 use crate::html::markdown;
13 use crate::html::markdown::{find_testable_code, ErrorCodes, IdMap, Markdown, MarkdownWithToc};
14
15 /// Separate any lines at the start of the file that begin with `# ` or `%`.
16 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
17     let mut metadata = Vec::new();
18     let mut count = 0;
19
20     for line in s.lines() {
21         if line.starts_with("# ") || line.starts_with('%') {
22             // trim the whitespace after the symbol
23             metadata.push(line[1..].trim_start());
24             count += line.len() + 1;
25         } else {
26             return (metadata, &s[count..]);
27         }
28     }
29
30     // if we're here, then all lines were metadata `# ` or `%` lines.
31     (metadata, "")
32 }
33
34 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
35 /// (e.g., output = "bar" => "bar/foo.html").
36 crate fn render<P: AsRef<Path>>(
37     input: P,
38     options: RenderOptions,
39     edition: Edition,
40 ) -> Result<(), String> {
41     if let Err(e) = create_dir_all(&options.output) {
42         return Err(format!("{}: {}", options.output.display(), e));
43     }
44
45     let input = input.as_ref();
46     let mut output = options.output;
47     output.push(input.file_name().unwrap());
48     output.set_extension("html");
49
50     let mut css = String::new();
51     for name in &options.markdown_css {
52         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
53         css.push_str(&s)
54     }
55
56     let input_str = read_to_string(input).map_err(|err| format!("{}: {}", input.display(), err))?;
57     let playground_url = options.markdown_playground_url.or(options.playground_url);
58     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
59
60     let mut out = File::create(&output).map_err(|e| format!("{}: {}", output.display(), e))?;
61
62     let (metadata, text) = extract_leading_metadata(&input_str);
63     if metadata.is_empty() {
64         return Err("invalid markdown file: no initial lines starting with `# ` or `%`".to_owned());
65     }
66     let title = metadata[0];
67
68     let mut ids = IdMap::new();
69     let error_codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
70     let text = if !options.markdown_no_toc {
71         MarkdownWithToc(text, &mut ids, error_codes, edition, &playground).into_string()
72     } else {
73         Markdown(text, &[], &mut ids, error_codes, edition, &playground).into_string()
74     };
75
76     let err = write!(
77         &mut out,
78         r#"<!DOCTYPE html>
79 <html lang="en">
80 <head>
81     <meta charset="utf-8">
82     <meta name="viewport" content="width=device-width, initial-scale=1.0">
83     <meta name="generator" content="rustdoc">
84     <title>{title}</title>
85
86     {css}
87     {in_header}
88 </head>
89 <body class="rustdoc">
90     <!--[if lte IE 8]>
91     <div class="warning">
92         This old browser is unsupported and will most likely display funky
93         things.
94     </div>
95     <![endif]-->
96
97     {before_content}
98     <h1 class="title">{title}</h1>
99     {text}
100     {after_content}
101 </body>
102 </html>"#,
103         title = Escape(title),
104         css = css,
105         in_header = options.external_html.in_header,
106         before_content = options.external_html.before_content,
107         text = text,
108         after_content = options.external_html.after_content,
109     );
110
111     match err {
112         Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)),
113         Ok(_) => Ok(()),
114     }
115 }
116
117 /// Runs any tests/code examples in the markdown file `input`.
118 crate fn test(options: Options) -> Result<(), String> {
119     let input_str = read_to_string(&options.input)
120         .map_err(|err| format!("{}: {}", options.input.display(), err))?;
121     let mut opts = TestOptions::default();
122     opts.no_crate_inject = true;
123     opts.display_warnings = options.display_warnings;
124     let mut collector = Collector::new(
125         Symbol::intern(&options.input.display().to_string()),
126         options.clone(),
127         true,
128         opts,
129         None,
130         Some(options.input),
131         options.enable_per_target_ignores,
132     );
133     collector.set_position(DUMMY_SP);
134     let codes = ErrorCodes::from(options.render_options.unstable_features.is_nightly_build());
135
136     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores, None);
137
138     crate::doctest::run_tests(
139         options.test_args,
140         options.nocapture,
141         options.display_warnings,
142         collector.tests,
143     );
144     Ok(())
145 }