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