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