nb-api 0.4.4

Typed Rust interface to the nb note-taking CLI (subprocess wrapper: escaping, validation, output parsing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use std::collections::HashSet;
use std::time::Duration;

use crate::NbClient;
use crate::error::NbError;
use crate::fingerprint::Fingerprint;
use crate::types::{LineEdit, NoteTarget, Occurrence};
use std::path::Path;

use super::virtual_tree::normalize_rel;

/// In-memory plan bound to one notebook. Drop discards; no begin/rollback.
pub struct Transaction {
    pub(super) client: NbClient,
    pub(super) notebook: String,
    pub(super) plan: Vec<PlanOp>,
    pub(super) gate_timeout: Duration,
}

#[derive(Debug, Clone)]
pub(super) enum PlanOp {
    AddNote {
        path: String,
        title: Option<String>,
        content: String,
        tags: Vec<String>,
    },
    AddTodo {
        path: String,
        title: String,
        description: Option<String>,
        tasks: Vec<String>,
        tags: Vec<String>,
    },
    AddBookmark {
        path: String,
        url: String,
        title: Option<String>,
        tags: Vec<String>,
        comment: Option<String>,
    },
    AddFolder {
        path: String,
    },
    DeleteNote {
        target: NoteTarget,
    },
    DeleteFolder {
        target: NoteTarget,
        recursive: bool,
    },
    MoveNote {
        target: NoteTarget,
        destination: String,
    },
    MarkTaskDone {
        target: NoteTarget,
        task_number: Option<u32>,
    },
    UnmarkTaskDone {
        target: NoteTarget,
        task_number: Option<u32>,
    },
    ReplaceNoteBody {
        target: NoteTarget,
        new_body: String,
        fingerprint: Fingerprint,
    },
    EditNoteSubstring {
        target: NoteTarget,
        pattern: String,
        replacement: String,
        occurrence: Occurrence,
        expected_count: u32,
        fingerprint: Option<Fingerprint>,
    },
    EditNoteLines {
        target: NoteTarget,
        edits: Vec<LineEdit>,
    },
    RetitleNote {
        target: NoteTarget,
        title: String,
    },
    EditNoteTags {
        target: NoteTarget,
        add: Vec<String>,
        remove: Vec<String>,
    },
    AssertRevision {
        expected: String,
    },
}
impl Transaction {
    pub(crate) fn new(
        client: NbClient,
        notebook: String,
        gate_timeout: Duration,
    ) -> Self {
        Self {
            client,
            notebook,
            plan: Vec::new(),
            gate_timeout,
        }
    }

    pub fn add_note(
        &mut self,
        path: &str,
        title: Option<&str>,
        content: &str,
        tags: &[String],
    ) -> Result<(), NbError> {
        let path = validate_create_path(path, true)?;
        if let Some(t) = title
            && let Some(heading) =
                crate::validate::detect_duplicate_title_heading(t, content)
        {
            return Err(NbError::DuplicateTitleHeading {
                title: t.to_string(),
                heading,
            });
        }
        self.plan.push(PlanOp::AddNote {
            path,
            title: title.map(str::to_string),
            content: content.to_string(),
            tags: tags.to_vec(),
        });
        Ok(())
    }

    pub fn add_todo(
        &mut self,
        path: &str,
        title: &str,
        description: Option<&str>,
        tasks: &[String],
        tags: &[String],
    ) -> Result<(), NbError> {
        let path = validate_create_path(path, true)?;
        if title.trim().is_empty() {
            return Err(NbError::ValidationError {
                reason: "todo title must not be empty".into(),
                location: None,
            });
        }
        self.plan.push(PlanOp::AddTodo {
            path,
            title: title.to_string(),
            description: description.map(str::to_string),
            tasks: tasks.to_vec(),
            tags: tags.to_vec(),
        });
        Ok(())
    }

    pub fn add_bookmark(
        &mut self,
        path: &str,
        url: &str,
        title: Option<&str>,
        tags: &[String],
        comment: Option<&str>,
    ) -> Result<(), NbError> {
        let path = validate_create_path(path, true)?;
        if url.trim().is_empty() {
            return Err(NbError::ValidationError {
                reason: "bookmark url must not be empty".into(),
                location: None,
            });
        }
        self.plan.push(PlanOp::AddBookmark {
            path,
            url: url.to_string(),
            title: title.map(str::to_string),
            tags: tags.to_vec(),
            comment: comment.map(str::to_string),
        });
        Ok(())
    }

    pub fn add_folder(&mut self, path: &str) -> Result<(), NbError> {
        let path = validate_create_path(path, false)?;
        self.plan.push(PlanOp::AddFolder { path });
        Ok(())
    }

    pub fn delete_note(&mut self, target: NoteTarget) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::DeleteNote { target });
        Ok(())
    }

    /// Delete a folder. `recursive = false` refuses non-empty folders,
    /// listing their contents; `recursive = true` removes the whole
    /// subtree. Marker files (`.gitkeep`) and `.index` files alone do
    /// not count as contents.
    pub fn delete_folder(
        &mut self,
        target: NoteTarget,
        recursive: bool,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::DeleteFolder { target, recursive });
        Ok(())
    }

    pub fn move_note(
        &mut self,
        target: NoteTarget,
        destination: &str,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        crate::validate::validate_destination(destination)?;
        // Preserve a trailing slash: `foo/` means "into folder foo" (basename
        // kept). `normalize_rel` trims slashes, so re-attach the marker for
        // `resolve_move_destination`.
        let into_folder = destination.trim_end().ends_with('/');
        let mut destination = normalize_rel(destination);
        if destination.is_empty() || destination.contains("..") {
            return Err(NbError::ValidationError {
                reason: "invalid move destination".into(),
                location: None,
            });
        }
        if into_folder {
            destination.push('/');
        }
        self.plan.push(PlanOp::MoveNote {
            target,
            destination,
        });
        Ok(())
    }

    pub fn mark_task_done(
        &mut self,
        target: NoteTarget,
        task_number: Option<u32>,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::MarkTaskDone {
            target,
            task_number,
        });
        Ok(())
    }

    pub fn unmark_task_done(
        &mut self,
        target: NoteTarget,
        task_number: Option<u32>,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::UnmarkTaskDone {
            target,
            task_number,
        });
        Ok(())
    }

    pub fn replace_note_body(
        &mut self,
        target: NoteTarget,
        new_body: &str,
        fingerprint: Fingerprint,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::ReplaceNoteBody {
            target,
            new_body: new_body.to_string(),
            fingerprint,
        });
        Ok(())
    }

    pub fn edit_note_substring(
        &mut self,
        target: NoteTarget,
        pattern: &str,
        replacement: &str,
        occurrence: Occurrence,
        expected_count: u32,
        fingerprint: Option<Fingerprint>,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        if pattern.is_empty() {
            return Err(NbError::EmptySubstringPattern);
        }
        self.plan.push(PlanOp::EditNoteSubstring {
            target,
            pattern: pattern.to_string(),
            replacement: replacement.to_string(),
            occurrence,
            expected_count,
            fingerprint,
        });
        Ok(())
    }

    pub fn edit_note_lines(
        &mut self,
        target: NoteTarget,
        edits: Vec<LineEdit>,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        if edits.is_empty() {
            return Err(NbError::ValidationError {
                reason: "edit_note_lines requires a non-empty edits batch"
                    .into(),
                location: None,
            });
        }
        self.plan.push(PlanOp::EditNoteLines { target, edits });
        Ok(())
    }

    pub fn retitle_note(
        &mut self,
        target: NoteTarget,
        title: &str,
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        self.plan.push(PlanOp::RetitleNote {
            target,
            title: title.to_string(),
        });
        Ok(())
    }

    pub fn edit_note_tags(
        &mut self,
        target: NoteTarget,
        add: &[String],
        remove: &[String],
    ) -> Result<(), NbError> {
        validate_target(&target)?;
        let add_set: HashSet<&str> =
            add.iter().map(|s| s.trim_start_matches('#')).collect();
        for r in remove {
            let key = r.trim_start_matches('#');
            if add_set.contains(key) {
                return Err(NbError::ValidationError {
                    reason: format!(
                        "contradictory tag add/remove for `{key}`"
                    ),
                    location: None,
                });
            }
        }
        self.plan.push(PlanOp::EditNoteTags {
            target,
            add: add.to_vec(),
            remove: remove.to_vec(),
        });
        Ok(())
    }

    /// Assert the notebook revision is unchanged since capture.
    ///
    /// Composable optimistic-concurrency precondition: evaluated at
    /// commit time, before any materialization, so a mismatch
    /// refuses cleanly with nothing applied. Capture the expected
    /// revision with [`crate::git::git_rev_parse_in`]
    /// (`&["HEAD"]`) at the moment the plan's assumptions are
    /// taken, and push this op into the same [`Transaction`].
    pub fn assert_revision(&mut self, expected: &str) -> Result<(), NbError> {
        if expected.trim().is_empty() {
            return Err(NbError::ValidationError {
                reason:
                    "assert_revision requires a non-empty expected revision"
                        .into(),
                location: None,
            });
        }
        self.plan.push(PlanOp::AssertRevision {
            expected: expected.to_string(),
        });
        Ok(())
    }
}
pub(super) fn annotate_plan_index(err: NbError, index: u32) -> NbError {
    match err {
        NbError::PathCollision { path, .. } => NbError::PathCollision {
            path,
            plan_index: Some(index),
        },
        NbError::PathIgnored { path, guidance, .. } => NbError::PathIgnored {
            path,
            guidance,
            plan_index: Some(index),
        },
        NbError::FingerprintMismatch { .. }
        | NbError::AnchorMismatch { .. }
        | NbError::OccurrenceMismatch { .. }
        | NbError::OverlappingEdits { .. }
        | NbError::FragmentedBody { .. }
        | NbError::EmptySubstringPattern
        | NbError::NotFound { .. }
        | NbError::UnsupportedStructure { .. } => err,
        NbError::PlanValidation {
            kind,
            message,
            plan_index: _,
        } => NbError::PlanValidation {
            kind,
            message,
            plan_index: Some(index),
        },
        other => NbError::PlanValidation {
            kind: "op_failed".into(),
            message: other.to_string(),
            plan_index: Some(index),
        },
    }
}

fn validate_target(target: &NoteTarget) -> Result<(), NbError> {
    if target.value().trim().is_empty() {
        return Err(NbError::ValidationError {
            reason: "note target must not be empty".into(),
            location: None,
        });
    }
    Ok(())
}

fn validate_create_path(path: &str, file: bool) -> Result<String, NbError> {
    // Validate the caller-supplied string before any normalization so
    // absolute and backslash forms cannot be silently rewritten.
    let raw = path.trim();
    if raw.is_empty() {
        return Err(NbError::ValidationError {
            reason: "path must not be empty".into(),
            location: None,
        });
    }
    if raw.starts_with('/')
        || raw.starts_with('\\')
        || Path::new(raw).is_absolute()
    {
        return Err(NbError::ValidationError {
            reason: "path must be notebook-relative (absolute paths refused)"
                .into(),
            location: None,
        });
    }
    if raw.contains('\\') {
        return Err(NbError::ValidationError {
            reason: "path must not contain backslash separators".into(),
            location: None,
        });
    }
    if raw.contains('\0') {
        return Err(NbError::ValidationError {
            reason: "path must not contain NUL".into(),
            location: None,
        });
    }
    let path = normalize_rel(raw);
    if path.is_empty() {
        return Err(NbError::ValidationError {
            reason: "path must not be empty".into(),
            location: None,
        });
    }
    if path
        .split('/')
        .any(|p| p.is_empty() || p == "." || p == "..")
    {
        return Err(NbError::ValidationError {
            reason: "path must not contain empty, `.`, or `..` segments"
                .into(),
            location: None,
        });
    }
    if file {
        let name = Path::new(&path)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        if name.is_empty() {
            return Err(NbError::ValidationError {
                reason: "create path must include a filename".into(),
                location: None,
            });
        }
    }
    Ok(path)
}