]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Auto merge of #67733 - pietroalbini:gha-2, r=alexcrichton
[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 rustc_feature::UnstableFeatures;
7 use rustc_span::edition::Edition;
8 use rustc_span::source_map::DUMMY_SP;
9 use testing;
10
11 use crate::config::{Options, RenderOptions};
12 use crate::externalfiles::{load_string, LoadStringError};
13 use crate::html::escape::Escape;
14 use crate::html::markdown;
15 use crate::html::markdown::{find_testable_code, ErrorCodes, IdMap, Markdown, MarkdownWithToc};
16 use crate::test::{Collector, TestOptions};
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.or(options.playground_url);
61     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
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, &mut ids, error_codes, edition, &playground).to_string()
82     } else {
83         Markdown(text, &[], &mut ids, error_codes, edition, &playground).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 /// Runs any tests/code examples in the markdown file `input`.
131 pub fn test(mut options: Options, diag: &errors::Handler) -> i32 {
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(
142         options.input.display().to_string(),
143         options.clone(),
144         true,
145         opts,
146         None,
147         Some(options.input),
148         options.enable_per_target_ignores,
149     );
150     collector.set_position(DUMMY_SP);
151     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
152
153     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores);
154
155     options.test_args.insert(0, "rustdoctest".to_string());
156     testing::test_main(
157         &options.test_args,
158         collector.tests,
159         Some(testing::Options::new().display_output(options.display_warnings)),
160     );
161     0
162 }