medi 0.13.1

CLI driven Markdown manager.
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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
use assert_cmd::Command;
use predicates::prelude::*;
use rand::distr::{Alphanumeric, SampleString};
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::{tempdir, TempDir};

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;

/// TestHarness manages the temporary directory and paths for our tests.
struct TestHarness {
    _temp_dir: TempDir,
    db_path: PathBuf,
    editor_script_path: PathBuf,
}

/// Creates a new TestHarness instance, setting up the temporary directory
/// and copying the mock editor script to a known location.
/// The mock editor script is used to simulate user input in tests.
impl TestHarness {
    fn new() -> Self {
        let temp_dir = tempdir().unwrap();
        let db_path = temp_dir.path().join("test_db");
        let editor_script_path = temp_dir.path().join("mock_editor.sh");
        let source_script_path =
            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/resources/mock_editor.sh");

        fs::copy(source_script_path, &editor_script_path).unwrap();

        #[cfg(unix)]
        {
            let mut perms = fs::metadata(&editor_script_path).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&editor_script_path, perms).unwrap();
        }

        TestHarness {
            _temp_dir: temp_dir,
            db_path,
            editor_script_path,
        }
    }
}

// A temporary struct for deserializing only the part of the JSON we need.
#[derive(Deserialize)]
struct NoteTags {
    tags: Vec<String>,
}

/// Tests the `-m` flag, the most reliable non-interactive input.
#[test]
fn test_new_with_message_flag() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "flag-note", "-m", "content from flag"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "flag-note"])
        .assert()
        .success()
        .stdout(predicate::str::contains("content from flag"));
    Ok(())
}

/// Tests piped input using the recommended `.write_stdin()` method.
#[test]
fn test_new_with_piped_input() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "piped-note"])
        .write_stdin("content from pipe")
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "piped-note"])
        .assert()
        .success()
        .stdout(predicate::str::contains("content from pipe"));
    Ok(())
}

/// The only test that uses the mock editor. This is known to be
/// flaky in some test runners due to I/O capture conflicts.
#[test]
#[ignore]
fn test_new_with_editor() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    Command::cargo_bin("medi")?
        .env("EDITOR", &harness.editor_script_path)
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "editor-note"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Successfully created note"));
    Ok(())
}

/// A single, logical test for the core list and delete workflow.
/// It uses the reliable `-m` flag for setup.
#[test]
fn test_core_list_and_delete_workflow() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "b-note", "-m", "b"])
        .assert()
        .success();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "a-note", "-m", "a"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::is_match("(?s)a-note.*b-note").unwrap());

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["delete", "a-note", "--force"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "a-note"])
        .assert()
        .failure();

    Ok(())
}

#[test]
fn test_new_with_tags() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    // TEST: Create a new note with multiple tags.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "tagged-note",
            "-m",
            "content",
            "--tag",
            "rust",
            "--tag",
            "cli",
        ])
        .assert()
        .success();

    // VERIFY: Get the note as JSON and check if the tags are present.
    let output = Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "tagged-note", "--json"])
        .output()?;

    let output_str = String::from_utf8_lossy(&output.stdout);
    let note: NoteTags = serde_json::from_str(&output_str)?;

    assert_eq!(note.tags.len(), 2);
    assert!(note.tags.contains(&"rust".to_string()));
    assert!(note.tags.contains(&"cli".to_string()));

    Ok(())
}

#[test]
fn test_list_empty() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .arg("list")
        .assert()
        .success()
        .stderr(predicate::str::contains("No notes found."));
    Ok(())
}

#[test]
fn test_get_by_tag() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    // SETUP: Create three notes, two of which share a tag.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "note1",
            "-m",
            "content for alpha one",
            "--tag",
            "project-alpha",
        ])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "note2",
            "-m",
            "content for bravo",
            "--tag",
            "project-bravo",
        ])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "note3",
            "-m",
            "content for alpha two",
            "--tag",
            "project-alpha",
        ])
        .assert()
        .success();

    // TEST: Run `get --tag` for "project-alpha".
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "--tag", "project-alpha"])
        .assert()
        .success()
        // VERIFY: Check that the output contains the content of the two matching notes.
        .stdout(
            predicate::str::contains("content for alpha one")
                .and(predicate::str::contains("content for alpha two")),
        )
        // VERIFY: Check that the output does NOT contain the content of the other note.
        .stdout(predicate::str::contains("content for bravo").not());

    Ok(())
}

#[test]
fn test_edit_command() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "edit-me", "-m", "initial content"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("EDITOR", &harness.editor_script_path) // This script provides the new content
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["edit", "edit-me"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Successfully updated note"));

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "edit-me"])
        .assert()
        .success()
        .stdout(predicate::str::contains("integration test content")); // This is from mock_editor.sh

    Ok(())
}

#[test]
fn test_edit_tags() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "note-to-edit", "-m", "content", "--tag", "initial"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "edit",
            "note-to-edit",
            "--add-tag",
            "added1",
            "--add-tag",
            "added2",
        ])
        .assert()
        .success();

    // VERIFY 1: Check for all three tags by parsing the JSON.
    let output1 = Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "note-to-edit", "--json"])
        .output()?;

    let note1: NoteTags = serde_json::from_slice(&output1.stdout)?;
    assert_eq!(note1.tags.len(), 3);
    assert!(note1.tags.contains(&"initial".to_string()));
    assert!(note1.tags.contains(&"added1".to_string()));
    assert!(note1.tags.contains(&"added2".to_string()));

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "edit",
            "note-to-edit",
            "--rm-tag",
            "initial",
            "--rm-tag",
            "added1",
        ])
        .assert()
        .success();

    let output2 = Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "note-to-edit", "--json"])
        .output()?;

    let note2: NoteTags = serde_json::from_slice(&output2.stdout)?;
    assert_eq!(note2.tags, vec!["added2"]);

    Ok(())
}

#[test]
fn test_import_single_file() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    let import_file_path = harness._temp_dir.path().join("imported_note.txt");
    fs::write(&import_file_path, "This is an imported note.").unwrap();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "import",
            "--file",
            &import_file_path.to_string_lossy().as_ref(),
            "--key",
            "imported-note",
        ])
        .assert()
        .success()
        // The assertion is now simpler and matches your actual output
        .stdout(predicate::str::contains("Imported 'imported-note'"));

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "imported-note"])
        .assert()
        .success()
        .stdout(predicate::str::contains("This is an imported note."));

    Ok(())
}

#[test]
fn test_import_directory() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    let import_dir = harness._temp_dir.path().join("import_test");
    fs::create_dir_all(&import_dir)?;
    fs::write(import_dir.join("import-one.md"), "content for import one")?;
    fs::write(import_dir.join("import-two.md"), "content for import two")?;

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["import", "--dir", &import_dir.to_string_lossy()])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Imported 'import-one'")
                .and(predicate::str::contains("Imported 'import-two'")),
        );

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["get", "import-one"])
        .assert()
        .success()
        .stdout(predicate::str::contains("content for import one"));

    Ok(())
}

#[test]
fn test_export_command() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    // Create two notes to export.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "note-one", "-m", "content for note one"])
        .assert()
        .success();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "note-two", "-m", "content for note two"])
        .assert()
        .success();

    // Define a path for the export directory.
    let export_dir = harness._temp_dir.path().join("export_test");

    // Run the `export` command.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .arg("export")
        .arg(&export_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("Successfully exported 2 notes"));

    // VERIFY: Check that the files were created with the correct content.
    let note_one_path = export_dir.join("note-one.md");
    let note_two_path = export_dir.join("note-two.md");

    assert!(note_one_path.exists());
    assert!(note_two_path.exists());

    let content_one = fs::read_to_string(note_one_path)?;
    let content_two = fs::read_to_string(note_two_path)?;

    assert_eq!(content_one, "content for note one");
    assert_eq!(content_two, "content for note two");

    Ok(())
}

#[test]
fn test_search_command() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    // Create some notes to search through.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "rust-note",
            "-m",
            "A note about the Rust language and its features.",
        ])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "python-note",
            "-m",
            "A note about the Python language.",
        ])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args([
            "new",
            "general-note",
            "-m",
            "A general note about programming languages.",
        ])
        .assert()
        .success();

    // TEST 1: Search for a term that matches a single note.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["search", "Rust"])
        .assert()
        .success()
        .stdout(predicate::str::contains("rust-note"))
        .stdout(predicate::str::contains("python-note").not());

    // TEST 2: Search for a term that matches multiple notes.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["search", "language"])
        .assert()
        .success()
        .stdout(predicate::str::contains("rust-note").and(predicate::str::contains("python-note")));

    // TEST 3: Search for a term that matches no notes.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["search", "java"])
        .assert()
        .success()
        .stderr(predicate::str::contains("No matching notes found."));

    Ok(())
}

#[test]
fn test_task_workflow() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();

    // First, create a note to associate tasks with.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["new", "task-note", "-m", "A note for my tasks"])
        .assert()
        .success();

    // TEST 1: Add a couple of tasks.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "add", "task-note", "My first task"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Added new task with ID: 1"));

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "add", "task-note", "My second task"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Added new task with ID: 2"));

    // TEST 2: List the tasks to verify they were added.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "[1] [Open]: My first task (for note task-note)",
        ))
        .stdout(predicate::str::contains(
            "[2] [Open]: My second task (for note task-note)",
        ));

    // TEST 3: Mark the first task as done.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "done", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Completed task: 1"));

    // TEST 4: List tasks again to verify the first one is gone.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "[1] [Done]: My first task (for note task-note)",
        ));

    // TEST 5: Prioritise the second task.
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "prio", "2"])
        .assert()
        .success();

    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["task", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "[2] [Prio] ⭐: My second task (for note task-note)",
        ));

    Ok(())
}

#[test]
#[ignore] // Ignore this test by default, run it explicitly when needed.
fn test_performance() -> Result<(), Box<dyn std::error::Error>> {
    let harness = TestHarness::new();
    let note_count = 1000; // Configurable: change this value for larger tests
    let search_term = "performance";

    // ---  Generate Notes ---
    println!("\n--- Generating {} notes... ---", note_count);
    let start_gen = Instant::now();
    for i in 1..=note_count {
        let key = format!("perf-test-{}", i);
        let mut content = Alphanumeric.sample_string(&mut rand::rng(), 5_000);

        // Inject the search term into one note
        if i == note_count / 2 {
            content.push_str(" ");
            content.push_str(search_term);
        }

        Command::cargo_bin("medi")?
            .env("MEDI_DB_PATH", &harness.db_path)
            .args(["new", &key, "-m", &content])
            .assert()
            .success();

        if i % 100 == 0 {
            println!("Created {} / {} notes...", i, note_count);
        }
    }
    println!("Note generation finished in: {:?}", start_gen.elapsed());

    // --- Time Reindex and Search ---
    println!("\n--- Rebuilding search index... ---");
    let start_reindex = Instant::now();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .arg("reindex")
        .assert()
        .success();
    println!("Reindexing finished in: {:?}", start_reindex.elapsed());

    println!("\n--- Timing search for '{}'... ---", search_term);
    let start_search = Instant::now();
    Command::cargo_bin("medi")?
        .env("MEDI_DB_PATH", &harness.db_path)
        .args(["search", search_term])
        .assert()
        .success()
        .stdout(predicate::str::contains(format!(
            "perf-test-{}",
            note_count / 2
        )));
    println!("Search finished in: {:?}", start_search.elapsed());

    // Cleanup is handled automatically when `harness` goes out of scope and `TempDir` is dropped.
    Ok(())
}