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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//Copyright (c) 2020 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 libzettels. If not, see http://www.gnu.org/licenses/.
#![doc(html_logo_url = "https://assets.gitlab-static.net/uploads/-/system/project/avatar/3505512/libzettels.png")]

//! Module to generate a set of example files.
//!
//! It provides three functions intended for application developers to
//! - test their application against valid data
//! - provide their users way to quickly try out the respective application
//!   without having to create a bunch of zettel files
//! 
//! All three functions take a path to a directory as an argument. They will
//! panic if that path doesn't exist, is not a directory, isn't writable
//! etc.
//!
//! Inside the specified directory, they generate two directories with one
//! subdirectory each:
//! ```text, no_run
//! example_config      // equivalent to user config dir, e.g. $HOME/.config
//! └── libzettels      // equivalent to $HOME/.config/YourApplication
//! examples            // somewhere in the user's files, e.g. $HOME/Documents
//! └── Zettelkasten    // equivalent to the user's chosen root directory
//! ```
//! The three functions differ in how they populate these directories:
//! - [`generate_bare_examples`](fn.generate_bare_examples.html) only
//!   populates `examples/Zettelkasten` with a bunch of zettel files
//!   (and some other files a user might have in there).
//!   It's intended to test/try starting from scratch (i.e. let the user
//!   create a configuration and create a fresh index.)
//! - [`generate_examples_with_config`](fn.generate_examples_with_config.html)
//!   also writes a configuration file (in YAML) to 
//!   `example_config/libzettels`. It's intended to test/try creating a fresh
//!   index without going through the setup process.
//! - [`generate_examples_with_index`](fn.generate_examples_with_index.html)
//!   adds a ready-made index file inside `example_config/libzettels`. It's 
//!   intended to test/try user interaction with the Zettelkasten (e.g. 
//!   querying, updating etc.)
//!
//! # Note to application developers:
//! If you pass the path to a temporary directory to these functions, make sure
//! the actual directory lives long enough.
//! For example, if you use the [tempfile](https://crates.io/crates/tempfile) 
//! crate:
//! # Panics - Don't do this
//! ```rust, should_panic
//! # extern crate libzettels;
//! # use libzettels::examples::generate_bare_examples;
//! extern crate tempfile;
//! use tempfile::tempdir;
//! fn setup_tmp_dir() -> std::path::PathBuf {
//!     let tmp_dir = tempdir().expect("Failed to create tmp_dir");
//!     // do a lot of setup stuff
//!     // -- snip --
//!     // just return the path to our nicely prepared temp dir
//!     tmp_dir.path().to_path_buf()
//! }
//!
//! fn main() {
//!     let dir = setup_tmp_dir();
//!     generate_bare_examples(dir).expect("The temporary directory no longer exists!");
//! }
//! ```
//! # Instead, do this
//! ```rust
//! # extern crate libzettels;
//! # use libzettels::examples::generate_bare_examples;
//! extern crate tempfile;
//! use tempfile::tempdir;
//!
//! fn main() {
//!     let tmp_dir = tempdir().expect("Failed to create tmp_dir");
//!     generate_bare_examples(tmp_dir.path());
//! }
//! ```
//! # Or this
//! ```rust
//! # extern crate libzettels;
//! # use libzettels::examples::generate_bare_examples;
//! extern crate tempfile;
//! use tempfile::{tempdir, TempDir};
//!
//! fn setup_tmp_dir() -> TempDir {
//!     let tmp_dir = tempdir().expect("Failed to create tmp_dir");
//!     // do a lot of setup stuff
//!     // -- snip --
//!     // return `TempDir` itself to keep it alive
//!     tmp_dir
//! }
//!
//! fn main() {
//!     let tmp_dir = setup_tmp_dir();
//!     generate_bare_examples(tmp_dir.path());
//! }
//! ```
// --------------------------------------------------------------------------
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use {Config, Index, IndexingMethod};

/// Takes the path to a directory and creates a directory structure with set of
/// example files inside it.
/// 
/// The result can be represented as follows:
/// ```text, no_run
/// examples
/// └── Zettelkasten
///     └── file1.md
///     └── file2.md
///     └── file3.md
///     └── subdir
///         └── file4.md
///         └── file5.md
///     └── onlies
///         └── markdown-only.md
///         └── pure-yaml.yaml
///     └── .hiddendir
///         └── .hiddenfile2.txt
///         └── a-file.txt
///     └── .gitignore
///     └── .zettelsignore
/// └── config
/// ```
/// A few notes:
/// - The zettel files in `examples/Zettelkasten` contain nonsense text and
///   are (probably just as nonsensically) interlinked with each other in
///   various ways.
/// - `.gitignore`'s contents are simply `/.*`, which means all hidden files
///   and directories are ignored.
/// - The subdirectory `onlies` contains files that are not proper zettel 
///   files. One is a markdown file without a YAML-header, the other a 
///   YAML-file (might be a pandoc metadata file). They are still added to the 
///   index, with making the best of the present data and sensible defaults:
///   1. The entry for `markdown-only.md` looks like this:
///      ```yaml
///      onlies/markdown-only.md:
///         title: untitled
///         links:
///             - file2.md
///         followups: []
///         keywords: []
///      ```
///      Everything was filled with empty or default values, but the one link
///      in the markdown was parsed and correctly added to the zettels links.
///   2. The entry for `pure-yaml.yaml` looks like this:
///      ```yaml
///      onlies/pure-yaml.yaml:
///         title: Pure Yaml
///         links: []
///         followups: []
///         keywords:
///             - example
///             - pureyaml
///      ```
///      All YAML-fields that make sense for a Zettel, were used, the rest
///      was filled with empty values.
///
/// # Errors
/// - [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) of
///   the
/// [`InvalidInput`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.InvalidInput)
///   kind if the provided path is not a directory or cannot be accessed.
/// - A variety of other
///   [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html)s
///   for problems with creating and writing to the files in the directory.
pub fn generate_bare_examples<P: AsRef<Path>>(dir: P) -> std::io::Result<()> {
    use std::io::{Error, ErrorKind};
    let dir = dir.as_ref();

    if dir.is_dir() {
        setup_config_dir(&dir)?;
        setup_root_dir(dir)?;
        Ok(())
    } else {
        let message = format!("{:?} is not a directory or cannot be accessed.", 
                              dir.to_str());
        Err(Error::new(ErrorKind::InvalidInput, message))
    }
}

/// Takes the path to a directory and creates a directory structure with set of
/// example files and a sample config file inside it.
/// 
/// The result can be represented as follows:
/// ```text, no_run
/// examples
/// └── Zettelkasten
///     └── file1.md
///     └── file2.md
///     └── file3.md
///     └── subdir
///         └── file4.md
///         └── file5.md
///     └── onlies
///         └── markdown-only.md
///         └── pure-yaml.yaml
///     └── .hiddendir
///         └── .hiddenfile2.txt
///         └── a-file.txt
///     └── .gitignore
///     └── .zettelsignore
/// └── config
///     └── libzettels.cfg.yaml
/// ```
/// This is almost identical to the result of 
/// [`generate_bare_examples`](fn.generate_bare_examples.html) (see there
/// for details), except `example/config` is no longer empty. It 
/// contains a sample config file in YAML-format, which:
/// - points to `examples/Zettelkasten` as root dir.
/// - points to `example/config/index.yaml` as index file, which 
///   doesn't exist, yet.
/// - sets the [`IndexingMethod`](../enum.IndexingMethod.html) to `Grep`.
/// - sets the ignore file to `.gitignore`.
/// # Errors
/// - [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) of
///   the
/// [`InvalidInput`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.InvalidInput)
///   kind if the provided path is not a directory or cannot be accessed.
/// - A variety of other
///   [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html)s
///   for problems with creating and writing to the files in the directory.
/// # Panics
/// - Panics if the generated `Config` can't be written to file. This
///   should only happen if something is wrong with the example data. In
///   other words: it shouldn't happen and is considered a bug.
pub fn generate_examples_with_config<P: AsRef<Path>>(dir: P) -> std::io::Result<()> {
    let dir = dir.as_ref();
    generate_bare_examples(dir)?;
    
    let config_dir = dir.join("examples/config/");
    let rootdir = dir.join("examples/Zettelkasten/");
    let indexfile = config_dir.join("index.yaml"); //doesn't exist yet. Only
                                                   //entry in Config 
    let mut cfg = Config::new(&rootdir, &indexfile);
    cfg.indexingmethod = IndexingMethod::Native;
    let cfg_file = config_dir.join("libzettels.cfg.yaml");
    cfg.to_file(&cfg_file)
        .expect("It seems something is wrong with the example data.
        Failed to write Config to file. Please file a bug.");
    Ok(())
}

/// Takes the path to a directory and creates a directory structure with set of
/// example files and a sample config file inside it, indexes the files and 
/// saves the index.
/// 
/// The result can be represented as follows:
/// ```text, no_run
/// examples
/// └── Zettelkasten
///     └── file1.md
///     └── file2.md
///     └── file3.md
///     └── subdir
///         └── file4.md
///         └── file5.md
///     └── onlies
///         └── markdown-only.md
///         └── pure-yaml.yaml
///     └── .hiddendir
///         └── .hiddenfile2.txt
///         └── a-file.txt
///     └── .gitignore
///     └── .zettelsignore
/// └── config
///     └── libzettels.cfg.yaml
///     └── index.yaml
/// ```
/// This is almost identical to the result of 
/// [`generate_examples_with_config`](fn.generate_examples_with_config.html) 
/// (see there for details), except `example/config/index.yaml` 
/// now actually exists.
/// # Errors
/// - [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) of
///   the
/// [`InvalidInput`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.InvalidInput)
///   kind if the provided path is not a directory or cannot be accessed.
/// - A variety of other
///   [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html)s
///   for problems with creating and writing to the files in the directory.
/// # Panics
/// - if the generated `Config` can't be written to or read from file. This
///   should only happen if something is wrong with the example data. In
///   other words: it shouldn't happen and is considered a bug.
/// - if the generated files cannot be indexed, properly. This
///   should only happen if something is wrong with the example data. In
///   other words: it shouldn't happen and is considered a bug.
pub fn generate_examples_with_index<P: AsRef<Path>>(dir: P)  -> std::io::Result<()> {
    let dir = dir.as_ref();
    generate_examples_with_config(dir)?;
    
    //let config_dir = dir.join("example_config/libzettels");
    let config_dir = dir.join("examples/config");
    let _rootdir = dir.join("examples/Zettelkasten/");
    let _indexfile = config_dir.join("index.yaml");
    let cfg_file = config_dir.join("libzettels.cfg.yaml");
    let cfg = Config::from_file(cfg_file)
        .expect("It seems something is wrong with the example data.
        Failed to read config from wile. Please file a bug.");
    let index = Index::new(&cfg)
        .expect("It seems something is wrong with the example data.
        Failed to create the index. Please file a bug.");
    index.save(&cfg)
        .expect("It seems something is wrong with the example data.
        Failed to write the index to file. Please file a bug.");
    Ok(())
}

fn setup_config_dir<P: AsRef<Path>>(dir: P) -> std::io::Result<()> {
    let dir = dir.as_ref(); 
    let config_dir = dir.join("examples/config");
    fs::create_dir_all(config_dir)?;
    Ok(())
}

fn setup_root_dir<P: AsRef<Path>>(dir: P) -> std::io::Result<()> {
    let dir = dir.as_ref();
    let rootdir = dir.join("examples/Zettelkasten/");
    fs::create_dir_all(rootdir.join("subdir"))?;
    fs::create_dir_all(rootdir.join("onlies"))?;
    let mut file1 = File::create(rootdir.join("file1.md"))?;
    writeln!(file1, "{}", FILE1)?; //see below
    let mut file2 = File::create(rootdir.join("file2.md"))?;
    writeln!(file2, "{}", FILE2)?; //see below
    let mut file3 = File::create(rootdir.join("file3.md"))?;
    writeln!(file3, "{}", FILE3)?; //see below
    let mut file4 = File::create(rootdir.join("subdir/file4.md"))?;
    writeln!(file4, "{}", FILE4)?; //see below
    let mut file5 = File::create(rootdir.join("subdir/file5.md"))?;
    writeln!(file5, "{}", FILE5)?; //see below
    let mut markdown_only = File::create(rootdir.join("onlies/markdown-only.md"))?;
    writeln!(markdown_only, "{}", MARKDOWN_ONLY)?; //see below
    let mut pure_yaml = File::create(rootdir.join("onlies/pure-yaml.yaml"))?;
    writeln!(pure_yaml, "{}", PURE_YAML)?; //see below
    // Just any old hidden file
    let mut hiddenfile = File::create(rootdir.join(".hiddenfile.txt"))?;
    writeln!(hiddenfile, "{}", "Nothing important.")?;
    fs::create_dir_all(rootdir.join(".hiddendir"))?;
    let mut hiddenfile2 = File::create(rootdir.join(".hiddendir/.hiddenfile2.txt"))?;
    writeln!(hiddenfile2, "{}", "Also not important.")?;
    let mut file_in_hidden_dir = File::create(rootdir.join(".hiddendir/a-file.txt"))?;
    writeln!(file_in_hidden_dir, "{}", "even less important.")?;
    // A .gitignore file to ignore all hidden files.    
    let mut gitignore = File::create(rootdir.join(".gitignore"))?;
    writeln!(gitignore, "{}", "/.*")?;
    // And a .zettelsignore file with the same content.    
    let mut zettelsignore = File::create(rootdir.join(".zettelsignore"))?;
    writeln!(zettelsignore, "{}", "/.*")?;
    
    //let image_file = rootdir.join("foo.png");
    //// 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 the root directory.
    //non_text.save(&image_file).unwrap();
    
    Ok(())
}


const FILE1: &str = "---
title:  'File 1'
keywords: [example, first, test]
followups: [file2.md, file3.md]
...

My kinda people, my kinda place. There's something special about this place. 
Got no reason to stray too far, 'cause it's all right here in my own backyard! 
This is a Burger King town, it's made just for me! This is a Burger King town, 
we know how burgers should be! Right up the road, left at the sign. My way, 
your way, one at a time, hot off the fire with anything on it! And don't it 
feel good when it's just how you want it? This is a Burger King town, it's made 
just for me! This is a Burger King town, we know how burgers should be!

The year is 1987 and NASA [launches](file2.md) the last of America's deep space 
probes. In a freak mishap, Ranger 3 and its pilot Captain William 'Buck' Rogers 
are blown out of their trajectory into an orbit which freezes his life support 
system and returns Buck Rogers to Earth five hundred years later.

Steve Austin: Astronaut. A man barely alive. Gentlemen... we can rebuild him. 
We have the technology. We have the [capability](file3.md) to make the world's first bionic 
man. Steve Austin will be that man. Better than he was before. Better. 
Stronger. Faster.";

const FILE2: &str = "---
title:  'File 2'
keywords: [example, second]
followups: []
...

Here's [one more hyperlink](http://example.com). Let's see.

Marshall, Will, and Holly on a routine expedition, met the greatest earthquake 
ever known. High on the rapids, it struck their tiny raft! And plunged them 
down a thousand feet below... to the Land of the Lost! Lost! Lost! Lost! Lost!

Here's the story of a lovely lady, who was bringing up three very lovely girls. 
All of them had [hair](file3.md) of gold, like their mother, the youngest one 
in curls. Here's the store, of a man named Brady, who was busy with three boys 
of his own. They were four men, living all together, yet they were all alone. 
'Til the one day when the lady met this fellow. And they knew it was much more 
than a hunch, that this group would somehow form a family. That's the way we 
all became the Brady Bunch, the Brady Bunch. That's the way we all became the 
Brady Bunch. The Brady Bunch!

You unlock this door with the key of imagination. Beyond it is another 
dimension: a dimension of sound, a dimension of sight, a dimension of mind. 
You're moving into a land of both shadow and substance, of things and ideas; 
you've just crossed over into the Twilight Zone.";


const FILE3: &str = "---
title:  'File 3'
author:
- name: John Doe
  affiliation: University of Somewhere
keywords: [example, third]
followups: []
...

Spiderman, Spiderman, does whatever a spider can. Spins a web, any size, 
catches thieves just like flies, look out! Here comes the Spiderman. Is he 
strong? Listen bud, he's got radioactive blood. Can he swing from a thread? 
Take a look overhead. Hey there, there goes the Spiderman. In the chill of 
night at the scene of a crime, like a streak of light he arrives just in time! 
Spiderman, Spiderman, friendly neighborhood Spiderman. Wealth and fame, He's 
ignored. Action is his reward. To him, life is a great big bang up. Whenever 
there's a hang up, you'll find the Spiderman!

Come and knock on our door. We've been waiting for you. Where the kisses are 
hers and hers and his, three's company, too! Come and dance on our floor. Take 
a step that is [new](file1.md). We've a lovable space that needs your face, 
three's company, too! You'll see that life is a ball again and laughter is 
callin' for you. Down at our rendezvous, three's company, too!

Well we're movin' on up, to the east side. To a deluxe apartment in the sky. 
Movin' on up, To the east side. We finally got a piece of the pie. Fish don't 
fry in the kitchen, beans don't burn on the grill. Took a whole lotta tryin' 
just to get up that hill. Now we're up in the big leagues, gettin' our turn at 
bat. As long as we live, it's you and me baby, There ain't nothin' wrong with 
that. Well we're movin' on up, to the east side. To a deluxe apartment in the 
sky. Movin' on up, to the east side. We finally got a piece of the pie.";

const FILE4: &str = "---
title:  'File 4'
keywords: [example, fourth]
followups: ['../file1.md', 'file5.md']
...

This is points to [File 1 in the root directory](../file1.md)";

const MARKDOWN_ONLY: &str = "This example file comes without a 
[yaml-metadata-block](http://pandoc.org/README.html#yaml_metadata_block) as 
suggested by pandoc. I contains, however not only the external link above, 
but also a relative link to [another file](../file2.md). The rest is not important.
You can stop reading now. Seriously, nothing interesting beyond this point. I 
don't even know why I'm writing this. I could even break up in the middle of";

const PURE_YAML: &str = "---
title:  'Pure Yaml'
author:
- name: John Doe
  affiliation: University of Somewhere
keywords: [example, pureyaml]
...

";

const FILE5: &str = "---
title:  'File 5'
keywords: []
followups: []
---

# Let's see

What happens if the metadata [block](../file1.md) doesn't end with three dots, 
but three dashes? And does it also work if the rest of the document contains 
\"...\"?
And \"---\", too?
And as a single line?
...
And \"---\", too?
---";