summaryrefslogtreecommitdiff
path: root/libimagstore/src/file_abstraction/stdio/mapper/json.rs
blob: 0b66f91c4254b12bae8b630d5f9d206c6a524d4d (plain)
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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::PathBuf;

use serde_json;
use toml;

use error::StoreErrorKind as SEK;
use error::MapErrInto;
use super::Mapper;
use store::Result;
use store::Entry;
use storeid::StoreId;

use libimagerror::into::IntoError;

#[derive(Debug, Deserialize, Serialize)]
struct BackendEntry {
    header: serde_json::Value,
    content: String,
}

impl BackendEntry {

    fn to_string(self) -> Result<String> {
        toml::to_string(&self.header)
            .map_err_into(SEK::IoError)
            .map(|hdr| {
                format!("---\n{header}---\n{content}",
                        header  = hdr,
                        content = self.content)
            })
    }

}

#[derive(Debug, Deserialize, Serialize)]
struct Document {
    version: String,
    store: HashMap<PathBuf, BackendEntry>,
}

pub struct JsonMapper;

impl JsonMapper {

    pub fn new() -> JsonMapper {
        JsonMapper
    }

}

impl Mapper for JsonMapper {
    fn read_to_fs<R: Read>(&self, r: &mut R, hm: &mut HashMap<PathBuf, Entry>)   -> Result<()> {
        let mut document = {
            debug!("Reading Document");
            let mut s = String::new();
            try!(r.read_to_string(&mut s).map_err_into(SEK::IoError));
            debug!("Document = {:?}", s);
            debug!("Parsing Document");
            let doc : Document = try!(serde_json::from_str(&s).map_err_into(SEK::IoError));
            debug!("Document = {:?}", doc);
            doc
        };

        let _ = try!(::semver::Version::parse(&document.version)
            .map_err_into(SEK::VersionError)
            .and_then(|doc_vers| {
                // safe because cargo does not compile if crate version is not valid
                let crate_version = ::semver::Version::parse(version!()).unwrap();

                debug!("Document version vs. own version: {doc_vers} > {crate_vers}",
                       doc_vers = doc_vers,
                       crate_vers = crate_version);

                if doc_vers > crate_version {
                    Err(SEK::VersionError.into_error())
                } else {
                    Ok(())
                }
            }));

        for (key, val) in document.store.drain() {
            debug!("(key, value) ({:?}, {:?})", key, val);
            let res = val
                .to_string()
                .and_then(|vals| {
                    debug!("value string = {:?}", vals);
                    StoreId::new_baseless(key.clone())
                        .and_then(|id| Entry::from_str(id, &vals))
                        .map(|entry| hm.insert(key, entry))
                })
                .map(|_| ());

            let _ = try!(res);
        }

        Ok(())
    }

    fn fs_to_write<W: Write>(&self, hm: &mut HashMap<PathBuf, Entry>, out: &mut W) -> Result<()> {
        #[derive(Serialize)]
        struct BackendEntry {
            header: ::toml::Value,
            content: String,
        }

        impl BackendEntry {
            fn construct_from(e: Entry) -> BackendEntry {
                BackendEntry {
                    header:  e.get_header().clone(),
                    content: e.get_content().clone(),
                }
            }
        }

        #[derive(Serialize)]
        struct OutDocument {
            version: String,
            store: HashMap<PathBuf, BackendEntry>,
        }

        let mut store = HashMap::new();
        for (key, value) in hm.drain() {
            store.insert(key, BackendEntry::construct_from(value));
        }

        let doc = OutDocument {
            version: String::from(version!()),
            store:   store,
        };

        serde_json::to_string(&doc)
            .map_err_into(SEK::IoError)
            .and_then(|json| out.write(&json.into_bytes()).map_err_into(SEK::IoError))
            .and_then(|_| out.flush().map_err_into(SEK::IoError))
            .map(|_| ())
    }
}

#[cfg(test)]
mod test {
    use std::io::Cursor;

    use super::*;

    #[test]
    fn test_empty_json_to_fs() {
        let json = r#"{"version":"0.4.0","store":{}}"#;
        let mut json = Cursor::new(String::from(json).into_bytes());
        let mapper   = JsonMapper::new();
        let mut hm   = HashMap::new();

        let io_res  = mapper.read_to_fs(&mut json, &mut hm);
        assert!(io_res.is_ok());
        assert!(hm.is_empty());
    }

    #[test]
    fn test_json_to_fs() {
        let json = r#"
        { "version": "0.4.0",
          "store": {
            "example": {
                "header": {
                    "imag": {
                        "version": "0.4.0"
                    }
                },
                "content": "test"
            }
          }
        }
        "#;
        let mut json = Cursor::new(String::from(json).into_bytes());
        let mapper   = JsonMapper::new();
        let mut hm   = HashMap::new();

        let io_res  = mapper.read_to_fs(&mut json, &mut hm);
        assert!(io_res.is_ok());

        assert_eq!(1, hm.len()); // we should have exactly one entry
    }

    #[test]
    fn test_fs_to_json() {
        let mapper                    = JsonMapper::new();
        let mut out : Cursor<Vec<u8>> = Cursor::new(vec![]);

        let mut hm = {
            let mut hm = HashMap::new();
            let content = r#"---
[imag]
version = "0.4.0"
---
hi there!"#;

            let id = PathBuf::from("example");
            let entry = Entry::from_str(id.clone(), content).unwrap();
            hm.insert(id, entry);
            hm
        };

        let io_res = mapper.fs_to_write(&mut hm, &mut out);
        assert!(io_res.is_ok());

        let example = r#"
        {
            "version": "0.4.0",
            "store": {
                "example": {
                    "header": {
                        "imag": {
                            "version": "0.4.0"
                        }
                    },
                    "content": "hi there!"
                }
            }
        }
        "#;

        let example_json : ::serde_json::Value = ::serde_json::from_str(example).unwrap();

        let output_json = String::from_utf8(out.into_inner()).unwrap();
        let output_json : ::serde_json::Value = ::serde_json::from_str(&output_json).unwrap();

        assert_eq!(example_json, output_json);
    }
}