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    /// Moves or renames a note (one-shot transaction).
96    pub async fn move_note(
97        &self,
98        id: &str,
99        destination: &str,
100        notebook: Option<&str>,
101    ) -> Result<CommitOutcome, NbError> {
102        validate_destination(destination)?;
103        let (nb, selector) =
104            self.resolve_target_selector(id, notebook).await?;
105        let target = self.note_target_for_selector(&nb, &selector).await?;
106        let mut tx = self.transaction(Some(&nb)).await?;
107        tx.move_note(target, destination)?;
108        tx.commit().await
109    }
110
111    async fn note_target_for_selector(
112        &self,
113        notebook: &str,
114        selector: &str,
115    ) -> Result<NoteTarget, NbError> {
116        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
117        let stripped = selector
118            .rsplit_once(':')
119            .map(|(_, rest)| rest)
120            .unwrap_or(selector);
121        let direct = root.join(stripped);
122        if direct.is_file() {
123            return Ok(NoteTarget::path(stripped));
124        }
125        // Fall back to `nb show --path` for numeric ids / titles.
126        let abs = self.resolve_item_path(selector).await?;
127        let rel = path_relative_to(&root, &abs)?;
128        Ok(NoteTarget::path(rel))
129    }
130
131    /// Creates a todo item (one-shot transaction; nb-mangled filename).
132    pub async fn add_todo(
133        &self,
134        title: &str,
135        description: Option<&str>,
136        tasks: &[String],
137        tags: &[String],
138        folder: Option<&str>,
139        notebook: Option<&str>,
140    ) -> Result<CommitOutcome, NbError> {
141        self.require_folder_for_new_note(folder)?;
142        validate_folder_option(folder)?;
143        let filename = transaction::filename_for_title(Some(title), "todo.md");
144        self.create_with_retry(notebook, folder, filename, |tx, path| {
145            tx.add_todo(&path, title, description, tasks, tags)
146        })
147        .await
148    }
149
150    /// Marks a todo as done (one-shot transaction).
151    pub async fn mark_task_done(
152        &self,
153        id: &str,
154        task_number: Option<u32>,
155        notebook: Option<&str>,
156    ) -> Result<CommitOutcome, NbError> {
157        let (nb, selector) =
158            self.resolve_target_selector(id, notebook).await?;
159        let target = self.note_target_for_selector(&nb, &selector).await?;
160        let mut tx = self.transaction(Some(&nb)).await?;
161        tx.mark_task_done(target, task_number)?;
162        tx.commit().await
163    }
164
165    /// Marks a todo as not done (one-shot transaction).
166    pub async fn unmark_task_done(
167        &self,
168        id: &str,
169        task_number: Option<u32>,
170        notebook: Option<&str>,
171    ) -> Result<CommitOutcome, NbError> {
172        let (nb, selector) =
173            self.resolve_target_selector(id, notebook).await?;
174        let target = self.note_target_for_selector(&nb, &selector).await?;
175        let mut tx = self.transaction(Some(&nb)).await?;
176        tx.unmark_task_done(target, task_number)?;
177        tx.commit().await
178    }
179
180    /// Replace contiguous body text (one-shot).
181    pub async fn replace_note_body(
182        &self,
183        target: NoteTarget,
184        new_body: &str,
185        fingerprint: Fingerprint,
186        notebook: Option<&str>,
187    ) -> Result<CommitOutcome, NbError> {
188        let mut tx = self.transaction(notebook).await?;
189        tx.replace_note_body(target, new_body, fingerprint)?;
190        tx.commit().await
191    }
192
193    /// Substring edit on contiguous body (one-shot).
194    #[allow(clippy::too_many_arguments)]
195    pub async fn edit_note_substring(
196        &self,
197        target: NoteTarget,
198        pattern: &str,
199        replacement: &str,
200        occurrence: Occurrence,
201        expected_count: u32,
202        fingerprint: Option<Fingerprint>,
203        notebook: Option<&str>,
204    ) -> Result<CommitOutcome, NbError> {
205        let mut tx = self.transaction(notebook).await?;
206        tx.edit_note_substring(
207            target,
208            pattern,
209            replacement,
210            occurrence,
211            expected_count,
212            fingerprint,
213        )?;
214        tx.commit().await
215    }
216
217    /// Line-oriented body edit batch (one-shot).
218    pub async fn edit_note_lines(
219        &self,
220        target: NoteTarget,
221        edits: Vec<LineEdit>,
222        notebook: Option<&str>,
223    ) -> Result<CommitOutcome, NbError> {
224        let mut tx = self.transaction(notebook).await?;
225        tx.edit_note_lines(target, edits)?;
226        tx.commit().await
227    }
228
229    /// Retitle a note without changing path (one-shot).
230    pub async fn retitle_note(
231        &self,
232        target: NoteTarget,
233        title: &str,
234        notebook: Option<&str>,
235    ) -> Result<CommitOutcome, NbError> {
236        let mut tx = self.transaction(notebook).await?;
237        tx.retitle_note(target, title)?;
238        tx.commit().await
239    }
240
241    /// Add/remove tags (one-shot).
242    pub async fn edit_note_tags(
243        &self,
244        target: NoteTarget,
245        add: &[String],
246        remove: &[String],
247        notebook: Option<&str>,
248    ) -> Result<CommitOutcome, NbError> {
249        let mut tx = self.transaction(notebook).await?;
250        tx.edit_note_tags(target, add, remove)?;
251        tx.commit().await
252    }
253
254    /// Lists checklist items within todos.
255    ///
256    /// Invokes `nb todos tasks` per scope. The method enumerates
257    /// the checklist items within todos (and recursively into
258    /// subfolders when `recursive = true`), filtered by
259    /// `status` if provided. An empty scope returns the empty
260    /// signal (`0 open tasks.`) rather than an error. A future
261    /// `list_todos` method for the todo **container** listing
262    /// (invoking `nb todos`) is tracked at
263    /// `nb-api:todos/api/5` (deferred to `0.5.0`).
264    pub async fn list_tasks(
265        &self,
266        folder: Option<&str>,
267        status: Option<TaskStatus>,
268        recursive: bool,
269        notebook: Option<&str>,
270    ) -> Result<String, NbError> {
271        validate_folder_option(folder)?;
272        let notebook = self.resolve_notebook(notebook).await?;
273        let folder = folder.map(normalize_folder);
274        let scopes = if recursive {
275            self.tasks_scopes_recursive(&notebook, folder.as_deref())
276                .await?
277        } else {
278            vec![tasks_scope(&notebook, folder.as_deref())]
279        };
280
281        let mut outputs: Vec<String> = Vec::new();
282        let mut saw_empty = false;
283        let mut empty_signal: Option<String> = None;
284        for scope in scopes {
285            match self.exec_vec(todos_tasks_command_args(scope, status)).await
286            {
287                Ok(output) => {
288                    let output = output.trim();
289                    if !output.is_empty() {
290                        outputs.push(output.to_string());
291                    }
292                },
293                Err(NbError::CommandFailed { stderr, .. })
294                    if is_empty_tasks_error(&stderr) =>
295                {
296                    saw_empty = true;
297                    empty_signal = Some(empty_tasks_signal(&stderr));
298                },
299                Err(err) => return Err(err),
300            }
301        }
302        if outputs.is_empty() && saw_empty {
303            // An empty scope is an empty list, not a failure: return
304            // the normalized empty signal (`0 open tasks.`) so
305            // callers can enumerate todos notebook-wide without
306            // treating "no tasks here" as an error.
307            return Ok(empty_signal.unwrap_or_default());
308        }
309        Ok(outputs.join("\n"))
310    }
311
312    async fn tasks_scopes_recursive(
313        &self,
314        notebook: &str,
315        folder: Option<&str>,
316    ) -> Result<Vec<String>, NbError> {
317        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
318        let start = folder.unwrap_or_default().to_string();
319        let mut queue = VecDeque::new();
320        queue.push_back(start.clone());
321
322        let mut scopes = vec![tasks_scope(notebook, folder)];
323        while let Some(current) = queue.pop_front() {
324            let base = if current.is_empty() {
325                notebook_root.clone()
326            } else {
327                notebook_root.join(&current)
328            };
329            let children = child_folder_names(&base)?;
330            for child in children {
331                let next = if current.is_empty() {
332                    child
333                } else {
334                    format!("{}/{}", current, child)
335                };
336                scopes.push(tasks_scope(notebook, Some(&next)));
337                queue.push_back(next);
338            }
339        }
340        Ok(scopes)
341    }
342
343    /// Creates a bookmark (one-shot transaction; nb-mangled filename).
344    pub async fn add_bookmark(
345        &self,
346        url: &str,
347        title: Option<&str>,
348        tags: &[String],
349        comment: Option<&str>,
350        folder: Option<&str>,
351        notebook: Option<&str>,
352    ) -> Result<CommitOutcome, NbError> {
353        self.require_folder_for_new_note(folder)?;
354        validate_folder_option(folder)?;
355        let filename = transaction::filename_for_title(title, "bookmark.md");
356        self.create_with_retry(notebook, folder, filename, |tx, path| {
357            tx.add_bookmark(&path, url, title, tags, comment)
358        })
359        .await
360    }
361
362    /// Lists folders in a notebook.
363    pub async fn list_folders(
364        &self,
365        parent: Option<&str>,
366        notebook: Option<&str>,
367    ) -> Result<String, NbError> {
368        let mut args = vec!["list".to_string()];
369        validate_folder_option(parent)?;
370
371        let notebook = self.resolve_notebook(notebook).await?;
372        let path = match parent {
373            Some(p) => format!("{}:{}/", notebook, p),
374            None => format!("{}:", notebook),
375        };
376        args.push(path);
377
378        // Filter to only show folders
379        args.push("--type".to_string());
380        args.push("folder".to_string());
381        args.push("--no-color".to_string());
382
383        // Strip the trailing usage/help hint block from empty
384        // results (`0 folders.` followed by `Import a file:`,
385        // `Help information:`). Detection keys off the
386        // empty-result signal per the `output-behavior`
387        // specification. See `output.rs` for the helper's
388        // contract.
389        self.exec_vec(args)
390            .await
391            .map(|output| strip_empty_result_hint(&output))
392    }
393
394    /// Creates a folder (one-shot transaction).
395    pub async fn add_folder(
396        &self,
397        path: &str,
398        notebook: Option<&str>,
399    ) -> Result<CommitOutcome, NbError> {
400        validate_folder_path(path)?;
401        let mut tx = self.transaction(notebook).await?;
402        tx.add_folder(path)?;
403        tx.commit().await
404    }
405
406    /// Imports a file or URL into the notebook as a note.
407    ///
408    /// One-shot only under the process-shared notebook gate. Not a
409    /// [`Transaction`] plan op in 0.3.0.
410    pub async fn import_note(
411        &self,
412        source: &str,
413        folder: Option<&str>,
414        filename: Option<&str>,
415        convert: bool,
416        notebook: Option<&str>,
417    ) -> Result<String, NbError> {
418        let mut args = Vec::new();
419        self.require_folder_for_new_note(folder)?;
420        validate_folder_option(folder)?;
421
422        let notebook = self.resolve_notebook(notebook).await?;
423        self.with_notebook_gate(&notebook, async {
424            let cmd = format!("{}:import", notebook);
425            args.push(cmd);
426            args.push(source.to_string());
427            if convert {
428                args.push("--convert".to_string());
429            }
430            if folder.is_some() || filename.is_some() {
431                let dest = match (folder, filename) {
432                    (Some(f), Some(n)) => format!("{}/{}", f, n),
433                    (Some(f), None) => format!("{}/", f),
434                    (None, Some(n)) => n.to_string(),
435                    (None, None) => unreachable!(),
436                };
437                args.push(dest);
438            }
439            self.exec_vec(args)
440                .await
441                .map(|output| self.append_notebook_warning(output, &notebook))
442        })
443        .await
444    }
445}