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