libzettels 0.4.1

A library intended as a backend for applications which implement Niklas Luhmann's system of a 'Zettelkasten'.
Documentation
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
//Copyright (c) 2020-2022 Stefan Thesing
//
//This file is part of libzettels.
//
//libzettels is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//libzettels 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 General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Zettels. If not, see http://www.gnu.org/licenses/.

//! Module for handling configuration files.

// --------------------------------------------------------------------------
extern crate serde_yaml;

use std::fs;
use std::fs::File;
use std::io::{Write};
use std::path::{Path, PathBuf};


use backstage::indexing::IndexingMethod;
use backstage::querying::sequences::SequenceStart;
use backstage::error::Error;

/// `Config` represents the user's configuration. See "Fields" for details of 
/// what each value represents. It bundles user specified settings from a 
/// configuration file and can be serialized to and deserialized from such a 
/// file.
///
/// `Config` derives Serialize and Deserialize via [serde](https://serde.rs/) 
/// and can thus be serialized and deserialized to any format supported by 
/// serde. See README.md for details.
///
/// The included methods [`from_file`](struct.Config.html#method.from_file) and
/// [`to_file`](struct.Config.html#method.to_file) (de)serialize from/to YAML.
/// 
/// # Example
/// ## Minimal Configuration file (YAML)
/// ```yaml,no_run
/// ---
/// rootdir: examples/Zettelkasten
/// indexfile: examples/index.yaml
/// ``` 
/// ## Full Configuration file (YAML)
/// ```yaml,no_run
/// ---
/// rootdir: examples/Zettelkasten
/// indexfile: examples/index.yaml
/// indexingmethod: Grep
/// sequencestart: Keyword
/// ignorefile: .gitignore
/// ```
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
    /// The path to the root directory of the Zettelkasten, i.e. the directory 
    /// containing the zettel files.
    pub rootdir: PathBuf,
    /// The path to the index file.
    pub indexfile: PathBuf,
    /// **Optional:** Indexing method
    ///
    /// **Default:** `IndexingMethod::Native`
    #[serde(default = "default_indexingmethod")]
    pub indexingmethod: IndexingMethod,
    /// **Optional:** Criteria how libzettels identifies a Zettel as the start of
    /// a sequence.
    ///
    /// **Default:** `SequenceStart::Keyword`
    #[serde(default = "default_sequencestart")]
    pub sequencestart: SequenceStart,
    /// **Optional:** A file specifying patterns to be ignored by the 
    // Zettelkasten, relative to the root directory. It uses the same syntax 
    /// as 
    /// [gitignore](https://www.kernel.org/pub/software/scm/git/docs/gitignore.html#_pattern_format)
    /// files.
    ///
    /// **Default:** By default, it *is* `.gitignore` (because you might manage your 
    /// Zettelkasten with git).
    /// But in case you want different ignore-patterns for git and your
    /// Zettelkasten, you can specify an alternative file, here (e.g. 
    /// `.zettelsignore`).
    #[serde(default = "default_ignorefile")]
    pub ignorefile: PathBuf,
}

// Default values for serde
fn default_indexingmethod() -> IndexingMethod {
    IndexingMethod::Native
}

fn default_sequencestart() -> SequenceStart {
    SequenceStart::Keyword
}

// Default values for serde
fn default_ignorefile() -> PathBuf {
    PathBuf::from(".gitignore")
}

impl Config {
    /// Creates a new Config by specifying a root directory and a file name
    /// for the index file as strings.
    /// # Example
    /// ```
    /// # use libzettels::Config;
    /// # use std::path::Path;
    /// let cfg = Config::new("examples/Zettelkasten", 
    ///                       "examples/index.yaml");
    ///
    /// assert_eq!(&cfg.rootdir, Path::new("examples/Zettelkasten"));
    /// assert_eq!(&cfg.indexfile, Path::new("examples/index.yaml"));
    /// assert_eq!(&cfg.ignorefile, Path::new(".gitignore"));
    /// ```
    pub fn new<T: AsRef<Path>>(rootdir: T, 
                               indexfile: T) -> Config {
        let rootdir = rootdir.as_ref();
        let indexfile = indexfile.as_ref();
        Config {
            rootdir: PathBuf::from(rootdir),
            indexfile: PathBuf::from(indexfile),
            indexingmethod: default_indexingmethod(),
            sequencestart: default_sequencestart(),
            ignorefile: default_ignorefile(), 
        }
    }

    /// Creates a new Config by deserializing it from a YAML-file.
    /// # Example
    /// ```rust,no_run
    /// # use libzettels::{Config, Error};
    /// # use std::path::Path;
    /// # fn foo() -> Result<Config, Error>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// # Ok((cfg))
    /// # }
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems with the 
    ///   specified file.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) for problems 
    ///   deserializing from YAML.
    pub fn from_file<P: AsRef<Path>>(configfile: P) -> Result<Config, Error> {
        let contents = fs::read_to_string(configfile)?;       // std::io::Error
        let cfg: Config = serde_yaml::from_str(&contents)?; // serde_yaml::Error
        Ok(cfg)
    }

    /// Serializes the Config `self` to a YAML-file.
    /// # Example
    /// ```rust,no_run
    /// # use libzettels::Config;
    /// # use std::path::Path;
    /// let cfg = Config::new("examples/Zettelkasten", 
    ///                       "examples/index.yaml");
    /// match cfg.to_file(Path::new("examples/zettels-examples.cfg.yaml")) {
    ///    Ok(_) => println!("Saved config."), 
    ///    Err(error) => panic!("Failed to write config to file. {}", error),
    /// };
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems with the 
    ///   specified file.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) for problems 
    ///   serializing to YAML.
    pub fn to_file<P: AsRef<Path>>(&self, configfile: P) -> Result<(), Error> {
        let s = serde_yaml::to_string(self)?;               //serde_yaml::Error
        let mut file = File::create(configfile)?;             //io::Error
        writeln!(file, "{}", s)?;                           //io:Error
        Ok(())
    }
}

// --------------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    extern crate tempfile;
    use self::tempfile::tempdir;
    
    use super::*;
    use examples::*;
    
    // ----------------------------------------------------------------------
    // valid data
    // ----------------------------------------------------------------------
    
    #[test]
    fn test_default_indexing_method() {
        assert_eq!(default_indexingmethod(), IndexingMethod::Native);
    }
    
    #[test]
    fn test_default_ignorefile() {
        assert_eq!(default_ignorefile(), PathBuf::from(".gitignore"));
    }
    
    #[test]
    fn new_config() {
        let cfg = Config::new("examples/Zettelkasten", 
                              "examples/index.yaml");
        
        assert_eq!(&cfg.rootdir, std::path::Path::new("examples/Zettelkasten"));
        assert_eq!(&cfg.indexfile, std::path::Path::new("examples/index.yaml"));
        assert_eq!(&cfg.ignorefile, std::path::Path::new(".gitignore"));
    }
    
    #[test]
    fn test_cfg_from_file() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let dir = &tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        // Setup
        let config_dir = dir.join("examples/config/");
        let cfg_file_path = config_dir.join("libzettels.cfg.yaml");
        let rootdir = dir.join("examples/Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let cfg = Config::from_file(cfg_file_path).unwrap(); //panics on fail
        assert_eq!(cfg.rootdir, rootdir);
        assert_eq!(cfg.indexfile, indexfile);
        assert_eq!(cfg.ignorefile, std::path::Path::new(".gitignore"));
    }
    
    #[test]
    fn test_cfg_from_file_minimal() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let cfg_file_path = tmp_dir.path().join("libzettels.cfg.yaml");
        let mut f = std::fs::File::create(&cfg_file_path)
                    .expect("Failed to create file");
        let yaml = "---
rootdir: examples/Zettelkasten
indexfile: examples/index.yaml";
        write!(f, "{}", yaml).expect("Failed to write to file");
        
        let cfg = Config::from_file(cfg_file_path).unwrap(); //panics on fail
        assert_eq!(cfg.rootdir, std::path::Path::new("examples/Zettelkasten"));
        assert_eq!(cfg.indexfile, std::path::Path::new("examples/index.yaml"));
        assert_eq!(cfg.ignorefile, std::path::Path::new(".gitignore"));
    }
    
    #[test]
    fn test_cfg_to_file() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let cfg_file_path = tmp_dir.path().join("libzettels.cfg.yaml");
        std::fs::File::create(&cfg_file_path)
                    .expect("Failed to create file");
        let cfg = Config::new("examples/Zettelkasten", 
                              "examples/index.yaml");
        // Test
        assert!(cfg.to_file(cfg_file_path).is_ok());
    }
    
    // ----------------------------------------------------------------------
    // invalid data aka test error handling
    // ----------------------------------------------------------------------
    
    // fn test_config_new(): No test. The compiler accepts only things that can
    // be converted into strings and every string can be used to construct a 
    // PathBuf. Whether or not invalid paths are a problem becomes visible in
    // other functions.
    
    #[test]
    fn test_cfg_from_nonexistent_file() {
        // Setup
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let cfg_file_path = tmp_dir.path().join("foo");
        let cfg = Config::from_file(cfg_file_path);
        assert!(cfg.is_err());
        let e = cfg.unwrap_err();
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or \
                        directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_cfg_from_random_text_file() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let dir = &tmp_dir.path();
        generate_bare_examples(dir).expect("Failed to generate examples");
        // Setup
        let cfg_file_path = dir.join("foo");
        let mut test_config_file = File::create(&cfg_file_path)
                .expect("Something went wrong with creating a temporary file for
                the test.");
        writeln!(test_config_file, "Some random stuff.")
                .expect("Something went wrong with writing to the temporary file
                for the test.");
        //Test        
        let cfg = Config::from_file(cfg_file_path);
        assert!(cfg.is_err());
        let e = cfg.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid type"));
                assert!(message.contains("expected struct Config"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_cfg_from_file_missing_field() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let cfg_file_path = tmp_dir.path().join("foo");
        let mut test_config_file = File::create(&cfg_file_path)
                .expect("Something went wrong with creating a temporary file for
                the test.");
        let erroneous_config = "---
    roodir: examples/Zettelkasten
    indexfile: examples/index.yaml
    indexingmethod: Grep
    ignorefile: \".gitignore\"";
        writeln!(test_config_file, "{}", erroneous_config)
                .expect("Something went wrong with writing to the temporary file
                for the test.");
        //Test        
        let cfg = Config::from_file(cfg_file_path);
        assert!(cfg.is_err());
        let e = cfg.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("missing field `rootdir`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_cfg_from_file_unknown_variant() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let cfg_file_path = tmp_dir.path().join("foo");
        let mut test_config_file = File::create(&cfg_file_path)
                .expect("Something went wrong with creating a temporary file for
                the test.");
        let erroneous_config = "---
    rootdir: examples/Zettelkasten
    indexfile: examples/index.yaml
    indexingmethod: Gep
    ignorefile: \".gitignore\"";
        writeln!(test_config_file, "{}", erroneous_config)
                .expect("Something went wrong with writing to the temporary file
                for the test.");
        //Test        
        let cfg = Config::from_file(cfg_file_path);
        assert!(cfg.is_err());
        let e = cfg.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("unknown variant"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_cfg_from_non_text_file() {
        let tmp_dir = tempdir().expect("Failed to create tempdir");
        let image_file = tmp_dir.path().join("foo.png");
        let cfg_file_path = tmp_dir.path().join("foo");
         // Generate an image
        let width: u32 = 10;
        let height: u32 = 10;
        let mut non_text = image::ImageBuffer::new(width, height);
         //color all pixels white
        for (_, _, pixel) in non_text.enumerate_pixels_mut() {
            *pixel = image::Rgb([255, 255, 255]);
        }
         // write it to where our confing file is supposed to be.
        non_text.save(&image_file).unwrap();
         // The ImageBuffer needed the extension `.png` do determine the
         // file format. Bet we don't want to give Config::from_file any hints.
         //  So let's rename it.
        std::fs::rename(image_file, &cfg_file_path).expect("Failed to rename");
                
        let cfg = Config::from_file(cfg_file_path);
        assert!(cfg.is_err());
        let e = cfg.unwrap_err();
        match e {
            Error::Io(inner) => assert_eq!(inner.kind(), 
                                           std::io::ErrorKind::InvalidData),
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }        
    }
    
    #[test]
    fn test_cfg_to_file_wrong_path() {
        //Setup
        let tmp_dir = tempdir().expect("Failed to create temp dir");
        let config_dir = tmp_dir.path().join("foo"); // doesn't exist
        let cfg = Config::new("examples/Zettelkasten", 
                              "examples/index.yaml");
        // Test
        let configfile = config_dir.join("foo");
        let result = cfg.to_file(&configfile);
        assert!(result.is_err());
        let e = result.unwrap_err();
        
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or \
                        directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_cfg_to_file_read_only() {
        use std::fs;
        //Setup
        let tmp_dir = tempdir().expect("Failed to create temp dir");
        let config_dir = tmp_dir.path();
            // equivalent to e.g. $HOME/.config/libzettels
        let config_file = config_dir.join("foo");
        fs::File::create(&config_file)
            .expect("Failed to setup config file");
        let metadata = fs::metadata(&config_file)
            .expect("Failed to get metadata");
        let mut perms = metadata.permissions();
        perms.set_readonly(true);
        fs::set_permissions(&config_file, perms)
            .expect("Failed to set the config file to read_only");
        
        
        let cfg = Config::new("examples/Zettelkasten", 
                              "examples/index.yaml");
        // Test
        let result = cfg.to_file(&config_file);
        assert!(result.is_err());
        let e = result.unwrap_err();
            match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::PermissionDenied => {
                        assert!(inner.to_string().contains("Permission denied"));
                    },
                    _ => panic!("Expected a PermissionDenied error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
}