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