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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
extern crate rustc_serialize;
extern crate docopt;
extern crate exec;
extern crate regex;

#[cfg(test)]
extern crate rand;

pub mod command;
pub mod cli;
pub mod message;

use std::env;
use std::path::PathBuf;
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;
use rustc_serialize::json;

/// The main Key-Value structure.
pub struct Slate {

    /// Where the file containing the data is.
    pub filepath: PathBuf,
}

impl Default for Slate {

    /// Get a default Slate. It will use a default file
    /// in your home directory, the `.slate` file.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    ///
    /// let slate: Slate = Default::default();
    /// println!("{}", slate.filepath.to_str().unwrap());
    /// //=> $HOME/.slate
    /// ```
    fn default() -> Slate {
        let mut path = match env::home_dir() {
            Some(home) => home,
            None => panic!("No HOME dir found"),
        };
        path.push(".slate");

        Slate { filepath: path }
    }
}

impl Slate {

    /// Set a key with its value.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    /// let key = "foo".to_string();
    /// let value = "bar".to_string();
    ///
    /// match slate.set(&key, &value) {
    ///   Ok(_) => println!("Saved"),
    ///   Err(e) => panic!("{}", e),
    /// };
    /// ```
    pub fn set(&self, key: &String, value: &String) -> Result<(), &'static str> {
        let mut contents = match self.read() {
            Ok(contents) => contents,
            Err(e) => { return Err(e) },
        };

        contents.insert(key.to_owned(), value.to_owned());

        self.write(&contents)
    }

    /// Get the value of a key
    ///
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    /// let key = "foo".to_string();
    ///
    /// match slate.get(&key) {
    ///   Ok(value) => println!("{}", value), //=> bar
    ///   Err(e) => panic!("{}", e),
    /// };
    /// ```
    pub fn get(&self, key: &String) -> Result<String, &'static str> {
        let contents = match self.read() {
            Ok(contents) => contents,
            Err(e) => { return Err(e) },
        };

        match contents.get(key) {
            Some(value) => Ok(value.to_string()),
            None => Ok(String::new()),
        }
    }

    /// Remove completely a key with its value.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    /// let key = "foo".to_string();
    ///
    /// match slate.remove(&key) {
    ///   Ok(_) => println!("Key removed"),
    ///   Err(e) => panic!("{}", e),
    /// };
    /// ```
    pub fn remove(&self, key: &String) -> Result<(), &'static str> {
        let mut contents = match self.read() {
            Ok(contents) => contents,
            Err(e) => { return Err(e) },
        };

        contents.remove(key);

        self.write(&contents)
    }

    /// Remove all keys.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    ///
    /// match slate.clear() {
    ///   Ok(_) => println!("Keys removed"),
    ///   Err(e) => panic!("{}", e),
    /// };
    /// ```
    pub fn clear(&self) -> Result<(), &'static str> {
        let mut contents = match self.read() {
            Ok(contents) => contents,
            Err(e) => { return Err(e) },
        };

        contents.clear();

        self.write(&contents)
    }

    /// Rename a key.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    /// let old = "foo".to_string();
    /// let new = "bar".to_string();
    ///
    /// match slate.rename(&old, &new) {
    ///   Ok(_) => println!("Renamed!"),
    ///   Err(e) => panic!("{}", e),
    /// };
    /// ```
    pub fn rename(&self, src: &String, dts: &String) -> Result<(), &'static str> {
        let value = match self.get(src) {
            Ok(v) => v,
            Err(e) => { return Err(e) },
        };

        if let Err(e) = self.set(dts, &value) {
            return Err(e);
        };

        if let Err(e) = self.remove(src) {
            return Err(e);
        };

        Ok(())
    }

    /// Get a list of all keys.
    ///
    /// # Example
    ///
    /// ```
    /// use slate::Slate;
    /// use std::env;
    ///
    /// // Create a temporal file for
    /// // the example. You can use Default::default();
    /// // to create the Slate and skip this part.
    /// let mut temp = env::temp_dir();
    /// temp.push(".slate");
    ///
    /// let slate: Slate = Slate { filepath: temp };
    /// let list = match slate.list() {
    ///   Ok(all) => all,
    ///   Err(e) => panic!("{}", e),
    /// };
    ///
    /// for key in &list {
    ///   println!("{}", key);
    /// }
    /// ```
    pub fn list(&self) -> Result<Vec<String>, &'static str> {
        let contents = match self.read() {
            Ok(contents) => contents,
            Err(e) => { return Err(e) },
        };

        let mut keys: Vec<_> = contents.keys().collect();
        keys.sort(); // sort needs a mutable instance!!

        let list: Vec<_> = keys.iter().map(|&s| s.clone()).collect();

        Ok(list)
    }

    /// Read the contents of the Slate file.
    fn read(&self) -> Result<HashMap<String, String>, &'static str> {
        let mut r = match File::open(&self.filepath) {
            Ok(file) => file,
            Err(_) => {
                let empty = HashMap::new();
                match self.write(&empty) {
                    Ok(_) => File::open(&self.filepath).unwrap(),
                    Err(e) => { return Err(e) }
                }
            },
        };

        let mut buffer = String::new();
        if let Err(_) = r.read_to_string(&mut buffer) {
            return Err("Error reading file");
        };

        let contents: HashMap<String, String> = match json::decode(&buffer) {
            Ok(hash) => hash,
            Err(_) => HashMap::new(),
        };

        Ok(contents)
    }

    /// Write to the Slate file.
    fn write(&self, contents: &HashMap<String, String>) -> Result<(), &'static str> {
        let encoded = json::encode(&contents).unwrap();

        let mut f = match File::create(&self.filepath) {
            Ok(file) => file,
            Err(_) => { return Err("Cannot create file") },
        };
        match f.write_all(encoded.as_bytes()) {
            Ok(_) => Ok(()),
            Err(_) => Err("Cannot save file"),
        }
    }
}


/// Get the version of the library.
pub fn version() -> String {
    let (maj, min, pat) = (
        option_env!("CARGO_PKG_VERSION_MAJOR"),
        option_env!("CARGO_PKG_VERSION_MINOR"),
        option_env!("CARGO_PKG_VERSION_PATCH"),
    );

    match (maj, min, pat) {
        (Some(maj), Some(min), Some(pat)) =>
            format!("{}.{}.{}", maj, min, pat),
            _ => "".to_owned(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::path::PathBuf;
    use std::io::prelude::*;
    use std::fs::File;
    use rand::{thread_rng, Rng};

    fn create_temp_file(body: &str) -> PathBuf {
        let random_name: String = thread_rng().gen_ascii_chars().take(10).collect();
        let random_name = random_name + ".json";

        let mut temp = env::temp_dir();
        temp.push(&random_name);

        let mut file = match File::create(&temp) {
            Ok(file) => file,
            Err(e) => panic!("Cannot create temporal file for tests: {:?}", e),
        };
        if let Err(e) = file.write_all(body.as_bytes()) {
            panic!("Cannot add data to temporal file for tests: {:?}", e);
        };

        temp
    }

    #[test]
    fn test_default_slate() {
        let slate: Slate = Default::default();
        let mut expected: PathBuf = env::home_dir().unwrap();
        expected.push(".slate");

        assert_eq!(expected, slate.filepath);
    }

    #[test]
    fn it_sets_keys_with_values() {
        let temp = create_temp_file("");
        let mut file = File::open(&temp).unwrap();
        let slate = Slate { filepath: temp };
        let key = "test".to_string();
        let value = "expected".to_string();

        if let Err(e) = slate.set(&key, &value) {
            panic!("Cannot set a value: {:?}", e);
        };

        let mut buffer = String::new();
        let expected = "{\"test\":\"expected\"}";
        if let Err(e) = file.read_to_string(&mut buffer) {
            panic!("Cannot read temporal file for tests: {:?}", e);
        };
        assert_eq!(expected, buffer);
    }

    #[test]
    fn it_gets_keys() {
        let temp = create_temp_file("{\"test\":\"expected\"}");
        let slate = Slate { filepath: temp };
        let key = "test".to_string();

        match slate.get(&key) {
            Ok(value) => assert_eq!("expected", value),
            Err(e) => panic!("Cannot get a value from slate: {:?}", e),
        }
    }

    #[test]
    fn it_gets_missing_keys() {
        let temp = create_temp_file("{\"test\":\"expected\"}");
        let slate = Slate { filepath: temp };
        let key = "missing".to_string();

        match slate.get(&key) {
            Ok(value) => assert_eq!("", value),
            Err(e) => panic!("Cannot get a value from slate: {:?}", e),
        }
    }

    #[test]
    fn it_lists_keys() {
        let temp = create_temp_file("{\"a\":\"1\",\"b\":\"2\"}");
        let slate = Slate { filepath: temp };

        match slate.list() {
            Ok(list) => assert_eq!(vec!["a", "b"], list),
            Err(e) => panic!("Cannot get list of values: {:?}", e),
        }
    }

    #[test]
    fn it_removes_keys() {
        let temp = create_temp_file("{\"test\":\"expected\"}");
        let mut file = File::open(&temp).unwrap();
        let slate = Slate { filepath: temp };
        let key = "test".to_string();

        if let Err(e) = slate.remove(&key) {
            panic!("Cannot remove the key: {:?}", e);
        };

        let mut buffer = String::new();
        let expected = "{}";
        if let Err(e) = file.read_to_string(&mut buffer) {
            panic!("Cannot read temporal file for tests: {:?}", e);
        };
        assert_eq!(expected, buffer);
    }

    #[test]
    fn it_renames_keys() {
        let temp = create_temp_file("{\"test\":\"expected\"}");
        let mut file = File::open(&temp).unwrap();
        let slate = Slate { filepath: temp };
        let key = "test".to_string();
        let new_key = "spec".to_string();

        if let Err(e) = slate.rename(&key, &new_key) {
            panic!("Cannot move the key: {:?}", e);
        };

        let mut buffer = String::new();
        let expected = "{\"spec\":\"expected\"}";
        if let Err(e) = file.read_to_string(&mut buffer) {
            panic!("Cannot read temporal file for tests: {:?}", e);
        };
        assert_eq!(expected, buffer);
    }

    #[test]
    fn it_clears_keys() {
        let temp = create_temp_file("{\"test\":\"expected\"}");
        let mut file = File::open(&temp).unwrap();
        let slate = Slate { filepath: temp };

        if let Err(e) = slate.clear() {
            panic!("Cannot clear keys: {:?}", e);
        };

        let mut buffer = String::new();
        let expected = "{}";
        if let Err(e) = file.read_to_string(&mut buffer) {
            panic!("Cannot read temporal file for tests: {:?}", e);
        };
        assert_eq!(expected, buffer);
    }
}