Skip to main content

nb_api/transaction/
plan.rs

1use std::collections::HashSet;
2use std::time::Duration;
3
4use crate::NbClient;
5use crate::error::NbError;
6use crate::fingerprint::Fingerprint;
7use crate::types::{LineEdit, NoteTarget, Occurrence};
8use std::path::Path;
9
10use super::virtual_tree::normalize_rel;
11
12/// In-memory plan bound to one notebook. Drop discards; no begin/rollback.
13pub struct Transaction {
14    pub(super) client: NbClient,
15    pub(super) notebook: String,
16    pub(super) plan: Vec<PlanOp>,
17    pub(super) gate_timeout: Duration,
18}
19
20#[derive(Debug, Clone)]
21pub(super) enum PlanOp {
22    AddNote {
23        path: String,
24        title: Option<String>,
25        content: String,
26        tags: Vec<String>,
27    },
28    AddTodo {
29        path: String,
30        title: String,
31        description: Option<String>,
32        tasks: Vec<String>,
33        tags: Vec<String>,
34    },
35    AddBookmark {
36        path: String,
37        url: String,
38        title: Option<String>,
39        tags: Vec<String>,
40        comment: Option<String>,
41    },
42    AddFolder {
43        path: String,
44    },
45    DeleteNote {
46        target: NoteTarget,
47    },
48    MoveNote {
49        target: NoteTarget,
50        destination: String,
51    },
52    MarkTaskDone {
53        target: NoteTarget,
54        task_number: Option<u32>,
55    },
56    UnmarkTaskDone {
57        target: NoteTarget,
58        task_number: Option<u32>,
59    },
60    ReplaceNoteBody {
61        target: NoteTarget,
62        new_body: String,
63        fingerprint: Fingerprint,
64    },
65    EditNoteSubstring {
66        target: NoteTarget,
67        pattern: String,
68        replacement: String,
69        occurrence: Occurrence,
70        expected_count: u32,
71        fingerprint: Option<Fingerprint>,
72    },
73    EditNoteLines {
74        target: NoteTarget,
75        edits: Vec<LineEdit>,
76    },
77    RetitleNote {
78        target: NoteTarget,
79        title: String,
80    },
81    EditNoteTags {
82        target: NoteTarget,
83        add: Vec<String>,
84        remove: Vec<String>,
85    },
86}
87impl Transaction {
88    pub(crate) fn new(client: NbClient, notebook: String, gate_timeout: Duration) -> Self {
89        Self {
90            client,
91            notebook,
92            plan: Vec::new(),
93            gate_timeout,
94        }
95    }
96
97    pub fn add_note(
98        &mut self,
99        path: &str,
100        title: Option<&str>,
101        content: &str,
102        tags: &[String],
103    ) -> Result<(), NbError> {
104        let path = validate_create_path(path, true)?;
105        if let Some(t) = title
106            && let Some(heading) = crate::validate::detect_duplicate_title_heading(t, content)
107        {
108            return Err(NbError::DuplicateTitleHeading {
109                title: t.to_string(),
110                heading,
111            });
112        }
113        self.plan.push(PlanOp::AddNote {
114            path,
115            title: title.map(str::to_string),
116            content: content.to_string(),
117            tags: tags.to_vec(),
118        });
119        Ok(())
120    }
121
122    pub fn add_todo(
123        &mut self,
124        path: &str,
125        title: &str,
126        description: Option<&str>,
127        tasks: &[String],
128        tags: &[String],
129    ) -> Result<(), NbError> {
130        let path = validate_create_path(path, true)?;
131        if title.trim().is_empty() {
132            return Err(NbError::ValidationError {
133                reason: "todo title must not be empty".into(),
134                location: None,
135            });
136        }
137        self.plan.push(PlanOp::AddTodo {
138            path,
139            title: title.to_string(),
140            description: description.map(str::to_string),
141            tasks: tasks.to_vec(),
142            tags: tags.to_vec(),
143        });
144        Ok(())
145    }
146
147    pub fn add_bookmark(
148        &mut self,
149        path: &str,
150        url: &str,
151        title: Option<&str>,
152        tags: &[String],
153        comment: Option<&str>,
154    ) -> Result<(), NbError> {
155        let path = validate_create_path(path, true)?;
156        if url.trim().is_empty() {
157            return Err(NbError::ValidationError {
158                reason: "bookmark url must not be empty".into(),
159                location: None,
160            });
161        }
162        self.plan.push(PlanOp::AddBookmark {
163            path,
164            url: url.to_string(),
165            title: title.map(str::to_string),
166            tags: tags.to_vec(),
167            comment: comment.map(str::to_string),
168        });
169        Ok(())
170    }
171
172    pub fn add_folder(&mut self, path: &str) -> Result<(), NbError> {
173        let path = validate_create_path(path, false)?;
174        self.plan.push(PlanOp::AddFolder { path });
175        Ok(())
176    }
177
178    pub fn delete_note(&mut self, target: NoteTarget) -> Result<(), NbError> {
179        validate_target(&target)?;
180        self.plan.push(PlanOp::DeleteNote { target });
181        Ok(())
182    }
183
184    pub fn move_note(&mut self, target: NoteTarget, destination: &str) -> Result<(), NbError> {
185        validate_target(&target)?;
186        crate::validate::validate_destination(destination)?;
187        // Preserve a trailing slash: `foo/` means "into folder foo" (basename
188        // kept). `normalize_rel` trims slashes, so re-attach the marker for
189        // `resolve_move_destination`.
190        let into_folder = destination.trim_end().ends_with('/');
191        let mut destination = normalize_rel(destination);
192        if destination.is_empty() || destination.contains("..") {
193            return Err(NbError::ValidationError {
194                reason: "invalid move destination".into(),
195                location: None,
196            });
197        }
198        if into_folder {
199            destination.push('/');
200        }
201        self.plan.push(PlanOp::MoveNote {
202            target,
203            destination,
204        });
205        Ok(())
206    }
207
208    pub fn mark_task_done(
209        &mut self,
210        target: NoteTarget,
211        task_number: Option<u32>,
212    ) -> Result<(), NbError> {
213        validate_target(&target)?;
214        self.plan.push(PlanOp::MarkTaskDone {
215            target,
216            task_number,
217        });
218        Ok(())
219    }
220
221    pub fn unmark_task_done(
222        &mut self,
223        target: NoteTarget,
224        task_number: Option<u32>,
225    ) -> Result<(), NbError> {
226        validate_target(&target)?;
227        self.plan.push(PlanOp::UnmarkTaskDone {
228            target,
229            task_number,
230        });
231        Ok(())
232    }
233
234    pub fn replace_note_body(
235        &mut self,
236        target: NoteTarget,
237        new_body: &str,
238        fingerprint: Fingerprint,
239    ) -> Result<(), NbError> {
240        validate_target(&target)?;
241        self.plan.push(PlanOp::ReplaceNoteBody {
242            target,
243            new_body: new_body.to_string(),
244            fingerprint,
245        });
246        Ok(())
247    }
248
249    pub fn edit_note_substring(
250        &mut self,
251        target: NoteTarget,
252        pattern: &str,
253        replacement: &str,
254        occurrence: Occurrence,
255        expected_count: u32,
256        fingerprint: Option<Fingerprint>,
257    ) -> Result<(), NbError> {
258        validate_target(&target)?;
259        if pattern.is_empty() {
260            return Err(NbError::EmptySubstringPattern);
261        }
262        self.plan.push(PlanOp::EditNoteSubstring {
263            target,
264            pattern: pattern.to_string(),
265            replacement: replacement.to_string(),
266            occurrence,
267            expected_count,
268            fingerprint,
269        });
270        Ok(())
271    }
272
273    pub fn edit_note_lines(
274        &mut self,
275        target: NoteTarget,
276        edits: Vec<LineEdit>,
277    ) -> Result<(), NbError> {
278        validate_target(&target)?;
279        if edits.is_empty() {
280            return Err(NbError::ValidationError {
281                reason: "edit_note_lines requires a non-empty edits batch".into(),
282                location: None,
283            });
284        }
285        self.plan.push(PlanOp::EditNoteLines { target, edits });
286        Ok(())
287    }
288
289    pub fn retitle_note(&mut self, target: NoteTarget, title: &str) -> Result<(), NbError> {
290        validate_target(&target)?;
291        self.plan.push(PlanOp::RetitleNote {
292            target,
293            title: title.to_string(),
294        });
295        Ok(())
296    }
297
298    pub fn edit_note_tags(
299        &mut self,
300        target: NoteTarget,
301        add: &[String],
302        remove: &[String],
303    ) -> Result<(), NbError> {
304        validate_target(&target)?;
305        let add_set: HashSet<&str> = add.iter().map(|s| s.trim_start_matches('#')).collect();
306        for r in remove {
307            let key = r.trim_start_matches('#');
308            if add_set.contains(key) {
309                return Err(NbError::ValidationError {
310                    reason: format!("contradictory tag add/remove for `{key}`"),
311                    location: None,
312                });
313            }
314        }
315        self.plan.push(PlanOp::EditNoteTags {
316            target,
317            add: add.to_vec(),
318            remove: remove.to_vec(),
319        });
320        Ok(())
321    }
322}
323pub(super) fn annotate_plan_index(err: NbError, index: u32) -> NbError {
324    match err {
325        NbError::PathCollision { path, .. } => NbError::PathCollision {
326            path,
327            plan_index: Some(index),
328        },
329        NbError::PathIgnored { path, guidance, .. } => NbError::PathIgnored {
330            path,
331            guidance,
332            plan_index: Some(index),
333        },
334        NbError::FingerprintMismatch { .. }
335        | NbError::AnchorMismatch { .. }
336        | NbError::OccurrenceMismatch { .. }
337        | NbError::OverlappingEdits { .. }
338        | NbError::FragmentedBody { .. }
339        | NbError::EmptySubstringPattern
340        | NbError::NotFound { .. }
341        | NbError::UnsupportedStructure { .. } => err,
342        NbError::PlanValidation {
343            kind,
344            message,
345            plan_index: _,
346        } => NbError::PlanValidation {
347            kind,
348            message,
349            plan_index: Some(index),
350        },
351        other => NbError::PlanValidation {
352            kind: "op_failed".into(),
353            message: other.to_string(),
354            plan_index: Some(index),
355        },
356    }
357}
358
359fn validate_target(target: &NoteTarget) -> Result<(), NbError> {
360    if target.value().trim().is_empty() {
361        return Err(NbError::ValidationError {
362            reason: "note target must not be empty".into(),
363            location: None,
364        });
365    }
366    Ok(())
367}
368
369fn validate_create_path(path: &str, file: bool) -> Result<String, NbError> {
370    // Validate the caller-supplied string before any normalization so
371    // absolute and backslash forms cannot be silently rewritten.
372    let raw = path.trim();
373    if raw.is_empty() {
374        return Err(NbError::ValidationError {
375            reason: "path must not be empty".into(),
376            location: None,
377        });
378    }
379    if raw.starts_with('/') || raw.starts_with('\\') || Path::new(raw).is_absolute() {
380        return Err(NbError::ValidationError {
381            reason: "path must be notebook-relative (absolute paths refused)".into(),
382            location: None,
383        });
384    }
385    if raw.contains('\\') {
386        return Err(NbError::ValidationError {
387            reason: "path must not contain backslash separators".into(),
388            location: None,
389        });
390    }
391    if raw.contains('\0') {
392        return Err(NbError::ValidationError {
393            reason: "path must not contain NUL".into(),
394            location: None,
395        });
396    }
397    let path = normalize_rel(raw);
398    if path.is_empty() {
399        return Err(NbError::ValidationError {
400            reason: "path must not be empty".into(),
401            location: None,
402        });
403    }
404    if path
405        .split('/')
406        .any(|p| p.is_empty() || p == "." || p == "..")
407    {
408        return Err(NbError::ValidationError {
409            reason: "path must not contain empty, `.`, or `..` segments".into(),
410            location: None,
411        });
412    }
413    if file {
414        let name = Path::new(&path)
415            .file_name()
416            .and_then(|s| s.to_str())
417            .unwrap_or("");
418        if name.is_empty() {
419            return Err(NbError::ValidationError {
420                reason: "create path must include a filename".into(),
421                location: None,
422            });
423        }
424    }
425    Ok(path)
426}