]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Auto merge of #58180 - davidtwco:issue-58053, r=estebank
[rust.git] / src / librustdoc / markdown.rs
1 use std::default::Default;
2 use std::fs::File;
3 use std::io::prelude::*;
4 use std::path::PathBuf;
5 use std::cell::RefCell;
6
7 use errors;
8 use testing;
9 use syntax::source_map::DUMMY_SP;
10 use syntax::feature_gate::UnstableFeatures;
11
12 use externalfiles::{LoadStringError, load_string};
13
14 use config::{Options, RenderOptions};
15 use html::escape::Escape;
16 use html::markdown;
17 use html::markdown::{ErrorCodes, IdMap, Markdown, MarkdownWithToc, find_testable_code};
18 use test::{TestOptions, Collector};
19
20 /// Separate any lines at the start of the file that begin with `# ` or `%`.
21 fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
22     let mut metadata = Vec::new();
23     let mut count = 0;
24
25     for line in s.lines() {
26         if line.starts_with("# ") || line.starts_with("%") {
27             // trim the whitespace after the symbol
28             metadata.push(line[1..].trim_start());
29             count += line.len() + 1;
30         } else {
31             return (metadata, &s[count..]);
32         }
33     }
34
35     // if we're here, then all lines were metadata `# ` or `%` lines.
36     (metadata, "")
37 }
38
39 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
40 /// (e.g., output = "bar" => "bar/foo.html").
41 pub fn render(input: PathBuf, options: RenderOptions, diag: &errors::Handler) -> isize {
42     let mut output = options.output;
43     output.push(input.file_stem().unwrap());
44     output.set_extension("html");
45
46     let mut css = String::new();
47     for name in &options.markdown_css {
48         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
49         css.push_str(&s)
50     }
51
52     let input_str = match load_string(&input, diag) {
53         Ok(s) => s,
54         Err(LoadStringError::ReadFail) => return 1,
55         Err(LoadStringError::BadUtf8) => return 2,
56     };
57     let playground_url = options.markdown_playground_url
58                             .or(options.playground_url);
59     if let Some(playground) = playground_url {
60         markdown::PLAYGROUND.with(|s| { *s.borrow_mut() = Some((None, playground)); });
61     }
62
63     let mut out = match File::create(&output) {
64         Err(e) => {
65             diag.struct_err(&format!("{}: {}", output.display(), e)).emit();
66             return 4;
67         }
68         Ok(f) => f,
69     };
70
71     let (metadata, text) = extract_leading_metadata(&input_str);
72     if metadata.is_empty() {
73         diag.struct_err("invalid markdown file: no initial lines starting with `# ` or `%`").emit();
74         return 5;
75     }
76     let title = metadata[0];
77
78     let mut ids = IdMap::new();
79     let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
80     let text = if !options.markdown_no_toc {
81         MarkdownWithToc(text, RefCell::new(&mut ids), error_codes).to_string()
82     } else {
83         Markdown(text, &[], RefCell::new(&mut ids), error_codes).to_string()
84     };
85
86     let err = write!(
87         &mut out,
88         r#"<!DOCTYPE html>
89 <html lang="en">
90 <head>
91     <meta charset="utf-8">
92     <meta name="viewport" content="width=device-width, initial-scale=1.0">
93     <meta name="generator" content="rustdoc">
94     <title>{title}</title>
95
96     {css}
97     {in_header}
98 </head>
99 <body class="rustdoc">
100     <!--[if lte IE 8]>
101     <div class="warning">
102         This old browser is unsupported and will most likely display funky
103         things.
104     </div>
105     <![endif]-->
106
107     {before_content}
108     <h1 class="title">{title}</h1>
109     {text}
110     {after_content}
111 </body>
112 </html>"#,
113         title = Escape(title),
114         css = css,
115         in_header = options.external_html.in_header,
116         before_content = options.external_html.before_content,
117         text = text,
118         after_content = options.external_html.after_content,
119     );
120
121     match err {
122         Err(e) => {
123             diag.struct_err(&format!("cannot write to `{}`: {}", output.display(), e)).emit();
124             6
125         }
126         Ok(_) => 0,
127     }
128 }
129
130 /// Run any tests/code examples in the markdown file `input`.
131 pub fn test(mut options: Options, diag: &errors::Handler) -> isize {
132     let input_str = match load_string(&options.input, diag) {
133         Ok(s) => s,
134         Err(LoadStringError::ReadFail) => return 1,
135         Err(LoadStringError::BadUtf8) => return 2,
136     };
137
138     let mut opts = TestOptions::default();
139     opts.no_crate_inject = true;
140     opts.display_warnings = options.display_warnings;
141     let mut collector = Collector::new(options.input.display().to_string(), options.cfgs,
142                                        options.libs, options.codegen_options, options.externs,
143                                        true, opts, options.maybe_sysroot, None,
144                                        Some(options.input),
145                                        options.linker, options.edition, options.persist_doctests);
146     collector.set_position(DUMMY_SP);
147     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
148     let res = find_testable_code(&input_str, &mut collector, codes);
149     if let Err(err) = res {
150         diag.span_warn(DUMMY_SP, &err.to_string());
151     }
152     options.test_args.insert(0, "rustdoctest".to_string());
153     testing::test_main(&options.test_args, collector.tests,
154                        testing::Options::new().display_output(options.display_warnings));
155     0
156 }