Skip to main content

nb_api/client/
write.rs

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