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