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