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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
use std::collections::VecDeque;
use crate::argv::{
child_folder_names, empty_tasks_signal, is_empty_tasks_error,
normalize_folder, tasks_scope, todos_tasks_command_args,
};
use crate::error::NbError;
use crate::fingerprint::Fingerprint;
use crate::output::strip_empty_result_hint;
use crate::transaction;
use crate::transaction::Transaction;
use crate::types::{CommitOutcome, LineEdit, NoteTarget, Occurrence};
use crate::validate::{
detect_duplicate_title_heading, validate_destination,
validate_folder_option, validate_folder_path,
};
use crate::{NbClient, TaskStatus};
impl NbClient {
/// Creates a new note (one-shot transaction; nb-mangled filename).
pub async fn add_note(
&self,
title: Option<&str>,
content: &str,
tags: &[String],
folder: Option<&str>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
if let Some(t) = title
&& let Some(heading) = detect_duplicate_title_heading(t, content)
{
return Err(NbError::DuplicateTitleHeading {
title: t.to_string(),
heading,
});
}
self.require_folder_for_new_note(folder)?;
validate_folder_option(folder)?;
let filename = transaction::filename_for_title(title, "md");
self.create_with_retry(notebook, folder, filename, |tx, path| {
tx.add_note(&path, title, content, tags)
})
.await
}
/// One-shot create with `-N` collision retry on the auto filename.
///
/// Explicit-path `Transaction` plans keep hard `PathCollision` errors;
/// the mangled/titleless one-shot names instead gain `-1`, `-2`, …
/// until free (basenames stay unique per folder, which keeps post-write
/// `.index` lookup unambiguous).
async fn create_with_retry(
&self,
notebook: Option<&str>,
folder: Option<&str>,
filename: String,
plan: impl Fn(&mut Transaction, String) -> Result<(), NbError>,
) -> Result<CommitOutcome, NbError> {
let mut name = filename.clone();
for attempt in 0..100u32 {
if attempt > 0 {
name = transaction::suffixed_filename(&filename, attempt);
}
let path = transaction::join_folder_file(folder, &name);
let mut tx = self.transaction(notebook).await?;
plan(&mut tx, path)?;
match tx.commit().await {
Ok(outcome) => return Ok(outcome),
Err(NbError::PathCollision { .. }) => continue,
Err(other) => return Err(other),
}
}
Err(NbError::PathCollision {
path: transaction::join_folder_file(folder, &filename),
plan_index: None,
})
}
/// Deletes a note (one-shot transaction).
pub async fn delete_note(
&self,
id: &str,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let (nb, selector) =
self.resolve_target_selector(id, notebook).await?;
let target = self.note_target_for_selector(&nb, &selector).await?;
let mut tx = self.transaction(Some(&nb)).await?;
tx.delete_note(target)?;
tx.commit().await
}
/// Deletes a folder (one-shot transaction).
///
/// `recursive = false` refuses non-empty folders, listing their
/// contents; `recursive = true` removes the whole subtree. There
/// is no `force` flag: deletion is explicit by call.
pub async fn delete_folder(
&self,
id: &str,
recursive: bool,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let (nb, selector) =
self.resolve_target_selector(id, notebook).await?;
let target = self.note_target_for_selector(&nb, &selector).await?;
let mut tx = self.transaction(Some(&nb)).await?;
tx.delete_folder(target, recursive)?;
tx.commit().await
}
/// Moves or renames a note (one-shot transaction).
pub async fn move_note(
&self,
id: &str,
destination: &str,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
validate_destination(destination)?;
let (nb, selector) =
self.resolve_target_selector(id, notebook).await?;
let target = self.note_target_for_selector(&nb, &selector).await?;
let mut tx = self.transaction(Some(&nb)).await?;
tx.move_note(target, destination)?;
tx.commit().await
}
/// Resolve a write one-shot selector to a [`NoteTarget`]:
/// direct filesystem hit first, else the native pinned table
/// (numeric id, then root title) inside one no-ensure gate hold.
/// Spawns zero `nb` subprocesses; notebook existence is ensured
/// upstream by the caller. Missing inputs are terminal
/// `NotFound` with the original selector.
async fn note_target_for_selector(
&self,
notebook: &str,
selector: &str,
) -> Result<NoteTarget, NbError> {
let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
let stripped = selector
.rsplit_once(':')
.map(|(_, rest)| rest)
.unwrap_or(selector);
if stripped.is_empty() {
return Ok(NoteTarget::path(stripped));
}
// Lexically confined exact hit first (symlinks never
// followed); anything else goes through the pinned table
// inside one gate hold.
match crate::native::resolve_exact(&root, stripped) {
Ok(rel) => return Ok(NoteTarget::path(rel)),
Err(NbError::NotFound { .. }) => {},
Err(other) => return Err(other),
}
self.with_notebook_gate_native(&root, async {
let rel = crate::native::resolve_selector(&root, stripped)
.map_err(|e| match e {
NbError::NotFound { .. } => NbError::NotFound {
selector: selector.to_string(),
},
other => other,
})?;
Ok(NoteTarget::path(rel))
})
.await
}
/// Creates a todo item (one-shot transaction; nb-mangled filename).
pub async fn add_todo(
&self,
title: &str,
description: Option<&str>,
tasks: &[String],
tags: &[String],
folder: Option<&str>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
self.require_folder_for_new_note(folder)?;
validate_folder_option(folder)?;
let filename = transaction::filename_for_title(Some(title), "todo.md");
self.create_with_retry(notebook, folder, filename, |tx, path| {
tx.add_todo(&path, title, description, tasks, tags)
})
.await
}
/// Marks a todo as done (one-shot transaction).
pub async fn mark_task_done(
&self,
id: &str,
task_number: Option<u32>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let (nb, selector) =
self.resolve_target_selector(id, notebook).await?;
let target = self.note_target_for_selector(&nb, &selector).await?;
let mut tx = self.transaction(Some(&nb)).await?;
tx.mark_task_done(target, task_number)?;
tx.commit().await
}
/// Marks a todo as not done (one-shot transaction).
pub async fn unmark_task_done(
&self,
id: &str,
task_number: Option<u32>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let (nb, selector) =
self.resolve_target_selector(id, notebook).await?;
let target = self.note_target_for_selector(&nb, &selector).await?;
let mut tx = self.transaction(Some(&nb)).await?;
tx.unmark_task_done(target, task_number)?;
tx.commit().await
}
/// Replace contiguous body text (one-shot).
pub async fn replace_note_body(
&self,
target: NoteTarget,
new_body: &str,
fingerprint: Fingerprint,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let mut tx = self.transaction(notebook).await?;
tx.replace_note_body(target, new_body, fingerprint)?;
tx.commit().await
}
/// Substring edit on contiguous body (one-shot).
#[allow(clippy::too_many_arguments)]
pub async fn edit_note_substring(
&self,
target: NoteTarget,
pattern: &str,
replacement: &str,
occurrence: Occurrence,
expected_count: u32,
fingerprint: Option<Fingerprint>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let mut tx = self.transaction(notebook).await?;
tx.edit_note_substring(
target,
pattern,
replacement,
occurrence,
expected_count,
fingerprint,
)?;
tx.commit().await
}
/// Line-oriented body edit batch (one-shot).
pub async fn edit_note_lines(
&self,
target: NoteTarget,
edits: Vec<LineEdit>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let mut tx = self.transaction(notebook).await?;
tx.edit_note_lines(target, edits)?;
tx.commit().await
}
/// Retitle a note without changing path (one-shot).
pub async fn retitle_note(
&self,
target: NoteTarget,
title: &str,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let mut tx = self.transaction(notebook).await?;
tx.retitle_note(target, title)?;
tx.commit().await
}
/// Add/remove tags (one-shot).
pub async fn edit_note_tags(
&self,
target: NoteTarget,
add: &[String],
remove: &[String],
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
let mut tx = self.transaction(notebook).await?;
tx.edit_note_tags(target, add, remove)?;
tx.commit().await
}
/// Lists checklist items within todos.
///
/// Invokes `nb todos tasks` per scope. The method enumerates
/// the checklist items within todos (and recursively into
/// subfolders when `recursive = true`), filtered by
/// `status` if provided. An empty scope returns the empty
/// signal (`0 open tasks.`) rather than an error. A future
/// `list_todos` method for the todo **container** listing
/// (invoking `nb todos`) is tracked at
/// `nb-api:todos/api/5` (deferred to `0.5.0`).
pub async fn list_tasks(
&self,
folder: Option<&str>,
status: Option<TaskStatus>,
recursive: bool,
notebook: Option<&str>,
) -> Result<String, NbError> {
validate_folder_option(folder)?;
let notebook = self.resolve_notebook(notebook).await?;
let folder = folder.map(normalize_folder);
let scopes = if recursive {
self.tasks_scopes_recursive(¬ebook, folder.as_deref())
.await?
} else {
vec![tasks_scope(¬ebook, folder.as_deref())]
};
let mut outputs: Vec<String> = Vec::new();
let mut saw_empty = false;
let mut empty_signal: Option<String> = None;
for scope in scopes {
match self.exec_vec(todos_tasks_command_args(scope, status)).await
{
Ok(output) => {
let output = output.trim();
if !output.is_empty() {
outputs.push(output.to_string());
}
},
Err(NbError::CommandFailed { stderr, .. })
if is_empty_tasks_error(&stderr) =>
{
saw_empty = true;
empty_signal = Some(empty_tasks_signal(&stderr));
},
Err(err) => return Err(err),
}
}
if outputs.is_empty() && saw_empty {
// An empty scope is an empty list, not a failure: return
// the normalized empty signal (`0 open tasks.`) so
// callers can enumerate todos notebook-wide without
// treating "no tasks here" as an error.
return Ok(empty_signal.unwrap_or_default());
}
Ok(outputs.join("\n"))
}
/// Lists todo checklist items natively: one [`crate::ListEntry`]
/// per `- [ ]` / `- [x]` / `- [X]` item in `.todo.md` files
/// under the scope (recursive iff set), in file order with
/// 1-based task positions. Selectors append `#task-<n>` to the
/// shadow-aware canonical file selector; kind is `Todo` and
/// `numeric_id` rides along from the file. `status` filters by
/// item state (`None` keeps all). Scopes skip dotfiles and
/// symlinks; a missing scope is terminal `NotFound`. Zero `nb`
/// spawns.
pub async fn list_tasks_typed(
&self,
folder: Option<&str>,
status: Option<TaskStatus>,
recursive: bool,
notebook: Option<&str>,
) -> Result<Vec<crate::ListEntry>, NbError> {
validate_folder_option(folder)?;
let notebook = self.resolve_notebook_name(notebook)?;
let root = self.native_notebook_root(¬ebook).await?;
// Leading slashes are NOT trimmed: absolute forms
// fail closed as NotFound inside confinement.
let scope = folder.unwrap_or_default().to_string();
let want_closed = status.map(|s| matches!(s, TaskStatus::Closed));
self.with_notebook_gate_native(&root, async {
let rels = if recursive {
crate::scope::scope_files_recursive(&root, &scope)?
} else {
crate::scope::scope_files(&root, &scope)?
};
let mut out = Vec::new();
for rel in rels {
if crate::native::document_kind_for_rel(&rel)
!= crate::DocumentKind::Todo
{
continue;
}
let abs = root.join(&rel);
let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
path: abs.clone(),
source: e.into(),
})?;
let file = self.list_entry_for(¬ebook, &root, &rel).await?;
for (i, closed) in
crate::scope::todo_items(&bytes).into_iter().enumerate()
{
if let Some(want) = want_closed
&& want != closed
{
continue;
}
out.push(crate::ListEntry {
selector: format!("{}#task-{}", file.selector, i + 1),
path: file.path.clone(),
kind: crate::EntityKind::Todo,
numeric_id: file.numeric_id,
});
}
}
Ok(out)
})
.await
}
/// Lists todo files as summaries: one [`crate::TodoSummary`] per
/// `.todo.md` file under the scope (recursive iff set) with task
/// counts and derived state (`Done` iff at least one item exists
/// and all are completed, else `Open`). `state` filters files
/// (`None` keeps all). Titles are checkbox-stripped and trimmed,
/// falling back to the filename. Zero `nb` spawns.
pub async fn list_todos(
&self,
folder: Option<&str>,
state: Option<crate::TodoState>,
recursive: bool,
notebook: Option<&str>,
) -> Result<Vec<crate::TodoSummary>, NbError> {
use crate::parser::{ParseContext, parse};
validate_folder_option(folder)?;
let notebook = self.resolve_notebook_name(notebook)?;
let root = self.native_notebook_root(¬ebook).await?;
// Leading slashes are NOT trimmed: absolute forms
// fail closed as NotFound inside confinement.
let scope = folder.unwrap_or_default().to_string();
self.with_notebook_gate_native(&root, async {
let rels = if recursive {
crate::scope::scope_files_recursive(&root, &scope)?
} else {
crate::scope::scope_files(&root, &scope)?
};
let mut out = Vec::new();
for rel in rels {
if crate::native::document_kind_for_rel(&rel)
!= crate::DocumentKind::Todo
{
continue;
}
let abs = root.join(&rel);
let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
path: abs.clone(),
source: e.into(),
})?;
// Malformed containers surface instead of skipping:
// without valid UTF-8 there is no faithful title,
// state, or task text to report.
if std::str::from_utf8(&bytes).is_err() {
let selector = crate::native::canonical_selector(
¬ebook, &root, &rel,
)?;
return Err(NbError::NonUtf8 {
selector,
path: rel.clone(),
kind: "todo".to_string(),
mime_hint: None,
});
}
let items = crate::scope::todo_items(&bytes);
let completed = items.iter().filter(|&&c| c).count() as u32;
let total = items.len() as u32;
// Malformed containers surface their parse error;
// only a missing title falls back to the filename.
let doc =
parse(&bytes, ParseContext::FromPath(rel.clone().into()))?;
// Explicit container state wins: a checked title
// decides even when the counts disagree. Without a
// title checkbox, all-checked (non-empty) is Done.
let file_state = match doc.todo_state() {
Some(explicit) => explicit,
None if total > 0 && completed == total => {
crate::TodoState::Done
},
None => crate::TodoState::Open,
};
if let Some(want) = state
&& want != file_state
{
continue;
}
let title = doc
.title()
.map(|t| {
let s = String::from_utf8_lossy(t);
let s = s
.trim_end_matches('\n')
.trim_start_matches('#')
.trim();
let s = s
.strip_prefix("[ ]")
.or_else(|| s.strip_prefix("[x]"))
.or_else(|| s.strip_prefix("[X]"))
.unwrap_or(s);
s.trim().to_string()
})
.filter(|t| !t.is_empty())
.unwrap_or_else(|| {
rel.rsplit('/').next().unwrap_or(&rel).to_string()
});
let file = self.list_entry_for(¬ebook, &root, &rel).await?;
out.push(crate::TodoSummary {
id: file.selector,
title,
path: rel,
task_count: total,
completed_count: completed,
state: file_state,
});
}
Ok(out)
})
.await
}
async fn tasks_scopes_recursive(
&self,
notebook: &str,
folder: Option<&str>,
) -> Result<Vec<String>, NbError> {
let notebook_root = self.show_notebook_path(Some(notebook)).await?;
let start = folder.unwrap_or_default().to_string();
let mut queue = VecDeque::new();
queue.push_back(start.clone());
let mut scopes = vec![tasks_scope(notebook, folder)];
while let Some(current) = queue.pop_front() {
let base = if current.is_empty() {
notebook_root.clone()
} else {
notebook_root.join(¤t)
};
let children = child_folder_names(&base)?;
for child in children {
let next = if current.is_empty() {
child
} else {
format!("{}/{}", current, child)
};
scopes.push(tasks_scope(notebook, Some(&next)));
queue.push_back(next);
}
}
Ok(scopes)
}
/// Creates a bookmark (one-shot transaction; nb-mangled filename).
pub async fn add_bookmark(
&self,
url: &str,
title: Option<&str>,
tags: &[String],
comment: Option<&str>,
folder: Option<&str>,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
self.require_folder_for_new_note(folder)?;
validate_folder_option(folder)?;
let filename = transaction::filename_for_title(title, "bookmark.md");
self.create_with_retry(notebook, folder, filename, |tx, path| {
tx.add_bookmark(&path, url, title, tags, comment)
})
.await
}
/// Lists folders in a notebook.
pub async fn list_folders(
&self,
parent: Option<&str>,
notebook: Option<&str>,
) -> Result<String, NbError> {
let mut args = vec!["list".to_string()];
validate_folder_option(parent)?;
let notebook = self.resolve_notebook(notebook).await?;
let path = match parent {
Some(p) => format!("{}:{}/", notebook, p),
None => format!("{}:", notebook),
};
args.push(path);
// Filter to only show folders
args.push("--type".to_string());
args.push("folder".to_string());
args.push("--no-color".to_string());
// Strip the trailing usage/help hint block from empty
// results (`0 folders.` followed by `Import a file:`,
// `Help information:`). Detection keys off the
// empty-result signal per the `output-behavior`
// specification. See `output.rs` for the helper's
// contract.
self.exec_vec(args)
.await
.map(|output| strip_empty_result_hint(&output))
}
/// Lists folders in a notebook as typed entries: one
/// [`crate::ListEntry`] per direct child directory of the
/// scope (non-recursive), excluding dot-directories, ordered
/// lexically by relative path. Each entry is kind `Folder`
/// with the exact-path selector and no numeric id. A missing
/// scope is terminal `NotFound`. Zero `nb` spawns.
pub async fn list_folders_typed(
&self,
parent: Option<&str>,
notebook: Option<&str>,
) -> Result<Vec<crate::ListEntry>, NbError> {
validate_folder_option(parent)?;
let notebook = self.resolve_notebook_name(notebook)?;
let root = self.native_notebook_root(¬ebook).await?;
// Leading slashes are NOT trimmed: absolute forms
// fail closed as NotFound inside confinement.
let scope = parent.unwrap_or_default().to_string();
self.with_notebook_gate_native(&root, async {
let mut out = Vec::new();
for rel in crate::scope::scope_dirs(&root, &scope)? {
out.push(self.list_entry_for(¬ebook, &root, &rel).await?);
}
Ok(out)
})
.await
}
/// Creates a folder (one-shot transaction).
pub async fn add_folder(
&self,
path: &str,
notebook: Option<&str>,
) -> Result<CommitOutcome, NbError> {
validate_folder_path(path)?;
let mut tx = self.transaction(notebook).await?;
tx.add_folder(path)?;
tx.commit().await
}
/// Imports a file or URL into the notebook as a note.
///
/// One-shot only under the process-shared notebook gate. Not a
/// [`Transaction`] plan op in 0.3.0.
///
/// NOTE (0.4.3, evaluated): `nb import` accepts no `--wait`
/// flag — an unknown flag would be misparsed as an import
/// path — and a standalone `nb git checkpoint --wait` cannot
/// join the import's already-backgrounded checkpoint job, so
/// there is no `--wait` containment for the import race window.
/// Containment waits on 0.5.0 (native import with proper
/// locking); meanwhile the commit guard absorbs index-only
/// droppings and note-content leftovers still refuse loudly.
pub async fn import_note(
&self,
source: &str,
folder: Option<&str>,
filename: Option<&str>,
convert: bool,
notebook: Option<&str>,
) -> Result<String, NbError> {
let mut args = Vec::new();
self.require_folder_for_new_note(folder)?;
validate_folder_option(folder)?;
let notebook = self.resolve_notebook(notebook).await?;
self.with_notebook_gate(¬ebook, async {
let cmd = format!("{}:import", notebook);
args.push(cmd);
args.push(source.to_string());
if convert {
args.push("--convert".to_string());
}
if folder.is_some() || filename.is_some() {
let dest = match (folder, filename) {
(Some(f), Some(n)) => format!("{}/{}", f, n),
(Some(f), None) => format!("{}/", f),
(None, Some(n)) => n.to_string(),
(None, None) => unreachable!(),
};
args.push(dest);
}
self.exec_vec(args)
.await
.map(|output| self.append_notebook_warning(output, ¬ebook))
})
.await
}
}