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
12pub 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 DeleteFolder {
49 target: NoteTarget,
50 recursive: bool,
51 },
52 MoveNote {
53 target: NoteTarget,
54 destination: String,
55 },
56 MarkTaskDone {
57 target: NoteTarget,
58 task_number: Option<u32>,
59 },
60 UnmarkTaskDone {
61 target: NoteTarget,
62 task_number: Option<u32>,
63 },
64 ReplaceNoteBody {
65 target: NoteTarget,
66 new_body: String,
67 fingerprint: Fingerprint,
68 },
69 EditNoteSubstring {
70 target: NoteTarget,
71 pattern: String,
72 replacement: String,
73 occurrence: Occurrence,
74 expected_count: u32,
75 fingerprint: Option<Fingerprint>,
76 },
77 EditNoteLines {
78 target: NoteTarget,
79 edits: Vec<LineEdit>,
80 },
81 RetitleNote {
82 target: NoteTarget,
83 title: String,
84 },
85 EditNoteTags {
86 target: NoteTarget,
87 add: Vec<String>,
88 remove: Vec<String>,
89 },
90 AssertRevision {
91 expected: String,
92 },
93}
94impl Transaction {
95 pub(crate) fn new(
96 client: NbClient,
97 notebook: String,
98 gate_timeout: Duration,
99 ) -> Self {
100 Self {
101 client,
102 notebook,
103 plan: Vec::new(),
104 gate_timeout,
105 }
106 }
107
108 pub fn add_note(
109 &mut self,
110 path: &str,
111 title: Option<&str>,
112 content: &str,
113 tags: &[String],
114 ) -> Result<(), NbError> {
115 let path = validate_create_path(path, true)?;
116 if let Some(t) = title
117 && let Some(heading) =
118 crate::validate::detect_duplicate_title_heading(t, content)
119 {
120 return Err(NbError::DuplicateTitleHeading {
121 title: t.to_string(),
122 heading,
123 });
124 }
125 self.plan.push(PlanOp::AddNote {
126 path,
127 title: title.map(str::to_string),
128 content: content.to_string(),
129 tags: tags.to_vec(),
130 });
131 Ok(())
132 }
133
134 pub fn add_todo(
135 &mut self,
136 path: &str,
137 title: &str,
138 description: Option<&str>,
139 tasks: &[String],
140 tags: &[String],
141 ) -> Result<(), NbError> {
142 let path = validate_create_path(path, true)?;
143 if title.trim().is_empty() {
144 return Err(NbError::ValidationError {
145 reason: "todo title must not be empty".into(),
146 location: None,
147 });
148 }
149 self.plan.push(PlanOp::AddTodo {
150 path,
151 title: title.to_string(),
152 description: description.map(str::to_string),
153 tasks: tasks.to_vec(),
154 tags: tags.to_vec(),
155 });
156 Ok(())
157 }
158
159 pub fn add_bookmark(
160 &mut self,
161 path: &str,
162 url: &str,
163 title: Option<&str>,
164 tags: &[String],
165 comment: Option<&str>,
166 ) -> Result<(), NbError> {
167 let path = validate_create_path(path, true)?;
168 if url.trim().is_empty() {
169 return Err(NbError::ValidationError {
170 reason: "bookmark url must not be empty".into(),
171 location: None,
172 });
173 }
174 self.plan.push(PlanOp::AddBookmark {
175 path,
176 url: url.to_string(),
177 title: title.map(str::to_string),
178 tags: tags.to_vec(),
179 comment: comment.map(str::to_string),
180 });
181 Ok(())
182 }
183
184 pub fn add_folder(&mut self, path: &str) -> Result<(), NbError> {
185 let path = validate_create_path(path, false)?;
186 self.plan.push(PlanOp::AddFolder { path });
187 Ok(())
188 }
189
190 pub fn delete_note(&mut self, target: NoteTarget) -> Result<(), NbError> {
191 validate_target(&target)?;
192 self.plan.push(PlanOp::DeleteNote { target });
193 Ok(())
194 }
195
196 pub fn delete_folder(
201 &mut self,
202 target: NoteTarget,
203 recursive: bool,
204 ) -> Result<(), NbError> {
205 validate_target(&target)?;
206 self.plan.push(PlanOp::DeleteFolder { target, recursive });
207 Ok(())
208 }
209
210 pub fn move_note(
211 &mut self,
212 target: NoteTarget,
213 destination: &str,
214 ) -> Result<(), NbError> {
215 validate_target(&target)?;
216 crate::validate::validate_destination(destination)?;
217 let into_folder = destination.trim_end().ends_with('/');
221 let mut destination = normalize_rel(destination);
222 if destination.is_empty() || destination.contains("..") {
223 return Err(NbError::ValidationError {
224 reason: "invalid move destination".into(),
225 location: None,
226 });
227 }
228 if into_folder {
229 destination.push('/');
230 }
231 self.plan.push(PlanOp::MoveNote {
232 target,
233 destination,
234 });
235 Ok(())
236 }
237
238 pub fn mark_task_done(
239 &mut self,
240 target: NoteTarget,
241 task_number: Option<u32>,
242 ) -> Result<(), NbError> {
243 validate_target(&target)?;
244 self.plan.push(PlanOp::MarkTaskDone {
245 target,
246 task_number,
247 });
248 Ok(())
249 }
250
251 pub fn unmark_task_done(
252 &mut self,
253 target: NoteTarget,
254 task_number: Option<u32>,
255 ) -> Result<(), NbError> {
256 validate_target(&target)?;
257 self.plan.push(PlanOp::UnmarkTaskDone {
258 target,
259 task_number,
260 });
261 Ok(())
262 }
263
264 pub fn replace_note_body(
265 &mut self,
266 target: NoteTarget,
267 new_body: &str,
268 fingerprint: Fingerprint,
269 ) -> Result<(), NbError> {
270 validate_target(&target)?;
271 self.plan.push(PlanOp::ReplaceNoteBody {
272 target,
273 new_body: new_body.to_string(),
274 fingerprint,
275 });
276 Ok(())
277 }
278
279 pub fn edit_note_substring(
280 &mut self,
281 target: NoteTarget,
282 pattern: &str,
283 replacement: &str,
284 occurrence: Occurrence,
285 expected_count: u32,
286 fingerprint: Option<Fingerprint>,
287 ) -> Result<(), NbError> {
288 validate_target(&target)?;
289 if pattern.is_empty() {
290 return Err(NbError::EmptySubstringPattern);
291 }
292 self.plan.push(PlanOp::EditNoteSubstring {
293 target,
294 pattern: pattern.to_string(),
295 replacement: replacement.to_string(),
296 occurrence,
297 expected_count,
298 fingerprint,
299 });
300 Ok(())
301 }
302
303 pub fn edit_note_lines(
304 &mut self,
305 target: NoteTarget,
306 edits: Vec<LineEdit>,
307 ) -> Result<(), NbError> {
308 validate_target(&target)?;
309 if edits.is_empty() {
310 return Err(NbError::ValidationError {
311 reason: "edit_note_lines requires a non-empty edits batch"
312 .into(),
313 location: None,
314 });
315 }
316 self.plan.push(PlanOp::EditNoteLines { target, edits });
317 Ok(())
318 }
319
320 pub fn retitle_note(
321 &mut self,
322 target: NoteTarget,
323 title: &str,
324 ) -> Result<(), NbError> {
325 validate_target(&target)?;
326 self.plan.push(PlanOp::RetitleNote {
327 target,
328 title: title.to_string(),
329 });
330 Ok(())
331 }
332
333 pub fn edit_note_tags(
334 &mut self,
335 target: NoteTarget,
336 add: &[String],
337 remove: &[String],
338 ) -> Result<(), NbError> {
339 validate_target(&target)?;
340 let add_set: HashSet<&str> =
341 add.iter().map(|s| s.trim_start_matches('#')).collect();
342 for r in remove {
343 let key = r.trim_start_matches('#');
344 if add_set.contains(key) {
345 return Err(NbError::ValidationError {
346 reason: format!(
347 "contradictory tag add/remove for `{key}`"
348 ),
349 location: None,
350 });
351 }
352 }
353 self.plan.push(PlanOp::EditNoteTags {
354 target,
355 add: add.to_vec(),
356 remove: remove.to_vec(),
357 });
358 Ok(())
359 }
360
361 pub fn assert_revision(&mut self, expected: &str) -> Result<(), NbError> {
370 if expected.trim().is_empty() {
371 return Err(NbError::ValidationError {
372 reason:
373 "assert_revision requires a non-empty expected revision"
374 .into(),
375 location: None,
376 });
377 }
378 self.plan.push(PlanOp::AssertRevision {
379 expected: expected.to_string(),
380 });
381 Ok(())
382 }
383}
384pub(super) fn annotate_plan_index(err: NbError, index: u32) -> NbError {
385 match err {
386 NbError::PathCollision { path, .. } => NbError::PathCollision {
387 path,
388 plan_index: Some(index),
389 },
390 NbError::PathIgnored { path, guidance, .. } => NbError::PathIgnored {
391 path,
392 guidance,
393 plan_index: Some(index),
394 },
395 NbError::FingerprintMismatch { .. }
396 | NbError::AnchorMismatch { .. }
397 | NbError::OccurrenceMismatch { .. }
398 | NbError::OverlappingEdits { .. }
399 | NbError::FragmentedBody { .. }
400 | NbError::EmptySubstringPattern
401 | NbError::NotFound { .. }
402 | NbError::WrongKind { .. }
403 | NbError::UnsupportedStructure { .. } => err,
404 NbError::PlanValidation {
405 kind,
406 message,
407 plan_index: _,
408 } => NbError::PlanValidation {
409 kind,
410 message,
411 plan_index: Some(index),
412 },
413 other => NbError::PlanValidation {
414 kind: "op_failed".into(),
415 message: other.to_string(),
416 plan_index: Some(index),
417 },
418 }
419}
420
421fn validate_target(target: &NoteTarget) -> Result<(), NbError> {
422 if target.value().trim().is_empty() {
423 return Err(NbError::ValidationError {
424 reason: "note target must not be empty".into(),
425 location: None,
426 });
427 }
428 Ok(())
429}
430
431fn validate_create_path(path: &str, file: bool) -> Result<String, NbError> {
432 let raw = path.trim();
435 if raw.is_empty() {
436 return Err(NbError::ValidationError {
437 reason: "path must not be empty".into(),
438 location: None,
439 });
440 }
441 if raw.starts_with('/')
442 || raw.starts_with('\\')
443 || Path::new(raw).is_absolute()
444 {
445 return Err(NbError::ValidationError {
446 reason: "path must be notebook-relative (absolute paths refused)"
447 .into(),
448 location: None,
449 });
450 }
451 if raw.contains('\\') {
452 return Err(NbError::ValidationError {
453 reason: "path must not contain backslash separators".into(),
454 location: None,
455 });
456 }
457 if raw.contains('\0') {
458 return Err(NbError::ValidationError {
459 reason: "path must not contain NUL".into(),
460 location: None,
461 });
462 }
463 let path = normalize_rel(raw);
464 if path.is_empty() {
465 return Err(NbError::ValidationError {
466 reason: "path must not be empty".into(),
467 location: None,
468 });
469 }
470 if path
471 .split('/')
472 .any(|p| p.is_empty() || p == "." || p == "..")
473 {
474 return Err(NbError::ValidationError {
475 reason: "path must not contain empty, `.`, or `..` segments"
476 .into(),
477 location: None,
478 });
479 }
480 if file {
481 let name = Path::new(&path)
482 .file_name()
483 .and_then(|s| s.to_str())
484 .unwrap_or("");
485 if name.is_empty() {
486 return Err(NbError::ValidationError {
487 reason: "create path must include a filename".into(),
488 location: None,
489 });
490 }
491 }
492 Ok(path)
493}