Skip to main content

nb_api/client/
write.rs

1use std::collections::VecDeque;
2
3use crate::argv::{
4    child_folder_names, empty_tasks_signal, is_empty_tasks_error,
5    normalize_folder, tasks_scope, todos_tasks_command_args,
6};
7use crate::error::NbError;
8use crate::fingerprint::Fingerprint;
9use crate::output::strip_empty_result_hint;
10use crate::transaction;
11use crate::transaction::Transaction;
12use crate::types::{CommitOutcome, LineEdit, NoteTarget, Occurrence};
13use crate::validate::{
14    detect_duplicate_title_heading, validate_destination,
15    validate_folder_option, validate_folder_path,
16};
17use crate::{NbClient, TaskStatus};
18
19impl NbClient {
20    /// Creates a new note (one-shot transaction; nb-mangled filename).
21    pub async fn add_note(
22        &self,
23        title: Option<&str>,
24        content: &str,
25        tags: &[String],
26        folder: Option<&str>,
27        notebook: Option<&str>,
28    ) -> Result<CommitOutcome, NbError> {
29        if let Some(t) = title
30            && let Some(heading) = detect_duplicate_title_heading(t, content)
31        {
32            return Err(NbError::DuplicateTitleHeading {
33                title: t.to_string(),
34                heading,
35            });
36        }
37        self.require_folder_for_new_note(folder)?;
38        validate_folder_option(folder)?;
39        let filename = transaction::filename_for_title(title, "md");
40        self.create_with_retry(notebook, folder, filename, |tx, path| {
41            tx.add_note(&path, title, content, tags)
42        })
43        .await
44    }
45
46    /// One-shot create with `-N` collision retry on the auto filename.
47    ///
48    /// Explicit-path `Transaction` plans keep hard `PathCollision` errors;
49    /// the mangled/titleless one-shot names instead gain `-1`, `-2`, …
50    /// until free (basenames stay unique per folder, which keeps post-write
51    /// `.index` lookup unambiguous).
52    async fn create_with_retry(
53        &self,
54        notebook: Option<&str>,
55        folder: Option<&str>,
56        filename: String,
57        plan: impl Fn(&mut Transaction, String) -> Result<(), NbError>,
58    ) -> Result<CommitOutcome, NbError> {
59        let mut name = filename.clone();
60        for attempt in 0..100u32 {
61            if attempt > 0 {
62                name = transaction::suffixed_filename(&filename, attempt);
63            }
64            let path = transaction::join_folder_file(folder, &name);
65            let mut tx = self.transaction(notebook).await?;
66            plan(&mut tx, path)?;
67            match tx.commit().await {
68                Ok(outcome) => return Ok(outcome),
69                Err(NbError::PathCollision { .. }) => continue,
70                Err(other) => return Err(other),
71            }
72        }
73        Err(NbError::PathCollision {
74            path: transaction::join_folder_file(folder, &filename),
75            plan_index: None,
76        })
77    }
78
79    /// Deletes a note (one-shot transaction).
80    pub async fn delete_note(
81        &self,
82        id: &str,
83        notebook: Option<&str>,
84    ) -> Result<CommitOutcome, NbError> {
85        let (nb, selector) =
86            self.resolve_target_selector(id, notebook).await?;
87        let target = self.note_target_for_selector(&nb, &selector).await?;
88        let mut tx = self.transaction(Some(&nb)).await?;
89        tx.delete_note(target)?;
90        tx.commit().await
91    }
92
93    /// Deletes a folder (one-shot transaction).
94    ///
95    /// `recursive = false` refuses non-empty folders, listing their
96    /// contents; `recursive = true` removes the whole subtree. There
97    /// is no `force` flag: deletion is explicit by call.
98    pub async fn delete_folder(
99        &self,
100        id: &str,
101        recursive: bool,
102        notebook: Option<&str>,
103    ) -> Result<CommitOutcome, NbError> {
104        let (nb, selector) =
105            self.resolve_target_selector(id, notebook).await?;
106        let target = self.note_target_for_selector(&nb, &selector).await?;
107        let mut tx = self.transaction(Some(&nb)).await?;
108        tx.delete_folder(target, recursive)?;
109        tx.commit().await
110    }
111
112    /// Moves or renames a note (one-shot transaction).
113    pub async fn move_note(
114        &self,
115        id: &str,
116        destination: &str,
117        notebook: Option<&str>,
118    ) -> Result<CommitOutcome, NbError> {
119        validate_destination(destination)?;
120        let (nb, selector) =
121            self.resolve_target_selector(id, notebook).await?;
122        let target = self.note_target_for_selector(&nb, &selector).await?;
123        let mut tx = self.transaction(Some(&nb)).await?;
124        tx.move_note(target, destination)?;
125        tx.commit().await
126    }
127
128    /// Resolve a write one-shot selector to a [`NoteTarget`]:
129    /// direct filesystem hit first, else the native pinned table
130    /// (numeric id, then root title) inside one no-ensure gate hold.
131    /// Spawns zero `nb` subprocesses; notebook existence is ensured
132    /// upstream by the caller. Missing inputs are terminal
133    /// `NotFound` with the original selector.
134    async fn note_target_for_selector(
135        &self,
136        notebook: &str,
137        selector: &str,
138    ) -> Result<NoteTarget, NbError> {
139        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
140        let stripped = selector
141            .rsplit_once(':')
142            .map(|(_, rest)| rest)
143            .unwrap_or(selector);
144        if stripped.is_empty() {
145            return Ok(NoteTarget::path(stripped));
146        }
147        // Lexically confined exact hit first (symlinks never
148        // followed); anything else goes through the pinned table
149        // inside one gate hold.
150        match crate::native::resolve_exact(&root, stripped) {
151            Ok(rel) => return Ok(NoteTarget::path(rel)),
152            Err(NbError::NotFound { .. }) => {},
153            Err(other) => return Err(other),
154        }
155        self.with_notebook_gate_native(&root, async {
156            let rel = crate::native::resolve_selector(&root, stripped)
157                .map_err(|e| match e {
158                    NbError::NotFound { .. } => NbError::NotFound {
159                        selector: selector.to_string(),
160                    },
161                    other => other,
162                })?;
163            Ok(NoteTarget::path(rel))
164        })
165        .await
166    }
167
168    /// Creates a todo item (one-shot transaction; nb-mangled filename).
169    pub async fn add_todo(
170        &self,
171        title: &str,
172        description: Option<&str>,
173        tasks: &[String],
174        tags: &[String],
175        folder: Option<&str>,
176        notebook: Option<&str>,
177    ) -> Result<CommitOutcome, NbError> {
178        self.require_folder_for_new_note(folder)?;
179        validate_folder_option(folder)?;
180        let filename = transaction::filename_for_title(Some(title), "todo.md");
181        self.create_with_retry(notebook, folder, filename, |tx, path| {
182            tx.add_todo(&path, title, description, tasks, tags)
183        })
184        .await
185    }
186
187    /// Marks a todo as done (one-shot transaction).
188    pub async fn mark_task_done(
189        &self,
190        id: &str,
191        task_number: Option<u32>,
192        notebook: Option<&str>,
193    ) -> Result<CommitOutcome, NbError> {
194        let (nb, selector) =
195            self.resolve_target_selector(id, notebook).await?;
196        let target = self.note_target_for_selector(&nb, &selector).await?;
197        let mut tx = self.transaction(Some(&nb)).await?;
198        tx.mark_task_done(target, task_number)?;
199        tx.commit().await
200    }
201
202    /// Marks a todo as not done (one-shot transaction).
203    pub async fn unmark_task_done(
204        &self,
205        id: &str,
206        task_number: Option<u32>,
207        notebook: Option<&str>,
208    ) -> Result<CommitOutcome, NbError> {
209        let (nb, selector) =
210            self.resolve_target_selector(id, notebook).await?;
211        let target = self.note_target_for_selector(&nb, &selector).await?;
212        let mut tx = self.transaction(Some(&nb)).await?;
213        tx.unmark_task_done(target, task_number)?;
214        tx.commit().await
215    }
216
217    /// Replace contiguous body text (one-shot).
218    pub async fn replace_note_body(
219        &self,
220        target: NoteTarget,
221        new_body: &str,
222        fingerprint: Fingerprint,
223        notebook: Option<&str>,
224    ) -> Result<CommitOutcome, NbError> {
225        let mut tx = self.transaction(notebook).await?;
226        tx.replace_note_body(target, new_body, fingerprint)?;
227        tx.commit().await
228    }
229
230    /// Substring edit on contiguous body (one-shot).
231    #[allow(clippy::too_many_arguments)]
232    pub async fn edit_note_substring(
233        &self,
234        target: NoteTarget,
235        pattern: &str,
236        replacement: &str,
237        occurrence: Occurrence,
238        expected_count: u32,
239        fingerprint: Option<Fingerprint>,
240        notebook: Option<&str>,
241    ) -> Result<CommitOutcome, NbError> {
242        let mut tx = self.transaction(notebook).await?;
243        tx.edit_note_substring(
244            target,
245            pattern,
246            replacement,
247            occurrence,
248            expected_count,
249            fingerprint,
250        )?;
251        tx.commit().await
252    }
253
254    /// Line-oriented body edit batch (one-shot).
255    pub async fn edit_note_lines(
256        &self,
257        target: NoteTarget,
258        edits: Vec<LineEdit>,
259        notebook: Option<&str>,
260    ) -> Result<CommitOutcome, NbError> {
261        let mut tx = self.transaction(notebook).await?;
262        tx.edit_note_lines(target, edits)?;
263        tx.commit().await
264    }
265
266    /// Retitle a note without changing path (one-shot).
267    pub async fn retitle_note(
268        &self,
269        target: NoteTarget,
270        title: &str,
271        notebook: Option<&str>,
272    ) -> Result<CommitOutcome, NbError> {
273        let mut tx = self.transaction(notebook).await?;
274        tx.retitle_note(target, title)?;
275        tx.commit().await
276    }
277
278    /// Add/remove tags (one-shot).
279    pub async fn edit_note_tags(
280        &self,
281        target: NoteTarget,
282        add: &[String],
283        remove: &[String],
284        notebook: Option<&str>,
285    ) -> Result<CommitOutcome, NbError> {
286        let mut tx = self.transaction(notebook).await?;
287        tx.edit_note_tags(target, add, remove)?;
288        tx.commit().await
289    }
290
291    /// Lists checklist items within todos.
292    ///
293    /// Invokes `nb todos tasks` per scope. The method enumerates
294    /// the checklist items within todos (and recursively into
295    /// subfolders when `recursive = true`), filtered by
296    /// `status` if provided. An empty scope returns the empty
297    /// signal (`0 open tasks.`) rather than an error. A future
298    /// `list_todos` method for the todo **container** listing
299    /// (invoking `nb todos`) is tracked at
300    /// `nb-api:todos/api/5` (deferred to `0.5.0`).
301    pub async fn list_tasks(
302        &self,
303        folder: Option<&str>,
304        status: Option<TaskStatus>,
305        recursive: bool,
306        notebook: Option<&str>,
307    ) -> Result<String, NbError> {
308        validate_folder_option(folder)?;
309        let notebook = self.resolve_notebook(notebook).await?;
310        let folder = folder.map(normalize_folder);
311        let scopes = if recursive {
312            self.tasks_scopes_recursive(&notebook, folder.as_deref())
313                .await?
314        } else {
315            vec![tasks_scope(&notebook, folder.as_deref())]
316        };
317
318        let mut outputs: Vec<String> = Vec::new();
319        let mut saw_empty = false;
320        let mut empty_signal: Option<String> = None;
321        for scope in scopes {
322            match self.exec_vec(todos_tasks_command_args(scope, status)).await
323            {
324                Ok(output) => {
325                    let output = output.trim();
326                    if !output.is_empty() {
327                        outputs.push(output.to_string());
328                    }
329                },
330                Err(NbError::CommandFailed { stderr, .. })
331                    if is_empty_tasks_error(&stderr) =>
332                {
333                    saw_empty = true;
334                    empty_signal = Some(empty_tasks_signal(&stderr));
335                },
336                Err(err) => return Err(err),
337            }
338        }
339        if outputs.is_empty() && saw_empty {
340            // An empty scope is an empty list, not a failure: return
341            // the normalized empty signal (`0 open tasks.`) so
342            // callers can enumerate todos notebook-wide without
343            // treating "no tasks here" as an error.
344            return Ok(empty_signal.unwrap_or_default());
345        }
346        Ok(outputs.join("\n"))
347    }
348
349    /// Lists todo checklist items natively: one [`crate::ListEntry`]
350    /// per `- [ ]` / `- [x]` / `- [X]` item in `.todo.md` files
351    /// under the scope (recursive iff set), in file order with
352    /// 1-based task positions. Selectors append `#task-<n>` to the
353    /// shadow-aware canonical file selector; kind is `Todo` and
354    /// `numeric_id` rides along from the file. `status` filters by
355    /// item state (`None` keeps all). Scopes skip dotfiles and
356    /// symlinks; a missing scope is terminal `NotFound`. Zero `nb`
357    /// spawns.
358    pub async fn list_tasks_typed(
359        &self,
360        folder: Option<&str>,
361        status: Option<TaskStatus>,
362        recursive: bool,
363        notebook: Option<&str>,
364    ) -> Result<Vec<crate::ListEntry>, NbError> {
365        validate_folder_option(folder)?;
366        let notebook = self.resolve_notebook_name(notebook)?;
367        let root = self.native_notebook_root(&notebook).await?;
368        // Leading slashes are NOT trimmed: absolute forms
369        // fail closed as NotFound inside confinement.
370        let scope = folder.unwrap_or_default().to_string();
371        let want_closed = status.map(|s| matches!(s, TaskStatus::Closed));
372        self.with_notebook_gate_native(&root, async {
373            let rels = if recursive {
374                crate::scope::scope_files_recursive(&root, &scope)?
375            } else {
376                crate::scope::scope_files(&root, &scope)?
377            };
378            let mut out = Vec::new();
379            for rel in rels {
380                if crate::native::document_kind_for_rel(&rel)
381                    != crate::DocumentKind::Todo
382                {
383                    continue;
384                }
385                let abs = root.join(&rel);
386                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
387                    path: abs.clone(),
388                    source: e.into(),
389                })?;
390                let file = self.list_entry_for(&notebook, &root, &rel).await?;
391                for (i, closed) in
392                    crate::scope::todo_items(&bytes).into_iter().enumerate()
393                {
394                    if let Some(want) = want_closed
395                        && want != closed
396                    {
397                        continue;
398                    }
399                    out.push(crate::ListEntry {
400                        selector: format!("{}#task-{}", file.selector, i + 1),
401                        path: file.path.clone(),
402                        kind: crate::EntityKind::Todo,
403                        numeric_id: file.numeric_id,
404                    });
405                }
406            }
407            Ok(out)
408        })
409        .await
410    }
411
412    /// Lists todo files as summaries: one [`crate::TodoSummary`] per
413    /// `.todo.md` file under the scope (recursive iff set) with task
414    /// counts and derived state (`Done` iff at least one item exists
415    /// and all are completed, else `Open`). `state` filters files
416    /// (`None` keeps all). Titles are checkbox-stripped and trimmed,
417    /// falling back to the filename. Zero `nb` spawns.
418    pub async fn list_todos(
419        &self,
420        folder: Option<&str>,
421        state: Option<crate::TodoState>,
422        recursive: bool,
423        notebook: Option<&str>,
424    ) -> Result<Vec<crate::TodoSummary>, NbError> {
425        use crate::parser::{ParseContext, parse};
426
427        validate_folder_option(folder)?;
428        let notebook = self.resolve_notebook_name(notebook)?;
429        let root = self.native_notebook_root(&notebook).await?;
430        // Leading slashes are NOT trimmed: absolute forms
431        // fail closed as NotFound inside confinement.
432        let scope = folder.unwrap_or_default().to_string();
433        self.with_notebook_gate_native(&root, async {
434            let rels = if recursive {
435                crate::scope::scope_files_recursive(&root, &scope)?
436            } else {
437                crate::scope::scope_files(&root, &scope)?
438            };
439            let mut out = Vec::new();
440            for rel in rels {
441                if crate::native::document_kind_for_rel(&rel)
442                    != crate::DocumentKind::Todo
443                {
444                    continue;
445                }
446                let abs = root.join(&rel);
447                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
448                    path: abs.clone(),
449                    source: e.into(),
450                })?;
451                // Malformed containers surface instead of skipping:
452                // without valid UTF-8 there is no faithful title,
453                // state, or task text to report.
454                if std::str::from_utf8(&bytes).is_err() {
455                    let selector = crate::native::canonical_selector(
456                        &notebook, &root, &rel,
457                    )?;
458                    return Err(NbError::NonUtf8 {
459                        selector,
460                        path: rel.clone(),
461                        kind: "todo".to_string(),
462                        mime_hint: None,
463                    });
464                }
465                let items = crate::scope::todo_items(&bytes);
466                let completed = items.iter().filter(|&&c| c).count() as u32;
467                let total = items.len() as u32;
468                // Malformed containers surface their parse error;
469                // only a missing title falls back to the filename.
470                let doc =
471                    parse(&bytes, ParseContext::FromPath(rel.clone().into()))?;
472                // Explicit container state wins: a checked title
473                // decides even when the counts disagree. Without a
474                // title checkbox, all-checked (non-empty) is Done.
475                let file_state = match doc.todo_state() {
476                    Some(explicit) => explicit,
477                    None if total > 0 && completed == total => {
478                        crate::TodoState::Done
479                    },
480                    None => crate::TodoState::Open,
481                };
482                if let Some(want) = state
483                    && want != file_state
484                {
485                    continue;
486                }
487                let title = doc
488                    .title()
489                    .map(|t| {
490                        let s = String::from_utf8_lossy(t);
491                        let s = s
492                            .trim_end_matches('\n')
493                            .trim_start_matches('#')
494                            .trim();
495                        let s = s
496                            .strip_prefix("[ ]")
497                            .or_else(|| s.strip_prefix("[x]"))
498                            .or_else(|| s.strip_prefix("[X]"))
499                            .unwrap_or(s);
500                        s.trim().to_string()
501                    })
502                    .filter(|t| !t.is_empty())
503                    .unwrap_or_else(|| {
504                        rel.rsplit('/').next().unwrap_or(&rel).to_string()
505                    });
506                let file = self.list_entry_for(&notebook, &root, &rel).await?;
507                out.push(crate::TodoSummary {
508                    id: file.selector,
509                    title,
510                    path: rel,
511                    task_count: total,
512                    completed_count: completed,
513                    state: file_state,
514                });
515            }
516            Ok(out)
517        })
518        .await
519    }
520
521    async fn tasks_scopes_recursive(
522        &self,
523        notebook: &str,
524        folder: Option<&str>,
525    ) -> Result<Vec<String>, NbError> {
526        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
527        let start = folder.unwrap_or_default().to_string();
528        let mut queue = VecDeque::new();
529        queue.push_back(start.clone());
530
531        let mut scopes = vec![tasks_scope(notebook, folder)];
532        while let Some(current) = queue.pop_front() {
533            let base = if current.is_empty() {
534                notebook_root.clone()
535            } else {
536                notebook_root.join(&current)
537            };
538            let children = child_folder_names(&base)?;
539            for child in children {
540                let next = if current.is_empty() {
541                    child
542                } else {
543                    format!("{}/{}", current, child)
544                };
545                scopes.push(tasks_scope(notebook, Some(&next)));
546                queue.push_back(next);
547            }
548        }
549        Ok(scopes)
550    }
551
552    /// Creates a bookmark (one-shot transaction; nb-mangled filename).
553    pub async fn add_bookmark(
554        &self,
555        url: &str,
556        title: Option<&str>,
557        tags: &[String],
558        comment: Option<&str>,
559        folder: Option<&str>,
560        notebook: Option<&str>,
561    ) -> Result<CommitOutcome, NbError> {
562        self.require_folder_for_new_note(folder)?;
563        validate_folder_option(folder)?;
564        let filename = transaction::filename_for_title(title, "bookmark.md");
565        self.create_with_retry(notebook, folder, filename, |tx, path| {
566            tx.add_bookmark(&path, url, title, tags, comment)
567        })
568        .await
569    }
570
571    /// Lists folders in a notebook.
572    pub async fn list_folders(
573        &self,
574        parent: Option<&str>,
575        notebook: Option<&str>,
576    ) -> Result<String, NbError> {
577        let mut args = vec!["list".to_string()];
578        validate_folder_option(parent)?;
579
580        let notebook = self.resolve_notebook(notebook).await?;
581        let path = match parent {
582            Some(p) => format!("{}:{}/", notebook, p),
583            None => format!("{}:", notebook),
584        };
585        args.push(path);
586
587        // Filter to only show folders
588        args.push("--type".to_string());
589        args.push("folder".to_string());
590        args.push("--no-color".to_string());
591
592        // Strip the trailing usage/help hint block from empty
593        // results (`0 folders.` followed by `Import a file:`,
594        // `Help information:`). Detection keys off the
595        // empty-result signal per the `output-behavior`
596        // specification. See `output.rs` for the helper's
597        // contract.
598        self.exec_vec(args)
599            .await
600            .map(|output| strip_empty_result_hint(&output))
601    }
602
603    /// Lists folders in a notebook as typed entries: one
604    /// [`crate::ListEntry`] per direct child directory of the
605    /// scope (non-recursive), excluding dot-directories, ordered
606    /// lexically by relative path. Each entry is kind `Folder`
607    /// with the exact-path selector and no numeric id. A missing
608    /// scope is terminal `NotFound`. Zero `nb` spawns.
609    pub async fn list_folders_typed(
610        &self,
611        parent: Option<&str>,
612        notebook: Option<&str>,
613    ) -> Result<Vec<crate::ListEntry>, NbError> {
614        validate_folder_option(parent)?;
615        let notebook = self.resolve_notebook_name(notebook)?;
616        let root = self.native_notebook_root(&notebook).await?;
617        // Leading slashes are NOT trimmed: absolute forms
618        // fail closed as NotFound inside confinement.
619        let scope = parent.unwrap_or_default().to_string();
620        self.with_notebook_gate_native(&root, async {
621            let mut out = Vec::new();
622            for rel in crate::scope::scope_dirs(&root, &scope)? {
623                out.push(self.list_entry_for(&notebook, &root, &rel).await?);
624            }
625            Ok(out)
626        })
627        .await
628    }
629
630    /// Creates a folder (one-shot transaction).
631    pub async fn add_folder(
632        &self,
633        path: &str,
634        notebook: Option<&str>,
635    ) -> Result<CommitOutcome, NbError> {
636        validate_folder_path(path)?;
637        let mut tx = self.transaction(notebook).await?;
638        tx.add_folder(path)?;
639        tx.commit().await
640    }
641
642    /// Imports a file or URL into the notebook as a note.
643    ///
644    /// One-shot only under the process-shared notebook gate. Not a
645    /// [`Transaction`] plan op in 0.3.0.
646    ///
647    /// NOTE (0.4.3, evaluated): `nb import` accepts no `--wait`
648    /// flag — an unknown flag would be misparsed as an import
649    /// path — and a standalone `nb git checkpoint --wait` cannot
650    /// join the import's already-backgrounded checkpoint job, so
651    /// there is no `--wait` containment for the import race window.
652    /// Containment waits on 0.5.0 (native import with proper
653    /// locking); meanwhile the commit guard absorbs index-only
654    /// droppings and note-content leftovers still refuse loudly.
655    pub async fn import_note(
656        &self,
657        source: &str,
658        folder: Option<&str>,
659        filename: Option<&str>,
660        convert: bool,
661        notebook: Option<&str>,
662    ) -> Result<String, NbError> {
663        let mut args = Vec::new();
664        self.require_folder_for_new_note(folder)?;
665        validate_folder_option(folder)?;
666
667        let notebook = self.resolve_notebook(notebook).await?;
668        self.with_notebook_gate(&notebook, async {
669            let cmd = format!("{}:import", notebook);
670            args.push(cmd);
671            args.push(source.to_string());
672            if convert {
673                args.push("--convert".to_string());
674            }
675            if folder.is_some() || filename.is_some() {
676                let dest = match (folder, filename) {
677                    (Some(f), Some(n)) => format!("{}/{}", f, n),
678                    (Some(f), None) => format!("{}/", f),
679                    (None, Some(n)) => n.to_string(),
680                    (None, None) => unreachable!(),
681                };
682                args.push(dest);
683            }
684            self.exec_vec(args)
685                .await
686                .map(|output| self.append_notebook_warning(output, &notebook))
687        })
688        .await
689    }
690}