]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Rollup merge of #41135 - japaric:unstable-docs, r=steveklabnik
[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};
29 use test::{TestOptions, Collector};
30
31 /// Separate any lines at the start of the file that begin with `# ` or `%`.
32 fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
33     let mut metadata = Vec::new();
34     let mut count = 0;
35
36     for line in s.lines() {
37         if line.starts_with("# ") || line.starts_with("%") {
38             // trim the whitespace after the symbol
39             metadata.push(line[1..].trim_left());
40             count += line.len() + 1;
41         } else {
42             return (metadata, &s[count..]);
43         }
44     }
45
46     // if we're here, then all lines were metadata `# ` or `%` lines.
47     (metadata, "")
48 }
49
50 /// Render `input` (e.g. "foo.md") into an HTML file in `output`
51 /// (e.g. output = "bar" => "bar/foo.html").
52 pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
53               external_html: &ExternalHtml, include_toc: bool) -> isize {
54     let input_p = Path::new(input);
55     output.push(input_p.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) {
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             let _ = writeln!(&mut io::stderr(),
77                              "rustdoc: {}: {}",
78                              output.display(), e);
79             return 4;
80         }
81         Ok(f) => f
82     };
83
84     let (metadata, text) = extract_leading_metadata(&input_str);
85     if metadata.is_empty() {
86         let _ = writeln!(
87             &mut io::stderr(),
88             "rustdoc: invalid markdown file: no initial lines starting with `# ` or `%`"
89         );
90         return 5;
91     }
92     let title = metadata[0];
93
94     reset_ids(false);
95
96     let rendered = if include_toc {
97         format!("{}", MarkdownWithToc(text))
98     } else {
99         format!("{}", Markdown(text))
100     };
101
102     let err = write!(
103         &mut out,
104         r#"<!DOCTYPE html>
105 <html lang="en">
106 <head>
107     <meta charset="utf-8">
108     <meta name="viewport" content="width=device-width, initial-scale=1.0">
109     <meta name="generator" content="rustdoc">
110     <title>{title}</title>
111
112     {css}
113     {in_header}
114 </head>
115 <body class="rustdoc">
116     <!--[if lte IE 8]>
117     <div class="warning">
118         This old browser is unsupported and will most likely display funky
119         things.
120     </div>
121     <![endif]-->
122
123     {before_content}
124     <h1 class="title">{title}</h1>
125     {text}
126     {after_content}
127 </body>
128 </html>"#,
129         title = Escape(title),
130         css = css,
131         in_header = external_html.in_header,
132         before_content = external_html.before_content,
133         text = rendered,
134         after_content = external_html.after_content,
135         );
136
137     match err {
138         Err(e) => {
139             let _ = writeln!(&mut io::stderr(),
140                              "rustdoc: cannot write to `{}`: {}",
141                              output.display(), e);
142             6
143         }
144         Ok(_) => 0
145     }
146 }
147
148 /// Run any tests/code examples in the markdown file `input`.
149 pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
150             mut test_args: Vec<String>, maybe_sysroot: Option<PathBuf>) -> isize {
151     let input_str = match load_string(input) {
152         Ok(s) => s,
153         Err(LoadStringError::ReadFail) => return 1,
154         Err(LoadStringError::BadUtf8) => return 2,
155     };
156
157     let mut opts = TestOptions::default();
158     opts.no_crate_inject = true;
159     let mut collector = Collector::new(input.to_string(), cfgs, libs, externs,
160                                        true, opts, maybe_sysroot, None,
161                                        Some(input.to_owned()));
162     find_testable_code(&input_str, &mut collector, DUMMY_SP);
163     test_args.insert(0, "rustdoctest".to_string());
164     testing::test_main(&test_args, collector.tests);
165     0
166 }