]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
057ce69d9de8bcf925f59cb3a9c7700763202d40
[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::io;
15 use std::path::{PathBuf, Path};
16
17 use getopts;
18 use testing;
19 use rustc::session::search_paths::SearchPaths;
20 use rustc::session::config::Externs;
21 use syntax::codemap::DUMMY_SP;
22
23 use externalfiles::{ExternalHtml, LoadStringError, load_string};
24
25 use html::render::reset_ids;
26 use html::escape::Escape;
27 use html::markdown;
28 use html::markdown::{Markdown, MarkdownWithToc, find_testable_code, old_find_testable_code};
29 use html::markdown::RenderType;
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: &str, mut output: PathBuf, matches: &getopts::Matches,
54               external_html: &ExternalHtml, include_toc: bool,
55               render_type: RenderType) -> isize {
56     let input_p = Path::new(input);
57     output.push(input_p.file_stem().unwrap());
58     output.set_extension("html");
59
60     let mut css = String::new();
61     for name in &matches.opt_strs("markdown-css") {
62         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
63         css.push_str(&s)
64     }
65
66     let input_str = match load_string(input) {
67         Ok(s) => s,
68         Err(LoadStringError::ReadFail) => return 1,
69         Err(LoadStringError::BadUtf8) => return 2,
70     };
71     if let Some(playground) = matches.opt_str("markdown-playground-url").or(
72                               matches.opt_str("playground-url")) {
73         markdown::PLAYGROUND.with(|s| { *s.borrow_mut() = Some((None, playground)); });
74     }
75
76     let mut out = match File::create(&output) {
77         Err(e) => {
78             let _ = writeln!(&mut io::stderr(),
79                              "rustdoc: {}: {}",
80                              output.display(), e);
81             return 4;
82         }
83         Ok(f) => f
84     };
85
86     let (metadata, text) = extract_leading_metadata(&input_str);
87     if metadata.is_empty() {
88         let _ = writeln!(
89             &mut io::stderr(),
90             "rustdoc: invalid markdown file: no initial lines starting with `# ` or `%`"
91         );
92         return 5;
93     }
94     let title = metadata[0];
95
96     reset_ids(false);
97
98     let rendered = if include_toc {
99         format!("{}", MarkdownWithToc(text, render_type))
100     } else {
101         format!("{}", Markdown(text, render_type))
102     };
103
104     let err = write!(
105         &mut out,
106         r#"<!DOCTYPE html>
107 <html lang="en">
108 <head>
109     <meta charset="utf-8">
110     <meta name="viewport" content="width=device-width, initial-scale=1.0">
111     <meta name="generator" content="rustdoc">
112     <title>{title}</title>
113
114     {css}
115     {in_header}
116 </head>
117 <body class="rustdoc">
118     <!--[if lte IE 8]>
119     <div class="warning">
120         This old browser is unsupported and will most likely display funky
121         things.
122     </div>
123     <![endif]-->
124
125     {before_content}
126     <h1 class="title">{title}</h1>
127     {text}
128     {after_content}
129 </body>
130 </html>"#,
131         title = Escape(title),
132         css = css,
133         in_header = external_html.in_header,
134         before_content = external_html.before_content,
135         text = rendered,
136         after_content = external_html.after_content,
137         );
138
139     match err {
140         Err(e) => {
141             let _ = writeln!(&mut io::stderr(),
142                              "rustdoc: cannot write to `{}`: {}",
143                              output.display(), e);
144             6
145         }
146         Ok(_) => 0
147     }
148 }
149
150 /// Run any tests/code examples in the markdown file `input`.
151 pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
152             mut test_args: Vec<String>, maybe_sysroot: Option<PathBuf>,
153             render_type: RenderType, display_warnings: bool) -> isize {
154     let input_str = match load_string(input) {
155         Ok(s) => s,
156         Err(LoadStringError::ReadFail) => return 1,
157         Err(LoadStringError::BadUtf8) => return 2,
158     };
159
160     let mut opts = TestOptions::default();
161     opts.no_crate_inject = true;
162     let mut collector = Collector::new(input.to_string(), cfgs, libs, externs,
163                                        true, opts, maybe_sysroot, None,
164                                        Some(input.to_owned()),
165                                        render_type);
166     old_find_testable_code(&input_str, &mut collector, DUMMY_SP);
167     find_testable_code(&input_str, &mut collector, DUMMY_SP);
168     test_args.insert(0, "rustdoctest".to_string());
169     testing::test_main(&test_args, collector.tests,
170                        testing::Options::new().display_output(display_warnings));
171     0
172 }