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