summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/tools/fs.rs156
1 files changed, 125 insertions, 31 deletions
diff --git a/src/tools/fs.rs b/src/tools/fs.rs
index 6addf8d..e543cb6 100644
--- a/src/tools/fs.rs
+++ b/src/tools/fs.rs
@@ -1,9 +1,11 @@
1use std::fs; 1use std::fs;
2use std::io::{BufRead, BufReader};
2use std::path::{Path, PathBuf}; 3use std::path::{Path, PathBuf};
3 4
4use serde_json::Value; 5use serde_json::Value;
5 6
6const MAX_LINE_CHARS: usize = 400; 7const MAX_LINE_CHARS: usize = 400;
8const MAX_LINE_BYTES: usize = 4096;
7const MAX_READ_LINES: usize = 2000; 9const MAX_READ_LINES: usize = 2000;
8const MAX_MATCHES: usize = 200; 10const MAX_MATCHES: usize = 200;
9const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; 11const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024;
@@ -138,42 +140,134 @@ pub fn read(args: &Value) -> Result<String, String> {
138 .unwrap_or(MAX_READ_LINES as u64) 140 .unwrap_or(MAX_READ_LINES as u64)
139 .clamp(1, MAX_READ_LINES as u64) as usize; 141 .clamp(1, MAX_READ_LINES as u64) as usize;
140 142
141 let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; 143 let meta = fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?;
142 if bytes.iter().take(8192).any(|&b| b == 0) { 144 if meta.is_dir() {
143 return Err(format!( 145 return Err(format!("{path} is a directory; use glob or grep"));
144 "{path}: looks like a binary file and will not be shown"
145 ));
146 } 146 }
147 let text = String::from_utf8_lossy(&bytes); 147
148 let lines: Vec<&str> = text.lines().collect(); 148 let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?;
149 if lines.is_empty() { 149 let mut reader = BufReader::with_capacity(64 * 1024, file);
150 return Ok(format!("{path}: empty file")); 150
151 } 151 if let Ok(head) = reader.fill_buf() {
152 if offset > lines.len() { 152 if head.iter().take(8192).any(|&b| b == 0) {
153 return Ok(format!( 153 return Err(format!(
154 "{path} has {} lines; offset {offset} is past the end", 154 "{path}: looks like a binary file and will not be shown"
155 lines.len() 155 ));
156 )); 156 }
157 } 157 }
158 158
159 let end = (offset + limit - 1).min(lines.len()); 159 // Skip to the first requested line without buffering what is skipped, so a
160 let mut out = String::with_capacity((end - offset + 2) * 40); 160 // 500 MB log with offset near the end costs a scan, not a 500 MB allocation.
161 for number in offset..=end { 161 for _ in 1..offset {
162 out.push_str(&format!( 162 match skip_line(&mut reader).map_err(|e| format!("{path}: {e}"))? {
163 "{number:>6}\t{}\n", 163 true => {}
164 clip(lines[number - 1], MAX_LINE_CHARS) 164 false => return Ok(format!("{path} has fewer than {offset} lines")),
165 )); 165 }
166 } 166 }
167 if end < lines.len() { 167
168 out.push_str(&format!( 168 let mut out = String::new();
169 "… {} more line(s); continue with offset={}\n", 169 let mut produced = 0usize;
170 lines.len() - end, 170 let mut number = offset;
171 end + 1 171
172 )); 172 while produced < limit {
173 let (bytes, truncated) = match read_line_limited(&mut reader, MAX_LINE_BYTES)
174 .map_err(|e| format!("{path}: {e}"))?
175 {
176 Some(line) => line,
177 None => break,
178 };
179 let text = String::from_utf8_lossy(&bytes);
180 let text = text.trim_end_matches('\n');
181 let mut rendered = clip(text, MAX_LINE_CHARS);
182 if truncated {
183 rendered.push_str(" …(line truncated)");
184 }
185 out.push_str(&format!("{number:>6}\t{rendered}\n"));
186 produced += 1;
187 number += 1;
188 }
189
190 if produced == 0 {
191 return Ok(if offset == 1 {
192 format!("{path}: empty file")
193 } else {
194 format!("{path} has fewer than {offset} lines")
195 });
196 }
197
198 if let Ok(head) = reader.fill_buf() {
199 if !head.is_empty() {
200 out.push_str(&format!("… more lines; continue with offset={number}\n"));
201 }
173 } 202 }
203
174 Ok(out) 204 Ok(out)
175} 205}
176 206
207/// Consumes one line without keeping it. False at end of file.
208fn skip_line<R: BufRead>(reader: &mut R) -> std::io::Result<bool> {
209 let mut any = false;
210 loop {
211 let buf = reader.fill_buf()?;
212 if buf.is_empty() {
213 return Ok(any);
214 }
215 any = true;
216 match buf.iter().position(|&b| b == b'\n') {
217 Some(index) => {
218 reader.consume(index + 1);
219 return Ok(true);
220 }
221 None => {
222 let len = buf.len();
223 reader.consume(len);
224 }
225 }
226 }
227}
228
229/// Reads one line, keeping at most `max` bytes but consuming the whole line.
230/// Returns `(bytes, truncated)`; `None` at end of file.
231fn read_line_limited<R: BufRead>(
232 reader: &mut R,
233 max: usize,
234) -> std::io::Result<Option<(Vec<u8>, bool)>> {
235 let mut kept: Vec<u8> = Vec::new();
236 let mut any = false;
237 let mut truncated = false;
238
239 loop {
240 let buf = reader.fill_buf()?;
241 if buf.is_empty() {
242 return Ok(if any { Some((kept, truncated)) } else { None });
243 }
244 any = true;
245
246 let newline = buf.iter().position(|&b| b == b'\n');
247 let take = match newline {
248 Some(index) => index + 1,
249 None => buf.len(),
250 };
251
252 if kept.len() < max {
253 let room = max - kept.len();
254 let slice = &buf[..take.min(room)];
255 kept.extend_from_slice(slice);
256 if take > slice.len() {
257 truncated = true;
258 }
259 } else {
260 truncated = true;
261 }
262
263 reader.consume(take);
264
265 if newline.is_some() {
266 return Ok(Some((kept, truncated)));
267 }
268 }
269}
270
177pub fn grep(args: &Value) -> Result<String, String> { 271pub fn grep(args: &Value) -> Result<String, String> {
178 let pattern = req(args, "pattern")?; 272 let pattern = req(args, "pattern")?;
179 if pattern.is_empty() { 273 if pattern.is_empty() {