]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/externalfiles.rs
Rollup merge of #31199 - steveklabnik:gh31181, r=Manishearth
[rust.git] / src / librustdoc / externalfiles.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::prelude::*;
13 use std::io;
14 use std::path::{PathBuf, Path};
15 use std::str;
16
17 #[derive(Clone)]
18 pub struct ExternalHtml{
19     pub in_header: String,
20     pub before_content: String,
21     pub after_content: String
22 }
23
24 impl ExternalHtml {
25     pub fn load(in_header: &[String], before_content: &[String], after_content: &[String])
26             -> Option<ExternalHtml> {
27         match (load_external_files(in_header),
28                load_external_files(before_content),
29                load_external_files(after_content)) {
30             (Some(ih), Some(bc), Some(ac)) => Some(ExternalHtml {
31                 in_header: ih,
32                 before_content: bc,
33                 after_content: ac
34             }),
35             _ => None
36         }
37     }
38 }
39
40 pub fn load_string(input: &Path) -> io::Result<Option<String>> {
41     let mut f = try!(File::open(input));
42     let mut d = Vec::new();
43     try!(f.read_to_end(&mut d));
44     Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
45 }
46
47 macro_rules! load_or_return {
48     ($input: expr, $cant_read: expr, $not_utf8: expr) => {
49         {
50             let input = PathBuf::from(&$input[..]);
51             match ::externalfiles::load_string(&input) {
52                 Err(e) => {
53                     let _ = writeln!(&mut io::stderr(),
54                                      "error reading `{}`: {}", input.display(), e);
55                     return $cant_read;
56                 }
57                 Ok(None) => {
58                     let _ = writeln!(&mut io::stderr(),
59                                      "error reading `{}`: not UTF-8", input.display());
60                     return $not_utf8;
61                 }
62                 Ok(Some(s)) => s
63             }
64         }
65     }
66 }
67
68 pub fn load_external_files(names: &[String]) -> Option<String> {
69     let mut out = String::new();
70     for name in names {
71         out.push_str(&*load_or_return!(&name, None, None));
72         out.push('\n');
73     }
74     Some(out)
75 }