kimun-notes 0.3.5

A terminal-based notes application
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
// tui/src/cli/commands/note_ops.rs
//
// CLI commands for note create, append, and journal operations.

use clap::Subcommand;
use color_eyre::eyre::Result;
use kimun_core::{NoteVault, error::VaultError};

const NOTE_SEPARATOR: &str = "================================================================================";

#[derive(Subcommand, Debug)]
pub enum NoteSubcommand {
    /// Create a new note (fails if the note already exists)
    Create {
        /// Note path, relative to quick_note_path or absolute from vault root
        path: String,
        /// Note content (reads from stdin if omitted and stdin is not a TTY)
        content: Option<String>,
    },
    /// Append text to a note (creates the note if it does not exist)
    Append {
        /// Note path, relative to quick_note_path or absolute from vault root
        path: String,
        /// Text to append (reads from stdin if omitted and stdin is not a TTY)
        content: Option<String>,
    },
    /// Append text to today's journal entry (creates it if it does not exist)
    Journal {
        /// Text to append (reads from stdin if omitted and stdin is not a TTY)
        content: Option<String>,
    },
    /// Show note content and metadata (read one or more notes)
    Show {
        /// One or more note paths (relative to quick_note_path or absolute from vault root)
        paths: Vec<String>,
        #[arg(long, value_enum, default_value = "text")]
        format: crate::cli::output::OutputFormat,
    },
}

pub async fn run(
    subcommand: NoteSubcommand,
    vault: &NoteVault,
    quick_note_path: &str,
    workspace_name: &str,
) -> Result<()> {
    match subcommand {
        NoteSubcommand::Create { path, content } => {
            run_create(vault, &path, content, quick_note_path).await
        }
        NoteSubcommand::Append { path, content } => {
            run_append(vault, &path, content, quick_note_path).await
        }
        NoteSubcommand::Journal { content } => {
            run_journal(vault, content).await
        }
        NoteSubcommand::Show { paths, format } => {
            use std::io::IsTerminal;
            let reader = if std::io::stdin().is_terminal() {
                None
            } else {
                Some(std::io::BufReader::new(std::io::stdin().lock()))
            };
            let resolved = resolve_show_paths(paths, reader)?;
            run_show(vault, &resolved, quick_note_path, format, workspace_name).await
        }
    }
}

async fn run_create(
    vault: &NoteVault,
    path_input: &str,
    content: Option<String>,
    quick_note_path: &str,
) -> Result<()> {
    use crate::cli::helpers::resolve_note_path;

    let vault_path = resolve_note_path(path_input, quick_note_path)?;
    let text = resolve_content(content)?;

    vault.create_note(&vault_path, &text).await.map_err(|e| {
        match &e {
            VaultError::NoteExists { path } => {
                color_eyre::eyre::eyre!("Note already exists: {}", path)
            }
            _ => color_eyre::eyre::eyre!("{}", e),
        }
    })?;

    println!("Note saved: {}", vault_path);
    Ok(())
}

async fn run_append(
    vault: &NoteVault,
    path_input: &str,
    content: Option<String>,
    quick_note_path: &str,
) -> Result<()> {
    use crate::cli::helpers::resolve_note_path;
    use kimun_core::error::FSError;

    let vault_path = resolve_note_path(path_input, quick_note_path)?;
    let text = resolve_content(content)?;

    if text.is_empty() {
        return Ok(());
    }

    match vault.get_note_text(&vault_path).await {
        Ok(existing) => {
            let combined = format!("{}\n{}", existing, text);
            vault.save_note(&vault_path, &combined).await
                .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;
        }
        Err(VaultError::FSError(FSError::VaultPathNotFound { .. })) => {
            match vault.create_note(&vault_path, &text).await {
                Ok(_) => {}
                Err(VaultError::NoteExists { .. }) => {
                    // Race: note created between our get and create — re-read and save
                    let existing = vault.get_note_text(&vault_path).await
                        .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;
                    let combined = format!("{}\n{}", existing, text);
                    vault.save_note(&vault_path, &combined).await
                        .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;
                }
                Err(e) => return Err(color_eyre::eyre::eyre!("{}", e)),
            }
        }
        Err(e) => return Err(color_eyre::eyre::eyre!("{}", e)),
    }

    println!("Note saved: {}", vault_path);
    Ok(())
}

async fn run_journal(vault: &NoteVault, content: Option<String>) -> Result<()> {
    let text = resolve_content(content)?;

    if text.is_empty() {
        return Ok(());
    }

    // journal_entry() handles create-if-absent internally, so no TOCTOU retry needed here.
    let (details, existing) = vault.journal_entry().await
        .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;

    let combined = format!("{}\n{}", existing, text);
    vault.save_note(&details.path, &combined).await
        .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;

    println!("Note saved: {}", details.path);
    Ok(())
}

fn format_note_show_text(
    path: &kimun_core::nfs::VaultPath,
    content: &str,
    title: &str,
    tags: &[String],
    links: &[String],
    backlinks: &[String],
) -> String {
    let mut out = String::new();
    out.push_str(&format!("Path:      {}\n", path));
    if !title.is_empty() {
        out.push_str(&format!("Title:     {}\n", title));
    }
    if !tags.is_empty() {
        out.push_str(&format!("Tags:      {}\n", tags.join(" ")));
    }
    if !links.is_empty() {
        out.push_str(&format!("Links:     {}\n", links.join(", ")));
    }
    if !backlinks.is_empty() {
        out.push_str(&format!("Backlinks: {}\n", backlinks.join(", ")));
    }
    out.push_str("---\n");
    out.push_str(content);
    out
}

/// Resolves the effective path list for `note show`.
/// - If `args` is non-empty, returns it directly (reader is ignored).
/// - If `args` is empty and `reader` is `Some`, reads non-blank trimmed lines from it.
/// - If `args` is empty and `reader` is `None` (TTY), returns an error.
fn resolve_show_paths<R: std::io::BufRead>(
    args: Vec<String>,
    reader: Option<R>,
) -> color_eyre::eyre::Result<Vec<String>> {
    if !args.is_empty() {
        return Ok(args);
    }
    match reader {
        Some(r) => {
            let paths: Result<Vec<String>, _> = r
                .lines()
                .filter(|l| l.as_ref().map(|s| !s.trim().is_empty()).unwrap_or(true))
                .map(|l| l.map(|s| s.trim().split('\t').next().unwrap_or("").to_owned()))
                .collect();
            let paths = paths.map_err(|e| color_eyre::eyre::eyre!("Failed to read stdin: {}", e))?;
            if paths.is_empty() {
                return Err(color_eyre::eyre::eyre!(
                    "No paths provided — pass paths as arguments or pipe from stdin"
                ));
            }
            Ok(paths)
        }
        None => Err(color_eyre::eyre::eyre!(
            "No paths provided — pass paths as arguments or pipe from stdin"
        )),
    }
}

async fn run_show(
    vault: &NoteVault,
    path_inputs: &[String],
    quick_note_path: &str,
    format: crate::cli::output::OutputFormat,
    workspace_name: &str,
) -> Result<()> {
    use crate::cli::helpers::resolve_note_path;
    use crate::cli::metadata_extractor::{extract_tags, extract_links, extract_headers};
    use crate::cli::json_output::{JsonNoteEntry, JsonNoteMetadata, JsonOutput, JsonOutputMetadata};
    use crate::cli::output::OutputFormat;
    use kimun_core::nfs::NoteEntryData;
    use kimun_core::error::{VaultError, FSError};
    use chrono::Utc;
    use std::time::UNIX_EPOCH;

    if matches!(format, OutputFormat::Paths) {
        return Err(color_eyre::eyre::eyre!(
            "--format paths is not valid for note show; use 'text' or 'json'"
        ));
    }

    // One accumulator per format — only the active one is ever populated.
    enum Accumulator {
        Text(Vec<String>),
        Json(Vec<JsonNoteEntry>),
    }

    let mut acc = match format {
        OutputFormat::Text => Accumulator::Text(Vec::new()),
        OutputFormat::Json => Accumulator::Json(Vec::new()),
        OutputFormat::Paths => unreachable!("guarded above"),
    };
    let mut had_errors = false;

    for input in path_inputs {
        let vault_path = match resolve_note_path(input, quick_note_path) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("Error: {}", e);
                had_errors = true;
                continue;
            }
        };

        let note_details = match vault.load_note(&vault_path).await {
            Ok(nd) => nd,
            Err(VaultError::FSError(FSError::VaultPathNotFound { .. })) => {
                eprintln!("Error: Note not found: {}", vault_path);
                had_errors = true;
                continue;
            }
            Err(e) => return Err(color_eyre::eyre::eyre!("{}", e)),
        };

        let content = &note_details.raw_text;
        let content_data = note_details.get_content_data();

        let backlink_results = vault
            .get_backlinks(&vault_path)
            .await
            .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;
        let backlink_paths: Vec<String> = backlink_results
            .iter()
            .map(|(e, _)| e.path.to_string())
            .collect();

        match &mut acc {
            Accumulator::Text(entries) => {
                let tags = extract_tags(content);
                let links = extract_links(content);
                entries.push(format_note_show_text(
                    &vault_path,
                    content,
                    &content_data.title,
                    &tags,
                    &links,
                    &backlink_paths,
                ));
            }
            Accumulator::Json(entries) => {
                let meta = tokio::fs::metadata(vault.path_to_pathbuf(&vault_path))
                    .await
                    .map_err(|e| color_eyre::eyre::eyre!("{}", e))?;
                let modified_secs = meta
                    .modified()
                    .map(|t| t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())
                    .unwrap_or(0);
                let entry_data = NoteEntryData {
                    path: vault_path.clone(),
                    size: meta.len(),
                    modified_secs,
                };
                let tags = extract_tags(content);
                let links = extract_links(content);
                let headers = extract_headers(content);
                let journal_date = vault
                    .journal_date(&vault_path)
                    .map(|d| d.format("%Y-%m-%d").to_string());
                entries.push(JsonNoteEntry {
                    path: vault_path.to_string_with_ext(),
                    title: content_data.title.clone(),
                    content: content.clone(),
                    size: entry_data.size,
                    modified: entry_data.modified_secs,
                    created: entry_data.modified_secs, // TODO: track actual creation time
                    hash: format!("{:x}", content_data.hash),
                    journal_date,
                    metadata: JsonNoteMetadata { tags, links, headers },
                    backlinks: if backlink_paths.is_empty() { None } else { Some(backlink_paths) },
                });
            }
        }
    }

    let is_empty = match &acc {
        Accumulator::Text(v) => v.is_empty(),
        Accumulator::Json(v) => v.is_empty(),
    };
    if is_empty {
        return Err(color_eyre::eyre::eyre!(
            "No notes found — all specified paths were missing"
        ));
    }

    // Output whatever was found — the JSON/text is valid for the notes that succeeded.
    // had_errors (non-zero exit) signals that some notes were missing; those were
    // already reported to stderr in the loop above.
    match acc {
        Accumulator::Text(entries) => {
            let sep = format!("\n{}\n\n", NOTE_SEPARATOR);
            print!("{}", entries.join(&sep));
        }
        Accumulator::Json(notes) => {
            let output = JsonOutput {
                metadata: JsonOutputMetadata {
                    workspace: workspace_name.to_string(),
                    workspace_path: vault.workspace_path.to_string_lossy().to_string(),
                    total_results: notes.len(),
                    query: None,
                    is_listing: false,
                    generated_at: Utc::now().to_rfc3339(),
                },
                notes,
            };
            print!(
                "{}",
                serde_json::to_string(&output)
                    .map_err(|e| color_eyre::eyre::eyre!("{}", e))?
            );
        }
    }

    if had_errors {
        return Err(color_eyre::eyre::eyre!("One or more notes could not be found"));
    }

    Ok(())
}

/// Returns content from the Option, or reads from stdin if not a TTY.
/// Returns an empty string if content is None and stdin is a TTY.
/// Propagates I/O errors from stdin.
fn resolve_content(content: Option<String>) -> color_eyre::eyre::Result<String> {
    use std::io::IsTerminal;
    match content {
        Some(c) => Ok(c),
        None => {
            if std::io::stdin().is_terminal() {
                Ok(String::new())
            } else {
                use std::io::Read;
                let mut buf = String::new();
                std::io::stdin().read_to_string(&mut buf)
                    .map_err(|e| color_eyre::eyre::eyre!("Failed to read stdin: {}", e))?;
                Ok(buf.trim_end_matches(|c| c == '\n' || c == '\r').to_string())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::resolve_show_paths;
    use std::io::Cursor;

    #[test]
    fn test_resolve_show_paths_uses_args_when_given() {
        let args = vec!["projects/foo".to_string(), "inbox/bar".to_string()];
        let result = resolve_show_paths(args.clone(), None::<Cursor<&[u8]>>).unwrap();
        assert_eq!(result, args);
    }

    #[test]
    fn test_resolve_show_paths_reads_from_reader() {
        let input = b"projects/foo\ninbox/bar\n";
        let reader = Cursor::new(input.as_ref());
        let result = resolve_show_paths(vec![], Some(reader)).unwrap();
        assert_eq!(result, vec!["projects/foo", "inbox/bar"]);
    }

    #[test]
    fn test_resolve_show_paths_skips_blank_lines() {
        let input = b"projects/foo\n\n  \ninbox/bar\n";
        let reader = Cursor::new(input.as_ref());
        let result = resolve_show_paths(vec![], Some(reader)).unwrap();
        assert_eq!(result, vec!["projects/foo", "inbox/bar"]);
    }

    #[test]
    fn test_resolve_show_paths_all_blank_stdin_returns_empty() {
        let input = b"\n  \n\t\n";
        let reader = Cursor::new(input.as_ref());
        let result = resolve_show_paths(vec![], Some(reader));
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("No paths provided"), "got: {}", msg);
    }

    #[test]
    fn test_resolve_show_paths_strips_tab_separated_fields() {
        // kimun notes outputs tab-separated lines: path\ttitle\tsize\ttimestamp
        let input = b"projects/foo\tFoo Note\t1234\t1700000000\ninbox/bar\tBar\t42\t1700000001\n";
        let reader = Cursor::new(input.as_ref());
        let result = resolve_show_paths(vec![], Some(reader)).unwrap();
        assert_eq!(result, vec!["projects/foo", "inbox/bar"]);
    }

    #[test]
    fn test_resolve_show_paths_no_args_no_reader_errors() {
        let result = resolve_show_paths(vec![], None::<Cursor<&[u8]>>);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("No paths provided"), "got: {}", msg);
    }
}