1use std::collections::VecDeque;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use serde_json::{Value, json};
9
10use aidaemon_core::{AccessManifest, ToolAnnotations};
11
12use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
13use crate::backend::{BackendMetadata, BackendPath};
14use crate::outcome::{OutcomeTool, core_tool};
15use crate::semantics::{
16 AttachmentProvenance, MessageAttachment, ReadFileResultMetadata, ReadFileSelectionMetadata,
17 ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics, ToolCapabilities,
18 ToolRole, ToolTargetHintKind, ToolVerificationMode,
19};
20use crate::workspace::Workspace;
21
22pub const MAX_READ_CHARS: usize = 100 * 1024;
26const MAX_LINE_CHARS: usize = 2_000;
29
30pub struct ReadFile {
31 backend: SharedBackend,
32 policy: Arc<dyn FilePolicy>,
33 text: ToolText,
34}
35
36impl ReadFile {
37 pub fn new(workspace: Workspace) -> Self {
39 let (backend, policy) = workspace_parts(workspace);
40 Self::on_backend(backend, policy)
41 }
42
43 pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
45 Self {
46 backend,
47 policy,
48 text: ToolText {
49 short: "Read a text file with line numbers and metadata".into(),
50 schema: "Read a file with line numbers and metadata. Read a file in full once when it fits the limit; oversized reads return the first page plus an exact continuation call to follow.".into(),
51 },
52 }
53 }
54
55 pub fn with_text(mut self, text: ToolText) -> Self {
57 self.text = text;
58 self
59 }
60}
61
62#[async_trait]
63impl OutcomeTool for ReadFile {
64 fn name(&self) -> &str {
65 "read_file"
66 }
67
68 fn description(&self) -> &str {
69 &self.text.short
70 }
71
72 fn schema(&self) -> Value {
73 json!({
74 "name": "read_file",
75 "description": self.text.schema,
76 "parameters": {
77 "type": "object",
78 "properties": {
79 "path": {
80 "type": "string",
81 "description": "Path to the file (supports ~ expansion)"
82 },
83 "start_line": {
84 "type": "integer",
85 "description": "Start line number (1-based, inclusive). Omit to start from beginning."
86 },
87 "end_line": {
88 "type": "integer",
89 "description": "End line number (1-based, inclusive). Omit to read to end."
90 },
91 "tail_lines": {
92 "type": "integer",
93 "minimum": 1,
94 "description": "Read the last N lines of the file. Useful for large logs."
95 }
96 },
97 "required": ["path"],
98 "additionalProperties": false
99 }
100 })
101 }
102
103 async fn execute(
104 &self,
105 arguments: &str,
106 facts: &ToolCallContext,
107 ) -> anyhow::Result<ToolCallOutcome> {
108 self.read_outcome(arguments, crate::semantics::file_fence(facts))
109 .await
110 }
111}
112
113core_tool!(
114 ReadFile,
115 annotations: ToolAnnotations::READ_ONLY,
116 access: |this, arguments| AccessManifest {
117 reads: path_arg(arguments)
118 .map(|path| vec![this.policy.declare_path(path)])
119 .unwrap_or_default(),
120 ..Default::default()
121 }
122);
123
124impl crate::semantics::ToolSemantics for ReadFile {
125 fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
126 crate::semantics::ToolDispatchFacts {
127 offering: crate::semantics::Offering::Core,
128 same_tool_streak: crate::semantics::SameToolStreak::Versatile,
129 file_guard: crate::semantics::FileGuard::Reads,
130 recap: crate::semantics::RecapKind::FileRead,
131 activity: crate::semantics::ToolActivity::Fixed(
132 aidaemon_core::card::ActivityKind::Read,
133 ),
134 opens_project_instructions: true,
135 status_label: Some("reading a file"),
136 result_fit: crate::semantics::ResultFit {
137 pages_spilled_results: true,
138 ..Default::default()
139 },
140 evidence: crate::semantics::EvidenceSource::FileRead,
141 semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
142 ..Default::default()
143 }
144 }
145
146 fn tool_role(&self) -> ToolRole {
147 ToolRole::Action
148 }
149
150 fn capabilities(&self) -> ToolCapabilities {
151 ToolCapabilities {
152 read_only: true,
153 external_side_effect: false,
154 needs_approval: false,
155 idempotent: true,
156 high_impact_write: false,
157 }
158 }
159
160 fn output_trust(
161 &self,
162 arguments: &str,
163 roots: &crate::semantics::TrustRoots<'_>,
164 ) -> aidaemon_core::SourceTrust {
165 crate::semantics::file_output_trust(
166 arguments,
167 &["path", "file_path", "file", "filename"],
168 roots,
169 )
170 }
171
172 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
173 let path = serde_json::from_str::<Value>(arguments)
174 .ok()
175 .and_then(|args| {
176 for key in ["path", "file_path", "file", "filename"] {
177 if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
178 return Some(path.to_string());
179 }
180 }
181 None
182 })
183 .unwrap_or_default();
184
185 ToolCallSemantics::observation()
186 .with_verification_mode(ToolVerificationMode::ResultContent)
187 .with_target_hint(ToolTargetHintKind::Path, path)
188 }
189}
190
191impl ReadFile {
192 pub(crate) async fn read_outcome(
193 &self,
194 arguments: &str,
195 fence: Option<&Arc<dyn crate::semantics::FileFence>>,
196 ) -> anyhow::Result<ToolCallOutcome> {
197 let args: Value = serde_json::from_str(arguments)?;
198 let path_str = args["path"]
200 .as_str()
201 .or_else(|| args["file_path"].as_str())
202 .or_else(|| args["file"].as_str())
203 .or_else(|| args["filename"].as_str())
204 .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
205
206 let has_start = args.get("start_line").is_some_and(|value| !value.is_null());
207 let has_end = args.get("end_line").is_some_and(|value| !value.is_null());
208 let tail_value = args
209 .get("tail_lines")
210 .or_else(|| args.get("last_lines"))
211 .or_else(|| args.get("last_n_lines"));
212 let tail_value = tail_value.filter(|_| !(has_start || has_end));
216 let requested_start = args.get("start_line").and_then(Value::as_u64);
217 let requested_end = args.get("end_line").and_then(Value::as_u64);
218
219 let backend = self.backend.clone();
220 let path = backend.resolve_path(path_str).await?;
221 let metadata = backend
222 .metadata(&path)
223 .await
224 .map_err(|_| crate::TargetNotFound(format!("File not found: {path_str}")))?;
225
226 if metadata.is_dir() {
227 anyhow::bail!("Path is a directory, not a file: {}", path_str);
228 }
229
230 let file_size = metadata.len;
231 let modified = format_modified_rfc3339(&metadata);
232 let bytes = backend.read(&path).await?;
233 if let Some(fence) = fence {
234 fence.observed(path_str, &bytes).await;
235 }
236
237 if let Some(mime_type) =
238 sniff_file_image_mime(&bytes).filter(|_| self.policy.attaches_images())
239 {
240 return image_file_outcome(
241 backend,
242 path_str,
243 &path,
244 file_size,
245 modified.as_deref(),
246 mime_type,
247 )
248 .await;
249 }
250
251 if let Some(kind) = sniff_document_kind(&path, &bytes) {
257 return Ok(ToolCallOutcome::from_output(document_extraction_stub(
258 kind,
259 path_str,
260 file_size,
261 modified.as_deref(),
262 self.policy.shell_tool_name(),
263 cfg!(target_os = "macos")
266 && matches!(self.backend.kind(), crate::backend::BackendKind::Local),
267 )));
268 }
269
270 if bytes.iter().take(8192).any(|byte| *byte == 0) {
272 let mut out = format!("Binary file: {}\nSize: {} bytes\n", path_str, file_size);
273 if let Some(modified) = &modified {
274 out.push_str(&format!("Modified: {}\n", modified));
275 }
276 out.push_str("Type: binary (cannot display contents).\n");
277 out.push_str(&format!(
278 "If you need its contents, run the {} tool with: file \"{}\" to identify the format, then choose a matching extraction command.",
279 self.policy.shell_tool_name(),
280 shell_safe_path(path_str)
281 ));
282 return Ok(ToolCallOutcome::from_output(out));
283 }
284
285 if requested_start.is_some_and(|line| line == 0)
289 || requested_end.is_some_and(|line| line == 0)
290 {
291 return Ok(ToolCallOutcome::contract_rejection(
292 "read_file line numbers are 1-based and must be positive",
293 ));
294 }
295 if matches!((requested_start, requested_end), (Some(start), Some(end)) if end < start) {
296 return Ok(ToolCallOutcome::contract_rejection(
297 "read_file end_line must be greater than or equal to start_line",
298 ));
299 }
300 let start = args["start_line"]
301 .as_u64()
302 .map(|n| (n as usize).saturating_sub(1))
303 .unwrap_or(0);
304
305 let end = args["end_line"]
306 .as_u64()
307 .map(|n| n as usize)
308 .unwrap_or(usize::MAX);
309
310 let tail_lines = tail_value
311 .and_then(Value::as_u64)
312 .filter(|n| *n > 0)
316 .map(|n| n as usize);
317
318 let uses_subset = start > 0 || end != usize::MAX || tail_lines.is_some();
319 let selection = if let Some(count) = tail_lines {
324 ReadSelection::Tail { count }
325 } else if uses_subset {
326 ReadSelection::Range {
327 start,
328 end_exclusive: (end != usize::MAX).then_some(end),
329 }
330 } else {
331 ReadSelection::Full
332 };
333
334 let text = String::from_utf8(bytes)
335 .map_err(|_| anyhow::anyhow!("Cannot display non-UTF-8 file: {}", path_str))?;
336 let selected = read_selected_lines(&text, selection);
337 let total_lines = selected.total_lines;
338 let selection_metadata = match selection {
339 ReadSelection::Full => ReadFileSelectionMetadata::Full,
340 ReadSelection::Range {
341 start,
342 end_exclusive: Some(end),
343 } => ReadFileSelectionMetadata::BoundedRange {
344 start_line: start + 1,
345 end_line: end,
346 },
347 ReadSelection::Range {
348 start,
349 end_exclusive: None,
350 } => ReadFileSelectionMetadata::OpenEndedRange {
351 start_line: start + 1,
352 },
353 ReadSelection::Tail { count } => ReadFileSelectionMetadata::Tail {
354 requested_lines: count,
355 },
356 };
357 let canonical_path = backend
358 .canonicalize(&path)
359 .await
360 .unwrap_or_else(|_| path.clone())
361 .to_string();
362 let read_metadata = ReadFileResultMetadata {
363 display_path: path_str.to_string(),
364 canonical_path,
365 selection: selection_metadata,
366 returned_start_line: (!selected.lines.is_empty()).then_some(selected.start_index + 1),
367 returned_end_line: (!selected.lines.is_empty()).then_some(selected.end_display),
368 total_lines,
369 file_size,
370 modified: modified.clone(),
371 selected_lines: selected.lines.clone(),
372 truncated: selected.truncated,
373 };
374
375 if total_lines == 0 {
376 let header =
377 format_text_file_header(path_str, "0 lines, empty", file_size, modified.as_deref());
378 return Ok(ToolCallOutcome {
379 output: header.trim_end().to_string(),
380 metadata: ToolCallMetadata {
381 read_file: Some(read_metadata),
382 ..ToolCallMetadata::default()
383 },
384 finish: None,
385 });
386 }
387
388 if selected.start_index >= total_lines {
389 anyhow::bail!(
390 "start_line {} exceeds total lines {} in file",
391 selected.start_index + 1,
392 total_lines
393 );
394 }
395
396 Ok(ToolCallOutcome {
397 output: render_read_file_output(&read_metadata),
398 metadata: ToolCallMetadata {
399 read_file: Some(read_metadata),
400 ..ToolCallMetadata::default()
401 },
402 finish: None,
403 })
404 }
405}
406
407pub fn render_read_file_output(metadata: &ReadFileResultMetadata) -> String {
408 if metadata.total_lines == 0 {
409 return format_text_file_header(
410 &metadata.display_path,
411 "0 lines, empty",
412 metadata.file_size,
413 metadata.modified.as_deref(),
414 )
415 .trim_end()
416 .to_string();
417 }
418
419 let start_line = metadata.returned_start_line.unwrap_or(1);
420 let end_line = metadata.returned_end_line.unwrap_or(start_line);
421 let header_summary = match metadata.selection {
422 ReadFileSelectionMetadata::Full if !metadata.truncated => {
423 format!("{} lines", metadata.total_lines)
424 }
425 ReadFileSelectionMetadata::Full
426 | ReadFileSelectionMetadata::BoundedRange { .. }
427 | ReadFileSelectionMetadata::OpenEndedRange { .. } => {
428 format!(
429 "lines {}-{} of {}",
430 start_line, end_line, metadata.total_lines
431 )
432 }
433 ReadFileSelectionMetadata::Tail { .. } => format!(
434 "last {} lines of {}",
435 metadata.selected_lines.len(),
436 metadata.total_lines
437 ),
438 };
439 let header = format_text_file_header(
440 &metadata.display_path,
441 &header_summary,
442 metadata.file_size,
443 metadata.modified.as_deref(),
444 );
445 let selected_content = metadata.selected_lines.join("\n");
446 let formatted = super::format_with_line_numbers(&selected_content, start_line - 1);
447 match continuation_hint(metadata) {
448 Some(hint) => format!("{}{}\n{}", header, formatted, hint),
449 None => format!("{}{}", header, formatted),
450 }
451}
452
453pub fn render_read_file_output_within(
462 metadata: &ReadFileResultMetadata,
463 max_chars: usize,
464) -> String {
465 let full = render_read_file_output(metadata);
466 if full.chars().count() <= max_chars {
467 return full;
468 }
469
470 const HINT_RESERVE: usize = 360;
473 let start_line = metadata.returned_start_line.unwrap_or(1);
474 let end_line = metadata.returned_end_line.unwrap_or(start_line);
475 let keep_from_end = matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. });
476 let number_width = end_line.to_string().len().max(3) + 3; let budget = max_chars.saturating_sub(HINT_RESERVE + 120);
478
479 let mut kept: Vec<String> = Vec::new();
480 let mut used = 0usize;
481 let lines: Box<dyn Iterator<Item = &String>> = if keep_from_end {
482 Box::new(metadata.selected_lines.iter().rev())
483 } else {
484 Box::new(metadata.selected_lines.iter())
485 };
486 for line in lines {
487 let cost = number_width + line.chars().count() + 1;
488 if !kept.is_empty() && used + cost > budget {
489 break;
490 }
491 used += cost;
492 kept.push(line.clone());
493 }
494 if keep_from_end {
495 kept.reverse();
496 }
497
498 let mut adjusted = metadata.clone();
499 adjusted.truncated = true;
500 if keep_from_end {
501 adjusted.returned_start_line = Some(end_line.saturating_sub(kept.len()).saturating_add(1));
502 } else {
503 adjusted.returned_end_line = Some(start_line + kept.len() - 1);
504 }
505 adjusted.selected_lines = kept;
506 render_read_file_output(&adjusted)
507}
508
509pub(crate) fn continuation_hint(metadata: &ReadFileResultMetadata) -> Option<String> {
513 if !metadata.truncated {
514 return None;
515 }
516 let start_line = metadata.returned_start_line?;
517 let end_line = metadata.returned_end_line?;
518 if matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. }) {
519 return Some(format!(
520 "[NOTE: tail output truncated to fit the output limit — only the last {} lines were returned; lines before {} are NOT visible to you. Use start_line/end_line to read earlier sections.]",
521 metadata.selected_lines.len(),
522 start_line
523 ));
524 }
525 let shown = end_line
526 .saturating_sub(start_line)
527 .saturating_add(1)
528 .max(50);
529 let next_start = end_line + 1;
530 let next_end = end_line.saturating_add(shown).min(metadata.total_lines);
531 Some(format!(
532 "[NOTE: output truncated at line {} — lines {}-{} of {} were NOT returned and are NOT visible to you. Do not guess their content. To continue reading, call read_file with {{\"path\": \"{}\", \"start_line\": {}, \"end_line\": {}}}.]",
533 end_line,
534 next_start,
535 metadata.total_lines,
536 metadata.total_lines,
537 metadata.display_path,
538 next_start,
539 next_end
540 ))
541}
542
543#[derive(Clone, Copy)]
544enum ReadSelection {
545 Full,
546 Range {
547 start: usize,
548 end_exclusive: Option<usize>,
549 },
550 Tail {
551 count: usize,
552 },
553}
554
555struct SelectedLines {
556 lines: Vec<String>,
557 total_lines: usize,
558 start_index: usize,
559 end_display: usize,
560 truncated: bool,
562}
563
564fn cap_line(line: String) -> String {
567 if line.len() <= MAX_LINE_CHARS {
568 return line;
569 }
570 let total_chars = line.chars().count();
571 if total_chars <= MAX_LINE_CHARS {
572 return line;
573 }
574 let mut kept: String = line.chars().take(MAX_LINE_CHARS).collect();
575 kept.push_str(&format!("… [line truncated; {} chars total]", total_chars));
576 kept
577}
578
579fn read_selected_lines(content: &str, selection: ReadSelection) -> SelectedLines {
580 match selection {
581 ReadSelection::Full | ReadSelection::Range { .. } => {
582 let (start, end_exclusive) = match selection {
583 ReadSelection::Range {
584 start,
585 end_exclusive,
586 } => (start, end_exclusive),
587 _ => (0, None),
588 };
589
590 let mut lines = Vec::new();
591 let mut total_lines: usize = 0;
592 let mut stored_bytes: usize = 0;
593 let mut capped = false;
594
595 for line in content.lines() {
596 total_lines += 1;
597 let zero_based_index = total_lines - 1;
598 let in_range = zero_based_index >= start
599 && end_exclusive.is_none_or(|end| zero_based_index < end);
600 if in_range && !capped {
601 let line = cap_line(line.to_string());
602 if !lines.is_empty() && stored_bytes + line.len() > MAX_READ_CHARS {
603 capped = true;
604 } else {
605 stored_bytes += line.len() + 1;
606 lines.push(line);
607 }
608 }
609 }
612
613 let (end_display, truncated) = if capped {
614 (start + lines.len(), true)
615 } else {
616 (end_exclusive.unwrap_or(total_lines).min(total_lines), false)
617 };
618 SelectedLines {
619 lines,
620 total_lines,
621 start_index: start,
622 end_display,
623 truncated,
624 }
625 }
626 ReadSelection::Tail { count } => {
627 let mut lines: VecDeque<String> = VecDeque::new();
628 let mut total_lines: usize = 0;
629 let mut stored_bytes: usize = 0;
630
631 for line in content.lines() {
632 total_lines += 1;
633 if lines.len() == count
634 && let Some(dropped) = lines.pop_front()
635 {
636 stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
637 }
638 let line = cap_line(line.to_string());
639 stored_bytes += line.len() + 1;
640 lines.push_back(line);
641 while stored_bytes > MAX_READ_CHARS && lines.len() > 1 {
644 if let Some(dropped) = lines.pop_front() {
645 stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
646 }
647 }
648 }
649
650 let lines: Vec<String> = lines.into_iter().collect();
651 let start_index = total_lines.saturating_sub(lines.len());
652 let truncated = lines.len() < count.min(total_lines);
653 SelectedLines {
654 lines,
655 total_lines,
656 start_index,
657 end_display: total_lines,
658 truncated,
659 }
660 }
661 }
662}
663
664#[derive(Clone, Copy, Debug, PartialEq, Eq)]
667enum DocumentKind {
668 Pdf,
669 Word,
670}
671
672fn sniff_document_kind(path: &BackendPath, bytes: &[u8]) -> Option<DocumentKind> {
674 let header = &bytes[..bytes.len().min(8)];
675 if header.starts_with(b"%PDF") {
676 return Some(DocumentKind::Pdf);
677 }
678
679 let extension = path.extension().map(|ext| ext.to_ascii_lowercase());
680 let is_zip = header.starts_with(b"PK\x03\x04");
681 let is_ole = header.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]);
682 match extension.as_deref() {
683 Some("docx") if is_zip => Some(DocumentKind::Word),
684 Some("doc") if is_ole => Some(DocumentKind::Word),
685 _ => None,
686 }
687}
688
689fn shell_safe_path(path: &str) -> String {
692 path.replace('"', "\\\"")
693}
694
695fn document_extraction_stub(
696 kind: DocumentKind,
697 display_path: &str,
698 file_size: u64,
699 modified: Option<&str>,
700 shell: &str,
701 macos: bool,
702) -> String {
703 let label = match kind {
704 DocumentKind::Pdf => "PDF document",
705 DocumentKind::Word => "Word document",
706 };
707 let mut out = format!("{}: {}\nSize: {} bytes\n", label, display_path, file_size);
708 if let Some(modified) = modified {
709 out.push_str(&format!("Modified: {}\n", modified));
710 }
711 let quoted = shell_safe_path(display_path);
712 match kind {
713 DocumentKind::Pdf => {
714 out.push_str(&format!(
715 "This tool cannot extract PDF text directly. Run the {shell} tool to extract it:\n"
716 ));
717 out.push_str(&format!(" pdftotext -layout \"{}\" -\n", quoted));
718 if macos {
719 out.push_str(&format!(
720 "If pdftotext is not installed, use Spotlight's extracted text:\n mdls -raw -name kMDItemTextContent \"{}\"\n",
721 quoted
722 ));
723 } else {
724 out.push_str(
725 "If pdftotext is not installed, install poppler-utils (e.g. apt install poppler-utils) or use pandoc.\n",
726 );
727 }
728 }
729 DocumentKind::Word => {
730 out.push_str(&format!(
731 "This tool cannot extract Word document text directly. Run the {shell} tool to extract it:\n"
732 ));
733 if macos {
734 out.push_str(&format!(" textutil -convert txt -stdout \"{}\"\n", quoted));
735 } else {
736 out.push_str(&format!(" pandoc -t plain \"{}\"\n", quoted));
737 }
738 }
739 }
740 out.push_str("Do not ask the user to convert the file — extract it yourself.");
741 out
742}
743
744fn sniff_file_image_mime(bytes: &[u8]) -> Option<&'static str> {
745 crate::util::sniff_image_mime(&bytes[..bytes.len().min(16)])
746}
747
748async fn image_file_outcome(
749 backend: SharedBackend,
750 display_path: &str,
751 path: &BackendPath,
752 file_size: u64,
753 modified: Option<&str>,
754 mime_type: &str,
755) -> anyhow::Result<ToolCallOutcome> {
756 let mut output = format!("Image file: {}\nSize: {} bytes\n", display_path, file_size);
757 if let Some(modified) = modified {
758 output.push_str(&format!("Modified: {}\n", modified));
759 }
760 output.push_str(&format!("Type: {mime_type}\n"));
761 output.push_str("Attached for vision analysis.");
762
763 let filename = path.file_name().unwrap_or("image").to_string();
764 let staging_dir = std::env::temp_dir().join("aidaemon-execution-observations");
765 tokio::fs::create_dir_all(&staging_dir).await?;
766 let local_path = staging_dir.join(format!("{}-{}", uuid::Uuid::new_v4(), filename));
767 backend.export_local_file(path, &local_path).await?;
768
769 Ok(ToolCallOutcome {
770 output,
771 metadata: ToolCallMetadata {
772 attachments: vec![MessageAttachment {
773 local_path: local_path.to_string_lossy().into_owned(),
774 filename,
775 mime_type: mime_type.to_string(),
776 size_bytes: file_size,
777 provenance: AttachmentProvenance::ToolObservation,
778 source_tool: Some("read_file".to_string()),
779 ..MessageAttachment::default()
780 }],
781 ..ToolCallMetadata::default()
782 },
783 finish: None,
784 })
785}
786
787fn format_modified_rfc3339(metadata: &BackendMetadata) -> Option<String> {
788 let modified = metadata.modified?;
789 let modified_utc: chrono::DateTime<chrono::Utc> = modified.into();
790 Some(modified_utc.to_rfc3339())
791}
792
793fn format_text_file_header(
794 path: &str,
795 line_summary: &str,
796 file_size: u64,
797 modified: Option<&str>,
798) -> String {
799 match modified {
800 Some(modified) => format!(
801 "File: {} ({}, {} bytes, modified {})\n",
802 path, line_summary, file_size, modified
803 ),
804 None => format!("File: {} ({}, {} bytes)\n", path, line_summary, file_size),
805 }
806}
807
808#[cfg(test)]
809mod document_stub_tests {
810 use super::*;
811
812 #[test]
815 fn extraction_commands_follow_where_the_file_is() {
816 let remote = document_extraction_stub(
817 DocumentKind::Pdf,
818 "/workspace/report.pdf",
819 10,
820 None,
821 "terminal",
822 false,
823 );
824 assert!(
825 remote.contains("pdftotext") && !remote.contains("mdls"),
826 "{remote}"
827 );
828 let word = document_extraction_stub(
829 DocumentKind::Word,
830 "/workspace/notes.docx",
831 10,
832 None,
833 "terminal",
834 false,
835 );
836 assert!(
837 word.contains("pandoc") && !word.contains("textutil"),
838 "{word}"
839 );
840 let mac = document_extraction_stub(
841 DocumentKind::Pdf,
842 "/Users/synthetic/report.pdf",
843 10,
844 None,
845 "terminal",
846 true,
847 );
848 assert!(mac.contains("mdls"), "{mac}");
849 }
850}