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
19use super::read::path_relative_to;
20
21impl NbClient {
22    /// Creates a new note (one-shot transaction; nb-mangled filename).
23    pub async fn add_note(
24        &self,
25        title: Option<&str>,
26        content: &str,
27        tags: &[String],
28        folder: Option<&str>,
29        notebook: Option<&str>,
30    ) -> Result<CommitOutcome, NbError> {
31        if let Some(t) = title
32            && let Some(heading) = detect_duplicate_title_heading(t, content)
33        {
34            return Err(NbError::DuplicateTitleHeading {
35                title: t.to_string(),
36                heading,
37            });
38        }
39        self.require_folder_for_new_note(folder)?;
40        validate_folder_option(folder)?;
41        let filename = transaction::filename_for_title(title, "md");
42        self.create_with_retry(notebook, folder, filename, |tx, path| {
43            tx.add_note(&path, title, content, tags)
44        })
45        .await
46    }
47
48    /// One-shot create with `-N` collision retry on the auto filename.
49    ///
50    /// Explicit-path `Transaction` plans keep hard `PathCollision` errors;
51    /// the mangled/titleless one-shot names instead gain `-1`, `-2`, …
52    /// until free (basenames stay unique per folder, which keeps post-write
53    /// `.index` lookup unambiguous).
54    async fn create_with_retry(
55        &self,
56        notebook: Option<&str>,
57        folder: Option<&str>,
58        filename: String,
59        plan: impl Fn(&mut Transaction, String) -> Result<(), NbError>,
60    ) -> Result<CommitOutcome, NbError> {
61        let mut name = filename.clone();
62        for attempt in 0..100u32 {
63            if attempt > 0 {
64                name = transaction::suffixed_filename(&filename, attempt);
65            }
66            let path = transaction::join_folder_file(folder, &name);
67            let mut tx = self.transaction(notebook).await?;
68            plan(&mut tx, path)?;
69            match tx.commit().await {
70                Ok(outcome) => return Ok(outcome),
71                Err(NbError::PathCollision { .. }) => continue,
72                Err(other) => return Err(other),
73            }
74        }
75        Err(NbError::PathCollision {
76            path: transaction::join_folder_file(folder, &filename),
77            plan_index: None,
78        })
79    }
80
81    /// Deletes a note (one-shot transaction).
82    pub async fn delete_note(
83        &self,
84        id: &str,
85        notebook: Option<&str>,
86    ) -> Result<CommitOutcome, NbError> {
87        let (nb, selector) =
88            self.resolve_target_selector(id, notebook).await?;
89        let target = self.note_target_for_selector(&nb, &selector).await?;
90        let mut tx = self.transaction(Some(&nb)).await?;
91        tx.delete_note(target)?;
92        tx.commit().await
93    }
94
95    /// Deletes a folder (one-shot transaction).
96    ///
97    /// `recursive = false` refuses non-empty folders, listing their
98    /// contents; `recursive = true` removes the whole subtree. There
99    /// is no `force` flag: deletion is explicit by call.
100    pub async fn delete_folder(
101        &self,
102        id: &str,
103        recursive: bool,
104        notebook: Option<&str>,
105    ) -> Result<CommitOutcome, NbError> {
106        let (nb, selector) =
107            self.resolve_target_selector(id, notebook).await?;
108        let target = self.note_target_for_selector(&nb, &selector).await?;
109        let mut tx = self.transaction(Some(&nb)).await?;
110        tx.delete_folder(target, recursive)?;
111        tx.commit().await
112    }
113
114    /// Moves or renames a note (one-shot transaction).
115    pub async fn move_note(
116        &self,
117        id: &str,
118        destination: &str,
119        notebook: Option<&str>,
120    ) -> Result<CommitOutcome, NbError> {
121        validate_destination(destination)?;
122        let (nb, selector) =
123            self.resolve_target_selector(id, notebook).await?;
124        let target = self.note_target_for_selector(&nb, &selector).await?;
125        let mut tx = self.transaction(Some(&nb)).await?;
126        tx.move_note(target, destination)?;
127        tx.commit().await
128    }
129
130    async fn note_target_for_selector(
131        &self,
132        notebook: &str,
133        selector: &str,
134    ) -> Result<NoteTarget, NbError> {
135        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
136        let stripped = selector
137            .rsplit_once(':')
138            .map(|(_, rest)| rest)
139            .unwrap_or(selector);
140        let direct = root.join(stripped);
141        if direct.is_file() {
142            return Ok(NoteTarget::path(stripped));
143        }
144        // Fall back to `nb show --path` for numeric ids / titles.
145        let abs = self.resolve_item_path(selector).await?;
146        let rel = path_relative_to(&root, &abs)?;
147        Ok(NoteTarget::path(rel))
148    }
149
150    /// Creates a todo item (one-shot transaction; nb-mangled filename).
151    pub async fn add_todo(
152        &self,
153        title: &str,
154        description: Option<&str>,
155        tasks: &[String],
156        tags: &[String],
157        folder: Option<&str>,
158        notebook: Option<&str>,
159    ) -> Result<CommitOutcome, NbError> {
160        self.require_folder_for_new_note(folder)?;
161        validate_folder_option(folder)?;
162        let filename = transaction::filename_for_title(Some(title), "todo.md");
163        self.create_with_retry(notebook, folder, filename, |tx, path| {
164            tx.add_todo(&path, title, description, tasks, tags)
165        })
166        .await
167    }
168
169    /// Marks a todo as done (one-shot transaction).
170    pub async fn mark_task_done(
171        &self,
172        id: &str,
173        task_number: Option<u32>,
174        notebook: Option<&str>,
175    ) -> Result<CommitOutcome, NbError> {
176        let (nb, selector) =
177            self.resolve_target_selector(id, notebook).await?;
178        let target = self.note_target_for_selector(&nb, &selector).await?;
179        let mut tx = self.transaction(Some(&nb)).await?;
180        tx.mark_task_done(target, task_number)?;
181        tx.commit().await
182    }
183
184    /// Marks a todo as not done (one-shot transaction).
185    pub async fn unmark_task_done(
186        &self,
187        id: &str,
188        task_number: Option<u32>,
189        notebook: Option<&str>,
190    ) -> Result<CommitOutcome, NbError> {
191        let (nb, selector) =
192            self.resolve_target_selector(id, notebook).await?;
193        let target = self.note_target_for_selector(&nb, &selector).await?;
194        let mut tx = self.transaction(Some(&nb)).await?;
195        tx.unmark_task_done(target, task_number)?;
196        tx.commit().await
197    }
198
199    /// Replace contiguous body text (one-shot).
200    pub async fn replace_note_body(
201        &self,
202        target: NoteTarget,
203        new_body: &str,
204        fingerprint: Fingerprint,
205        notebook: Option<&str>,
206    ) -> Result<CommitOutcome, NbError> {
207        let mut tx = self.transaction(notebook).await?;
208        tx.replace_note_body(target, new_body, fingerprint)?;
209        tx.commit().await
210    }
211
212    /// Substring edit on contiguous body (one-shot).
213    #[allow(clippy::too_many_arguments)]
214    pub async fn edit_note_substring(
215        &self,
216        target: NoteTarget,
217        pattern: &str,
218        replacement: &str,
219        occurrence: Occurrence,
220        expected_count: u32,
221        fingerprint: Option<Fingerprint>,
222        notebook: Option<&str>,
223    ) -> Result<CommitOutcome, NbError> {
224        let mut tx = self.transaction(notebook).await?;
225        tx.edit_note_substring(
226            target,
227            pattern,
228            replacement,
229            occurrence,
230            expected_count,
231            fingerprint,
232        )?;
233        tx.commit().await
234    }
235
236    /// Line-oriented body edit batch (one-shot).
237    pub async fn edit_note_lines(
238        &self,
239        target: NoteTarget,
240        edits: Vec<LineEdit>,
241        notebook: Option<&str>,
242    ) -> Result<CommitOutcome, NbError> {
243        let mut tx = self.transaction(notebook).await?;
244        tx.edit_note_lines(target, edits)?;
245        tx.commit().await
246    }
247
248    /// Retitle a note without changing path (one-shot).
249    pub async fn retitle_note(
250        &self,
251        target: NoteTarget,
252        title: &str,
253        notebook: Option<&str>,
254    ) -> Result<CommitOutcome, NbError> {
255        let mut tx = self.transaction(notebook).await?;
256        tx.retitle_note(target, title)?;
257        tx.commit().await
258    }
259
260    /// Add/remove tags (one-shot).
261    pub async fn edit_note_tags(
262        &self,
263        target: NoteTarget,
264        add: &[String],
265        remove: &[String],
266        notebook: Option<&str>,
267    ) -> Result<CommitOutcome, NbError> {
268        let mut tx = self.transaction(notebook).await?;
269        tx.edit_note_tags(target, add, remove)?;
270        tx.commit().await
271    }
272
273    /// Lists checklist items within todos.
274    ///
275    /// Invokes `nb todos tasks` per scope. The method enumerates
276    /// the checklist items within todos (and recursively into
277    /// subfolders when `recursive = true`), filtered by
278    /// `status` if provided. An empty scope returns the empty
279    /// signal (`0 open tasks.`) rather than an error. A future
280    /// `list_todos` method for the todo **container** listing
281    /// (invoking `nb todos`) is tracked at
282    /// `nb-api:todos/api/5` (deferred to `0.5.0`).
283    pub async fn list_tasks(
284        &self,
285        folder: Option<&str>,
286        status: Option<TaskStatus>,
287        recursive: bool,
288        notebook: Option<&str>,
289    ) -> Result<String, NbError> {
290        validate_folder_option(folder)?;
291        let notebook = self.resolve_notebook(notebook).await?;
292        let folder = folder.map(normalize_folder);
293        let scopes = if recursive {
294            self.tasks_scopes_recursive(&notebook, folder.as_deref())
295                .await?
296        } else {
297            vec![tasks_scope(&notebook, folder.as_deref())]
298        };
299
300        let mut outputs: Vec<String> = Vec::new();
301        let mut saw_empty = false;
302        let mut empty_signal: Option<String> = None;
303        for scope in scopes {
304            match self.exec_vec(todos_tasks_command_args(scope, status)).await
305            {
306                Ok(output) => {
307                    let output = output.trim();
308                    if !output.is_empty() {
309                        outputs.push(output.to_string());
310                    }
311                },
312                Err(NbError::CommandFailed { stderr, .. })
313                    if is_empty_tasks_error(&stderr) =>
314                {
315                    saw_empty = true;
316                    empty_signal = Some(empty_tasks_signal(&stderr));
317                },
318                Err(err) => return Err(err),
319            }
320        }
321        if outputs.is_empty() && saw_empty {
322            // An empty scope is an empty list, not a failure: return
323            // the normalized empty signal (`0 open tasks.`) so
324            // callers can enumerate todos notebook-wide without
325            // treating "no tasks here" as an error.
326            return Ok(empty_signal.unwrap_or_default());
327        }
328        Ok(outputs.join("\n"))
329    }
330
331    async fn tasks_scopes_recursive(
332        &self,
333        notebook: &str,
334        folder: Option<&str>,
335    ) -> Result<Vec<String>, NbError> {
336        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
337        let start = folder.unwrap_or_default().to_string();
338        let mut queue = VecDeque::new();
339        queue.push_back(start.clone());
340
341        let mut scopes = vec![tasks_scope(notebook, folder)];
342        while let Some(current) = queue.pop_front() {
343            let base = if current.is_empty() {
344                notebook_root.clone()
345            } else {
346                notebook_root.join(&current)
347            };
348            let children = child_folder_names(&base)?;
349            for child in children {
350                let next = if current.is_empty() {
351                    child
352                } else {
353                    format!("{}/{}", current, child)
354                };
355                scopes.push(tasks_scope(notebook, Some(&next)));
356                queue.push_back(next);
357            }
358        }
359        Ok(scopes)
360    }
361
362    /// Creates a bookmark (one-shot transaction; nb-mangled filename).
363    pub async fn add_bookmark(
364        &self,
365        url: &str,
366        title: Option<&str>,
367        tags: &[String],
368        comment: Option<&str>,
369        folder: Option<&str>,
370        notebook: Option<&str>,
371    ) -> Result<CommitOutcome, NbError> {
372        self.require_folder_for_new_note(folder)?;
373        validate_folder_option(folder)?;
374        let filename = transaction::filename_for_title(title, "bookmark.md");
375        self.create_with_retry(notebook, folder, filename, |tx, path| {
376            tx.add_bookmark(&path, url, title, tags, comment)
377        })
378        .await
379    }
380
381    /// Lists folders in a notebook.
382    pub async fn list_folders(
383        &self,
384        parent: Option<&str>,
385        notebook: Option<&str>,
386    ) -> Result<String, NbError> {
387        let mut args = vec!["list".to_string()];
388        validate_folder_option(parent)?;
389
390        let notebook = self.resolve_notebook(notebook).await?;
391        let path = match parent {
392            Some(p) => format!("{}:{}/", notebook, p),
393            None => format!("{}:", notebook),
394        };
395        args.push(path);
396
397        // Filter to only show folders
398        args.push("--type".to_string());
399        args.push("folder".to_string());
400        args.push("--no-color".to_string());
401
402        // Strip the trailing usage/help hint block from empty
403        // results (`0 folders.` followed by `Import a file:`,
404        // `Help information:`). Detection keys off the
405        // empty-result signal per the `output-behavior`
406        // specification. See `output.rs` for the helper's
407        // contract.
408        self.exec_vec(args)
409            .await
410            .map(|output| strip_empty_result_hint(&output))
411    }
412
413    /// Creates a folder (one-shot transaction).
414    pub async fn add_folder(
415        &self,
416        path: &str,
417        notebook: Option<&str>,
418    ) -> Result<CommitOutcome, NbError> {
419        validate_folder_path(path)?;
420        let mut tx = self.transaction(notebook).await?;
421        tx.add_folder(path)?;
422        tx.commit().await
423    }
424
425    /// Imports a file or URL into the notebook as a note.
426    ///
427    /// One-shot only under the process-shared notebook gate. Not a
428    /// [`Transaction`] plan op in 0.3.0.
429    ///
430    /// NOTE (0.4.3, evaluated): `nb import` accepts no `--wait`
431    /// flag — an unknown flag would be misparsed as an import
432    /// path — and a standalone `nb git checkpoint --wait` cannot
433    /// join the import's already-backgrounded checkpoint job, so
434    /// there is no `--wait` containment for the import race window.
435    /// Containment waits on 0.5.0 (native import with proper
436    /// locking); meanwhile the commit guard absorbs index-only
437    /// droppings and note-content leftovers still refuse loudly.
438    pub async fn import_note(
439        &self,
440        source: &str,
441        folder: Option<&str>,
442        filename: Option<&str>,
443        convert: bool,
444        notebook: Option<&str>,
445    ) -> Result<String, NbError> {
446        let mut args = Vec::new();
447        self.require_folder_for_new_note(folder)?;
448        validate_folder_option(folder)?;
449
450        let notebook = self.resolve_notebook(notebook).await?;
451        self.with_notebook_gate(&notebook, async {
452            let cmd = format!("{}:import", notebook);
453            args.push(cmd);
454            args.push(source.to_string());
455            if convert {
456                args.push("--convert".to_string());
457            }
458            if folder.is_some() || filename.is_some() {
459                let dest = match (folder, filename) {
460                    (Some(f), Some(n)) => format!("{}/{}", f, n),
461                    (Some(f), None) => format!("{}/", f),
462                    (None, Some(n)) => n.to_string(),
463                    (None, None) => unreachable!(),
464                };
465                args.push(dest);
466            }
467            self.exec_vec(args)
468                .await
469                .map(|output| self.append_notebook_warning(output, &notebook))
470        })
471        .await
472    }
473}