1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use std::env;
use std::error::Error;
use std::io::{self, Read};
use std::fs;
use std::path::PathBuf;
use source::{Source, SourceBuilder};
mod nil;
#[cfg(feature = "toml")]
mod toml;
#[cfg(feature = "json")]
mod json;
pub enum FileFormat {
#[cfg(feature = "toml")]
Toml,
#[cfg(feature = "json")]
Json,
}
impl FileFormat {
fn extensions(&self) -> Vec<&'static str> {
match *self {
#[cfg(feature = "toml")]
FileFormat::Toml => vec!["toml"],
#[cfg(feature = "json")]
FileFormat::Json => vec!["json"],
}
}
#[allow(unused_variables)]
fn parse(&self, text: &str) -> Result<Box<Source>, Box<Error>> {
match *self {
#[cfg(feature = "toml")]
FileFormat::Toml => toml::Content::parse(text),
#[cfg(feature = "json")]
FileFormat::Json => json::Content::parse(text),
}
}
}
pub struct File {
name: String,
path: Option<String>,
namespace: Option<String>,
format: FileFormat,
required: bool,
}
impl File {
pub fn new(name: &str, format: FileFormat) -> File {
File {
name: name.into(),
format: format,
required: true,
path: None,
namespace: None,
}
}
pub fn path(&mut self, path: &str) -> &mut File {
self.path = Some(path.into());
self
}
pub fn namespace(&mut self, namespace: &str) -> &mut File {
self.namespace = Some(namespace.into());
self
}
pub fn required(&mut self, required: bool) -> &mut File {
self.required = required;
self
}
fn find_file(&self) -> Result<PathBuf, Box<Error>> {
let mut basename = PathBuf::new();
let extensions = self.format.extensions();
if let Some(ref path) = self.path {
basename.push(path.clone());
}
basename.push(self.name.clone());
let mut dir = env::current_dir()?;
loop {
let mut filename = dir.as_path().join(basename.clone());
for ext in &extensions {
filename.set_extension(ext);
if filename.is_file() {
return Ok(filename);
}
}
if !dir.pop() {
return Err(io::Error::new(io::ErrorKind::NotFound,
format!("configuration file \"{}\" not found",
basename.to_string_lossy()))
.into());
}
}
}
fn try_build(&self) -> Result<Box<Source>, Box<Error>> {
let filename = self.find_file()?;
let mut file = fs::File::open(filename)?;
let mut text = String::new();
file.read_to_string(&mut text)?;
self.format.parse(&text)
}
}
impl SourceBuilder for File {
fn build(&self) -> Result<Box<Source>, Box<Error>> {
if self.required {
self.try_build().or_else(|_| Ok(Box::new(nil::Nil {})))
} else {
self.try_build()
}
}
}