1use std::path::{Path, PathBuf};
2
3use crate::argv::search_command_args;
4use crate::diagnostics::is_selector_not_found;
5use crate::error::NbError;
6use crate::fingerprint;
7use crate::gate;
8use crate::lines::{
9 document_lines, note_line_from_body_line, require_contiguous_body,
10 search_lines,
11};
12use crate::output::strip_empty_result_hint;
13use crate::parser::{ParseContext, parse};
14use crate::transaction;
15use crate::types::{
16 BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
17};
18use crate::validate::validate_folder_option;
19use crate::{NbClient, SearchMode};
20
21use super::core::ShowClassification;
22
23impl NbClient {
24 pub async fn show_notebook_status(
37 &self,
38 notebook: Option<&str>,
39 ) -> Result<String, NbError> {
40 let name = self.resolve_notebook_name(notebook)?;
41 let index_only = notebook_dir_from_env(&name)
44 .map(|root| {
45 crate::git::notebook_status_porcelain(&root)
46 .map(|s| crate::git::status_is_index_only(&s))
47 .unwrap_or(false)
48 })
49 .unwrap_or(false);
50 let notebook = self.resolve_notebook(Some(&name)).await?;
51 let output = self
52 .exec_vec(vec![format!("{}:", notebook), "status".to_string()])
53 .await?;
54 if index_only {
55 return Ok(format!(
56 "{output}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
57 ));
58 }
59 Ok(output)
60 }
61
62 pub async fn list_notebooks(&self) -> Result<String, NbError> {
64 let _g = gate::acquire_global(self.gate_timeout).await?;
65 self.exec(&["notebooks", "--no-color"]).await
67 }
68
69 pub async fn show_notebook_path(
71 &self,
72 notebook: Option<&str>,
73 ) -> Result<PathBuf, NbError> {
74 let notebook = self.resolve_notebook_name(notebook)?;
75 self.ensure_notebook(¬ebook).await?;
76 self.with_notebook_gate(
77 ¬ebook,
78 self.show_notebook_path_unguarded(Some(¬ebook)),
79 )
80 .await
81 }
82
83 pub async fn show_note(
85 &self,
86 id: &str,
87 notebook: Option<&str>,
88 ) -> Result<ShowNote, NbError> {
89 let (notebook, selector) =
90 self.resolve_target_selector(id, notebook).await?;
91 self.with_notebook_gate(¬ebook, async {
92 self.show_note_inner(¬ebook, &selector).await
93 })
94 .await
95 }
96
97 async fn show_note_inner(
98 &self,
99 notebook: &str,
100 selector: &str,
101 ) -> Result<ShowNote, NbError> {
102 match self.probe_show_classification(selector).await {
103 ShowClassification::NonTextual { actual_type } => {
104 return Err(NbError::UnsupportedShowTarget {
105 selector: selector.to_string(),
106 actual_type,
107 });
108 },
109 ShowClassification::Textual | ShowClassification::ProbeFailure => {
110 },
111 }
112 let path = self.resolve_item_path(selector).await?;
113 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
114 let rel = path_relative_to(&root, &path)?;
115 let source = std::fs::read(&path).map_err(|e| NbError::Io {
116 path: path.clone(),
117 source: e.into(),
118 })?;
119 let doc = match parse(
120 &source,
121 ParseContext::FromPath(PathBuf::from(&rel)),
122 ) {
123 Ok(doc) => doc,
124 Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
127 &source,
128 ParseContext::Explicit(crate::DocumentKind::Note),
129 )?,
130 Err(err) => return Err(err),
131 };
132 let kind_str = format!("{:?}", doc.kind()).to_lowercase();
133 let non_utf8 = |path: String| NbError::NonUtf8 {
134 selector: selector.to_string(),
135 path,
136 kind: kind_str.clone(),
137 mime_hint: None,
138 };
139 let source_str = std::str::from_utf8(&source)
140 .map_err(|_| non_utf8(rel.clone()))?
141 .to_string();
142 let ranges = doc.body_ranges();
144 let mut fragments: Vec<BodyFragment> =
145 Vec::with_capacity(ranges.len());
146 for (i, span) in ranges.iter().enumerate() {
147 let bytes = std::str::from_utf8(&source[span.clone()])
148 .map_err(|_| non_utf8(rel.clone()))?
149 .to_string();
150 fragments.push(BodyFragment {
151 index: i as u32,
152 bytes,
153 start_byte: span.start as u32,
154 end_byte: span.end as u32,
155 });
156 }
157 let body_contiguous = fragments.len() <= 1;
158 let body_bytes = doc.body_bytes();
159 let body = std::str::from_utf8(&body_bytes)
160 .map_err(|_| non_utf8(rel.clone()))?
161 .to_string();
162 let tags: Vec<String> = doc
164 .tags()
165 .map(|t| {
166 String::from_utf8_lossy(t)
167 .trim_start_matches('#')
168 .to_string()
169 })
170 .collect();
171 let title = doc
172 .title()
173 .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
174 .transpose()
175 .map_err(|_| non_utf8(rel.clone()))?;
176 let title_text = doc.title().map(|bytes| {
177 let s = String::from_utf8_lossy(bytes);
178 s.trim_end_matches('\n')
179 .trim_start_matches('#')
180 .trim()
181 .to_string()
182 });
183 Ok(ShowNote {
184 selector: numeric_selector_for_path(
185 notebook, &root, &rel, selector,
186 ),
187 path: rel.clone(),
188 kind: doc.kind(),
189 todo_state: doc.todo_state(),
190 title,
191 title_text,
192 tags,
193 body_fragments: fragments,
194 body_contiguous,
195 body,
196 fingerprint: fingerprint::fingerprint(&doc),
197 source: source_str,
198 numeric_id: numeric_id_for_path(&root, &rel),
199 })
200 }
201
202 pub async fn read_note_source_bytes(
207 &self,
208 target: NoteTarget,
209 notebook: Option<&str>,
210 ) -> Result<Vec<u8>, NbError> {
211 let (notebook, selector) =
212 self.resolve_note_target(&target, notebook).await?;
213 self.with_notebook_gate(¬ebook, async {
214 let path = self.resolve_item_path(&selector).await?;
215 std::fs::read(&path).map_err(|e| NbError::Io {
216 path: path.clone(),
217 source: e.into(),
218 })
219 })
220 .await
221 }
222
223 pub async fn show_note_lines(
225 &self,
226 target: NoteTarget,
227 offset: Option<u32>,
228 limit: Option<u32>,
229 notebook: Option<&str>,
230 ) -> Result<ShowNoteLines, NbError> {
231 let (notebook, selector) =
232 self.resolve_note_target(&target, notebook).await?;
233 self.with_notebook_gate(¬ebook, async {
234 let shown = self.show_note_inner(¬ebook, &selector).await?;
235 let source = shown.source.as_bytes().to_vec();
236 let doc = parse(
237 &source,
238 ParseContext::FromPath(PathBuf::from(&shown.path)),
239 )?;
240 let body = require_contiguous_body(&doc)?;
241 let (eol, has_final_eol, lines) = document_lines(&body);
242 let total_lines = lines.len() as u32;
243 let offset = offset.unwrap_or(1);
244 let limit = limit.unwrap_or(100);
245 if offset == 0 {
246 return Err(NbError::InvalidLineWindow {
247 offset,
248 limit,
249 total_lines,
250 });
251 }
252 if total_lines == 0 {
253 if offset != 1 {
254 return Err(NbError::InvalidLineWindow {
255 offset,
256 limit,
257 total_lines,
258 });
259 }
260 return Ok(ShowNoteLines {
261 selector: shown.selector,
262 path: shown.path,
263 kind: shown.kind,
264 total_lines: 0,
265 offset,
266 limit,
267 next_offset: None,
268 lines: Vec::new(),
269 title: shown.title,
270 tags: shown.tags,
271 body_fingerprint: shown.fingerprint,
272 eol: None,
273 has_final_eol: false,
274 numeric_id: shown.numeric_id,
275 });
276 }
277 if offset > total_lines + 1 {
278 return Err(NbError::InvalidLineWindow {
279 offset,
280 limit,
281 total_lines,
282 });
283 }
284 let start_idx = (offset - 1) as usize;
285 let end_idx = (start_idx + limit as usize).min(lines.len());
286 let window: Vec<_> = lines[start_idx..end_idx]
287 .iter()
288 .map(|l| note_line_from_body_line(l, &body))
289 .collect();
290 let next_offset = if end_idx < lines.len() {
291 Some(offset + window.len() as u32)
292 } else {
293 None
294 };
295 Ok(ShowNoteLines {
296 selector: shown.selector,
297 path: shown.path,
298 kind: shown.kind,
299 total_lines,
300 offset,
301 limit,
302 next_offset,
303 lines: window,
304 title: shown.title,
305 tags: shown.tags,
306 body_fingerprint: shown.fingerprint,
307 eol,
308 has_final_eol,
309 numeric_id: shown.numeric_id,
310 })
311 })
312 .await
313 }
314
315 pub async fn search_note_lines(
317 &self,
318 target: NoteTarget,
319 pattern: &str,
320 notebook: Option<&str>,
321 ) -> Result<SearchNoteLines, NbError> {
322 let (notebook, selector) =
323 self.resolve_note_target(&target, notebook).await?;
324 self.with_notebook_gate(¬ebook, async {
325 let shown = self.show_note_inner(¬ebook, &selector).await?;
326 let source = shown.source.as_bytes().to_vec();
327 let doc = parse(
328 &source,
329 ParseContext::FromPath(PathBuf::from(&shown.path)),
330 )?;
331 let body = require_contiguous_body(&doc)?;
332 let hits = search_lines(&body, pattern.as_bytes())?;
333 Ok(SearchNoteLines {
334 selector: shown.selector,
335 path: shown.path,
336 kind: shown.kind,
337 hits,
338 body_fingerprint: shown.fingerprint,
339 })
340 })
341 .await
342 }
343
344 pub(super) async fn resolve_item_path(
345 &self,
346 selector: &str,
347 ) -> Result<PathBuf, NbError> {
348 let output = self
349 .exec_vec(vec![
350 "show".to_string(),
351 selector.to_string(),
352 "--path".to_string(),
353 "--no-color".to_string(),
354 ])
355 .await
356 .map_err(|err| match err {
357 NbError::CommandFailed { stderr, .. }
358 if is_selector_not_found(&stderr, selector) =>
359 {
360 NbError::NotFound {
361 selector: selector.to_string(),
362 }
363 },
364 other => other,
365 })?;
366 let path = output.trim();
367 if path.is_empty() {
368 return Err(NbError::CommandFailed {
369 command: format!("nb show {selector} --path"),
370 stderr: "empty path".into(),
371 exit_code: None,
372 });
373 }
374 Ok(PathBuf::from(path))
375 }
376
377 async fn resolve_note_target(
378 &self,
379 target: &NoteTarget,
380 notebook: Option<&str>,
381 ) -> Result<(String, String), NbError> {
382 match target {
383 NoteTarget::Selector { value } => {
384 self.resolve_target_selector(value, notebook).await
385 },
386 NoteTarget::Path { value } => {
387 let notebook = self.resolve_notebook(notebook).await?;
388 Ok((notebook.clone(), format!("{notebook}:{value}")))
389 },
390 }
391 }
392
393 async fn probe_show_classification(
405 &self,
406 selector: &str,
407 ) -> ShowClassification {
408 let textual = self
409 .exec_vec(vec![
410 "show".to_string(),
411 selector.to_string(),
412 "--type".to_string(),
413 "text".to_string(),
414 "--no-color".to_string(),
415 ])
416 .await;
417 if textual.is_ok() {
418 return ShowClassification::Textual;
419 }
420 match self
421 .exec_vec(vec![
422 "show".to_string(),
423 selector.to_string(),
424 "--type".to_string(),
425 "--no-color".to_string(),
426 ])
427 .await
428 {
429 Ok(stdout) => {
430 let trimmed = stdout.trim();
431 if trimmed.is_empty() {
432 ShowClassification::ProbeFailure
433 } else {
434 ShowClassification::NonTextual {
435 actual_type: trimmed.to_string(),
436 }
437 }
438 },
439 Err(_) => ShowClassification::ProbeFailure,
440 }
441 }
442
443 pub async fn list_notes(
445 &self,
446 folder: Option<&str>,
447 tags: &[String],
448 limit: Option<u32>,
449 notebook: Option<&str>,
450 ) -> Result<String, NbError> {
451 let mut args = Vec::new();
452 validate_folder_option(folder)?;
453
454 let notebook = self.resolve_notebook(notebook).await?;
455 let cmd = match folder {
456 Some(f) => format!("{}:{}/", notebook, f),
457 None => format!("{}:", notebook),
458 };
459
460 args.push("list".to_string());
461 args.push(cmd);
462
463 args.push("--no-color".to_string());
465
466 if let Some(n) = limit {
468 args.push("-n".to_string());
469 args.push(n.to_string());
470 }
471
472 for tag in tags {
474 args.push("--tags".to_string());
475 let tag_str = if tag.starts_with('#') {
476 tag.clone()
477 } else {
478 format!("#{}", tag)
479 };
480 args.push(tag_str);
481 }
482
483 self.exec_vec(args)
490 .await
491 .map(|output| strip_empty_result_hint(&output))
492 }
493
494 pub async fn search_notes(
496 &self,
497 queries: &[String],
498 mode: SearchMode,
499 tags: &[String],
500 folder: Option<&str>,
501 notebook: Option<&str>,
502 ) -> Result<String, NbError> {
503 validate_folder_option(folder)?;
504 if queries.is_empty() {
505 return Err(NbError::ValidationError {
506 reason: "at least one search query is required".to_string(),
507 location: None,
508 });
509 }
510
511 let notebook = self.resolve_notebook(notebook).await?;
512 let scope = match folder {
513 Some(f) => format!("{}:{}/", notebook, f),
514 None => format!("{}:", notebook),
515 };
516 let args = search_command_args(scope, queries, mode, tags);
517 self.exec_vec(args).await
518 }
519}
520
521fn numeric_id_for_path(notebook_root: &Path, rel: &str) -> Option<u32> {
524 let (folder, basename) = match rel.rfind('/') {
525 Some(i) => (rel[..i].to_string(), rel[i + 1..].to_string()),
526 None => (String::new(), rel.to_string()),
527 };
528 transaction::index_id_in_folder(notebook_root, &folder, &basename)
529}
530
531fn numeric_selector_for_path(
534 notebook: &str,
535 notebook_root: &Path,
536 rel: &str,
537 fallback: &str,
538) -> String {
539 match numeric_id_for_path(notebook_root, rel) {
540 Some(id) => match rel.rfind('/') {
541 Some(i) => format!("{notebook}:{}/{}", &rel[..i], id),
542 None => format!("{notebook}:{id}"),
543 },
544 None => fallback.to_string(),
545 }
546}
547
548pub(super) fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
549 let nb_dir = std::env::var_os("NB_DIR")?;
550 let path = PathBuf::from(nb_dir).join(notebook);
551 if path.is_dir() && path.join(".git").exists() {
552 Some(path)
553 } else {
554 None
555 }
556}
557
558pub(super) fn path_relative_to(
559 root: &Path,
560 path: &Path,
561) -> Result<String, NbError> {
562 let root = root.canonicalize().map_err(|e| NbError::Io {
563 path: root.to_path_buf(),
564 source: e.into(),
565 })?;
566 let path = path.canonicalize().map_err(|e| NbError::Io {
567 path: path.to_path_buf(),
568 source: e.into(),
569 })?;
570 let rel =
571 path.strip_prefix(&root)
572 .map_err(|_| NbError::ValidationError {
573 reason: format!(
574 "path {} is not under notebook root {}",
575 path.display(),
576 root.display()
577 ),
578 location: None,
579 })?;
580 Ok(rel.to_string_lossy().replace('\\', "/"))
581}