quicknotes/
lib.rs

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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::enum_variant_names)]

use std::collections::HashMap;
use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};

use chrono::{DateTime, NaiveDate, TimeZone};
use index::{LookupError as IndexLookupError, OpenError as IndexOpenError};
use io::Write;
use note::{Preamble, SerializeError};
use rusqlite::Connection;
use storage::{
    store_if_different, StoreIfDifferentError, StoreNote, StoreNoteAt, StoreNoteIn, TempFileHandle,
};
use tempfile::{Builder as TempFileBuilder, NamedTempFile, TempPath};
use thiserror::Error;
use walkdir::{DirEntry, WalkDir};

pub use edit::{CommandEditor, Editor};
pub use index::{IndexedNote, NoteKind};
pub use note::Preamble as NotePreamble;

mod edit;
mod index;
mod note;
mod storage;

macro_rules! warning {
        ($($arg:tt)*) => {{
            use colored::Colorize;

            eprint!("{}: ", "warning".yellow());
            eprintln!($($arg)*)
        }};
    }

pub(crate) use warning;

pub struct NoteConfig {
    pub root_dir: PathBuf,
    pub file_extension: String,
    pub temp_root_override: Option<PathBuf>,
}

impl NoteConfig {
    #[must_use]
    pub fn notes_directory_path(&self) -> PathBuf {
        self.root_dir.join(Path::new("notes"))
    }

    #[must_use]
    pub fn daily_directory_path(&self) -> PathBuf {
        self.root_dir.join(Path::new("daily"))
    }

    #[must_use]
    pub fn index_db_path(&self) -> PathBuf {
        self.root_dir.join(Path::new(".index.sqlite3"))
    }
}

/// Create a new note.
///
/// The note will be created in the notes directory, with a name as close to the given title as
/// possible, and then opened in the editor.
///
/// Returns the path of the note, or None if nothing was written to the note.
///
/// # Errors
///
/// Returns an error if there is an I/O failure creating the note, the editor fails to launch, or
/// if there is a problem adding the note to the index.
pub fn make_note<E: Editor, Tz: TimeZone>(
    config: &NoteConfig,
    editor: E,
    title: String,
    creation_time: &DateTime<Tz>,
) -> Result<Option<PathBuf>, MakeNoteError> {
    let filename_stem = note::filename_stem_for_title(&title);
    let store = StoreNoteIn {
        storage_directory: config.notes_directory_path(),
        preferred_file_stem: filename_stem,
        file_extension: config.file_extension.clone(),
    };

    let maybe_written_path =
        make_note_with_store(config, store, editor, title, creation_time, NoteKind::Note)?;

    Ok(maybe_written_path)
}

/// An error that occurred during a call to [`make_note`]. [errors section](`make_note#Errors`)
/// for more details.
#[derive(Error, Debug)]
#[error(transparent)]
pub struct MakeNoteError {
    #[from]
    inner: MakeNoteAtError,
}

/// Create or open a daily note for the given date.
///
/// This operates very similarly to [`make_note`], but the title of the note will be the
/// date part of the creation time. If one already exists, it will be opened instead of
/// creating a new one.
///
/// Returns the path of the note, or None if nothing was written to the note.
///
/// # Errors
///
/// Returns an error if there is an I/O failure creating the note, the editor fails to launch, or
/// if there is a problem adding the note to the index.
pub fn make_or_open_daily<E: Editor, Tz: TimeZone>(
    config: &NoteConfig,
    editor: E,
    for_day: NaiveDate,
    creation_time: &DateTime<Tz>,
) -> Result<Option<PathBuf>, MakeOrOpenDailyNoteError> {
    let filename_stem = note::filename_stem_for_date(for_day);
    let destination_path = config
        .daily_directory_path()
        .join(filename_stem)
        .with_extension(&config.file_extension);

    let destination_exists = ensure_note_exists(&destination_path)
        .map(|()| true)
        .or_else(|err| {
            if err.kind() == io::ErrorKind::NotFound {
                Ok(false)
            } else {
                Err(InnerMakeOrOpenDailyNoteError::NoteLookupError {
                    destination: destination_path.display().to_string(),
                    err,
                })
            }
        })?;

    if destination_exists {
        open_existing_note_in_editor(config, editor, NoteKind::Daily, &destination_path)
            .map_err(InnerMakeOrOpenDailyNoteError::from)?;

        Ok(Some(destination_path))
    } else {
        // We should be able to store the note with the date's name.
        //
        // Technically someone could come in and put a file there while we are
        // editing this note, but that is not behavior we really support.
        // That file will not be overwritten.
        //
        // Plus, the dailies directory is separate from the notes directory,
        // so without manual intervention, one cannot enter this scenario.
        let store = StoreNoteAt {
            destination: destination_path,
        };

        let maybe_actual_path = make_note_with_store(
            config,
            store,
            editor,
            for_day.format("%Y-%m-%d").to_string(),
            creation_time,
            NoteKind::Daily,
        )
        .map_err(InnerMakeOrOpenDailyNoteError::from)?;

        Ok(maybe_actual_path)
    }
}

/// An error that occurred during a call to [`make_or_open_daily`]. See its
/// [errors section](`make_or_open_daily#Errors`) for more details.
#[derive(Error, Debug)]
#[error(transparent)]
pub struct MakeOrOpenDailyNoteError {
    #[from]
    inner: InnerMakeOrOpenDailyNoteError,
}

#[derive(Error, Debug)]
enum InnerMakeOrOpenDailyNoteError {
    #[error("could not check if note exists at {destination:?}: {err}")]
    NoteLookupError {
        destination: String,
        #[source]
        err: io::Error,
    },

    #[error("could not open daily note: {0}")]
    OpenNoteError(#[from] OpenExistingNoteInEditorError),

    #[error("could not create new daily note: {0}")]
    MakeNoteAtError(#[from] MakeNoteAtError),
}

/// Open an existing note at the given path in the editor.
///
/// # Errors
///
/// Returns an error if there was an I/O problem locating the existing note, the editor
/// fails to launch, or there is a problem updating the note's entry in the index.
pub fn open_note<E: Editor>(
    config: &NoteConfig,
    editor: E,
    kind: NoteKind,
    path: &Path,
) -> Result<(), OpenNoteError> {
    open_existing_note(config, editor, kind, path)?;

    Ok(())
}

#[derive(Error, Debug)]
#[error(transparent)]
pub struct OpenNoteError {
    #[from]
    inner: OpenExistingNoteError,
}

/// Index all notes in the notes and dailies directories. This will also remove deleted files
/// from the index.
///
/// # Errors
///
/// Returns an error if there is a problem opening or the index.
///
/// Note that this will return `Ok` if there is a problem indexing an individual note, but a
/// warning will be printed to stderr.
pub fn index_notes(config: &NoteConfig) -> Result<(), IndexNotesError> {
    index_all_notes(config)?;

    Ok(())
}

#[derive(Error, Debug)]
#[error(transparent)]
pub struct IndexNotesError {
    #[from]
    inner: IndexAllNotesError,
}

/// Get all of the notes currently stored in the index, and metadata about them.
///
/// The returned `HashMap` maps from the path where the note to the metadata stored in its preamble.
///
/// # Errors
///
/// Returns an error if there was a problem opening or reading from the index.
pub fn indexed_notes(
    config: &NoteConfig,
) -> Result<HashMap<PathBuf, IndexedNote>, IndexedNotesError> {
    let notes = all_indexed_notes(config)?;

    Ok(notes)
}

#[derive(Error, Debug)]
#[error(transparent)]
pub struct IndexedNotesError {
    #[from]
    inner: AllIndexedNotesError,
}

/// Get all of the notes currently stored in the index with the given kind, and metadata about them.
///
/// The returned `HashMap` maps from the path where the note to the metadata stored in its preamble.
///
/// # Errors
///
/// Returns an error if there was a problem opening or reading from the index.
pub fn indexed_notes_with_kind(
    config: &NoteConfig,
    kind: NoteKind,
) -> Result<HashMap<PathBuf, IndexedNote>, IndexedNotesWithKindError> {
    let notes = kinded_indexed_notes(config, kind)?;

    Ok(notes)
}

#[derive(Error, Debug)]
#[error(transparent)]
pub struct IndexedNotesWithKindError {
    #[from]
    inner: KindedIndexedNotesError,
}

fn make_note_with_store<E: Editor, Tz: TimeZone, S: StoreNote>(
    config: &NoteConfig,
    store: S,
    editor: E,
    title: String,
    creation_time: &DateTime<Tz>,
    kind: NoteKind,
) -> Result<Option<PathBuf>, MakeNoteAtError> {
    let tempfile = make_tempfile(config).map_err(MakeNoteAtError::CreateTempfileError)?;
    let preamble = Preamble::new(title, creation_time.fixed_offset());

    let serialized_preamble = write_preamble(&preamble, &tempfile)?;
    open_in_editor(editor, &tempfile)?;

    let handle = TempFileHandle::open(tempfile).map_err(MakeNoteAtError::OpenNoteError)?;
    let maybe_actual_path = store_if_different(store, handle, &serialized_preamble)?;

    match maybe_actual_path {
        Some(actual_destination_path) => {
            let mut index_connection = open_index_database(config)?;
            index_note(&mut index_connection, kind, &actual_destination_path)?;

            Ok(Some(actual_destination_path))
        }

        None => Ok(None),
    }
}

#[derive(Error, Debug)]
#[error(transparent)]
enum MakeNoteAtError {
    #[error("could not create temporary file: {0}")]
    CreateTempfileError(io::Error),

    #[error("could not write preamble to file: {0}")]
    WritePreambleError(#[from] WritePreambleError),

    #[error("could not open note for storage: {0}")]
    OpenNoteError(io::Error),

    #[error(transparent)]
    StoreNoteError(#[from] StoreIfDifferentError),

    #[error(transparent)]
    EditorSpawnError(#[from] OpenInEditorError),

    #[error(transparent)]
    IndexNoteError(#[from] IndexNoteError),

    #[error(transparent)]
    IndexOpenError(#[from] IndexOpenError),
}

fn make_tempfile(config: &NoteConfig) -> Result<TempPath, io::Error> {
    let mut builder = TempFileBuilder::new();
    let file_extension_suffix = format!(".{}", config.file_extension);
    let builder = builder.suffix(&file_extension_suffix);

    if let Some(temp_dir) = config.temp_root_override.as_ref() {
        builder
            .tempfile_in(temp_dir)
            .map(NamedTempFile::into_temp_path)
    } else {
        builder.tempfile().map(NamedTempFile::into_temp_path)
    }
}

fn write_preamble(preamble: &Preamble, path: &Path) -> Result<String, WritePreambleError> {
    let mut file = OpenOptions::new()
        .write(true)
        .create(false)
        .open(path)
        .map_err(WritePreambleError::OpenError)?;

    let serialized_preamble = preamble.serialize()?;
    let to_write = format!("{serialized_preamble}\n\n");
    file.write_all(to_write.as_bytes())
        .map_err(WritePreambleError::WriteError)?;

    Ok(to_write)
}

#[derive(Error, Debug)]
#[error(transparent)]
enum WritePreambleError {
    OpenError(io::Error),
    EncodeError(#[from] SerializeError),
    WriteError(io::Error),
}

fn open_existing_note<E: Editor>(
    config: &NoteConfig,
    editor: E,
    kind: NoteKind,
    path: &Path,
) -> Result<(), OpenExistingNoteError> {
    ensure_note_exists(path).map_err(|error| OpenExistingNoteError::LookupError {
        path: path.to_owned(),
        error,
    })?;
    open_existing_note_in_editor(config, editor, kind, path)?;

    Ok(())
}

#[derive(Error, Debug)]
#[error(transparent)]
enum OpenExistingNoteError {
    #[error("could not open note at {path}: {error}")]
    LookupError {
        path: PathBuf,
        #[source]
        error: io::Error,
    },

    #[error(transparent)]
    OpenNoteInEditorError(#[from] OpenExistingNoteInEditorError),
}

fn ensure_note_exists(path: &Path) -> Result<(), io::Error> {
    fs::metadata(path).and_then(|metadata| {
        if metadata.is_dir() {
            Err(io::Error::new(
                io::ErrorKind::IsADirectory,
                "file is a directory",
            ))
        } else {
            Ok(())
        }
    })
}

fn open_existing_note_in_editor<E: Editor>(
    config: &NoteConfig,
    editor: E,
    kind: NoteKind,
    path: &Path,
) -> Result<(), OpenExistingNoteInEditorError> {
    open_in_editor(editor, path)?;

    let mut index_connection = open_index_database(config)?;

    index_note(&mut index_connection, kind, path)
        .or_else(|err| {
            let IndexNoteError::PreambleError(err) = err else {
                return Err(err)
            };

            match index::delete_note(&mut index_connection, path) {
                Ok(()) => {
                    warning!("After editing, the note could not be reindexed. It has been removed from the index. Original error: {err}");
                    Ok(())
                }

                Err(delete_err) => {
                    warning!("After editing, the note could not be reindexed. There was a subsequent failure that prevented it from being removed from the index, so there is now a stale entry. You can fix this by running `quicknotes index`. Original error: {err}; Delete error: {delete_err}");
                    Ok(())
                }
            }
        })?;

    Ok(())
}

#[derive(Error, Debug)]
#[allow(clippy::enum_variant_names)]
enum OpenExistingNoteInEditorError {
    #[error(transparent)]
    EditorSpawnError(#[from] OpenInEditorError),

    #[error(transparent)]
    IndexOpenError(#[from] IndexOpenError),

    #[error(transparent)]
    IndexNoteError(#[from] IndexNoteError),
}

fn open_in_editor<E: Editor>(editor: E, path: &Path) -> Result<(), OpenInEditorError> {
    editor.edit(path).map_err(|err| OpenInEditorError {
        editor: editor.name().to_owned(),
        err,
    })
}

#[derive(Error, Debug)]
#[error("could not spawn editor '{editor}': {err}")]
struct OpenInEditorError {
    editor: String,
    #[source]
    err: io::Error,
}

fn index_all_notes(config: &NoteConfig) -> Result<(), IndexAllNotesError> {
    // This is a bit of a hack, but is easier than trying to prune stale entries from
    // the index
    reset_index_database(config)?;
    let mut connection = open_index_database(config)?;

    for (kind, path) in note_file_paths(config) {
        if let Err(err) = index_note(&mut connection, kind, &path) {
            warning!("could not index note at {}: {}", path.display(), err);
        }
    }

    Ok(())
}

#[derive(Error, Debug)]
enum IndexAllNotesError {
    #[error(transparent)]
    IndexResetError(#[from] index::ResetError),

    #[error(transparent)]
    IndexOpenError(#[from] IndexOpenError),
}

fn all_indexed_notes(
    config: &NoteConfig,
) -> Result<HashMap<PathBuf, IndexedNote>, AllIndexedNotesError> {
    let mut connection = open_index_database(config)?;
    let notes = index::all_notes(&mut connection)?;

    Ok(notes)
}

#[derive(Error, Debug)]
enum AllIndexedNotesError {
    #[error(transparent)]
    IndexOpenError(#[from] IndexOpenError),

    #[error("could not query index database: {0}")]
    QueryError(#[from] IndexLookupError),
}

fn kinded_indexed_notes(
    config: &NoteConfig,
    kind: NoteKind,
) -> Result<HashMap<PathBuf, IndexedNote>, KindedIndexedNotesError> {
    let mut connection = open_index_database(config)?;
    let notes = index::notes_with_kind(&mut connection, kind)?;

    Ok(notes)
}

#[derive(Error, Debug)]
enum KindedIndexedNotesError {
    #[error(transparent)]
    IndexOpenError(#[from] IndexOpenError),

    #[error("could not query index database: {0}")]
    QueryError(#[from] IndexLookupError),
}

fn reset_index_database(config: &NoteConfig) -> Result<(), index::ResetError> {
    index::reset(&config.index_db_path())
}

fn open_index_database(config: &NoteConfig) -> Result<Connection, IndexOpenError> {
    index::open(&config.index_db_path())
}

/// Get all note file paths in a best-effort fashion. If there is an error where some
/// notes cannot be read, warnings will be logged.
fn note_file_paths(config: &NoteConfig) -> impl Iterator<Item = (NoteKind, PathBuf)> {
    WalkDir::new(config.notes_directory_path())
        .into_iter()
        .map(|entry| (NoteKind::Note, entry))
        .chain(
            WalkDir::new(config.daily_directory_path())
                .into_iter()
                .map(|entry| (NoteKind::Daily, entry)),
        )
        .filter_map(|(note_kind, entry_res)| {
            // skip entires we can't read, so we can get the rest
            unpack_walkdir_entry_result(entry_res)
                .ok()
                .and_then(|entry| {
                    let isnt_dir = !entry.file_type().is_dir();
                    isnt_dir.then_some((note_kind, entry.into_path()))
                })
        })
}

fn unpack_walkdir_entry_result(
    entry_res: Result<DirEntry, walkdir::Error>,
) -> Result<DirEntry, ()> {
    match entry_res {
        Ok(entry) => Ok(entry),
        Err(err) => {
            if let Some(path) = err.path() {
                warning!(
                    "Cannot traverse {}: {}",
                    path.display().to_string(),
                    io::Error::from(err)
                );
            } else {
                warning!("Cannot traverse notes: {}", io::Error::from(err));
            }

            Err(())
        }
    }
}

fn index_note(
    index_connection: &mut Connection,
    kind: NoteKind,
    path: &Path,
) -> Result<(), IndexNoteError> {
    let mut file = File::open(path).map_err(IndexNoteError::OpenError)?;
    let preamble = note::extract_preamble(&mut file).map_err(IndexNoteError::PreambleError)?;

    index::add_note(index_connection, &preamble, kind, path).map_err(IndexNoteError::IndexError)
}

#[derive(Error, Debug)]
#[allow(clippy::enum_variant_names)]
enum IndexNoteError {
    #[error("could not open note for indexing: {0}")]
    OpenError(io::Error),

    #[error("could not read preamble from note: {0}")]
    PreambleError(note::InvalidPreambleError),

    #[error(transparent)]
    IndexError(index::InsertError),
}