]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/markdown.rs
Imported Upstream version 1.0.0~beta
[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::fs::File;
12 use std::io;
13 use std::io::prelude::*;
14 use std::path::{PathBuf, Path};
15
16 use core;
17 use getopts;
18 use testing;
19 use rustc::session::search_paths::SearchPaths;
20
21 use externalfiles::ExternalHtml;
22
23 use html::escape::Escape;
24 use html::markdown;
25 use html::markdown::{Markdown, MarkdownWithToc, find_testable_code, reset_headers};
26 use test::Collector;
27
28 /// Separate any lines at the start of the file that begin with `%`.
29 fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
30 let mut metadata = Vec::new();
31 for line in s.lines() {
32 if line.starts_with("%") {
33 // remove %<whitespace>
34 metadata.push(line[1..].trim_left())
35 } else {
36 let line_start_byte = s.subslice_offset(line);
37 return (metadata, &s[line_start_byte..]);
38 }
39 }
40 // if we're here, then all lines were metadata % lines.
41 (metadata, "")
42 }
43
44 /// Render `input` (e.g. "foo.md") into an HTML file in `output`
45 /// (e.g. output = "bar" => "bar/foo.html").
46 pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
47 external_html: &ExternalHtml, include_toc: bool) -> isize {
48 let input_p = Path::new(input);
49 output.push(input_p.file_stem().unwrap());
50 output.set_extension("html");
51
52 let mut css = String::new();
53 for name in &matches.opt_strs("markdown-css") {
54 let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
55 css.push_str(&s)
56 }
57
58 let input_str = load_or_return!(input, 1, 2);
59 let playground = matches.opt_str("markdown-playground-url");
60 if playground.is_some() {
61 markdown::PLAYGROUND_KRATE.with(|s| { *s.borrow_mut() = None; });
62 }
63 let playground = playground.unwrap_or("".to_string());
64
65 let mut out = match File::create(&output) {
66 Err(e) => {
67 let _ = writeln!(&mut io::stderr(),
68 "error opening `{}` for writing: {}",
69 output.display(), e);
70 return 4;
71 }
72 Ok(f) => f
73 };
74
75 let (metadata, text) = extract_leading_metadata(&input_str);
76 if metadata.len() == 0 {
77 let _ = writeln!(&mut io::stderr(),
78 "invalid markdown file: expecting initial line with `% ...TITLE...`");
79 return 5;
80 }
81 let title = metadata[0];
82
83 reset_headers();
84
85 let rendered = if include_toc {
86 format!("{}", MarkdownWithToc(text))
87 } else {
88 format!("{}", Markdown(text))
89 };
90
91 let err = write!(
92 &mut out,
93 r#"<!DOCTYPE html>
94 <html lang="en">
95 <head>
96 <meta charset="utf-8">
97 <meta name="viewport" content="width=device-width, initial-scale=1.0">
98 <meta name="generator" content="rustdoc">
99 <title>{title}</title>
100
101 {css}
102 {in_header}
103 </head>
104 <body class="rustdoc">
105 <!--[if lte IE 8]>
106 <div class="warning">
107 This old browser is unsupported and will most likely display funky
108 things.
109 </div>
110 <![endif]-->
111
112 {before_content}
113 <h1 class="title">{title}</h1>
114 {text}
115 <script type="text/javascript">
116 window.playgroundUrl = "{playground}";
117 </script>
118 {after_content}
119 </body>
120 </html>"#,
121 title = Escape(title),
122 css = css,
123 in_header = external_html.in_header,
124 before_content = external_html.before_content,
125 text = rendered,
126 after_content = external_html.after_content,
127 playground = playground,
128 );
129
130 match err {
131 Err(e) => {
132 let _ = writeln!(&mut io::stderr(),
133 "error writing to `{}`: {}",
134 output.display(), e);
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, libs: SearchPaths, externs: core::Externs,
143 mut test_args: Vec<String>) -> isize {
144 let input_str = load_or_return!(input, 1, 2);
145
146 let mut collector = Collector::new(input.to_string(), libs, externs, true, false);
147 find_testable_code(&input_str, &mut collector);
148 test_args.insert(0, "rustdoctest".to_string());
149 testing::test_main(&test_args, collector.tests);
150 0
151 }