1 use std::fmt::Write as _;
2 use std::fs::{create_dir_all, read_to_string, File};
3 use std::io::prelude::*;
6 use rustc_span::edition::Edition;
7 use rustc_span::source_map::DUMMY_SP;
9 use crate::config::{Options, RenderOptions};
10 use crate::doctest::{Collector, GlobalTestOptions};
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,
17 /// Separate any lines at the start of the file that begin with `# ` or `%`.
18 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
19 let mut metadata = Vec::new();
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;
28 return (metadata, &s[count..]);
32 // if we're here, then all lines were metadata `# ` or `%` lines.
36 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
37 /// (e.g., output = "bar" => "bar/foo.html").
39 /// Requires session globals to be available, for symbol interning.
40 pub(crate) fn render<P: AsRef<Path>>(
42 options: RenderOptions,
44 ) -> Result<(), String> {
45 if let Err(e) = create_dir_all(&options.output) {
46 return Err(format!("{}: {}", options.output.display(), e));
49 let input = input.as_ref();
50 let mut output = options.output;
51 output.push(input.file_name().unwrap());
52 output.set_extension("html");
54 let mut css = String::new();
55 for name in &options.markdown_css {
56 write!(css, r#"<link rel="stylesheet" type="text/css" href="{name}">"#)
57 .expect("Writing to a String can't fail");
60 let input_str = read_to_string(input).map_err(|err| format!("{}: {}", input.display(), err))?;
61 let playground_url = options.markdown_playground_url.or(options.playground_url);
62 let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
64 let mut out = File::create(&output).map_err(|e| format!("{}: {}", output.display(), e))?;
66 let (metadata, text) = extract_leading_metadata(&input_str);
67 if metadata.is_empty() {
68 return Err("invalid markdown file: no initial lines starting with `# ` or `%`".to_owned());
70 let title = metadata[0];
72 let mut ids = IdMap::new();
73 let error_codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
74 let text = if !options.markdown_no_toc {
75 MarkdownWithToc(text, &mut ids, error_codes, edition, &playground).into_string()
83 playground: &playground,
84 heading_offset: HeadingOffset::H1,
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>
102 <body class="rustdoc">
104 <div class="warning">
105 This old browser is unsupported and will most likely display funky
111 <h1 class="title">{title}</h1>
116 title = Escape(title),
118 in_header = options.external_html.in_header,
119 before_content = options.external_html.before_content,
121 after_content = options.external_html.after_content,
125 Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)),
130 /// Runs any tests/code examples in the markdown file `input`.
131 pub(crate) fn test(options: Options) -> Result<(), String> {
132 let input_str = read_to_string(&options.input)
133 .map_err(|err| format!("{}: {}", options.input.display(), err))?;
134 let mut opts = GlobalTestOptions::default();
135 opts.no_crate_inject = true;
136 let mut collector = Collector::new(
137 options.input.display().to_string(),
143 options.enable_per_target_ignores,
145 collector.set_position(DUMMY_SP);
146 let codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
148 find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores, None);
150 crate::doctest::run_tests(options.test_args, options.nocapture, collector.tests);