nb-api 0.4.3

Typed Rust interface to the nb note-taking CLI (subprocess wrapper: escaping, validation, output parsing)
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
use std::path::{Path, PathBuf};

use crate::argv::search_command_args;
use crate::diagnostics::is_selector_not_found;
use crate::error::NbError;
use crate::fingerprint;
use crate::gate;
use crate::lines::{
    document_lines, note_line_from_body_line, require_contiguous_body,
    search_lines,
};
use crate::output::strip_empty_result_hint;
use crate::parser::{ParseContext, parse};
use crate::transaction;
use crate::types::{
    BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
};
use crate::validate::validate_folder_option;
use crate::{NbClient, SearchMode};

use super::core::ShowClassification;

impl NbClient {
    /// Returns status information about the resolved notebook.
    ///
    /// When the only notebook dirt is harmless `.index`
    /// reconciliation (see `git::status_is_index_only`), an
    /// explanatory note is appended; the raw `nb` output is
    /// otherwise returned verbatim. The dirt classification runs
    /// BEFORE any `nb` subprocess in this call: `nb` fires
    /// fire-and-forget background checkpoints that could otherwise
    /// commit the very dirt being described between the check and
    /// the read. Root resolution prefers `NB_DIR` and never shells
    /// out when it is set; if the root cannot be resolved, the
    /// verbatim output is returned.
    pub async fn show_notebook_status(
        &self,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let name = self.resolve_notebook_name(notebook)?;
        // Classify first: an `nb` invocation below may background a
        // checkpoint that reconciles the dirt away mid-call.
        let index_only = notebook_dir_from_env(&name)
            .map(|root| {
                crate::git::notebook_status_porcelain(&root)
                    .map(|s| crate::git::status_is_index_only(&s))
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        let notebook = self.resolve_notebook(Some(&name)).await?;
        let output = self
            .exec_vec(vec![format!("{}:", notebook), "status".to_string()])
            .await?;
        if index_only {
            return Ok(format!(
                "{output}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
            ));
        }
        Ok(output)
    }

    /// Lists available notebooks.
    pub async fn list_notebooks(&self) -> Result<String, NbError> {
        let _g = gate::acquire_global(self.gate_timeout).await?;
        // Use --no-color to avoid ANSI escape codes
        self.exec(&["notebooks", "--no-color"]).await
    }

    /// Returns the path for a notebook.
    pub async fn show_notebook_path(
        &self,
        notebook: Option<&str>,
    ) -> Result<PathBuf, NbError> {
        let notebook = self.resolve_notebook_name(notebook)?;
        self.ensure_notebook(&notebook).await?;
        self.with_notebook_gate(
            &notebook,
            self.show_notebook_path_unguarded(Some(&notebook)),
        )
        .await
    }

    /// Shows a note as a structured [`ShowNote`] (gate-held).
    pub async fn show_note(
        &self,
        id: &str,
        notebook: Option<&str>,
    ) -> Result<ShowNote, NbError> {
        let (notebook, selector) =
            self.resolve_target_selector(id, notebook).await?;
        self.with_notebook_gate(&notebook, async {
            self.show_note_inner(&notebook, &selector).await
        })
        .await
    }

    async fn show_note_inner(
        &self,
        notebook: &str,
        selector: &str,
    ) -> Result<ShowNote, NbError> {
        match self.probe_show_classification(selector).await {
            ShowClassification::NonTextual { actual_type } => {
                return Err(NbError::UnsupportedShowTarget {
                    selector: selector.to_string(),
                    actual_type,
                });
            },
            ShowClassification::Textual | ShowClassification::ProbeFailure => {
            },
        }
        let path = self.resolve_item_path(selector).await?;
        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
        let rel = path_relative_to(&root, &path)?;
        let source = std::fs::read(&path).map_err(|e| NbError::Io {
            path: path.clone(),
            source: e.into(),
        })?;
        let doc = match parse(
            &source,
            ParseContext::FromPath(PathBuf::from(&rel)),
        ) {
            Ok(doc) => doc,
            // nb may classify additional textual extensions as showable; map
            // unrecognized formats to a Note partition for structured show.
            Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
                &source,
                ParseContext::Explicit(crate::DocumentKind::Note),
            )?,
            Err(err) => return Err(err),
        };
        let kind_str = format!("{:?}", doc.kind()).to_lowercase();
        let non_utf8 = |path: String| NbError::NonUtf8 {
            selector: selector.to_string(),
            path,
            kind: kind_str.clone(),
            mime_hint: None,
        };
        let source_str = std::str::from_utf8(&source)
            .map_err(|_| non_utf8(rel.clone()))?
            .to_string();
        // Fragment offsets into `source`: body_ranges are source-absolute.
        let ranges = doc.body_ranges();
        let mut fragments: Vec<BodyFragment> =
            Vec::with_capacity(ranges.len());
        for (i, span) in ranges.iter().enumerate() {
            let bytes = std::str::from_utf8(&source[span.clone()])
                .map_err(|_| non_utf8(rel.clone()))?
                .to_string();
            fragments.push(BodyFragment {
                index: i as u32,
                bytes,
                start_byte: span.start as u32,
                end_byte: span.end as u32,
            });
        }
        let body_contiguous = fragments.len() <= 1;
        let body_bytes = doc.body_bytes();
        let body = std::str::from_utf8(&body_bytes)
            .map_err(|_| non_utf8(rel.clone()))?
            .to_string();
        // Lossy convenience strings; raw title bytes remain authoritative.
        let tags: Vec<String> = doc
            .tags()
            .map(|t| {
                String::from_utf8_lossy(t)
                    .trim_start_matches('#')
                    .to_string()
            })
            .collect();
        let title = doc
            .title()
            .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
            .transpose()
            .map_err(|_| non_utf8(rel.clone()))?;
        let title_text = doc.title().map(|bytes| {
            let s = String::from_utf8_lossy(bytes);
            s.trim_end_matches('\n')
                .trim_start_matches('#')
                .trim()
                .to_string()
        });
        Ok(ShowNote {
            selector: numeric_selector_for_path(
                notebook, &root, &rel, selector,
            ),
            path: rel.clone(),
            kind: doc.kind(),
            todo_state: doc.todo_state(),
            title,
            title_text,
            tags,
            body_fragments: fragments,
            body_contiguous,
            body,
            fingerprint: fingerprint::fingerprint(&doc),
            source: source_str,
            numeric_id: numeric_id_for_path(&root, &rel),
        })
    }

    /// Raw-bytes escape hatch: full file bytes without UTF-8 validation.
    ///
    /// This is the only public read that returns `Vec<u8>`; every other
    /// structured read is text-only and returns `NonUtf8` on invalid UTF-8.
    pub async fn read_note_source_bytes(
        &self,
        target: NoteTarget,
        notebook: Option<&str>,
    ) -> Result<Vec<u8>, NbError> {
        let (notebook, selector) =
            self.resolve_note_target(&target, notebook).await?;
        self.with_notebook_gate(&notebook, async {
            let path = self.resolve_item_path(&selector).await?;
            std::fs::read(&path).map_err(|e| NbError::Io {
                path: path.clone(),
                source: e.into(),
            })
        })
        .await
    }

    /// Enumerate body lines for a contiguous-body note.
    pub async fn show_note_lines(
        &self,
        target: NoteTarget,
        offset: Option<u32>,
        limit: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<ShowNoteLines, NbError> {
        let (notebook, selector) =
            self.resolve_note_target(&target, notebook).await?;
        self.with_notebook_gate(&notebook, async {
            let shown = self.show_note_inner(&notebook, &selector).await?;
            let source = shown.source.as_bytes().to_vec();
            let doc = parse(
                &source,
                ParseContext::FromPath(PathBuf::from(&shown.path)),
            )?;
            let body = require_contiguous_body(&doc)?;
            let (eol, has_final_eol, lines) = document_lines(&body);
            let total_lines = lines.len() as u32;
            let offset = offset.unwrap_or(1);
            let limit = limit.unwrap_or(100);
            if offset == 0 {
                return Err(NbError::InvalidLineWindow {
                    offset,
                    limit,
                    total_lines,
                });
            }
            if total_lines == 0 {
                if offset != 1 {
                    return Err(NbError::InvalidLineWindow {
                        offset,
                        limit,
                        total_lines,
                    });
                }
                return Ok(ShowNoteLines {
                    selector: shown.selector,
                    path: shown.path,
                    kind: shown.kind,
                    total_lines: 0,
                    offset,
                    limit,
                    next_offset: None,
                    lines: Vec::new(),
                    title: shown.title,
                    tags: shown.tags,
                    body_fingerprint: shown.fingerprint,
                    eol: None,
                    has_final_eol: false,
                    numeric_id: shown.numeric_id,
                });
            }
            if offset > total_lines + 1 {
                return Err(NbError::InvalidLineWindow {
                    offset,
                    limit,
                    total_lines,
                });
            }
            let start_idx = (offset - 1) as usize;
            let end_idx = (start_idx + limit as usize).min(lines.len());
            let window: Vec<_> = lines[start_idx..end_idx]
                .iter()
                .map(|l| note_line_from_body_line(l, &body))
                .collect();
            let next_offset = if end_idx < lines.len() {
                Some(offset + window.len() as u32)
            } else {
                None
            };
            Ok(ShowNoteLines {
                selector: shown.selector,
                path: shown.path,
                kind: shown.kind,
                total_lines,
                offset,
                limit,
                next_offset,
                lines: window,
                title: shown.title,
                tags: shown.tags,
                body_fingerprint: shown.fingerprint,
                eol,
                has_final_eol,
                numeric_id: shown.numeric_id,
            })
        })
        .await
    }

    /// Search body line texts for a pattern (contiguous body only).
    pub async fn search_note_lines(
        &self,
        target: NoteTarget,
        pattern: &str,
        notebook: Option<&str>,
    ) -> Result<SearchNoteLines, NbError> {
        let (notebook, selector) =
            self.resolve_note_target(&target, notebook).await?;
        self.with_notebook_gate(&notebook, async {
            let shown = self.show_note_inner(&notebook, &selector).await?;
            let source = shown.source.as_bytes().to_vec();
            let doc = parse(
                &source,
                ParseContext::FromPath(PathBuf::from(&shown.path)),
            )?;
            let body = require_contiguous_body(&doc)?;
            let hits = search_lines(&body, pattern.as_bytes())?;
            Ok(SearchNoteLines {
                selector: shown.selector,
                path: shown.path,
                kind: shown.kind,
                hits,
                body_fingerprint: shown.fingerprint,
            })
        })
        .await
    }

    pub(super) async fn resolve_item_path(
        &self,
        selector: &str,
    ) -> Result<PathBuf, NbError> {
        let output = self
            .exec_vec(vec![
                "show".to_string(),
                selector.to_string(),
                "--path".to_string(),
                "--no-color".to_string(),
            ])
            .await
            .map_err(|err| match err {
                NbError::CommandFailed { stderr, .. }
                    if is_selector_not_found(&stderr, selector) =>
                {
                    NbError::NotFound {
                        selector: selector.to_string(),
                    }
                },
                other => other,
            })?;
        let path = output.trim();
        if path.is_empty() {
            return Err(NbError::CommandFailed {
                command: format!("nb show {selector} --path"),
                stderr: "empty path".into(),
                exit_code: None,
            });
        }
        Ok(PathBuf::from(path))
    }

    async fn resolve_note_target(
        &self,
        target: &NoteTarget,
        notebook: Option<&str>,
    ) -> Result<(String, String), NbError> {
        match target {
            NoteTarget::Selector { value } => {
                self.resolve_target_selector(value, notebook).await
            },
            NoteTarget::Path { value } => {
                let notebook = self.resolve_notebook(notebook).await?;
                Ok((notebook.clone(), format!("{notebook}:{value}")))
            },
        }
    }

    /// Probe the textual classification of a selector via `nb`'s
    /// native `--type` mechanism.
    ///
    /// Two-step probe: first `nb show <selector> --type text` to
    /// ask `nb` whether the type is text. If yes, return
    /// [`ShowClassification::Textual`]. If no, follow up with
    /// `nb show <selector> --type` to recover the `actual_type`
    /// for the error diagnostic. If the follow-up also fails
    /// (selector not found, internal error), return
    /// [`ShowClassification::ProbeFailure`] so the caller can
    /// fall through to the original show path.
    async fn probe_show_classification(
        &self,
        selector: &str,
    ) -> ShowClassification {
        let textual = self
            .exec_vec(vec![
                "show".to_string(),
                selector.to_string(),
                "--type".to_string(),
                "text".to_string(),
                "--no-color".to_string(),
            ])
            .await;
        if textual.is_ok() {
            return ShowClassification::Textual;
        }
        match self
            .exec_vec(vec![
                "show".to_string(),
                selector.to_string(),
                "--type".to_string(),
                "--no-color".to_string(),
            ])
            .await
        {
            Ok(stdout) => {
                let trimmed = stdout.trim();
                if trimmed.is_empty() {
                    ShowClassification::ProbeFailure
                } else {
                    ShowClassification::NonTextual {
                        actual_type: trimmed.to_string(),
                    }
                }
            },
            Err(_) => ShowClassification::ProbeFailure,
        }
    }

    /// Lists notes in a notebook or folder.
    pub async fn list_notes(
        &self,
        folder: Option<&str>,
        tags: &[String],
        limit: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let mut args = Vec::new();
        validate_folder_option(folder)?;

        let notebook = self.resolve_notebook(notebook).await?;
        let cmd = match folder {
            Some(f) => format!("{}:{}/", notebook, f),
            None => format!("{}:", notebook),
        };

        args.push("list".to_string());
        args.push(cmd);

        // No color for parsing
        args.push("--no-color".to_string());

        // Limit
        if let Some(n) = limit {
            args.push("-n".to_string());
            args.push(n.to_string());
        }

        // Tags filter
        for tag in tags {
            args.push("--tags".to_string());
            let tag_str = if tag.starts_with('#') {
                tag.clone()
            } else {
                format!("#{}", tag)
            };
            args.push(tag_str);
        }

        // Strip the trailing usage/help hint block from empty
        // results (`0 items.` followed by `Add a note:`,
        // `Import a file:`, `Help information:`). Detection
        // keys off the empty-result signal per the
        // `output-behavior` specification. See `output.rs`
        // for the helper's contract.
        self.exec_vec(args)
            .await
            .map(|output| strip_empty_result_hint(&output))
    }

    /// Searches notes.
    pub async fn search_notes(
        &self,
        queries: &[String],
        mode: SearchMode,
        tags: &[String],
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        validate_folder_option(folder)?;
        if queries.is_empty() {
            return Err(NbError::ValidationError {
                reason: "at least one search query is required".to_string(),
                location: None,
            });
        }

        let notebook = self.resolve_notebook(notebook).await?;
        let scope = match folder {
            Some(f) => format!("{}:{}/", notebook, f),
            None => format!("{}:", notebook),
        };
        let args = search_command_args(scope, queries, mode, tags);
        self.exec_vec(args).await
    }
}

/// Numeric `.index` id for a notebook-relative path, if the basename is
/// listed in its folder `.index` (blank/deleted lines never match).
fn numeric_id_for_path(notebook_root: &Path, rel: &str) -> Option<u32> {
    let (folder, basename) = match rel.rfind('/') {
        Some(i) => (rel[..i].to_string(), rel[i + 1..].to_string()),
        None => (String::new(), rel.to_string()),
    };
    transaction::index_id_in_folder(notebook_root, &folder, &basename)
}

/// `ShowNote`/`ShowNoteLines` selector: numeric `<folder>/<id>` form when the
/// path resolves via `.index`, else the qualified selector that was read.
fn numeric_selector_for_path(
    notebook: &str,
    notebook_root: &Path,
    rel: &str,
    fallback: &str,
) -> String {
    match numeric_id_for_path(notebook_root, rel) {
        Some(id) => match rel.rfind('/') {
            Some(i) => format!("{notebook}:{}/{}", &rel[..i], id),
            None => format!("{notebook}:{id}"),
        },
        None => fallback.to_string(),
    }
}

pub(super) fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
    let nb_dir = std::env::var_os("NB_DIR")?;
    let path = PathBuf::from(nb_dir).join(notebook);
    if path.is_dir() && path.join(".git").exists() {
        Some(path)
    } else {
        None
    }
}

pub(super) fn path_relative_to(
    root: &Path,
    path: &Path,
) -> Result<String, NbError> {
    let root = root.canonicalize().map_err(|e| NbError::Io {
        path: root.to_path_buf(),
        source: e.into(),
    })?;
    let path = path.canonicalize().map_err(|e| NbError::Io {
        path: path.to_path_buf(),
        source: e.into(),
    })?;
    let rel =
        path.strip_prefix(&root)
            .map_err(|_| NbError::ValidationError {
                reason: format!(
                    "path {} is not under notebook root {}",
                    path.display(),
                    root.display()
                ),
                location: None,
            })?;
    Ok(rel.to_string_lossy().replace('\\', "/"))
}