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
#[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),
}
pub trait FromFile {
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),
}
}
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)
}
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)
}
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),
}
}
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)
}
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()))
}
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()
}
);
}
}