1use std::path::{Path, PathBuf};
2
3use crate::argv::search_command_args;
4use crate::error::NbError;
5use crate::fingerprint;
6use crate::gate;
7use crate::lines::{
8 document_lines, note_line_from_body_line, require_contiguous_body,
9 search_lines,
10};
11use crate::output::strip_empty_result_hint;
12use crate::parser::{ParseContext, parse};
13use crate::types::{
14 BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
15};
16use crate::validate::validate_folder_option;
17use crate::{NbClient, SearchMode};
18
19impl NbClient {
20 pub async fn show_notebook_status(
27 &self,
28 notebook: Option<&str>,
29 ) -> Result<String, NbError> {
30 let name = self.resolve_notebook_name(notebook)?;
31 let root = self.native_notebook_root(&name).await?;
32 self.with_notebook_gate_native(&root, async {
33 let status = crate::git::notebook_status_porcelain(&root)?;
34 if crate::git::status_is_index_only(&status) {
35 return Ok(format!(
36 "{status}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
37 ));
38 }
39 Ok(status)
40 })
41 .await
42 }
43
44 pub async fn list_notebooks(&self) -> Result<String, NbError> {
46 let _g = gate::acquire_global(self.gate_timeout).await?;
47 self.exec(&["notebooks", "--no-color"]).await
49 }
50
51 pub async fn show_notebook_path(
53 &self,
54 notebook: Option<&str>,
55 ) -> Result<PathBuf, NbError> {
56 let notebook = self.resolve_notebook_name(notebook)?;
57 self.ensure_notebook(¬ebook).await?;
58 self.with_notebook_gate(
59 ¬ebook,
60 self.show_notebook_path_unguarded(Some(¬ebook)),
61 )
62 .await
63 }
64
65 pub async fn show_note(
71 &self,
72 id: &str,
73 notebook: Option<&str>,
74 ) -> Result<ShowNote, NbError> {
75 let (notebook, display, input, exact) = self
76 .resolve_read_identity(&NoteTarget::selector(id), notebook)
77 .await?;
78 let root = self.native_notebook_root(¬ebook).await?;
81 self.with_notebook_gate_native(&root, async {
82 self.show_note_native_inside(
83 ¬ebook, &display, &input, exact, &root,
84 )
85 .await
86 })
87 .await
88 }
89
90 async fn resolve_read_identity(
97 &self,
98 target: &NoteTarget,
99 notebook: Option<&str>,
100 ) -> Result<(String, String, String, bool), NbError> {
101 let (name, input, exact): (String, &str, bool) = match target {
104 NoteTarget::Selector { value } => {
105 match crate::validate::parse_qualified_selector(value)? {
106 Some((embedded, path)) => {
107 if let Some(field) = notebook {
108 crate::validate::validate_notebook_name(field)?;
109 if field != embedded {
110 return Err(NbError::ValidationError {
111 reason: format!(
112 "ambiguous selector: id targets notebook `{embedded}`, but notebook field is `{field}`"
113 ),
114 location: None,
115 });
116 }
117 }
118 (embedded.to_string(), path, false)
119 },
120 None => (
121 self.resolve_notebook_name(notebook)?,
122 value.as_str(),
123 false,
124 ),
125 }
126 },
127 NoteTarget::Path { value } => {
128 (self.resolve_notebook_name(notebook)?, value.as_str(), true)
129 },
130 };
131 let display = format!("{name}:{input}");
132 Ok((name, display, input.to_string(), exact))
133 }
134
135 fn map_native_miss(display: &str) -> impl Fn(NbError) -> NbError + '_ {
138 move |e| match e {
139 NbError::NotFound { .. } => NbError::NotFound {
140 selector: display.to_string(),
141 },
142 other => other,
143 }
144 }
145
146 pub(super) async fn native_notebook_root(
152 &self,
153 notebook: &str,
154 ) -> Result<PathBuf, NbError> {
155 match notebook_dir_from_env(notebook, self.require_explicit_nb_dir)? {
156 Some(path) => Ok(path),
157 None => Err(NbError::NotFound {
158 selector: format!("{notebook}:"),
159 }),
160 }
161 }
162
163 pub async fn classify(
170 &self,
171 id: &str,
172 notebook: Option<&str>,
173 ) -> Result<crate::Classify, NbError> {
174 let (notebook, display, input, exact) = self
175 .resolve_read_identity(&NoteTarget::selector(id), notebook)
176 .await?;
177 let root = self.native_notebook_root(¬ebook).await?;
178 self.with_notebook_gate_native(&root, async {
179 let rel = if exact {
180 crate::native::resolve_exact(&root, &input)
181 } else {
182 crate::native::resolve_selector(&root, &input)
183 }
184 .map_err(Self::map_native_miss(&display))?;
185 let abs = root.join(&rel);
186 let abs = crate::native::confine_canonical(&root, &abs, &display)?;
187 let class = crate::native::classify_path(&abs, &rel)?;
188 let kind = crate::native::entity_kind_for_rel(&rel, &class);
189 let selector =
190 crate::native::canonical_selector(¬ebook, &root, &rel)?;
191 let numeric_id = crate::native::numeric_id_for_rel(&root, &rel)?;
192 Ok(crate::Classify {
193 kind,
194 path: rel,
195 selector,
196 numeric_id,
197 })
198 })
199 .await
200 }
201
202 async fn show_note_native_inside(
210 &self,
211 notebook: &str,
212 display: &str,
213 input: &str,
214 exact: bool,
215 root: &Path,
216 ) -> Result<ShowNote, NbError> {
217 let rel = if exact {
218 crate::native::resolve_exact(root, input)
219 } else {
220 crate::native::resolve_selector(root, input)
221 }
222 .map_err(Self::map_native_miss(display))?;
223 let abs = root.join(&rel);
224 let abs = crate::native::confine_canonical(root, &abs, display)?;
225 match crate::native::classify_path(&abs, &rel)? {
226 crate::native::NativeClass::Folder => {
227 return Err(NbError::UnsupportedShowTarget {
228 selector: display.to_string(),
229 actual_type: "folder".to_string(),
230 });
231 },
232 crate::native::NativeClass::NonTextual { ext } => {
233 return Err(NbError::UnsupportedShowTarget {
234 selector: display.to_string(),
235 actual_type: ext,
236 });
237 },
238 crate::native::NativeClass::Text => {},
239 }
240 self.show_note_from_path(notebook, display, root, &abs)
241 .await
242 }
243
244 async fn show_note_from_path(
251 &self,
252 notebook: &str,
253 display: &str,
254 root: &Path,
255 path: &Path,
256 ) -> Result<ShowNote, NbError> {
257 let rel = path_relative_to(root, path)?;
258 let source = std::fs::read(path).map_err(|e| NbError::Io {
259 path: path.to_path_buf(),
260 source: e.into(),
261 })?;
262 let canonical =
263 crate::native::canonical_selector(notebook, root, &rel)?;
264 let numeric_id = crate::native::numeric_id_for_rel(root, &rel)?;
265 Self::assemble_show_note(display, &canonical, numeric_id, rel, source)
266 }
267 fn assemble_show_note(
272 diagnostic: &str,
273 canonical: &str,
274 numeric_id: Option<u32>,
275 rel: String,
276 source: Vec<u8>,
277 ) -> Result<ShowNote, NbError> {
278 let doc = match parse(
279 &source,
280 ParseContext::FromPath(PathBuf::from(&rel)),
281 ) {
282 Ok(doc) => doc,
283 Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
286 &source,
287 ParseContext::Explicit(crate::DocumentKind::Note),
288 )?,
289 Err(err) => return Err(err),
290 };
291 let kind_str = format!("{:?}", doc.kind()).to_lowercase();
292 let non_utf8 = |path: String| NbError::NonUtf8 {
293 selector: diagnostic.to_string(),
294 path,
295 kind: kind_str.clone(),
296 mime_hint: None,
297 };
298 let source_str = std::str::from_utf8(&source)
299 .map_err(|_| non_utf8(rel.clone()))?
300 .to_string();
301 let ranges = doc.body_ranges();
303 let mut fragments: Vec<BodyFragment> =
304 Vec::with_capacity(ranges.len());
305 for (i, span) in ranges.iter().enumerate() {
306 let bytes = std::str::from_utf8(&source[span.clone()])
307 .map_err(|_| non_utf8(rel.clone()))?
308 .to_string();
309 fragments.push(BodyFragment {
310 index: i as u32,
311 bytes,
312 start_byte: span.start as u32,
313 end_byte: span.end as u32,
314 });
315 }
316 let body_contiguous = fragments.len() <= 1;
317 let body_bytes = doc.body_bytes();
318 let body = std::str::from_utf8(&body_bytes)
319 .map_err(|_| non_utf8(rel.clone()))?
320 .to_string();
321 let tags: Vec<String> = doc
323 .tags()
324 .map(|t| {
325 String::from_utf8_lossy(t)
326 .trim_start_matches('#')
327 .to_string()
328 })
329 .collect();
330 let title = doc
331 .title()
332 .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
333 .transpose()
334 .map_err(|_| non_utf8(rel.clone()))?;
335 let title_text = doc.title().map(|bytes| {
336 let s = String::from_utf8_lossy(bytes);
337 s.trim_end_matches('\n')
338 .trim_start_matches('#')
339 .trim()
340 .to_string()
341 });
342 Ok(ShowNote {
343 selector: canonical.to_string(),
344 path: rel.clone(),
345 kind: doc.kind(),
346 todo_state: doc.todo_state(),
347 title,
348 title_text,
349 tags,
350 body_fragments: fragments,
351 body_contiguous,
352 body,
353 fingerprint: fingerprint::fingerprint(&doc),
354 source: source_str,
355 numeric_id,
356 })
357 }
358
359 pub async fn read_note_source_bytes(
364 &self,
365 target: NoteTarget,
366 notebook: Option<&str>,
367 ) -> Result<Vec<u8>, NbError> {
368 let (notebook, display, input, exact) =
372 self.resolve_read_identity(&target, notebook).await?;
373 let root = self.native_notebook_root(¬ebook).await?;
376 self.with_notebook_gate_native(&root, async {
377 let rel = if exact {
378 crate::native::resolve_exact(&root, &input)
379 } else {
380 crate::native::resolve_selector(&root, &input)
381 }
382 .map_err(Self::map_native_miss(&display))?;
383 let abs = root.join(&rel);
384 let abs = crate::native::confine_canonical(&root, &abs, &display)?;
385 std::fs::read(&abs).map_err(|e| NbError::Io {
386 path: abs.clone(),
387 source: e.into(),
388 })
389 })
390 .await
391 }
392
393 pub async fn show_note_lines(
395 &self,
396 target: NoteTarget,
397 offset: Option<u32>,
398 limit: Option<u32>,
399 notebook: Option<&str>,
400 ) -> Result<ShowNoteLines, NbError> {
401 let (notebook, display, input, exact) =
404 self.resolve_read_identity(&target, notebook).await?;
405 let root = self.native_notebook_root(¬ebook).await?;
408 self.with_notebook_gate_native(&root, async {
409 let shown = self
410 .show_note_native_inside(
411 ¬ebook, &display, &input, exact, &root,
412 )
413 .await?;
414 Self::show_lines_window(shown, offset, limit)
415 })
416 .await
417 }
418
419 fn show_lines_window(
422 shown: ShowNote,
423 offset: Option<u32>,
424 limit: Option<u32>,
425 ) -> Result<ShowNoteLines, NbError> {
426 let source = shown.source.as_bytes().to_vec();
427 let doc = parse(
428 &source,
429 ParseContext::FromPath(PathBuf::from(&shown.path)),
430 )?;
431 let body = require_contiguous_body(&doc)?;
432 let (eol, has_final_eol, lines) = document_lines(&body);
433 let total_lines = lines.len() as u32;
434 let offset = offset.unwrap_or(1);
435 let limit = limit.unwrap_or(100);
436 if offset == 0 {
437 return Err(NbError::InvalidLineWindow {
438 offset,
439 limit,
440 total_lines,
441 });
442 }
443 if total_lines == 0 {
444 if offset != 1 {
445 return Err(NbError::InvalidLineWindow {
446 offset,
447 limit,
448 total_lines,
449 });
450 }
451 return Ok(ShowNoteLines {
452 selector: shown.selector,
453 path: shown.path,
454 kind: shown.kind,
455 total_lines: 0,
456 offset,
457 limit,
458 next_offset: None,
459 lines: Vec::new(),
460 title: shown.title,
461 tags: shown.tags,
462 body_fingerprint: shown.fingerprint,
463 eol: None,
464 has_final_eol: false,
465 numeric_id: shown.numeric_id,
466 });
467 }
468 if offset > total_lines + 1 {
469 return Err(NbError::InvalidLineWindow {
470 offset,
471 limit,
472 total_lines,
473 });
474 }
475 let start_idx = (offset - 1) as usize;
476 let end_idx = (start_idx + limit as usize).min(lines.len());
477 let window: Vec<_> = lines[start_idx..end_idx]
478 .iter()
479 .map(|l| note_line_from_body_line(l, &body))
480 .collect();
481 let next_offset = if end_idx < lines.len() {
482 Some(offset + window.len() as u32)
483 } else {
484 None
485 };
486 Ok(ShowNoteLines {
487 selector: shown.selector,
488 path: shown.path,
489 kind: shown.kind,
490 total_lines,
491 offset,
492 limit,
493 next_offset,
494 lines: window,
495 title: shown.title,
496 tags: shown.tags,
497 body_fingerprint: shown.fingerprint,
498 eol,
499 has_final_eol,
500 numeric_id: shown.numeric_id,
501 })
502 }
503
504 pub async fn search_note_lines(
506 &self,
507 target: NoteTarget,
508 pattern: &str,
509 notebook: Option<&str>,
510 ) -> Result<SearchNoteLines, NbError> {
511 let (notebook, display, input, exact) =
514 self.resolve_read_identity(&target, notebook).await?;
515 let root = self.native_notebook_root(¬ebook).await?;
518 let pattern = pattern.to_string();
521 self.with_notebook_gate_native(&root, async {
522 let shown = self
523 .show_note_native_inside(
524 ¬ebook, &display, &input, exact, &root,
525 )
526 .await?;
527 Self::search_lines_hits(shown, &pattern)
528 })
529 .await
530 }
531
532 fn search_lines_hits(
535 shown: ShowNote,
536 pattern: &str,
537 ) -> Result<SearchNoteLines, NbError> {
538 let source = shown.source.as_bytes().to_vec();
539 let doc = parse(
540 &source,
541 ParseContext::FromPath(PathBuf::from(&shown.path)),
542 )?;
543 let body = require_contiguous_body(&doc)?;
544 let hits = search_lines(&body, pattern.as_bytes())?;
545 Ok(SearchNoteLines {
546 selector: shown.selector,
547 path: shown.path,
548 kind: shown.kind,
549 hits,
550 body_fingerprint: shown.fingerprint,
551 })
552 }
553
554 pub async fn list_notes(
556 &self,
557 folder: Option<&str>,
558 tags: &[String],
559 limit: Option<u32>,
560 notebook: Option<&str>,
561 ) -> Result<String, NbError> {
562 let mut args = Vec::new();
563 validate_folder_option(folder)?;
564
565 let notebook = self.resolve_notebook(notebook).await?;
566 let cmd = match folder {
567 Some(f) => format!("{}:{}/", notebook, f),
568 None => format!("{}:", notebook),
569 };
570
571 args.push("list".to_string());
572 args.push(cmd);
573
574 args.push("--no-color".to_string());
576
577 if let Some(n) = limit {
579 args.push("-n".to_string());
580 args.push(n.to_string());
581 }
582
583 for tag in tags {
585 args.push("--tags".to_string());
586 let tag_str = if tag.starts_with('#') {
587 tag.clone()
588 } else {
589 format!("#{}", tag)
590 };
591 args.push(tag_str);
592 }
593
594 self.exec_vec(args)
601 .await
602 .map(|output| strip_empty_result_hint(&output))
603 }
604
605 pub async fn search_notes(
607 &self,
608 queries: &[String],
609 mode: SearchMode,
610 tags: &[String],
611 folder: Option<&str>,
612 notebook: Option<&str>,
613 ) -> Result<String, NbError> {
614 validate_folder_option(folder)?;
615 if queries.is_empty() {
616 return Err(NbError::ValidationError {
617 reason: "at least one search query is required".to_string(),
618 location: None,
619 });
620 }
621
622 let notebook = self.resolve_notebook(notebook).await?;
623 let scope = match folder {
624 Some(f) => format!("{}:{}/", notebook, f),
625 None => format!("{}:", notebook),
626 };
627 let args = search_command_args(scope, queries, mode, tags);
628 self.exec_vec(args).await
629 }
630
631 pub async fn search_notes_typed(
638 &self,
639 queries: &[String],
640 mode: SearchMode,
641 tags: &[String],
642 folder: Option<&str>,
643 notebook: Option<&str>,
644 ) -> Result<Vec<crate::ListEntry>, NbError> {
645 validate_folder_option(folder)?;
646 if queries.is_empty() {
647 return Err(NbError::ValidationError {
648 reason: "at least one search query is required".to_string(),
649 location: None,
650 });
651 }
652 let notebook = self.resolve_notebook_name(notebook)?;
653 let root = self.native_notebook_root(¬ebook).await?;
654 let scope = folder.unwrap_or_default().to_string();
657 let lowered: Vec<String> =
658 queries.iter().map(|q| q.to_lowercase()).collect();
659 self.with_notebook_gate_native(&root, async {
660 let mut out = Vec::new();
661 for rel in crate::scope::scope_files_recursive(&root, &scope)? {
662 let abs = root.join(&rel);
663 let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
664 path: abs.clone(),
665 source: e.into(),
666 })?;
667 if !matches!(
670 crate::native::classify_path(&abs, &rel)?,
671 crate::native::NativeClass::Text
672 ) {
673 continue;
674 }
675 if !Self::tags_match(&bytes, &rel, tags) {
676 continue;
677 }
678 let doc = match parse(
679 &bytes,
680 ParseContext::FromPath(rel.clone().into()),
681 ) {
682 Ok(doc) => doc,
683 Err(_) => continue,
684 };
685 let mut haystack = String::new();
686 if let Some(title) = doc.title() {
687 haystack.push_str(&String::from_utf8_lossy(title));
688 haystack.push('\n');
689 }
690 haystack.push_str(&String::from_utf8_lossy(&doc.body_bytes()));
691 let haystack = haystack.to_lowercase();
692 let matched = match mode {
693 SearchMode::Any => {
694 lowered.iter().any(|q| haystack.contains(q))
695 },
696 SearchMode::All => {
697 lowered.iter().all(|q| haystack.contains(q))
698 },
699 };
700 if !matched {
701 continue;
702 }
703 out.push(self.list_entry_for(¬ebook, &root, &rel).await?);
704 }
705 Ok(out)
706 })
707 .await
708 }
709
710 pub(super) async fn list_entry_for(
715 &self,
716 notebook: &str,
717 root: &Path,
718 rel: &str,
719 ) -> Result<crate::ListEntry, NbError> {
720 let abs = root.join(rel);
721 let display = format!("{notebook}:{rel}");
722 let abs = crate::native::confine_canonical(root, &abs, &display)?;
723 let class = crate::native::classify_path(&abs, rel)?;
724 let kind = crate::native::entity_kind_for_rel(rel, &class);
725 let selector = crate::native::canonical_selector(notebook, root, rel)?;
726 let numeric_id = crate::native::numeric_id_for_rel(root, rel)?;
727 Ok(crate::ListEntry {
728 selector,
729 path: rel.to_string(),
730 kind,
731 numeric_id,
732 })
733 }
734
735 fn tags_match(bytes: &[u8], rel: &str, tags: &[String]) -> bool {
738 if tags.is_empty() {
739 return true;
740 }
741 let doc = match parse(bytes, ParseContext::FromPath(rel.into())) {
742 Ok(doc) => doc,
743 Err(_) => return false,
744 };
745 let have: Vec<String> = doc
746 .tags()
747 .map(|t| {
748 String::from_utf8_lossy(t)
749 .trim_start_matches('#')
750 .to_string()
751 })
752 .collect();
753 tags.iter().all(|wanted| {
754 let want = wanted.trim_start_matches('#');
755 have.iter().any(|got| got == want)
756 })
757 }
758
759 pub async fn list_notes_typed(
766 &self,
767 folder: Option<&str>,
768 tags: &[String],
769 limit: Option<u32>,
770 notebook: Option<&str>,
771 ) -> Result<Vec<crate::ListEntry>, NbError> {
772 validate_folder_option(folder)?;
773 let notebook = self.resolve_notebook_name(notebook)?;
774 let root = self.native_notebook_root(¬ebook).await?;
775 let scope = folder.unwrap_or_default().to_string();
778 self.with_notebook_gate_native(&root, async {
779 let mut out = Vec::new();
780 for rel in crate::scope::scope_files(&root, &scope)? {
781 if let Some(n) = limit
782 && out.len() >= n as usize
783 {
784 break;
785 }
786 let abs = root.join(&rel);
787 let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
788 path: abs.clone(),
789 source: e.into(),
790 })?;
791 if !Self::tags_match(&bytes, &rel, tags) {
792 continue;
793 }
794 out.push(self.list_entry_for(¬ebook, &root, &rel).await?);
795 }
796 Ok(out)
797 })
798 .await
799 }
800}
801
802pub(super) fn notebook_dir_from_env(
810 notebook: &str,
811 strict: bool,
812) -> Result<Option<PathBuf>, NbError> {
813 let nb_dir = crate::nbrc::resolve_store_dir(strict)?;
814 let path = nb_dir.join(notebook);
815 match std::fs::metadata(&path) {
820 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
821 Err(e) => Err(NbError::Io {
822 path: path.clone(),
823 source: e.into(),
824 }),
825 Ok(m) if !m.is_dir() => Ok(None),
826 Ok(_) => match std::fs::metadata(path.join(".git")) {
827 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
828 Err(e) => Err(NbError::Io {
829 path: path.join(".git"),
830 source: e.into(),
831 }),
832 Ok(_) => Ok(Some(path)),
833 },
834 }
835}
836
837pub(super) fn path_relative_to(
838 root: &Path,
839 path: &Path,
840) -> Result<String, NbError> {
841 let root = root.canonicalize().map_err(|e| NbError::Io {
842 path: root.to_path_buf(),
843 source: e.into(),
844 })?;
845 let path = path.canonicalize().map_err(|e| NbError::Io {
846 path: path.to_path_buf(),
847 source: e.into(),
848 })?;
849 let rel =
850 path.strip_prefix(&root)
851 .map_err(|_| NbError::ValidationError {
852 reason: format!(
853 "path {} is not under notebook root {}",
854 path.display(),
855 root.display()
856 ),
857 location: None,
858 })?;
859 #[cfg(windows)]
864 {
865 Ok(rel.to_string_lossy().replace('\\', "/"))
866 }
867 #[cfg(not(windows))]
868 {
869 Ok(rel.to_string_lossy().into_owned())
870 }
871}