]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Remove dependency on error handling from find_testable_code
[rust.git] / src / librustdoc / markdown.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::default::Default;
12 use std::fs::File;
13 use std::io::prelude::*;
14 use std::path::{PathBuf, Path};
15
16 use errors;
17 use getopts;
18 use testing;
19 use rustc::session::search_paths::SearchPaths;
20 use rustc::session::config::{Externs, CodegenOptions};
21 use syntax::codemap::DUMMY_SP;
22 use syntax::edition::Edition;
23
24 use externalfiles::{ExternalHtml, LoadStringError, load_string};
25
26 use html::render::reset_ids;
27 use html::escape::Escape;
28 use html::markdown;
29 use html::markdown::{Markdown, MarkdownWithToc, find_testable_code};
30 use test::{TestOptions, Collector};
31
32 /// Separate any lines at the start of the file that begin with `# ` or `%`.
33 fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
34     let mut metadata = Vec::new();
35     let mut count = 0;
36
37     for line in s.lines() {
38         if line.starts_with("# ") || line.starts_with("%") {
39             // trim the whitespace after the symbol
40             metadata.push(line[1..].trim_left());
41             count += line.len() + 1;
42         } else {
43             return (metadata, &s[count..]);
44         }
45     }
46
47     // if we're here, then all lines were metadata `# ` or `%` lines.
48     (metadata, "")
49 }
50
51 /// Render `input` (e.g. "foo.md") into an HTML file in `output`
52 /// (e.g. output = "bar" => "bar/foo.html").
53 pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches,
54               external_html: &ExternalHtml, include_toc: bool, diag: &errors::Handler) -> isize {
55     output.push(input.file_stem().unwrap());
56     output.set_extension("html");
57
58     let mut css = String::new();
59     for name in &matches.opt_strs("markdown-css") {
60         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
61         css.push_str(&s)
62     }
63
64     let input_str = match load_string(input, diag) {
65         Ok(s) => s,
66         Err(LoadStringError::ReadFail) => return 1,
67         Err(LoadStringError::BadUtf8) => return 2,
68     };
69     if let Some(playground) = matches.opt_str("markdown-playground-url").or(
70                               matches.opt_str("playground-url")) {
71         markdown::PLAYGROUND.with(|s| { *s.borrow_mut() = Some((None, playground)); });
72     }
73
74     let mut out = match File::create(&output) {
75         Err(e) => {
76             diag.struct_err(&format!("{}: {}", output.display(), e)).emit();
77             return 4;
78         }
79         Ok(f) => f
80     };
81
82     let (metadata, text) = extract_leading_metadata(&input_str);
83     if metadata.is_empty() {
84         diag.struct_err("invalid markdown file: no initial lines starting with `# ` or `%`").emit();
85         return 5;
86     }
87     let title = metadata[0];
88
89     reset_ids(false);
90
91     let text = if include_toc {
92         MarkdownWithToc(text).to_string()
93     } else {
94         Markdown(text, &[]).to_string()
95     };
96
97     let err = write!(
98         &mut out,
99         r#"<!DOCTYPE html>
100 <html lang="en">
101 <head>
102     <meta charset="utf-8">
103     <meta name="viewport" content="width=device-width, initial-scale=1.0">
104     <meta name="generator" content="rustdoc">
105     <title>{title}</title>
106
107     {css}
108     {in_header}
109 </head>
110 <body class="rustdoc">
111     <!--[if lte IE 8]>
112     <div class="warning">
113         This old browser is unsupported and will most likely display funky
114         things.
115     </div>
116     <![endif]-->
117
118     {before_content}
119     <h1 class="title">{title}</h1>
120     {text}
121     {after_content}
122 </body>
123 </html>"#,
124         title = Escape(title),
125         css = css,
126         in_header = external_html.in_header,
127         before_content = external_html.before_content,
128         text = text,
129         after_content = external_html.after_content,
130     );
131
132     match err {
133         Err(e) => {
134             diag.struct_err(&format!("cannot write to `{}`: {}", output.display(), e)).emit();
135             6
136         }
137         Ok(_) => 0,
138     }
139 }
140
141 /// Run any tests/code examples in the markdown file `input`.
142 pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
143             mut test_args: Vec<String>, maybe_sysroot: Option<PathBuf>,
144             display_warnings: bool, linker: Option<PathBuf>, edition: Edition,
145             cg: CodegenOptions, diag: &errors::Handler) -> isize {
146     let input_str = match load_string(input, diag) {
147         Ok(s) => s,
148         Err(LoadStringError::ReadFail) => return 1,
149         Err(LoadStringError::BadUtf8) => return 2,
150     };
151
152     let mut opts = TestOptions::default();
153     opts.no_crate_inject = true;
154     opts.display_warnings = display_warnings;
155     let mut collector = Collector::new(input.to_owned(), cfgs, libs, cg, externs,
156                                        true, opts, maybe_sysroot, None,
157                                        Some(PathBuf::from(input)),
158                                        linker, edition);
159     collector.set_position(DUMMY_SP);
160     let res = find_testable_code(&input_str, &mut collector);
161     if let Err(err) = res {
162         diag.span_warn(DUMMY_SP, &err.to_string());
163     }
164     test_args.insert(0, "rustdoctest".to_string());
165     testing::test_main(&test_args, collector.tests,
166                        testing::Options::new().display_output(display_warnings));
167     0
168 }