1use std::collections::VecDeque;
4use std::path::{Path, PathBuf};
5use std::process::Stdio;
6use std::sync::LazyLock;
7
8use regex::Regex;
9use tokio::process::Command;
10
11use crate::argv::{
12 child_folder_names, empty_tasks_message, is_empty_tasks_error, normalize_folder,
13 search_command_args, tasks_command_args, tasks_scope,
14};
15use crate::diagnostics::{append_warning, is_notebook_not_found, is_selector_not_found};
16use crate::error::NbError;
17use crate::fingerprint;
18use crate::fingerprint::Fingerprint;
19use crate::gate;
20use crate::git::derive_git_notebook_name;
21use crate::git_env::scrub_git_env;
22use crate::git_signing::apply_git_signing_env;
23use crate::lines::{
24 note_line_from_body_line, require_contiguous_body, search_lines, split_body_lines,
25};
26use crate::output::strip_empty_result_hint;
27use crate::parser::{ParseContext, parse};
28use crate::transaction::{self, Transaction};
29use crate::types::{
30 BodyFragment, ByteString, CommitOutcome, LineEdit, NoteTarget, Occurrence, SearchNoteLines,
31 ShowNote, ShowNoteLines,
32};
33use crate::validate::{
34 detect_duplicate_title_heading, parse_qualified_selector, validate_destination,
35 validate_folder_option, validate_folder_path, validate_notebook_name,
36};
37use crate::{Config, NbClient, SearchMode, TaskStatus};
38
39static ANSI_REGEX: LazyLock<Regex> =
46 LazyLock::new(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap());
47
48fn strip_ansi(text: &str) -> String {
50 ANSI_REGEX.replace_all(text, "").into_owned()
51}
52
53enum ShowClassification {
58 Textual,
61 NonTextual { actual_type: String },
65 ProbeFailure,
70}
71
72const FOLDER_REQUIRED_MESSAGE: &str = "This server is configured to require `folder` for new notes. Use the `nb.mkdir` tool to create new folders and the `nb.folders` tool to list existing folders.";
73
74impl NbClient {
75 pub fn new(config: &Config) -> anyhow::Result<Self> {
81 let default_notebook = config
82 .notebook
83 .as_deref()
84 .map(String::from)
85 .or_else(derive_git_notebook_name);
86 Ok(Self {
87 default_notebook,
88 create_notebook: config.create_notebook,
89 disable_git_signing: config.disable_git_signing,
90 allow_top_level_notes: config.allow_top_level_notes,
91 gate_timeout: config.gate_timeout,
92 })
93 }
94
95 pub async fn transaction(&self, notebook: Option<&str>) -> Result<Transaction, NbError> {
99 let notebook = self.resolve_notebook_name(notebook)?;
100 if notebook_dir_from_env(¬ebook).is_none() {
103 self.ensure_notebook(¬ebook).await?;
104 }
105 Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
106 }
107
108 pub fn gate_timeout(&self) -> std::time::Duration {
110 self.gate_timeout
111 }
112
113 pub(crate) async fn show_notebook_path_unguarded(
120 &self,
121 notebook: Option<&str>,
122 ) -> Result<PathBuf, NbError> {
123 let notebook = self.resolve_notebook_name(notebook)?;
124 if let Some(path) = notebook_dir_from_env(¬ebook) {
125 return Ok(path);
126 }
127 self.ensure_notebook(¬ebook).await?;
128 let output = self
129 .exec_vec(vec![
130 "notebooks".to_string(),
131 "show".to_string(),
132 notebook.clone(),
133 "--path".to_string(),
134 ])
135 .await?;
136 let path = output.trim();
137 if path.is_empty() {
138 return Err(NbError::CommandFailed {
139 command: format!("nb notebooks show {notebook} --path"),
140 stderr: "nb notebooks path output was empty".to_string(),
141 exit_code: None,
142 });
143 }
144 Ok(PathBuf::from(path))
145 }
146
147 async fn with_notebook_gate<F, T>(&self, notebook: &str, f: F) -> Result<T, NbError>
148 where
149 F: std::future::Future<Output = Result<T, NbError>>,
150 {
151 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
152 let key = gate::git_common_dir_realpath(&root)?;
153 let _hold = gate::acquire_notebook(key, self.gate_timeout, false).await?;
154 f.await
155 }
156
157 fn require_folder_for_new_note(&self, folder: Option<&str>) -> Result<(), NbError> {
158 if self.allow_top_level_notes || folder.is_some_and(|value| !value.trim().is_empty()) {
159 return Ok(());
160 }
161 Err(NbError::ValidationError {
162 reason: FOLDER_REQUIRED_MESSAGE.to_string(),
163 location: None,
164 })
165 }
166
167 async fn resolve_target_selector(
168 &self,
169 id: &str,
170 notebook: Option<&str>,
171 ) -> Result<(String, String), NbError> {
172 if let Some((embedded_notebook, path)) = parse_qualified_selector(id)? {
173 let notebook = match notebook {
174 Some(value) => {
175 validate_notebook_name(value)?;
176 if value != embedded_notebook {
177 return Err(NbError::ValidationError {
178 reason: format!(
179 "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
180 ),
181 location: None,
182 });
183 }
184 embedded_notebook.to_string()
185 }
186 _ => embedded_notebook.to_string(),
187 };
188 self.ensure_existing_notebook(¬ebook).await?;
189 return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
190 }
191 let notebook = self.resolve_notebook(notebook).await?;
192 Ok((notebook.clone(), format!("{}:{}", notebook, id)))
193 }
194
195 fn append_notebook_warning(&self, output: String, notebook: &str) -> String {
196 let Some(default_notebook) = self.default_notebook.as_deref() else {
197 return output;
198 };
199 if default_notebook == notebook {
200 return output;
201 }
202 append_warning(
203 output,
204 format!(
205 "Warning: wrote to notebook `{notebook}`, not the project default notebook `{default_notebook}`. If this was unintended, move or delete the note and retry with the correct notebook/folder."
206 ),
207 )
208 }
209
210 fn resolve_notebook_name(&self, notebook: Option<&str>) -> Result<String, NbError> {
212 if let Some(name) = notebook {
213 validate_notebook_name(name)?;
214 return Ok(name.to_string());
215 }
216 if let Some(name) = self.default_notebook.as_deref() {
217 validate_notebook_name(name)?;
218 return Ok(name.to_string());
219 }
220 Err(NbError::ValidationError {
221 reason: "notebook not configured; set --notebook or NB_MCP_NOTEBOOK".to_string(),
222 location: None,
223 })
224 }
225
226 async fn resolve_notebook(&self, notebook: Option<&str>) -> Result<String, NbError> {
227 let name = self.resolve_notebook_name(notebook)?;
228 self.ensure_notebook(&name).await?;
229 Ok(name)
230 }
231
232 async fn ensure_notebook(&self, notebook: &str) -> Result<(), NbError> {
233 match self.check_notebook(notebook).await {
234 Ok(()) => Ok(()),
235 Err(err @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. })) => Err(err),
238 Err(NbError::NotFound { .. }) => {
245 if !self.create_notebook {
246 return Err(NbError::ValidationError {
247 reason: format!(
248 "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
249 or remove --no-create-notebook",
250 notebook
251 ),
252 location: None,
253 });
254 }
255 self.exec_vec(vec![
256 "notebooks".to_string(),
257 "add".to_string(),
258 notebook.to_string(),
259 ])
260 .await?;
261 Ok(())
262 }
263 Err(err) => Err(err),
269 }
270 }
271
272 async fn ensure_existing_notebook(&self, notebook: &str) -> Result<(), NbError> {
273 match self.check_notebook(notebook).await {
274 Ok(()) => Ok(()),
275 Err(err @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. })) => Err(err),
277 Err(err @ NbError::NotFound { .. }) => Err(err),
288 Err(err) => Err(err),
291 }
292 }
293
294 async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
295 let show_result = self
296 .exec_vec(vec![
297 "notebooks".to_string(),
298 "show".to_string(),
299 notebook.to_string(),
300 "--path".to_string(),
301 ])
302 .await;
303 match show_result {
304 Ok(output) => {
305 if output.trim().is_empty() {
306 return Err(NbError::CommandFailed {
313 command: format!("nb notebooks show {notebook} --path"),
314 stderr: "nb notebooks path output was empty".to_string(),
315 exit_code: None,
316 });
317 }
318 Ok(())
319 }
320 Err(err) => {
321 match err {
336 NbError::ExecutableNotFound { .. } | NbError::Io { .. } => Err(err),
337 NbError::CommandFailed { ref stderr, .. }
338 if is_notebook_not_found(stderr, notebook) =>
339 {
340 Err(NbError::NotFound {
341 selector: format!("{notebook}:"),
342 })
343 }
344 other => Err(other),
345 }
346 }
347 }
348 }
349
350 async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
352 tracing::debug!(?args, "executing nb command");
353 let mut command = Command::new("nb");
354 scrub_git_env(&mut command);
366 command
367 .args(args)
368 .stdin(Stdio::null()) .stdout(Stdio::piped())
370 .stderr(Stdio::piped());
371 if self.disable_git_signing {
372 apply_git_signing_env(&mut command);
373 }
374 let joined = format!("nb {}", args.join(" "));
375 let output = command
376 .spawn()
377 .map_err(|e| {
378 if e.kind() == std::io::ErrorKind::NotFound {
379 NbError::ExecutableNotFound {
380 path: "nb".to_string(),
381 }
382 } else {
383 NbError::Io {
384 path: PathBuf::from("nb"),
385 source: e.into(),
386 }
387 }
388 })?
389 .wait_with_output()
390 .await
391 .map_err(|e| NbError::Io {
392 path: PathBuf::from("nb"),
393 source: e.into(),
394 })?;
395
396 if output.status.success() {
397 let stdout = String::from_utf8_lossy(&output.stdout);
398 Ok(strip_ansi(&stdout))
399 } else {
400 let stderr = String::from_utf8_lossy(&output.stderr);
401 let stdout = String::from_utf8_lossy(&output.stdout);
402 let stderr_text = if stderr.is_empty() {
404 strip_ansi(&stdout)
405 } else {
406 strip_ansi(&stderr)
407 };
408 Err(NbError::CommandFailed {
409 command: joined,
410 stderr: stderr_text,
411 exit_code: output.status.code(),
412 })
413 }
414 }
415
416 async fn exec_vec(&self, args: Vec<String>) -> Result<String, NbError> {
418 let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
419 self.exec(&args_ref).await
420 }
421
422 pub async fn show_notebook_status(&self, notebook: Option<&str>) -> Result<String, NbError> {
424 let notebook = self.resolve_notebook(notebook).await?;
425 self.exec_vec(vec![format!("{}:", notebook), "status".to_string()])
426 .await
427 }
428
429 pub async fn list_notebooks(&self) -> Result<String, NbError> {
431 let _g = gate::acquire_global(self.gate_timeout).await?;
432 self.exec(&["notebooks", "--no-color"]).await
434 }
435
436 pub async fn show_notebook_path(&self, notebook: Option<&str>) -> Result<PathBuf, NbError> {
438 let notebook = self.resolve_notebook_name(notebook)?;
439 self.ensure_notebook(¬ebook).await?;
440 self.with_notebook_gate(
441 ¬ebook,
442 self.show_notebook_path_unguarded(Some(¬ebook)),
443 )
444 .await
445 }
446
447 pub async fn add_note(
449 &self,
450 title: Option<&str>,
451 content: &str,
452 tags: &[String],
453 folder: Option<&str>,
454 notebook: Option<&str>,
455 ) -> Result<CommitOutcome, NbError> {
456 if let Some(t) = title
457 && let Some(heading) = detect_duplicate_title_heading(t, content)
458 {
459 return Err(NbError::DuplicateTitleHeading {
460 title: t.to_string(),
461 heading,
462 });
463 }
464 self.require_folder_for_new_note(folder)?;
465 validate_folder_option(folder)?;
466 let filename = transaction::auto_filename("md");
467 let path = transaction::join_folder_file(folder, &filename);
468 let mut tx = self.transaction(notebook).await?;
469 tx.add_note(&path, title, content, tags)?;
470 tx.commit().await
471 }
472
473 pub async fn show_note(&self, id: &str, notebook: Option<&str>) -> Result<ShowNote, NbError> {
475 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
476 self.with_notebook_gate(¬ebook, async {
477 self.show_note_inner(¬ebook, &selector).await
478 })
479 .await
480 }
481
482 async fn show_note_inner(&self, notebook: &str, selector: &str) -> Result<ShowNote, NbError> {
483 match self.probe_show_classification(selector).await {
484 ShowClassification::NonTextual { actual_type } => {
485 return Err(NbError::UnsupportedShowTarget {
486 selector: selector.to_string(),
487 actual_type,
488 });
489 }
490 ShowClassification::Textual | ShowClassification::ProbeFailure => {}
491 }
492 let path = self.resolve_item_path(selector).await?;
493 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
494 let rel = path_relative_to(&root, &path)?;
495 let source = std::fs::read(&path).map_err(|e| NbError::Io {
496 path: path.clone(),
497 source: e.into(),
498 })?;
499 let doc = match parse(&source, ParseContext::FromPath(PathBuf::from(&rel))) {
500 Ok(doc) => doc,
501 Err(NbError::UnsupportedDocumentFormat { .. }) => {
504 parse(&source, ParseContext::Explicit(crate::DocumentKind::Note))?
505 }
506 Err(err) => return Err(err),
507 };
508 let fragments: Vec<BodyFragment> = doc
509 .body()
510 .enumerate()
511 .map(|(i, bytes)| BodyFragment {
512 index: i as u32,
513 bytes: ByteString::from_bytes(bytes),
514 })
515 .collect();
516 let body_contiguous = fragments.len() <= 1;
517 let body_bytes = doc.body_bytes();
518 let tags: Vec<String> = doc
520 .tags()
521 .map(|t| {
522 String::from_utf8_lossy(t)
523 .trim_start_matches('#')
524 .to_string()
525 })
526 .collect();
527 let title = doc.title().map(ByteString::from_bytes);
528 let title_text = doc.title().map(|bytes| {
529 let s = String::from_utf8_lossy(bytes);
530 s.trim_end_matches('\n')
531 .trim_start_matches('#')
532 .trim()
533 .to_string()
534 });
535 Ok(ShowNote {
536 selector: selector.to_string(),
537 path: rel,
538 kind: doc.kind(),
539 todo_state: doc.todo_state(),
540 title,
541 title_text,
542 tags,
543 body_fragments: fragments,
544 body_contiguous,
545 body: ByteString::from_bytes(body_bytes),
546 fingerprint: fingerprint::fingerprint(&doc),
547 source: ByteString::from_bytes(source),
548 })
549 }
550
551 pub async fn show_note_lines(
553 &self,
554 target: NoteTarget,
555 offset: Option<u32>,
556 limit: Option<u32>,
557 notebook: Option<&str>,
558 ) -> Result<ShowNoteLines, NbError> {
559 let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
560 self.with_notebook_gate(¬ebook, async {
561 let shown = self.show_note_inner(¬ebook, &selector).await?;
562 let source = shown.source.as_bytes()?;
563 let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
564 let body = require_contiguous_body(&doc)?;
565 let lines = split_body_lines(&body);
566 let total_lines = lines.len() as u32;
567 let offset = offset.unwrap_or(1);
568 let limit = limit.unwrap_or(100);
569 if offset == 0 {
570 return Err(NbError::InvalidLineWindow {
571 offset,
572 limit,
573 total_lines,
574 });
575 }
576 if total_lines == 0 {
577 if offset != 1 {
578 return Err(NbError::InvalidLineWindow {
579 offset,
580 limit,
581 total_lines,
582 });
583 }
584 return Ok(ShowNoteLines {
585 selector: shown.selector,
586 path: shown.path,
587 kind: shown.kind,
588 total_lines: 0,
589 offset,
590 limit,
591 next_offset: None,
592 lines: Vec::new(),
593 title: shown.title,
594 tags: shown.tags,
595 body_fingerprint: shown.fingerprint,
596 });
597 }
598 if offset > total_lines + 1 {
599 return Err(NbError::InvalidLineWindow {
600 offset,
601 limit,
602 total_lines,
603 });
604 }
605 let start_idx = (offset - 1) as usize;
606 let end_idx = (start_idx + limit as usize).min(lines.len());
607 let window: Vec<_> = lines[start_idx..end_idx]
608 .iter()
609 .map(|l| note_line_from_body_line(l, &body))
610 .collect();
611 let next_offset = if end_idx < lines.len() {
612 Some(offset + window.len() as u32)
613 } else {
614 None
615 };
616 Ok(ShowNoteLines {
617 selector: shown.selector,
618 path: shown.path,
619 kind: shown.kind,
620 total_lines,
621 offset,
622 limit,
623 next_offset,
624 lines: window,
625 title: shown.title,
626 tags: shown.tags,
627 body_fingerprint: shown.fingerprint,
628 })
629 })
630 .await
631 }
632
633 pub async fn search_note_lines(
635 &self,
636 target: NoteTarget,
637 pattern: &[u8],
638 notebook: Option<&str>,
639 ) -> Result<SearchNoteLines, NbError> {
640 let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
641 self.with_notebook_gate(¬ebook, async {
642 let shown = self.show_note_inner(¬ebook, &selector).await?;
643 let source = shown.source.as_bytes()?;
644 let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
645 let body = require_contiguous_body(&doc)?;
646 let hits = search_lines(&body, pattern)?;
647 Ok(SearchNoteLines {
648 selector: shown.selector,
649 path: shown.path,
650 kind: shown.kind,
651 hits,
652 body_fingerprint: shown.fingerprint,
653 })
654 })
655 .await
656 }
657
658 async fn resolve_item_path(&self, selector: &str) -> Result<PathBuf, NbError> {
659 let output = self
660 .exec_vec(vec![
661 "show".to_string(),
662 selector.to_string(),
663 "--path".to_string(),
664 "--no-color".to_string(),
665 ])
666 .await
667 .map_err(|err| match err {
668 NbError::CommandFailed { stderr, .. }
669 if is_selector_not_found(&stderr, selector) =>
670 {
671 NbError::NotFound {
672 selector: selector.to_string(),
673 }
674 }
675 other => other,
676 })?;
677 let path = output.trim();
678 if path.is_empty() {
679 return Err(NbError::CommandFailed {
680 command: format!("nb show {selector} --path"),
681 stderr: "empty path".into(),
682 exit_code: None,
683 });
684 }
685 Ok(PathBuf::from(path))
686 }
687
688 async fn resolve_note_target(
689 &self,
690 target: &NoteTarget,
691 notebook: Option<&str>,
692 ) -> Result<(String, String), NbError> {
693 match target {
694 NoteTarget::Selector { value } => self.resolve_target_selector(value, notebook).await,
695 NoteTarget::Path { value } => {
696 let notebook = self.resolve_notebook(notebook).await?;
697 Ok((notebook.clone(), format!("{notebook}:{value}")))
698 }
699 }
700 }
701
702 async fn probe_show_classification(&self, selector: &str) -> ShowClassification {
714 let textual = self
715 .exec_vec(vec![
716 "show".to_string(),
717 selector.to_string(),
718 "--type".to_string(),
719 "text".to_string(),
720 "--no-color".to_string(),
721 ])
722 .await;
723 if textual.is_ok() {
724 return ShowClassification::Textual;
725 }
726 match self
727 .exec_vec(vec![
728 "show".to_string(),
729 selector.to_string(),
730 "--type".to_string(),
731 "--no-color".to_string(),
732 ])
733 .await
734 {
735 Ok(stdout) => {
736 let trimmed = stdout.trim();
737 if trimmed.is_empty() {
738 ShowClassification::ProbeFailure
739 } else {
740 ShowClassification::NonTextual {
741 actual_type: trimmed.to_string(),
742 }
743 }
744 }
745 Err(_) => ShowClassification::ProbeFailure,
746 }
747 }
748
749 pub async fn list_notes(
751 &self,
752 folder: Option<&str>,
753 tags: &[String],
754 limit: Option<u32>,
755 notebook: Option<&str>,
756 ) -> Result<String, NbError> {
757 let mut args = Vec::new();
758 validate_folder_option(folder)?;
759
760 let notebook = self.resolve_notebook(notebook).await?;
761 let cmd = match folder {
762 Some(f) => format!("{}:{}/", notebook, f),
763 None => format!("{}:", notebook),
764 };
765
766 args.push("list".to_string());
767 args.push(cmd);
768
769 args.push("--no-color".to_string());
771
772 if let Some(n) = limit {
774 args.push("-n".to_string());
775 args.push(n.to_string());
776 }
777
778 for tag in tags {
780 args.push("--tags".to_string());
781 let tag_str = if tag.starts_with('#') {
782 tag.clone()
783 } else {
784 format!("#{}", tag)
785 };
786 args.push(tag_str);
787 }
788
789 self.exec_vec(args)
796 .await
797 .map(|output| strip_empty_result_hint(&output))
798 }
799
800 pub async fn search_notes(
802 &self,
803 queries: &[String],
804 mode: SearchMode,
805 tags: &[String],
806 folder: Option<&str>,
807 notebook: Option<&str>,
808 ) -> Result<String, NbError> {
809 validate_folder_option(folder)?;
810 if queries.is_empty() {
811 return Err(NbError::ValidationError {
812 reason: "at least one search query is required".to_string(),
813 location: None,
814 });
815 }
816
817 let notebook = self.resolve_notebook(notebook).await?;
818 let scope = match folder {
819 Some(f) => format!("{}:{}/", notebook, f),
820 None => format!("{}:", notebook),
821 };
822 let args = search_command_args(scope, queries, mode, tags);
823 self.exec_vec(args).await
824 }
825
826 pub async fn delete_note(
828 &self,
829 id: &str,
830 notebook: Option<&str>,
831 ) -> Result<CommitOutcome, NbError> {
832 let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
833 let target = self.note_target_for_selector(&nb, &selector).await?;
834 let mut tx = self.transaction(Some(&nb)).await?;
835 tx.delete_note(target)?;
836 tx.commit().await
837 }
838
839 pub async fn move_note(
841 &self,
842 id: &str,
843 destination: &str,
844 notebook: Option<&str>,
845 ) -> Result<CommitOutcome, NbError> {
846 validate_destination(destination)?;
847 let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
848 let target = self.note_target_for_selector(&nb, &selector).await?;
849 let mut tx = self.transaction(Some(&nb)).await?;
850 tx.move_note(target, destination)?;
851 tx.commit().await
852 }
853
854 async fn note_target_for_selector(
855 &self,
856 notebook: &str,
857 selector: &str,
858 ) -> Result<NoteTarget, NbError> {
859 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
860 let stripped = selector
861 .rsplit_once(':')
862 .map(|(_, rest)| rest)
863 .unwrap_or(selector);
864 let direct = root.join(stripped);
865 if direct.is_file() {
866 return Ok(NoteTarget::path(stripped));
867 }
868 let abs = self.resolve_item_path(selector).await?;
870 let rel = path_relative_to(&root, &abs)?;
871 Ok(NoteTarget::path(rel))
872 }
873
874 pub async fn add_todo(
876 &self,
877 title: &str,
878 description: Option<&str>,
879 tasks: &[String],
880 tags: &[String],
881 folder: Option<&str>,
882 notebook: Option<&str>,
883 ) -> Result<CommitOutcome, NbError> {
884 self.require_folder_for_new_note(folder)?;
885 validate_folder_option(folder)?;
886 let filename = transaction::auto_filename("todo.md");
887 let path = transaction::join_folder_file(folder, &filename);
888 let mut tx = self.transaction(notebook).await?;
889 tx.add_todo(&path, title, description, tasks, tags)?;
890 tx.commit().await
891 }
892
893 pub async fn mark_task_done(
895 &self,
896 id: &str,
897 task_number: Option<u32>,
898 notebook: Option<&str>,
899 ) -> Result<CommitOutcome, NbError> {
900 let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
901 let target = self.note_target_for_selector(&nb, &selector).await?;
902 let mut tx = self.transaction(Some(&nb)).await?;
903 tx.mark_task_done(target, task_number)?;
904 tx.commit().await
905 }
906
907 pub async fn unmark_task_done(
909 &self,
910 id: &str,
911 task_number: Option<u32>,
912 notebook: Option<&str>,
913 ) -> Result<CommitOutcome, NbError> {
914 let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
915 let target = self.note_target_for_selector(&nb, &selector).await?;
916 let mut tx = self.transaction(Some(&nb)).await?;
917 tx.unmark_task_done(target, task_number)?;
918 tx.commit().await
919 }
920
921 pub async fn replace_note_body(
923 &self,
924 target: NoteTarget,
925 new_body: impl AsRef<[u8]>,
926 fingerprint: Fingerprint,
927 notebook: Option<&str>,
928 ) -> Result<CommitOutcome, NbError> {
929 let mut tx = self.transaction(notebook).await?;
930 tx.replace_note_body(target, new_body, fingerprint)?;
931 tx.commit().await
932 }
933
934 #[allow(clippy::too_many_arguments)]
936 pub async fn edit_note_substring(
937 &self,
938 target: NoteTarget,
939 pattern: impl AsRef<[u8]>,
940 replacement: impl AsRef<[u8]>,
941 occurrence: Occurrence,
942 expected_count: u32,
943 fingerprint: Option<Fingerprint>,
944 notebook: Option<&str>,
945 ) -> Result<CommitOutcome, NbError> {
946 let mut tx = self.transaction(notebook).await?;
947 tx.edit_note_substring(
948 target,
949 pattern,
950 replacement,
951 occurrence,
952 expected_count,
953 fingerprint,
954 )?;
955 tx.commit().await
956 }
957
958 pub async fn edit_note_lines(
960 &self,
961 target: NoteTarget,
962 edits: Vec<LineEdit>,
963 notebook: Option<&str>,
964 ) -> Result<CommitOutcome, NbError> {
965 let mut tx = self.transaction(notebook).await?;
966 tx.edit_note_lines(target, edits)?;
967 tx.commit().await
968 }
969
970 pub async fn retitle_note(
972 &self,
973 target: NoteTarget,
974 title: impl AsRef<[u8]>,
975 notebook: Option<&str>,
976 ) -> Result<CommitOutcome, NbError> {
977 let mut tx = self.transaction(notebook).await?;
978 tx.retitle_note(target, title)?;
979 tx.commit().await
980 }
981
982 pub async fn edit_note_tags(
984 &self,
985 target: NoteTarget,
986 add: &[String],
987 remove: &[String],
988 notebook: Option<&str>,
989 ) -> Result<CommitOutcome, NbError> {
990 let mut tx = self.transaction(notebook).await?;
991 tx.edit_note_tags(target, add, remove)?;
992 tx.commit().await
993 }
994
995 pub async fn list_tasks(
1006 &self,
1007 folder: Option<&str>,
1008 status: Option<TaskStatus>,
1009 recursive: bool,
1010 notebook: Option<&str>,
1011 ) -> Result<String, NbError> {
1012 validate_folder_option(folder)?;
1013 let notebook = self.resolve_notebook(notebook).await?;
1014 let folder = folder.map(normalize_folder);
1015 let scopes = if recursive {
1016 self.tasks_scopes_recursive(¬ebook, folder.as_deref())
1017 .await?
1018 } else {
1019 vec![tasks_scope(¬ebook, folder.as_deref())]
1020 };
1021
1022 let mut outputs: Vec<String> = Vec::new();
1023 let mut saw_empty = false;
1024 for scope in scopes {
1025 match self.exec_vec(tasks_command_args(scope, status)).await {
1026 Ok(output) => {
1027 let output = output.trim();
1028 if !output.is_empty() {
1029 outputs.push(output.to_string());
1030 }
1031 }
1032 Err(NbError::CommandFailed { stderr, .. }) if is_empty_tasks_error(&stderr) => {
1033 saw_empty = true;
1034 }
1035 Err(err) => return Err(err),
1036 }
1037 }
1038 if outputs.is_empty() && saw_empty {
1039 return Err(NbError::ValidationError {
1046 reason: empty_tasks_message(status),
1047 location: None,
1048 });
1049 }
1050 Ok(outputs.join("\n"))
1051 }
1052
1053 async fn tasks_scopes_recursive(
1054 &self,
1055 notebook: &str,
1056 folder: Option<&str>,
1057 ) -> Result<Vec<String>, NbError> {
1058 let notebook_root = self.show_notebook_path(Some(notebook)).await?;
1059 let start = folder.unwrap_or_default().to_string();
1060 let mut queue = VecDeque::new();
1061 queue.push_back(start.clone());
1062
1063 let mut scopes = vec![tasks_scope(notebook, folder)];
1064 while let Some(current) = queue.pop_front() {
1065 let base = if current.is_empty() {
1066 notebook_root.clone()
1067 } else {
1068 notebook_root.join(¤t)
1069 };
1070 let children = child_folder_names(&base)?;
1071 for child in children {
1072 let next = if current.is_empty() {
1073 child
1074 } else {
1075 format!("{}/{}", current, child)
1076 };
1077 scopes.push(tasks_scope(notebook, Some(&next)));
1078 queue.push_back(next);
1079 }
1080 }
1081 Ok(scopes)
1082 }
1083
1084 pub async fn add_bookmark(
1086 &self,
1087 url: &str,
1088 title: Option<&str>,
1089 tags: &[String],
1090 comment: Option<&str>,
1091 folder: Option<&str>,
1092 notebook: Option<&str>,
1093 ) -> Result<CommitOutcome, NbError> {
1094 self.require_folder_for_new_note(folder)?;
1095 validate_folder_option(folder)?;
1096 let filename = transaction::auto_filename("bookmark.md");
1097 let path = transaction::join_folder_file(folder, &filename);
1098 let mut tx = self.transaction(notebook).await?;
1099 tx.add_bookmark(&path, url, title, tags, comment)?;
1100 tx.commit().await
1101 }
1102
1103 pub async fn list_folders(
1105 &self,
1106 parent: Option<&str>,
1107 notebook: Option<&str>,
1108 ) -> Result<String, NbError> {
1109 let mut args = vec!["list".to_string()];
1110 validate_folder_option(parent)?;
1111
1112 let notebook = self.resolve_notebook(notebook).await?;
1113 let path = match parent {
1114 Some(p) => format!("{}:{}/", notebook, p),
1115 None => format!("{}:", notebook),
1116 };
1117 args.push(path);
1118
1119 args.push("--type".to_string());
1121 args.push("folder".to_string());
1122 args.push("--no-color".to_string());
1123
1124 self.exec_vec(args)
1131 .await
1132 .map(|output| strip_empty_result_hint(&output))
1133 }
1134
1135 pub async fn add_folder(
1137 &self,
1138 path: &str,
1139 notebook: Option<&str>,
1140 ) -> Result<CommitOutcome, NbError> {
1141 validate_folder_path(path)?;
1142 let mut tx = self.transaction(notebook).await?;
1143 tx.add_folder(path)?;
1144 tx.commit().await
1145 }
1146
1147 pub async fn import_note(
1152 &self,
1153 source: &str,
1154 folder: Option<&str>,
1155 filename: Option<&str>,
1156 convert: bool,
1157 notebook: Option<&str>,
1158 ) -> Result<String, NbError> {
1159 let mut args = Vec::new();
1160 self.require_folder_for_new_note(folder)?;
1161 validate_folder_option(folder)?;
1162
1163 let notebook = self.resolve_notebook(notebook).await?;
1164 self.with_notebook_gate(¬ebook, async {
1165 let cmd = format!("{}:import", notebook);
1166 args.push(cmd);
1167 args.push(source.to_string());
1168 if convert {
1169 args.push("--convert".to_string());
1170 }
1171 if folder.is_some() || filename.is_some() {
1172 let dest = match (folder, filename) {
1173 (Some(f), Some(n)) => format!("{}/{}", f, n),
1174 (Some(f), None) => format!("{}/", f),
1175 (None, Some(n)) => n.to_string(),
1176 (None, None) => unreachable!(),
1177 };
1178 args.push(dest);
1179 }
1180 self.exec_vec(args)
1181 .await
1182 .map(|output| self.append_notebook_warning(output, ¬ebook))
1183 })
1184 .await
1185 }
1186}
1187
1188fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
1189 let nb_dir = std::env::var_os("NB_DIR")?;
1190 let path = PathBuf::from(nb_dir).join(notebook);
1191 if path.is_dir() && path.join(".git").exists() {
1192 Some(path)
1193 } else {
1194 None
1195 }
1196}
1197
1198fn path_relative_to(root: &Path, path: &Path) -> Result<String, NbError> {
1199 let root = root.canonicalize().map_err(|e| NbError::Io {
1200 path: root.to_path_buf(),
1201 source: e.into(),
1202 })?;
1203 let path = path.canonicalize().map_err(|e| NbError::Io {
1204 path: path.to_path_buf(),
1205 source: e.into(),
1206 })?;
1207 let rel = path
1208 .strip_prefix(&root)
1209 .map_err(|_| NbError::ValidationError {
1210 reason: format!(
1211 "path {} is not under notebook root {}",
1212 path.display(),
1213 root.display()
1214 ),
1215 location: None,
1216 })?;
1217 Ok(rel.to_string_lossy().replace('\\', "/"))
1218}