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
use std::collections::VecDeque;

use crate::argv::{
    child_folder_names, empty_tasks_signal, is_empty_tasks_error,
    normalize_folder, tasks_scope, todos_tasks_command_args,
};
use crate::error::NbError;
use crate::fingerprint::Fingerprint;
use crate::output::strip_empty_result_hint;
use crate::transaction;
use crate::transaction::Transaction;
use crate::types::{CommitOutcome, LineEdit, NoteTarget, Occurrence};
use crate::validate::{
    detect_duplicate_title_heading, validate_destination,
    validate_folder_option, validate_folder_path,
};
use crate::{NbClient, TaskStatus};

use super::read::path_relative_to;

impl NbClient {
    /// Creates a new note (one-shot transaction; nb-mangled filename).
    pub async fn add_note(
        &self,
        title: Option<&str>,
        content: &str,
        tags: &[String],
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        if let Some(t) = title
            && let Some(heading) = detect_duplicate_title_heading(t, content)
        {
            return Err(NbError::DuplicateTitleHeading {
                title: t.to_string(),
                heading,
            });
        }
        self.require_folder_for_new_note(folder)?;
        validate_folder_option(folder)?;
        let filename = transaction::filename_for_title(title, "md");
        self.create_with_retry(notebook, folder, filename, |tx, path| {
            tx.add_note(&path, title, content, tags)
        })
        .await
    }

    /// One-shot create with `-N` collision retry on the auto filename.
    ///
    /// Explicit-path `Transaction` plans keep hard `PathCollision` errors;
    /// the mangled/titleless one-shot names instead gain `-1`, `-2`, …
    /// until free (basenames stay unique per folder, which keeps post-write
    /// `.index` lookup unambiguous).
    async fn create_with_retry(
        &self,
        notebook: Option<&str>,
        folder: Option<&str>,
        filename: String,
        plan: impl Fn(&mut Transaction, String) -> Result<(), NbError>,
    ) -> Result<CommitOutcome, NbError> {
        let mut name = filename.clone();
        for attempt in 0..100u32 {
            if attempt > 0 {
                name = transaction::suffixed_filename(&filename, attempt);
            }
            let path = transaction::join_folder_file(folder, &name);
            let mut tx = self.transaction(notebook).await?;
            plan(&mut tx, path)?;
            match tx.commit().await {
                Ok(outcome) => return Ok(outcome),
                Err(NbError::PathCollision { .. }) => continue,
                Err(other) => return Err(other),
            }
        }
        Err(NbError::PathCollision {
            path: transaction::join_folder_file(folder, &filename),
            plan_index: None,
        })
    }

    /// Deletes a note (one-shot transaction).
    pub async fn delete_note(
        &self,
        id: &str,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let (nb, selector) =
            self.resolve_target_selector(id, notebook).await?;
        let target = self.note_target_for_selector(&nb, &selector).await?;
        let mut tx = self.transaction(Some(&nb)).await?;
        tx.delete_note(target)?;
        tx.commit().await
    }

    /// Deletes a folder (one-shot transaction).
    ///
    /// `recursive = false` refuses non-empty folders, listing their
    /// contents; `recursive = true` removes the whole subtree. There
    /// is no `force` flag: deletion is explicit by call.
    pub async fn delete_folder(
        &self,
        id: &str,
        recursive: bool,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let (nb, selector) =
            self.resolve_target_selector(id, notebook).await?;
        let target = self.note_target_for_selector(&nb, &selector).await?;
        let mut tx = self.transaction(Some(&nb)).await?;
        tx.delete_folder(target, recursive)?;
        tx.commit().await
    }

    /// Moves or renames a note (one-shot transaction).
    pub async fn move_note(
        &self,
        id: &str,
        destination: &str,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        validate_destination(destination)?;
        let (nb, selector) =
            self.resolve_target_selector(id, notebook).await?;
        let target = self.note_target_for_selector(&nb, &selector).await?;
        let mut tx = self.transaction(Some(&nb)).await?;
        tx.move_note(target, destination)?;
        tx.commit().await
    }

    async fn note_target_for_selector(
        &self,
        notebook: &str,
        selector: &str,
    ) -> Result<NoteTarget, NbError> {
        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
        let stripped = selector
            .rsplit_once(':')
            .map(|(_, rest)| rest)
            .unwrap_or(selector);
        let direct = root.join(stripped);
        if direct.is_file() {
            return Ok(NoteTarget::path(stripped));
        }
        // Fall back to `nb show --path` for numeric ids / titles.
        let abs = self.resolve_item_path(selector).await?;
        let rel = path_relative_to(&root, &abs)?;
        Ok(NoteTarget::path(rel))
    }

    /// Creates a todo item (one-shot transaction; nb-mangled filename).
    pub async fn add_todo(
        &self,
        title: &str,
        description: Option<&str>,
        tasks: &[String],
        tags: &[String],
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        self.require_folder_for_new_note(folder)?;
        validate_folder_option(folder)?;
        let filename = transaction::filename_for_title(Some(title), "todo.md");
        self.create_with_retry(notebook, folder, filename, |tx, path| {
            tx.add_todo(&path, title, description, tasks, tags)
        })
        .await
    }

    /// Marks a todo as done (one-shot transaction).
    pub async fn mark_task_done(
        &self,
        id: &str,
        task_number: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let (nb, selector) =
            self.resolve_target_selector(id, notebook).await?;
        let target = self.note_target_for_selector(&nb, &selector).await?;
        let mut tx = self.transaction(Some(&nb)).await?;
        tx.mark_task_done(target, task_number)?;
        tx.commit().await
    }

    /// Marks a todo as not done (one-shot transaction).
    pub async fn unmark_task_done(
        &self,
        id: &str,
        task_number: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let (nb, selector) =
            self.resolve_target_selector(id, notebook).await?;
        let target = self.note_target_for_selector(&nb, &selector).await?;
        let mut tx = self.transaction(Some(&nb)).await?;
        tx.unmark_task_done(target, task_number)?;
        tx.commit().await
    }

    /// Replace contiguous body text (one-shot).
    pub async fn replace_note_body(
        &self,
        target: NoteTarget,
        new_body: &str,
        fingerprint: Fingerprint,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let mut tx = self.transaction(notebook).await?;
        tx.replace_note_body(target, new_body, fingerprint)?;
        tx.commit().await
    }

    /// Substring edit on contiguous body (one-shot).
    #[allow(clippy::too_many_arguments)]
    pub async fn edit_note_substring(
        &self,
        target: NoteTarget,
        pattern: &str,
        replacement: &str,
        occurrence: Occurrence,
        expected_count: u32,
        fingerprint: Option<Fingerprint>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let mut tx = self.transaction(notebook).await?;
        tx.edit_note_substring(
            target,
            pattern,
            replacement,
            occurrence,
            expected_count,
            fingerprint,
        )?;
        tx.commit().await
    }

    /// Line-oriented body edit batch (one-shot).
    pub async fn edit_note_lines(
        &self,
        target: NoteTarget,
        edits: Vec<LineEdit>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let mut tx = self.transaction(notebook).await?;
        tx.edit_note_lines(target, edits)?;
        tx.commit().await
    }

    /// Retitle a note without changing path (one-shot).
    pub async fn retitle_note(
        &self,
        target: NoteTarget,
        title: &str,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let mut tx = self.transaction(notebook).await?;
        tx.retitle_note(target, title)?;
        tx.commit().await
    }

    /// Add/remove tags (one-shot).
    pub async fn edit_note_tags(
        &self,
        target: NoteTarget,
        add: &[String],
        remove: &[String],
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        let mut tx = self.transaction(notebook).await?;
        tx.edit_note_tags(target, add, remove)?;
        tx.commit().await
    }

    /// Lists checklist items within todos.
    ///
    /// Invokes `nb todos tasks` per scope. The method enumerates
    /// the checklist items within todos (and recursively into
    /// subfolders when `recursive = true`), filtered by
    /// `status` if provided. An empty scope returns the empty
    /// signal (`0 open tasks.`) rather than an error. A future
    /// `list_todos` method for the todo **container** listing
    /// (invoking `nb todos`) is tracked at
    /// `nb-api:todos/api/5` (deferred to `0.5.0`).
    pub async fn list_tasks(
        &self,
        folder: Option<&str>,
        status: Option<TaskStatus>,
        recursive: bool,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        validate_folder_option(folder)?;
        let notebook = self.resolve_notebook(notebook).await?;
        let folder = folder.map(normalize_folder);
        let scopes = if recursive {
            self.tasks_scopes_recursive(&notebook, folder.as_deref())
                .await?
        } else {
            vec![tasks_scope(&notebook, folder.as_deref())]
        };

        let mut outputs: Vec<String> = Vec::new();
        let mut saw_empty = false;
        let mut empty_signal: Option<String> = None;
        for scope in scopes {
            match self.exec_vec(todos_tasks_command_args(scope, status)).await
            {
                Ok(output) => {
                    let output = output.trim();
                    if !output.is_empty() {
                        outputs.push(output.to_string());
                    }
                },
                Err(NbError::CommandFailed { stderr, .. })
                    if is_empty_tasks_error(&stderr) =>
                {
                    saw_empty = true;
                    empty_signal = Some(empty_tasks_signal(&stderr));
                },
                Err(err) => return Err(err),
            }
        }
        if outputs.is_empty() && saw_empty {
            // An empty scope is an empty list, not a failure: return
            // the normalized empty signal (`0 open tasks.`) so
            // callers can enumerate todos notebook-wide without
            // treating "no tasks here" as an error.
            return Ok(empty_signal.unwrap_or_default());
        }
        Ok(outputs.join("\n"))
    }

    async fn tasks_scopes_recursive(
        &self,
        notebook: &str,
        folder: Option<&str>,
    ) -> Result<Vec<String>, NbError> {
        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
        let start = folder.unwrap_or_default().to_string();
        let mut queue = VecDeque::new();
        queue.push_back(start.clone());

        let mut scopes = vec![tasks_scope(notebook, folder)];
        while let Some(current) = queue.pop_front() {
            let base = if current.is_empty() {
                notebook_root.clone()
            } else {
                notebook_root.join(&current)
            };
            let children = child_folder_names(&base)?;
            for child in children {
                let next = if current.is_empty() {
                    child
                } else {
                    format!("{}/{}", current, child)
                };
                scopes.push(tasks_scope(notebook, Some(&next)));
                queue.push_back(next);
            }
        }
        Ok(scopes)
    }

    /// Creates a bookmark (one-shot transaction; nb-mangled filename).
    pub async fn add_bookmark(
        &self,
        url: &str,
        title: Option<&str>,
        tags: &[String],
        comment: Option<&str>,
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        self.require_folder_for_new_note(folder)?;
        validate_folder_option(folder)?;
        let filename = transaction::filename_for_title(title, "bookmark.md");
        self.create_with_retry(notebook, folder, filename, |tx, path| {
            tx.add_bookmark(&path, url, title, tags, comment)
        })
        .await
    }

    /// Lists folders in a notebook.
    pub async fn list_folders(
        &self,
        parent: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let mut args = vec!["list".to_string()];
        validate_folder_option(parent)?;

        let notebook = self.resolve_notebook(notebook).await?;
        let path = match parent {
            Some(p) => format!("{}:{}/", notebook, p),
            None => format!("{}:", notebook),
        };
        args.push(path);

        // Filter to only show folders
        args.push("--type".to_string());
        args.push("folder".to_string());
        args.push("--no-color".to_string());

        // Strip the trailing usage/help hint block from empty
        // results (`0 folders.` followed by `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))
    }

    /// Creates a folder (one-shot transaction).
    pub async fn add_folder(
        &self,
        path: &str,
        notebook: Option<&str>,
    ) -> Result<CommitOutcome, NbError> {
        validate_folder_path(path)?;
        let mut tx = self.transaction(notebook).await?;
        tx.add_folder(path)?;
        tx.commit().await
    }

    /// Imports a file or URL into the notebook as a note.
    ///
    /// One-shot only under the process-shared notebook gate. Not a
    /// [`Transaction`] plan op in 0.3.0.
    ///
    /// NOTE (0.4.3, evaluated): `nb import` accepts no `--wait`
    /// flag — an unknown flag would be misparsed as an import
    /// path — and a standalone `nb git checkpoint --wait` cannot
    /// join the import's already-backgrounded checkpoint job, so
    /// there is no `--wait` containment for the import race window.
    /// Containment waits on 0.5.0 (native import with proper
    /// locking); meanwhile the commit guard absorbs index-only
    /// droppings and note-content leftovers still refuse loudly.
    pub async fn import_note(
        &self,
        source: &str,
        folder: Option<&str>,
        filename: Option<&str>,
        convert: bool,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let mut args = Vec::new();
        self.require_folder_for_new_note(folder)?;
        validate_folder_option(folder)?;

        let notebook = self.resolve_notebook(notebook).await?;
        self.with_notebook_gate(&notebook, async {
            let cmd = format!("{}:import", notebook);
            args.push(cmd);
            args.push(source.to_string());
            if convert {
                args.push("--convert".to_string());
            }
            if folder.is_some() || filename.is_some() {
                let dest = match (folder, filename) {
                    (Some(f), Some(n)) => format!("{}/{}", f, n),
                    (Some(f), None) => format!("{}/", f),
                    (None, Some(n)) => n.to_string(),
                    (None, None) => unreachable!(),
                };
                args.push(dest);
            }
            self.exec_vec(args)
                .await
                .map(|output| self.append_notebook_warning(output, &notebook))
        })
        .await
    }
}