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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! This crate provides the trait [FromFile] that can be implemented or derived
//! for any struct or enum. Upon doing so, you'll get a `from_file` method
//! that allows you to skip having read the file the disk & choosing the correct
//! serde method - that will be done based on the file extension.
//!
//! # Quick Preview
//!
//! All examples require that serde Deserialize is also derived.
//! (see below for copy/paste example)
//!
//! ```
//! # #[macro_use]
//! # extern crate serde_derive;
//! # extern crate serde;
//! # #[macro_use]
//! # extern crate from_file_derive;
//! # use from_file::FromFile;
//! #[derive(Deserialize)]
//! struct Person {
//!     name: String
//! }
//!
//! impl FromFile for Person {}
//!
//! fn main() {
//!     let path = "test/fixtures/person.json";
//!     let person = Person::from_file(path).expect("deserialize from file");
//!     assert_eq!(person.name, String::from("Shane"));
//! }
//! ```
//!
//! # Quick Preview with `from_file_derive`
//!
//! This requires the additional crate [from_file_derive](https://crates.io/crates/from_file_derive)
//!
//! ```
//! # #[macro_use]
//! # extern crate serde_derive;
//! # extern crate serde;
//! # #[macro_use]
//! # extern crate from_file_derive;
//! # use from_file::FromFile;
//! #[derive(Deserialize, FromFile)]
//! struct Person {
//!     name: String
//! }
//!
//! fn main() {
//!     let path = "test/fixtures/person.json";
//!     let person = Person::from_file(path).expect("deserialize from file");
//!     assert_eq!(person.name, String::from("Shane"));
//! }
//! ```
//!
//! # Copy/Paste example
//!
//! ```
//! #[macro_use]
//! extern crate serde_derive;
//! extern crate serde;
//!
//! #[macro_use]
//! extern crate from_file_derive;
//!
//! use from_file::FromFile;
//!
//! #[derive(Deserialize, FromFile)]
//! struct Person {
//!     name: String
//! }
//!
//! fn main() {
//!     let path = "test/fixtures/person.json";
//!     let person = Person::from_file(path).expect("deserialize from file");
//!     assert_eq!(person.name, String::from("Shane"));
//! }
//! ```
//!
//! ### Full example with imports and error handing
//!
//! ```rust
//! #[macro_use]
//! extern crate serde_derive;
//!
//! #[macro_use]
//! extern crate from_file_derive;
//! extern crate from_file;
//!
//! use from_file::FromFile;
//!
//! #[derive(Deserialize, FromFile, Debug, PartialEq)]
//! struct Person {
//!     name: String,
//!     age: usize
//! }
//!
//! fn main() {
//!     match Person::from_file("test/fixtures/person.json") {
//!         Ok(p) => println!("Got a Person from a file!"),
//!         Err(e) => eprintln!("{}", e)
//!     }
//! }
//! ```
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serde_yaml;

use serde::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;

#[derive(Debug)]
pub enum FromFileError {
    InvalidExtension,
    InvalidInput,
    FileOpen(PathBuf),
    FileRead,
    SerdeError(String),
}

///
/// Implement this trait to enable your Struct's to be deserialized
/// from a file-path like
///
/// - conf/app.yaml
/// - file:conf/app.yaml
///
pub trait FromFile {
    ///
    /// Support serialising to .yml, .yaml & .json files by
    /// looking at the file extension and then choosing the correct
    /// serde method
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate serde_derive;
    /// # extern crate serde;
    /// # #[macro_use]
    /// # extern crate from_file_derive;
    /// # use from_file::FromFile;
    /// #[derive(Deserialize)]
    /// struct Person {
    ///     name: String
    /// }
    ///
    /// impl FromFile for Person {}
    ///
    /// fn main() {
    ///     let path = "test/fixtures/person.json";
    ///     let person = Person::from_file(path).expect("deserialize from file");
    ///     assert_eq!(person.name, String::from("Shane"));
    /// }
    /// ```
    ///
    fn from_file(input: &str) -> Result<Self, FromFileError>
    where
        for<'de> Self: Deserialize<'de> + Sized,
    {
        let pb = PathBuf::from(input);
        let ext = pb
            .extension()
            .and_then(|ext| ext.to_str())
            .ok_or(FromFileError::InvalidExtension)?;
        match ext {
            "json" => <Self as FromFile>::from_json_file(input),
            "yml" | "yaml" => <Self as FromFile>::from_yml_file(input),
            _ => Err(FromFileError::InvalidExtension),
        }
    }

    ///
    /// From a string like `file:config.yaml`, try to read the file
    /// and if it exists, parse into a strongly typed struct `Self`
    ///
    fn from_yml_file(input: &str) -> Result<Self, FromFileError>
    where
        for<'de> Self: Deserialize<'de> + Sized,
    {
        <Self as FromFile>::get_file_path(input)
            .and_then(<Self as FromFile>::file_read)
            .and_then(<Self as FromFile>::from_yaml_string)
    }

    ///
    /// From a string like `file:config.yaml`, try to read the file
    /// and if it exists, parse into a strongly typed struct `Self`
    ///
    fn from_json_file(input: &str) -> Result<Self, FromFileError>
    where
        for<'de> Self: Deserialize<'de> + Sized,
    {
        <Self as FromFile>::get_file_path(input)
            .and_then(<Self as FromFile>::file_read)
            .and_then(<Self as FromFile>::from_json_string)
    }

    ///
    /// Parse strings like file:config.yaml to extract the file path only
    ///
    fn get_file_path(input: &str) -> Result<String, FromFileError> {
        let split: Vec<&str> = input.split(":").collect();
        match split.len() {
            1 => Ok(split[0].into()),
            2 => Ok(split[1].into()),
            _ => Err(FromFileError::InvalidInput),
        }
    }

    ///
    /// Attempt to Read the file's contents into a string
    ///
    fn file_read(input: String) -> Result<String, FromFileError> {
        let mut maybe_path = std::env::current_dir().expect("can read current dir");
        maybe_path.push(&input);
        let mut file = File::open(&input).map_err(|_| FromFileError::FileOpen(maybe_path))?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .map_err(|_| FromFileError::FileRead)?;
        Ok(contents)
    }

    ///
    /// Parse any YAML string directly into a Self
    ///
    fn from_yaml_string(contents: String) -> Result<Self, FromFileError>
    where
        for<'de> Self: Deserialize<'de>,
    {
        serde_yaml::from_str(&contents).map_err(|e| FromFileError::SerdeError(e.to_string()))
    }

    ///
    /// Parse json string directly into a Self
    ///
    fn from_json_string(contents: String) -> Result<Self, FromFileError>
    where
        for<'de> Self: Deserialize<'de>,
    {
        serde_json::from_str(&contents).map_err(|e| FromFileError::SerdeError(e.to_string()))
    }
}

impl std::fmt::Display for FromFileError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            FromFileError::InvalidExtension => write!(f, "FromFileError::InvalidExtension"),
            FromFileError::InvalidInput => write!(f, "FromFileError::InvalidInput"),
            FromFileError::FileOpen(path) => {
                write!(f, "FromFileError::FileOpen - couldn't open {:?}", path)
            }
            FromFileError::FileRead => write!(f, "FromFileError::FileRead"),
            FromFileError::SerdeError(e) => write!(f, "FromFileError::SerdeError - {}", e),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::FromFile;

    #[test]
    fn test_from_file() {
        #[derive(Deserialize, Debug, PartialEq)]
        struct Person {
            name: String,
        }
        impl FromFile for Person {}

        let p1 = Person::from_file("test/fixtures/person.json").expect("file->Person");
        assert_eq!(
            p1,
            Person {
                name: "Shane".into()
            }
        );

        let p1 = Person::from_file("test/fixtures/person.yaml").expect("file->Person");
        assert_eq!(
            p1,
            Person {
                name: "Shane".into()
            }
        );
    }
}