1mod git;
8mod git_env;
9mod output;
10
11#[cfg(feature = "testing")]
12pub mod testing;
13
14pub use git::{derive_git_notebook_name, git_rev_parse};
15pub use git_env::{leaked_git_names, scrub_git_env, scrub_git_env_std};
16
17use std::{collections::VecDeque, path::PathBuf, process::Stdio, sync::LazyLock};
18
19use regex::Regex;
20use serde::{Deserialize, Serialize};
21use tokio::process::Command;
22
23static ANSI_REGEX: LazyLock<Regex> =
30 LazyLock::new(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap());
31
32fn strip_ansi(text: &str) -> String {
34 ANSI_REGEX.replace_all(text, "").into_owned()
35}
36
37#[derive(Debug, thiserror::Error)]
39pub enum NbError {
40 #[error("nb command failed: {0}")]
41 CommandFailed(String),
42
43 #[error(
44 "nb not found in PATH; install via: brew install xwmx/taps/nb (macOS) or see https://github.com/xwmx/nb#installation"
45 )]
46 NotFound,
47
48 #[error("IO error: {0}")]
49 Io(#[from] std::io::Error),
50
51 #[error(
62 "selector `{selector}` resolved to non-textual type `{actual_type}`; \
63 `nb show` does not display non-textual content"
64 )]
65 UnsupportedShowTarget {
66 selector: String,
67 actual_type: String,
68 },
69
70 #[error(
80 "title `{title}` duplicates the first H1 in content (`{heading}`); \
81 remove the duplicate heading to avoid double-rendering"
82 )]
83 DuplicateTitleHeading { title: String, heading: String },
84}
85
86enum ShowClassification {
91 Textual,
94 NonTextual { actual_type: String },
98 ProbeFailure,
103}
104
105#[derive(Clone, Debug)]
110pub struct Config {
111 pub notebook: Option<String>,
113 pub create_notebook: bool,
115 pub allow_top_level_notes: bool,
117 pub disable_git_signing: bool,
119}
120
121impl Default for Config {
122 fn default() -> Self {
123 Self {
124 notebook: None,
125 create_notebook: true,
126 allow_top_level_notes: false,
127 disable_git_signing: false,
128 }
129 }
130}
131
132#[derive(Clone)]
134pub struct NbClient {
135 default_notebook: Option<String>,
137 create_notebook: bool,
139 disable_git_signing: bool,
141 allow_top_level_notes: bool,
143}
144
145const 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.";
146
147const NOTEBOOK_FIELD_MESSAGE: &str = "Invalid `notebook`: use a bare notebook name only. Use `folder` for folder paths and `id`/`selector` for note selectors.";
148
149const FOLDER_FIELD_MESSAGE: &str = "Invalid folder path: use `folder` for folder paths only, not notebook-qualified selectors. To choose a notebook, use the separate `notebook` field.";
150
151#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
192#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
193#[serde(rename_all = "lowercase")]
194pub enum EditMode {
195 #[default]
204 #[serde(alias = "replace")]
205 Overwrite,
206 Append,
210 Prepend,
213}
214
215#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
218#[serde(rename_all = "lowercase")]
219pub enum SearchMode {
220 #[default]
222 Any,
223 All,
225}
226
227#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
230#[serde(rename_all = "lowercase")]
231pub enum TaskStatus {
232 Open,
234 Closed,
236}
237
238impl NbClient {
239 pub fn new(config: &Config) -> anyhow::Result<Self> {
245 let default_notebook = config
246 .notebook
247 .as_deref()
248 .map(String::from)
249 .or_else(derive_git_notebook_name);
250 Ok(Self {
251 default_notebook,
252 create_notebook: config.create_notebook,
253 disable_git_signing: config.disable_git_signing,
254 allow_top_level_notes: config.allow_top_level_notes,
255 })
256 }
257
258 fn require_folder_for_new_note(&self, folder: Option<&str>) -> Result<(), NbError> {
259 if self.allow_top_level_notes || folder.is_some_and(|value| !value.trim().is_empty()) {
260 return Ok(());
261 }
262 Err(NbError::CommandFailed(FOLDER_REQUIRED_MESSAGE.to_string()))
263 }
264
265 async fn resolve_target_selector(
266 &self,
267 id: &str,
268 notebook: Option<&str>,
269 ) -> Result<(String, String), NbError> {
270 if let Some((embedded_notebook, path)) = parse_qualified_selector(id)? {
271 let notebook = match notebook {
272 Some(value) => {
273 validate_notebook_name(value)?;
274 if value != embedded_notebook {
275 return Err(NbError::CommandFailed(format!(
276 "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
277 )));
278 }
279 embedded_notebook.to_string()
280 }
281 _ => embedded_notebook.to_string(),
282 };
283 self.ensure_existing_notebook(¬ebook).await?;
284 return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
285 }
286 let notebook = self.resolve_notebook(notebook).await?;
287 Ok((notebook.clone(), format!("{}:{}", notebook, id)))
288 }
289
290 fn append_notebook_warning(&self, output: String, notebook: &str) -> String {
291 let Some(default_notebook) = self.default_notebook.as_deref() else {
292 return output;
293 };
294 if default_notebook == notebook {
295 return output;
296 }
297 append_warning(
298 output,
299 format!(
300 "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."
301 ),
302 )
303 }
304
305 fn resolve_notebook_name(&self, notebook: Option<&str>) -> Result<String, NbError> {
307 if let Some(name) = notebook {
308 validate_notebook_name(name)?;
309 return Ok(name.to_string());
310 }
311 if let Some(name) = self.default_notebook.as_deref() {
312 validate_notebook_name(name)?;
313 return Ok(name.to_string());
314 }
315 Err(NbError::CommandFailed(
316 "notebook not configured; set --notebook or NB_MCP_NOTEBOOK".to_string(),
317 ))
318 }
319
320 async fn resolve_notebook(&self, notebook: Option<&str>) -> Result<String, NbError> {
321 let name = self.resolve_notebook_name(notebook)?;
322 self.ensure_notebook(&name).await?;
323 Ok(name)
324 }
325
326 async fn ensure_notebook(&self, notebook: &str) -> Result<(), NbError> {
327 match self.check_notebook(notebook).await {
328 Ok(()) => Ok(()),
329 Err(_) => {
330 if !self.create_notebook {
331 return Err(NbError::CommandFailed(format!(
332 "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
333 or remove --no-create-notebook",
334 notebook
335 )));
336 }
337 self.exec_vec(vec![
338 "notebooks".to_string(),
339 "add".to_string(),
340 notebook.to_string(),
341 ])
342 .await?;
343 Ok(())
344 }
345 }
346 }
347
348 async fn ensure_existing_notebook(&self, notebook: &str) -> Result<(), NbError> {
349 self.check_notebook(notebook).await.map_err(|_| {
350 NbError::CommandFailed(format!(
351 "notebook not found: `{notebook}`. Use a copied selector only for an existing notebook."
352 ))
353 })
354 }
355
356 async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
357 let show_result = self
358 .exec_vec(vec![
359 "notebooks".to_string(),
360 "show".to_string(),
361 notebook.to_string(),
362 "--path".to_string(),
363 ])
364 .await;
365 match show_result {
366 Ok(output) => {
367 if output.trim().is_empty() {
368 return Err(NbError::CommandFailed(
369 "nb notebooks path output was empty".to_string(),
370 ));
371 }
372 Ok(())
373 }
374 Err(_) => Err(NbError::CommandFailed(format!(
375 "notebook not found: `{notebook}`"
376 ))),
377 }
378 }
379
380 async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
382 tracing::debug!(?args, "executing nb command");
383 let mut command = Command::new("nb");
384 scrub_git_env(&mut command);
396 command
397 .args(args)
398 .stdin(Stdio::null()) .stdout(Stdio::piped())
400 .stderr(Stdio::piped());
401 if self.disable_git_signing {
402 apply_git_signing_env(&mut command);
403 }
404 let output = command
405 .spawn()
406 .map_err(|e| {
407 if e.kind() == std::io::ErrorKind::NotFound {
408 NbError::NotFound
409 } else {
410 NbError::Io(e)
411 }
412 })?
413 .wait_with_output()
414 .await?;
415
416 if output.status.success() {
417 let stdout = String::from_utf8_lossy(&output.stdout);
418 Ok(strip_ansi(&stdout))
419 } else {
420 let stderr = String::from_utf8_lossy(&output.stderr);
421 let stdout = String::from_utf8_lossy(&output.stdout);
422 let msg = if stderr.is_empty() {
424 strip_ansi(&stdout)
425 } else {
426 strip_ansi(&stderr)
427 };
428 Err(NbError::CommandFailed(msg))
429 }
430 }
431
432 async fn exec_vec(&self, args: Vec<String>) -> Result<String, NbError> {
434 let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
435 self.exec(&args_ref).await
436 }
437
438 pub async fn show_notebook_status(&self, notebook: Option<&str>) -> Result<String, NbError> {
440 let notebook = self.resolve_notebook(notebook).await?;
441 self.exec_vec(vec![format!("{}:", notebook), "status".to_string()])
442 .await
443 }
444
445 pub async fn list_notebooks(&self) -> Result<String, NbError> {
447 self.exec(&["notebooks", "--no-color"]).await
449 }
450
451 pub async fn show_notebook_path(&self, notebook: Option<&str>) -> Result<PathBuf, NbError> {
453 let notebook = self.resolve_notebook(notebook).await?;
454 let output = self
455 .exec_vec(vec![
456 "notebooks".to_string(),
457 "show".to_string(),
458 notebook,
459 "--path".to_string(),
460 ])
461 .await?;
462 let path = output.trim();
463 if path.is_empty() {
464 return Err(NbError::CommandFailed(
465 "nb notebooks path output was empty".to_string(),
466 ));
467 }
468 Ok(PathBuf::from(path))
469 }
470
471 pub async fn add_note(
473 &self,
474 title: Option<&str>,
475 content: &str,
476 tags: &[String],
477 folder: Option<&str>,
478 notebook: Option<&str>,
479 ) -> Result<String, NbError> {
480 if let Some(t) = title
487 && let Some(heading) = detect_duplicate_title_heading(t, content)
488 {
489 return Err(NbError::DuplicateTitleHeading {
490 title: t.to_string(),
491 heading,
492 });
493 }
494 let mut args = Vec::new();
495 self.require_folder_for_new_note(folder)?;
496 validate_folder_option(folder)?;
497
498 let notebook = self.resolve_notebook(notebook).await?;
499 let cmd = format!("{}:add", notebook);
500 args.push(cmd);
501
502 if let Some(t) = title {
504 args.push("--title".to_string());
505 args.push(t.to_string());
506 }
507
508 args.push("--content".to_string());
510 args.push(content.to_string());
511
512 for tag in tags {
514 args.push("--tags".to_string());
515 let tag_str = if tag.starts_with('#') {
516 tag.clone()
517 } else {
518 format!("#{}", tag)
519 };
520 args.push(tag_str);
521 }
522
523 if let Some(f) = folder {
525 args.push("--folder".to_string());
526 args.push(f.to_string());
527 }
528
529 self.exec_vec(args)
530 .await
531 .map(|output| self.append_notebook_warning(output, ¬ebook))
532 }
533
534 pub async fn show_note(&self, id: &str, notebook: Option<&str>) -> Result<String, NbError> {
536 let (_, selector) = self.resolve_target_selector(id, notebook).await?;
537 match self.probe_show_classification(&selector).await {
549 ShowClassification::NonTextual { actual_type } => {
550 return Err(NbError::UnsupportedShowTarget {
551 selector: selector.clone(),
552 actual_type,
553 });
554 }
555 ShowClassification::Textual | ShowClassification::ProbeFailure => {
556 }
559 }
560 self.exec_vec(vec![
567 "show".to_string(),
568 selector,
569 "--print".to_string(),
570 "--no-color".to_string(),
571 ])
572 .await
573 }
574
575 async fn probe_show_classification(&self, selector: &str) -> ShowClassification {
587 let textual = self
588 .exec_vec(vec![
589 "show".to_string(),
590 selector.to_string(),
591 "--type".to_string(),
592 "text".to_string(),
593 "--no-color".to_string(),
594 ])
595 .await;
596 if textual.is_ok() {
597 return ShowClassification::Textual;
598 }
599 match self
600 .exec_vec(vec![
601 "show".to_string(),
602 selector.to_string(),
603 "--type".to_string(),
604 "--no-color".to_string(),
605 ])
606 .await
607 {
608 Ok(stdout) => {
609 let trimmed = stdout.trim();
610 if trimmed.is_empty() {
611 ShowClassification::ProbeFailure
612 } else {
613 ShowClassification::NonTextual {
614 actual_type: trimmed.to_string(),
615 }
616 }
617 }
618 Err(_) => ShowClassification::ProbeFailure,
619 }
620 }
621
622 pub async fn list_notes(
624 &self,
625 folder: Option<&str>,
626 tags: &[String],
627 limit: Option<u32>,
628 notebook: Option<&str>,
629 ) -> Result<String, NbError> {
630 let mut args = Vec::new();
631 validate_folder_option(folder)?;
632
633 let notebook = self.resolve_notebook(notebook).await?;
634 let cmd = match folder {
635 Some(f) => format!("{}:{}/", notebook, f),
636 None => format!("{}:", notebook),
637 };
638
639 args.push("list".to_string());
640 args.push(cmd);
641
642 args.push("--no-color".to_string());
644
645 if let Some(n) = limit {
647 args.push("-n".to_string());
648 args.push(n.to_string());
649 }
650
651 for tag in tags {
653 args.push("--tags".to_string());
654 let tag_str = if tag.starts_with('#') {
655 tag.clone()
656 } else {
657 format!("#{}", tag)
658 };
659 args.push(tag_str);
660 }
661
662 self.exec_vec(args)
669 .await
670 .map(|output| output::strip_empty_result_hint(&output))
671 }
672
673 pub async fn search_notes(
675 &self,
676 queries: &[String],
677 mode: SearchMode,
678 tags: &[String],
679 folder: Option<&str>,
680 notebook: Option<&str>,
681 ) -> Result<String, NbError> {
682 validate_folder_option(folder)?;
683 if queries.is_empty() {
684 return Err(NbError::CommandFailed(
685 "at least one search query is required".to_string(),
686 ));
687 }
688
689 let notebook = self.resolve_notebook(notebook).await?;
690 let scope = match folder {
691 Some(f) => format!("{}:{}/", notebook, f),
692 None => format!("{}:", notebook),
693 };
694 let args = search_command_args(scope, queries, mode, tags);
695 self.exec_vec(args).await
696 }
697
698 pub async fn edit_note(
708 &self,
709 id: &str,
710 content: &str,
711 mode: EditMode,
712 notebook: Option<&str>,
713 ) -> Result<String, NbError> {
714 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
715 let output = self.exec_vec(edit_args(selector, content, mode)).await?;
716 Ok(self.append_notebook_warning(output, ¬ebook))
717 }
718
719 pub async fn delete_note(&self, id: &str, notebook: Option<&str>) -> Result<String, NbError> {
721 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
722 let output = self
723 .exec_vec(vec!["delete".to_string(), selector, "--force".to_string()])
724 .await?;
725 Ok(self.append_notebook_warning(output, ¬ebook))
726 }
727
728 pub async fn move_note(
730 &self,
731 id: &str,
732 destination: &str,
733 notebook: Option<&str>,
734 ) -> Result<String, NbError> {
735 validate_destination(destination)?;
736 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
737 let output = self
738 .exec_vec(vec![
739 "move".to_string(),
740 selector,
741 destination.to_string(),
742 "--force".to_string(),
743 ])
744 .await?;
745 Ok(self.append_notebook_warning(output, ¬ebook))
746 }
747
748 pub async fn add_todo(
750 &self,
751 title: &str,
752 description: Option<&str>,
753 tasks: &[String],
754 tags: &[String],
755 folder: Option<&str>,
756 notebook: Option<&str>,
757 ) -> Result<String, NbError> {
758 self.require_folder_for_new_note(folder)?;
759 validate_folder_option(folder)?;
760 let notebook = self.resolve_notebook(notebook).await?;
761 let output = self
762 .exec_vec(todo_command_args(
763 ¬ebook,
764 title,
765 description,
766 tasks,
767 tags,
768 folder,
769 ))
770 .await?;
771 Ok(self.append_notebook_warning(output, ¬ebook))
772 }
773
774 pub async fn mark_task_done(
776 &self,
777 id: &str,
778 task_number: Option<u32>,
779 notebook: Option<&str>,
780 ) -> Result<String, NbError> {
781 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
782 let output = self
783 .exec_vec(task_command_args("do", selector, task_number))
784 .await?;
785 Ok(self.append_notebook_warning(output, ¬ebook))
786 }
787
788 pub async fn unmark_task_done(
790 &self,
791 id: &str,
792 task_number: Option<u32>,
793 notebook: Option<&str>,
794 ) -> Result<String, NbError> {
795 let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
796 let output = self
797 .exec_vec(task_command_args("undo", selector, task_number))
798 .await?;
799 Ok(self.append_notebook_warning(output, ¬ebook))
800 }
801
802 pub async fn list_tasks(
813 &self,
814 folder: Option<&str>,
815 status: Option<TaskStatus>,
816 recursive: bool,
817 notebook: Option<&str>,
818 ) -> Result<String, NbError> {
819 validate_folder_option(folder)?;
820 let notebook = self.resolve_notebook(notebook).await?;
821 let folder = folder.map(normalize_folder);
822 let scopes = if recursive {
823 self.tasks_scopes_recursive(¬ebook, folder.as_deref())
824 .await?
825 } else {
826 vec![tasks_scope(¬ebook, folder.as_deref())]
827 };
828
829 let mut outputs: Vec<String> = Vec::new();
830 let mut saw_empty = false;
831 for scope in scopes {
832 match self.exec_vec(tasks_command_args(scope, status)).await {
833 Ok(output) => {
834 let output = output.trim();
835 if !output.is_empty() {
836 outputs.push(output.to_string());
837 }
838 }
839 Err(NbError::CommandFailed(message)) if is_empty_tasks_error(&message) => {
840 saw_empty = true;
841 }
842 Err(err) => return Err(err),
843 }
844 }
845 if outputs.is_empty() && saw_empty {
846 return Err(NbError::CommandFailed(empty_tasks_message(status)));
847 }
848 Ok(outputs.join("\n"))
849 }
850
851 async fn tasks_scopes_recursive(
852 &self,
853 notebook: &str,
854 folder: Option<&str>,
855 ) -> Result<Vec<String>, NbError> {
856 let notebook_root = self.show_notebook_path(Some(notebook)).await?;
857 let start = folder.unwrap_or_default().to_string();
858 let mut queue = VecDeque::new();
859 queue.push_back(start.clone());
860
861 let mut scopes = vec![tasks_scope(notebook, folder)];
862 while let Some(current) = queue.pop_front() {
863 let base = if current.is_empty() {
864 notebook_root.clone()
865 } else {
866 notebook_root.join(¤t)
867 };
868 let children = child_folder_names(&base)?;
869 for child in children {
870 let next = if current.is_empty() {
871 child
872 } else {
873 format!("{}/{}", current, child)
874 };
875 scopes.push(tasks_scope(notebook, Some(&next)));
876 queue.push_back(next);
877 }
878 }
879 Ok(scopes)
880 }
881
882 pub async fn add_bookmark(
884 &self,
885 url: &str,
886 title: Option<&str>,
887 tags: &[String],
888 comment: Option<&str>,
889 folder: Option<&str>,
890 notebook: Option<&str>,
891 ) -> Result<String, NbError> {
892 let mut args = Vec::new();
893 self.require_folder_for_new_note(folder)?;
894 validate_folder_option(folder)?;
895
896 let notebook = self.resolve_notebook(notebook).await?;
898 let dest = match folder {
899 Some(f) => format!("{}:{}/", notebook, f),
900 None => format!("{}:", notebook),
901 };
902
903 let cmd = format!("{}bookmark", dest);
904 args.push(cmd);
905 args.push(url.to_string());
906
907 if let Some(t) = title {
908 args.push("--title".to_string());
909 args.push(t.to_string());
910 }
911
912 if let Some(c) = comment {
913 args.push("--comment".to_string());
914 args.push(c.to_string());
915 }
916
917 for tag in tags {
918 args.push("--tags".to_string());
919 let tag_str = if tag.starts_with('#') {
920 tag.clone()
921 } else {
922 format!("#{}", tag)
923 };
924 args.push(tag_str);
925 }
926
927 self.exec_vec(args)
928 .await
929 .map(|output| self.append_notebook_warning(output, ¬ebook))
930 }
931
932 pub async fn list_folders(
934 &self,
935 parent: Option<&str>,
936 notebook: Option<&str>,
937 ) -> Result<String, NbError> {
938 let mut args = vec!["list".to_string()];
939 validate_folder_option(parent)?;
940
941 let notebook = self.resolve_notebook(notebook).await?;
942 let path = match parent {
943 Some(p) => format!("{}:{}/", notebook, p),
944 None => format!("{}:", notebook),
945 };
946 args.push(path);
947
948 args.push("--type".to_string());
950 args.push("folder".to_string());
951 args.push("--no-color".to_string());
952
953 self.exec_vec(args)
960 .await
961 .map(|output| output::strip_empty_result_hint(&output))
962 }
963
964 pub async fn add_folder(&self, path: &str, notebook: Option<&str>) -> Result<String, NbError> {
966 validate_folder_path(path)?;
967 let notebook = self.resolve_notebook(notebook).await?;
968 let folder_path = mkdir_selector(¬ebook, path);
969 let output = self
970 .exec_vec(vec!["add".to_string(), "folder".to_string(), folder_path])
971 .await?;
972 Ok(self.append_notebook_warning(output, ¬ebook))
973 }
974
975 pub async fn import_note(
986 &self,
987 source: &str,
988 folder: Option<&str>,
989 filename: Option<&str>,
990 convert: bool,
991 notebook: Option<&str>,
992 ) -> Result<String, NbError> {
993 let mut args = Vec::new();
994 self.require_folder_for_new_note(folder)?;
995 validate_folder_option(folder)?;
996
997 let notebook = self.resolve_notebook(notebook).await?;
998 let cmd = format!("{}:import", notebook);
999 args.push(cmd);
1000
1001 args.push(source.to_string());
1003
1004 if convert {
1006 args.push("--convert".to_string());
1007 }
1008
1009 if folder.is_some() || filename.is_some() {
1012 let dest = match (folder, filename) {
1013 (Some(f), Some(n)) => format!("{}/{}", f, n),
1014 (Some(f), None) => format!("{}/", f),
1015 (None, Some(n)) => n.to_string(),
1016 (None, None) => unreachable!(),
1017 };
1018 args.push(dest);
1019 }
1020
1021 self.exec_vec(args)
1022 .await
1023 .map(|output| self.append_notebook_warning(output, ¬ebook))
1024 }
1025}
1026
1027fn append_warning(mut output: String, warning: String) -> String {
1028 if !output.trim().is_empty() {
1029 if !output.ends_with('\n') {
1030 output.push('\n');
1031 }
1032 output.push('\n');
1033 }
1034 output.push_str(&warning);
1035 output
1036}
1037
1038fn validate_notebook_name(name: &str) -> Result<(), NbError> {
1039 if name.trim().is_empty() || name.contains(':') || name.contains('/') || name.contains('\\') {
1040 return Err(NbError::CommandFailed(NOTEBOOK_FIELD_MESSAGE.to_string()));
1041 }
1042 Ok(())
1043}
1044
1045fn validate_folder_option(folder: Option<&str>) -> Result<(), NbError> {
1046 if let Some(path) = folder {
1047 validate_folder_path(path)?;
1048 }
1049 Ok(())
1050}
1051
1052fn validate_folder_path(path: &str) -> Result<(), NbError> {
1053 if path.trim().is_empty() || path.contains(':') {
1054 return Err(NbError::CommandFailed(FOLDER_FIELD_MESSAGE.to_string()));
1055 }
1056 Ok(())
1057}
1058
1059fn validate_destination(destination: &str) -> Result<(), NbError> {
1060 if destination.trim().is_empty() || destination.contains(':') {
1061 return Err(NbError::CommandFailed(
1062 "Invalid destination: use a folder path or filename only, not a notebook-qualified selector."
1063 .to_string(),
1064 ));
1065 }
1066 Ok(())
1067}
1068
1069fn parse_qualified_selector(selector: &str) -> Result<Option<(&str, &str)>, NbError> {
1070 let Some((notebook, path)) = selector.split_once(':') else {
1071 return Ok(None);
1072 };
1073 validate_notebook_name(notebook)?;
1074 if path.trim().is_empty() || path.contains(':') {
1075 return Err(NbError::CommandFailed(
1076 "Invalid selector: use at most one notebook qualifier, as `<notebook>:<folder>/<id>`."
1077 .to_string(),
1078 ));
1079 }
1080 Ok(Some((notebook, path)))
1081}
1082
1083fn detect_duplicate_title_heading(title: &str, content: &str) -> Option<String> {
1107 let trimmed_title = title.trim();
1108 if trimmed_title.is_empty() {
1109 return None;
1110 }
1111 let first_nonblank = content.lines().find(|line| !line.trim().is_empty())?;
1112 let bytes = first_nonblank.as_bytes();
1113
1114 let leading_spaces = bytes.iter().take_while(|&&b| b == b' ').count();
1116 if leading_spaces >= 4 {
1117 return None;
1118 }
1119 let after_indent = &first_nonblank[leading_spaces..];
1120
1121 if !after_indent.starts_with('#') {
1123 return None;
1124 }
1125 if after_indent.starts_with("##") {
1126 return None;
1127 }
1128 let after_hash = &after_indent[1..];
1129
1130 let after_hash_bytes = after_hash.as_bytes();
1136 let rest = match after_hash_bytes.first() {
1137 Some(b' ') | Some(b'\t') => &after_hash[1..],
1138 None => "",
1139 Some(_) => return None,
1140 };
1141
1142 let heading_text = strip_atx_closing_hashes(rest);
1144
1145 if heading_text.trim() == trimmed_title {
1146 Some(first_nonblank.to_string())
1147 } else {
1148 None
1149 }
1150}
1151
1152fn strip_atx_closing_hashes(s: &str) -> String {
1165 let bytes = s.as_bytes();
1166 let n = bytes.len();
1167
1168 let mut end = n;
1170 while end > 0 && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
1171 end -= 1;
1172 }
1173 if end == 0 || bytes[end - 1] != b'#' {
1174 return s.to_string();
1175 }
1176
1177 let mut hash_start = end;
1179 while hash_start > 0 && bytes[hash_start - 1] == b'#' {
1180 hash_start -= 1;
1181 }
1182
1183 if hash_start == 0 {
1193 return s[..0].to_string();
1194 }
1195 let prev = bytes[hash_start - 1];
1196 if prev != b' ' && prev != b'\t' {
1197 return s.to_string();
1198 }
1199
1200 s[..hash_start].to_string()
1201}
1202
1203fn edit_args(selector: String, content: &str, mode: EditMode) -> Vec<String> {
1204 let mut args = vec!["edit".to_string(), selector];
1205 match mode {
1206 EditMode::Overwrite => args.push("--overwrite".to_string()),
1207 EditMode::Append => {}
1208 EditMode::Prepend => args.push("--prepend".to_string()),
1209 }
1210 args.push("--content".to_string());
1211 args.push(content.to_string());
1212 args
1213}
1214
1215fn task_command_args(action: &str, selector: String, task_number: Option<u32>) -> Vec<String> {
1216 let mut args = vec![action.to_string(), selector];
1217 if let Some(number) = task_number {
1218 args.push(number.to_string());
1219 }
1220 args
1221}
1222
1223fn todo_command_args(
1224 notebook: &str,
1225 title: &str,
1226 description: Option<&str>,
1227 tasks: &[String],
1228 tags: &[String],
1229 folder: Option<&str>,
1230) -> Vec<String> {
1231 let mut args = vec![format!("{notebook}:todo"), "add".to_string()];
1232
1233 if let Some(folder) = folder {
1235 args.push(folder_scope(folder));
1236 }
1237
1238 args.push(title.to_string());
1239
1240 if let Some(description) = description {
1241 args.push("--description".to_string());
1242 args.push(description.to_string());
1243 }
1244
1245 for task in tasks {
1246 args.push("--task".to_string());
1247 args.push(task.to_string());
1248 }
1249
1250 for tag in tags {
1251 args.push("--tags".to_string());
1252 args.push(normalize_tag(tag));
1253 }
1254
1255 args
1256}
1257
1258fn folder_scope(folder: &str) -> String {
1259 if folder.ends_with('/') {
1260 folder.to_string()
1261 } else {
1262 format!("{folder}/")
1263 }
1264}
1265
1266fn normalize_tag(tag: &str) -> String {
1267 if tag.starts_with('#') {
1268 tag.to_string()
1269 } else {
1270 format!("#{tag}")
1271 }
1272}
1273
1274fn normalize_folder(folder: &str) -> String {
1275 folder.trim_matches('/').to_string()
1276}
1277
1278fn mkdir_selector(notebook: &str, path: &str) -> String {
1279 let normalized = normalize_folder(path);
1280 format!("{}:{}", notebook, normalized)
1281}
1282
1283fn tasks_scope(notebook: &str, folder: Option<&str>) -> String {
1284 match folder {
1285 Some(path) if !path.is_empty() => format!("{}:{}/", notebook, path),
1286 _ => format!("{}:", notebook),
1287 }
1288}
1289
1290fn tasks_command_args(scope: String, status: Option<TaskStatus>) -> Vec<String> {
1291 let mut args = vec!["tasks".to_string(), scope];
1292 if let Some(filter) = status {
1293 let status = match filter {
1294 TaskStatus::Open => "open",
1295 TaskStatus::Closed => "closed",
1296 };
1297 args.push(status.to_string());
1298 }
1299 args.push("--no-color".to_string());
1300 args
1301}
1302
1303fn search_command_args(
1304 scope: String,
1305 queries: &[String],
1306 mode: SearchMode,
1307 tags: &[String],
1308) -> Vec<String> {
1309 let mut args = vec!["search".to_string(), scope];
1310 let mut terms = queries.iter();
1311 if let Some(first) = terms.next() {
1312 args.push(first.to_string());
1313 }
1314 match mode {
1315 SearchMode::Any => {
1316 for query in terms {
1317 args.push("--or".to_string());
1318 args.push(query.to_string());
1319 }
1320 }
1321 SearchMode::All => {
1322 for query in terms {
1323 args.push(query.to_string());
1324 }
1325 }
1326 }
1327 for tag in tags {
1328 args.push("--tag".to_string());
1329 args.push(normalize_tag(tag));
1330 }
1331 args.push("--no-color".to_string());
1332 args
1333}
1334
1335fn is_empty_tasks_error(message: &str) -> bool {
1336 message.trim_start().starts_with("! 0 ") && message.contains(" tasks.")
1337}
1338
1339fn empty_tasks_message(status: Option<TaskStatus>) -> String {
1340 match status {
1341 Some(TaskStatus::Open) => "! 0 open tasks.".to_string(),
1342 Some(TaskStatus::Closed) => "! 0 closed tasks.".to_string(),
1343 None => "! 0 tasks.".to_string(),
1344 }
1345}
1346
1347fn child_folder_names(path: &std::path::Path) -> Result<Vec<String>, NbError> {
1348 let read_dir = match std::fs::read_dir(path) {
1349 Ok(entries) => entries,
1350 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1351 Err(err) => return Err(NbError::Io(err)),
1352 };
1353
1354 let mut names = Vec::new();
1355 for entry in read_dir {
1356 let entry = entry?;
1357 let Some(name) = entry.file_name().to_str().map(|value| value.to_string()) else {
1358 continue;
1359 };
1360 if name.starts_with('.') {
1361 continue;
1362 }
1363 let meta = match entry.metadata() {
1364 Ok(meta) => meta,
1365 Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
1366 Err(err) => return Err(NbError::Io(err)),
1367 };
1368 if meta.is_dir() {
1369 names.push(name);
1370 }
1371 }
1372 names.sort();
1373 Ok(names)
1374}
1375
1376const GIT_SIGNING_OVERRIDES: [(&str, &str); 2] =
1377 [("commit.gpgsign", "false"), ("tag.gpgsign", "false")];
1378
1379fn git_signing_env_vars(start_index: usize) -> Vec<(String, String)> {
1380 let total = start_index.saturating_add(GIT_SIGNING_OVERRIDES.len());
1381 let mut env_vars = Vec::with_capacity(1 + GIT_SIGNING_OVERRIDES.len() * 2);
1382 env_vars.push(("GIT_CONFIG_COUNT".to_string(), total.to_string()));
1383 for (offset, (key, value)) in GIT_SIGNING_OVERRIDES.iter().enumerate() {
1384 let index = start_index + offset;
1385 env_vars.push((format!("GIT_CONFIG_KEY_{index}"), (*key).to_string()));
1386 env_vars.push((format!("GIT_CONFIG_VALUE_{index}"), (*value).to_string()));
1387 }
1388 env_vars
1389}
1390
1391fn apply_git_signing_env(command: &mut Command) {
1392 for (name, value) in git_signing_env_vars(0) {
1404 command.env(name, value);
1405 }
1406}