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