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