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