]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Auto merge of #69898 - spastorino:rename-rustc-guide2, r=Xanewok
[rust.git] / src / librustdoc / markdown.rs
1 use std::fs::{create_dir_all, File};
2 use std::io::prelude::*;
3 use std::path::PathBuf;
4
5 use rustc_feature::UnstableFeatures;
6 use rustc_span::edition::Edition;
7 use rustc_span::source_map::DUMMY_SP;
8
9 use crate::config::{Options, RenderOptions};
10 use crate::externalfiles::{load_string, LoadStringError};
11 use crate::html::escape::Escape;
12 use crate::html::markdown;
13 use crate::html::markdown::{find_testable_code, ErrorCodes, IdMap, Markdown, MarkdownWithToc};
14 use crate::test::{Collector, TestOptions};
15
16 /// Separate any lines at the start of the file that begin with `# ` or `%`.
17 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
18     let mut metadata = Vec::new();
19     let mut count = 0;
20
21     for line in s.lines() {
22         if line.starts_with("# ") || line.starts_with('%') {
23             // trim the whitespace after the symbol
24             metadata.push(line[1..].trim_start());
25             count += line.len() + 1;
26         } else {
27             return (metadata, &s[count..]);
28         }
29     }
30
31     // if we're here, then all lines were metadata `# ` or `%` lines.
32     (metadata, "")
33 }
34
35 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
36 /// (e.g., output = "bar" => "bar/foo.html").
37 pub fn render(
38     input: PathBuf,
39     options: RenderOptions,
40     diag: &rustc_errors::Handler,
41     edition: Edition,
42 ) -> i32 {
43     if let Err(e) = create_dir_all(&options.output) {
44         diag.struct_err(&format!("{}: {}", options.output.display(), e)).emit();
45         return 4;
46     }
47
48     let mut output = options.output;
49     output.push(input.file_name().unwrap());
50     output.set_extension("html");
51
52     let mut css = String::new();
53     for name in &options.markdown_css {
54         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
55         css.push_str(&s)
56     }
57
58     let input_str = match load_string(&input, diag) {
59         Ok(s) => s,
60         Err(LoadStringError::ReadFail) => return 1,
61         Err(LoadStringError::BadUtf8) => return 2,
62     };
63     let playground_url = options.markdown_playground_url.or(options.playground_url);
64     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
65
66     let mut out = match File::create(&output) {
67         Err(e) => {
68             diag.struct_err(&format!("{}: {}", output.display(), e)).emit();
69             return 4;
70         }
71         Ok(f) => f,
72     };
73
74     let (metadata, text) = extract_leading_metadata(&input_str);
75     if metadata.is_empty() {
76         diag.struct_err("invalid markdown file: no initial lines starting with `# ` or `%`").emit();
77         return 5;
78     }
79     let title = metadata[0];
80
81     let mut ids = IdMap::new();
82     let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
83     let text = if !options.markdown_no_toc {
84         MarkdownWithToc(text, &mut ids, error_codes, edition, &playground).to_string()
85     } else {
86         Markdown(text, &[], &mut ids, error_codes, edition, &playground).to_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) => {
126             diag.struct_err(&format!("cannot write to `{}`: {}", output.display(), e)).emit();
127             6
128         }
129         Ok(_) => 0,
130     }
131 }
132
133 /// Runs any tests/code examples in the markdown file `input`.
134 pub fn test(mut options: Options, diag: &rustc_errors::Handler) -> i32 {
135     let input_str = match load_string(&options.input, diag) {
136         Ok(s) => s,
137         Err(LoadStringError::ReadFail) => return 1,
138         Err(LoadStringError::BadUtf8) => return 2,
139     };
140
141     let mut opts = TestOptions::default();
142     opts.no_crate_inject = true;
143     opts.display_warnings = options.display_warnings;
144     let mut collector = Collector::new(
145         options.input.display().to_string(),
146         options.clone(),
147         true,
148         opts,
149         None,
150         Some(options.input),
151         options.enable_per_target_ignores,
152     );
153     collector.set_position(DUMMY_SP);
154     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
155
156     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores);
157
158     options.test_args.insert(0, "rustdoctest".to_string());
159     testing::test_main(
160         &options.test_args,
161         collector.tests,
162         Some(testing::Options::new().display_output(options.display_warnings)),
163     );
164     0
165 }