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