codive_tools/
read_file.rs1use codive_core::tool::{Tool, ToolOutput};
7use async_trait::async_trait;
8use serde::Deserialize;
9use std::path::Path;
10use tokio::fs;
11use tracing::debug;
12
13const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
15
16const DEFAULT_MAX_LINES: usize = 2000;
18
19pub struct ReadFileTool {
21 max_file_size: u64,
23 max_lines: usize,
25}
26
27impl ReadFileTool {
28 pub fn new() -> Self {
30 Self {
31 max_file_size: MAX_FILE_SIZE,
32 max_lines: DEFAULT_MAX_LINES,
33 }
34 }
35
36 pub fn with_max_file_size(mut self, size: u64) -> Self {
38 self.max_file_size = size;
39 self
40 }
41
42 pub fn with_max_lines(mut self, lines: usize) -> Self {
44 self.max_lines = lines;
45 self
46 }
47}
48
49impl Default for ReadFileTool {
50 fn default() -> Self {
51 Self::new()
52 }
53}
54
55#[derive(Debug, Deserialize)]
57struct ReadFileParams {
58 path: String,
60 #[serde(default)]
62 offset: Option<usize>,
63 #[serde(default)]
65 limit: Option<usize>,
66}
67
68#[async_trait]
69impl Tool for ReadFileTool {
70 fn name(&self) -> &str {
71 "read_file"
72 }
73
74 fn description(&self) -> &str {
75 "Read the contents of a file. Returns the file content with line numbers. \
76 For large files, use offset and limit to read specific sections."
77 }
78
79 fn parameters_schema(&self) -> serde_json::Value {
80 serde_json::json!({
81 "type": "object",
82 "properties": {
83 "path": {
84 "type": "string",
85 "description": "The path to the file to read"
86 },
87 "offset": {
88 "type": "integer",
89 "description": "Line number to start from (1-indexed). Default: 1"
90 },
91 "limit": {
92 "type": "integer",
93 "description": "Maximum number of lines to read. Default: 2000"
94 }
95 },
96 "required": ["path"]
97 })
98 }
99
100 async fn execute(&self, params: serde_json::Value) -> ToolOutput {
101 let params: ReadFileParams = match serde_json::from_value(params) {
103 Ok(p) => p,
104 Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
105 };
106
107 let path = Path::new(¶ms.path);
108 debug!(path = %path.display(), "Reading file");
109
110 if !path.exists() {
112 return ToolOutput::error(format!("File not found: {}", path.display()));
113 }
114
115 if !path.is_file() {
117 return ToolOutput::error(format!("Not a file: {}", path.display()));
118 }
119
120 let metadata = match fs::metadata(path).await {
122 Ok(m) => m,
123 Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
124 };
125
126 if metadata.len() > self.max_file_size {
127 return ToolOutput::error(format!(
128 "File too large: {} bytes (max: {} bytes). Use offset/limit to read sections.",
129 metadata.len(),
130 self.max_file_size
131 ));
132 }
133
134 let content = match fs::read_to_string(path).await {
136 Ok(c) => c,
137 Err(e) => {
138 if e.kind() == std::io::ErrorKind::InvalidData {
140 return ToolOutput::error(
141 "File appears to be binary and cannot be read as text",
142 );
143 }
144 return ToolOutput::error(format!("Failed to read file: {}", e));
145 }
146 };
147
148 let lines: Vec<&str> = content.lines().collect();
150 let total_lines = lines.len();
151
152 let offset = params.offset.unwrap_or(1).saturating_sub(1); let limit = params.limit.unwrap_or(self.max_lines);
154
155 let start = offset.min(lines.len());
157 let end = (start + limit).min(lines.len());
158 let selected_lines = &lines[start..end];
159
160 let mut output = String::new();
162
163 if start > 0 || end < total_lines {
165 output.push_str(&format!(
166 "Showing lines {}-{} of {} total\n\n",
167 start + 1,
168 end,
169 total_lines
170 ));
171 }
172
173 for (i, line) in selected_lines.iter().enumerate() {
175 let line_num = start + i + 1;
176 output.push_str(&format!("{:>6}│{}\n", line_num, line));
177 }
178
179 if end < total_lines {
181 output.push_str(&format!(
182 "\n... {} more lines. Use offset={} to continue.",
183 total_lines - end,
184 end + 1
185 ));
186 }
187
188 ToolOutput::success(output)
189 }
190}
191
192#[cfg(test)]
197mod tests {
198 use super::*;
199 use std::io::Write;
200 use tempfile::NamedTempFile;
201
202 #[test]
203 fn test_read_file_tool_name() {
204 let tool = ReadFileTool::new();
205 assert_eq!(tool.name(), "read_file");
206 }
207
208 #[test]
209 fn test_read_file_schema() {
210 let tool = ReadFileTool::new();
211 let schema = tool.parameters_schema();
212 assert_eq!(schema["type"], "object");
213 assert!(schema["properties"]["path"].is_object());
214 assert_eq!(schema["required"][0], "path");
215 }
216
217 #[tokio::test]
218 async fn test_read_simple_file() {
219 let mut file = NamedTempFile::new().unwrap();
220 writeln!(file, "line 1").unwrap();
221 writeln!(file, "line 2").unwrap();
222 writeln!(file, "line 3").unwrap();
223
224 let tool = ReadFileTool::new();
225 let output = tool
226 .execute(serde_json::json!({
227 "path": file.path().to_str().unwrap()
228 }))
229 .await;
230
231 assert!(output.is_success());
232 assert!(output.content.contains("line 1"));
233 assert!(output.content.contains("line 2"));
234 assert!(output.content.contains("line 3"));
235 }
236
237 #[tokio::test]
238 async fn test_read_with_line_numbers() {
239 let mut file = NamedTempFile::new().unwrap();
240 writeln!(file, "first").unwrap();
241 writeln!(file, "second").unwrap();
242
243 let tool = ReadFileTool::new();
244 let output = tool
245 .execute(serde_json::json!({
246 "path": file.path().to_str().unwrap()
247 }))
248 .await;
249
250 assert!(output.is_success());
251 assert!(output.content.contains("1│"));
253 assert!(output.content.contains("2│"));
254 }
255
256 #[tokio::test]
257 async fn test_read_with_offset() {
258 let mut file = NamedTempFile::new().unwrap();
259 for i in 1..=10 {
260 writeln!(file, "line {}", i).unwrap();
261 }
262
263 let tool = ReadFileTool::new();
264 let output = tool
265 .execute(serde_json::json!({
266 "path": file.path().to_str().unwrap(),
267 "offset": 5
268 }))
269 .await;
270
271 assert!(output.is_success());
272 assert!(output.content.contains("line 5"));
273 assert!(!output.content.contains("│line 4"));
274 }
275
276 #[tokio::test]
277 async fn test_read_with_limit() {
278 let mut file = NamedTempFile::new().unwrap();
279 for i in 1..=10 {
280 writeln!(file, "line {}", i).unwrap();
281 }
282
283 let tool = ReadFileTool::new();
284 let output = tool
285 .execute(serde_json::json!({
286 "path": file.path().to_str().unwrap(),
287 "limit": 3
288 }))
289 .await;
290
291 assert!(output.is_success());
292 assert!(output.content.contains("line 1"));
293 assert!(output.content.contains("line 2"));
294 assert!(output.content.contains("line 3"));
295 assert!(!output.content.contains("│line 4"));
296 assert!(output.content.contains("more lines"));
297 }
298
299 #[tokio::test]
300 async fn test_read_nonexistent_file() {
301 let tool = ReadFileTool::new();
302 let output = tool
303 .execute(serde_json::json!({
304 "path": "/nonexistent/file/path/12345.txt"
305 }))
306 .await;
307
308 assert!(output.is_error);
309 assert!(output.content.contains("not found"));
310 }
311
312 #[tokio::test]
313 async fn test_read_directory() {
314 let tool = ReadFileTool::new();
315 let output = tool
316 .execute(serde_json::json!({
317 "path": "/tmp"
318 }))
319 .await;
320
321 assert!(output.is_error);
322 assert!(output.content.contains("Not a file"));
323 }
324
325 #[tokio::test]
326 async fn test_read_invalid_params() {
327 let tool = ReadFileTool::new();
328 let output = tool.execute(serde_json::json!({})).await;
329
330 assert!(output.is_error);
331 assert!(output.content.contains("Invalid parameters"));
332 }
333
334 #[tokio::test]
335 async fn test_read_empty_file() {
336 let file = NamedTempFile::new().unwrap();
337
338 let tool = ReadFileTool::new();
339 let output = tool
340 .execute(serde_json::json!({
341 "path": file.path().to_str().unwrap()
342 }))
343 .await;
344
345 assert!(output.is_success());
346 }
347}