vtcode_core/tools/file_ops/
mod.rs1mod diff_preview;
7mod list;
8mod path_policy;
9mod read;
10pub(crate) use read::{PATCH_READ_CACHE_NONCE, bounded_line_read_path, source_line_offset};
11mod tool;
12mod write;
13
14use anyhow::{Context, Result};
15use std::path::Path;
16use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, BufReader};
17use vtcode_commons::async_utils::read_exact_uninit;
18
19pub use diff_preview::{
20 SUPPRESSED_PREVIEW_REASON, build_diff_preview, canonical_diff_previews, diff_output_has_effective_change,
21 diff_preview_error_skip, diff_preview_size_skip, diff_preview_suppressed, diff_preview_user_message,
22};
23pub use tool::FileOpsTool;
24pub use vtcode_commons::fs::is_image_path;
25
26pub(crate) const MAX_LINE_READ_BYTES: usize = 64 * 1024;
33
34pub(crate) async fn read_bounded_line<R: AsyncBufRead + Unpin>(
41 reader: &mut R,
42 buffer: &mut Vec<u8>,
43) -> Result<Option<bool>> {
44 buffer.clear();
45 let mut limited = reader.take(MAX_LINE_READ_BYTES as u64 + 1);
46 let n = limited.read_until(b'\n', buffer).await.context("failed to read line")?;
47 if n == 0 {
48 return Ok(None);
49 }
50
51 let truncated = buffer.last() != Some(&b'\n') && buffer.len() > MAX_LINE_READ_BYTES;
52 if truncated {
53 let mut drain_buf = Vec::with_capacity(4096);
59 loop {
60 drain_buf.clear();
61 let mut chunk = reader.take(4096);
62 let n = chunk
63 .read_until(b'\n', &mut drain_buf)
64 .await
65 .context("failed to drain oversized line")?;
66 if n == 0 {
67 break;
68 }
69 if drain_buf.last() == Some(&b'\n') {
70 break;
71 }
72 }
73 buffer.truncate(MAX_LINE_READ_BYTES);
74 }
75 Ok(Some(truncated))
76}
77
78pub(crate) struct ByteRangeReadResult {
80 pub content: String,
81 pub has_more: bool,
82 pub lines_read: usize,
84}
85
86pub(crate) async fn read_byte_range(
92 file_path: &Path,
93 offset_bytes: u64,
94 page_size_bytes: usize,
95 line_numbers: bool,
96) -> Result<ByteRangeReadResult> {
97 let metadata = tokio::fs::metadata(file_path)
98 .await
99 .with_context(|| format!("Failed to read metadata for: {}", file_path.display()))?;
100
101 if !metadata.is_file() {
102 anyhow::bail!("Path is not a file: {}", file_path.display());
103 }
104
105 let file_size = metadata.len();
106
107 if offset_bytes >= file_size {
109 return Ok(ByteRangeReadResult {
110 content: String::new(),
111 has_more: false,
112 lines_read: 0,
113 });
114 }
115
116 let probe_leading_byte = line_numbers && offset_bytes > 0;
119 let read_start = if probe_leading_byte {
120 offset_bytes - 1
121 } else {
122 offset_bytes
123 };
124
125 let mut file = tokio::fs::File::open(file_path)
127 .await
128 .with_context(|| format!("Failed to open: {}", file_path.display()))?;
129
130 file.seek(std::io::SeekFrom::Start(read_start))
131 .await
132 .with_context(|| format!("Failed to seek to offset {} in: {}", read_start, file_path.display()))?;
133
134 let page_size_u64 = page_size_bytes as u64;
136 let end_pos = offset_bytes
137 .checked_add(page_size_u64)
138 .map(|end| std::cmp::min(end, file_size))
139 .unwrap_or(file_size);
140 let actual_read_size = (end_pos - offset_bytes) as usize + usize::from(probe_leading_byte);
141
142 let buffer = read_exact_uninit(&mut file, actual_read_size).await.with_context(|| {
143 format!("Failed to read {} bytes from offset {} in: {}", actual_read_size, read_start, file_path.display())
144 })?;
145
146 let (leading_byte, content_bytes) = if probe_leading_byte {
147 let (lead, rest) = buffer.split_first().context("leading probe byte missing from range read")?;
148 (Some(*lead), rest)
149 } else {
150 (None, buffer.as_slice())
151 };
152
153 let raw = String::from_utf8_lossy(content_bytes).into_owned();
154 let has_more = end_pos < file_size;
155
156 if !line_numbers {
157 return Ok(ByteRangeReadResult { content: raw, has_more, lines_read: 0 });
159 }
160
161 let start_line = count_lines_before(file_path, offset_bytes).await?;
163
164 let at_line_boundary = leading_byte.is_none_or(|byte| byte == b'\n');
166
167 let lines: Vec<&str> = raw.split('\n').collect();
168 let mut formatted_lines = Vec::new();
169 let mut current_line = start_line;
170
171 for (i, line) in lines.iter().enumerate() {
172 if i == 0 && !at_line_boundary && !line.is_empty() {
174 current_line += 1;
175 continue;
176 }
177
178 if i == lines.len() - 1 && has_more && line.is_empty() {
180 continue;
181 }
182
183 let trimmed = line.trim_end_matches('\r');
184 if !trimmed.is_empty() || i < lines.len() - 1 {
185 formatted_lines.push(format!("{current_line}: {trimmed}"));
186 current_line += 1;
187 }
188 }
189
190 let lines_read = formatted_lines.len();
191 let content = formatted_lines.join("\n");
192
193 Ok(ByteRangeReadResult { content, has_more, lines_read })
194}
195
196async fn count_lines_before(file_path: &Path, offset_bytes: u64) -> Result<usize> {
199 if offset_bytes == 0 {
200 return Ok(1);
201 }
202
203 let file = tokio::fs::File::open(file_path)
204 .await
205 .with_context(|| format!("Failed to open: {}", file_path.display()))?;
206
207 let mut reader = BufReader::new(file);
208 let mut line_count: usize = 1; let mut bytes_read: u64 = 0;
210 let mut buffer = Vec::new();
211
212 while bytes_read < offset_bytes {
213 let n = read_bounded_line(&mut reader, &mut buffer)
214 .await
215 .context("failed to count lines")?;
216
217 let Some(_) = n else { break };
218
219 bytes_read += buffer.len() as u64;
220 if bytes_read <= offset_bytes {
221 line_count += 1;
222 }
223 }
224
225 Ok(line_count)
226}
227
228pub(crate) fn restore_exact_text_content(content: &str, size_bytes: u64) -> Option<String> {
234 let content_size = content.len() as u64;
235 match size_bytes.checked_sub(content_size) {
236 Some(0) => Some(content.to_string()),
237 Some(1) => Some(format!("{content}\n")),
238 Some(2) if content.contains("\r\n") || !content.contains('\n') => Some(format!("{content}\r\n")),
239 _ => None,
240 }
241}