summaryrefslogtreecommitdiffstats
path: root/src/tools/fs.rs
blob: caa39928c2834ad54dc1ec7884ce8d2cd17b9d82 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use serde_json::Value;

const MAX_LINE_CHARS: usize = 400;
const MAX_LINE_BYTES: usize = 4096;
const MAX_READ_LINES: usize = 2000;
const MAX_MATCHES: usize = 200;
const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024;
const PREVIEW_BUDGET: usize = 60;

const SKIP_DIRS: &[&str] = &[
    ".git",
    "target",
    "node_modules",
    "dist",
    "build",
    ".venv",
    "vendor",
    ".cache",
];

/// A pending file change. Built and previewed first, applied only after the
/// human agrees.
pub enum Change {
    Write { path: String, content: String },
    Edit { path: String, old: String, new: String, text: String },
}

impl Change {
    pub fn path(&self) -> &str {
        match self {
            Change::Write { path, .. } | Change::Edit { path, .. } => path,
        }
    }

    pub fn preview(&self) -> String {
        match self {
            Change::Write { path, content } => match fs::read_to_string(path) {
                Ok(old) if old == *content => format!("{path}: unchanged"),
                Ok(old) => diff_preview(&old, content),
                Err(_) => new_file_preview(path, content),
            },
            Change::Edit {
                path,
                old,
                new,
                text,
            } => {
                let at = text.find(old.as_str()).unwrap_or(0);
                edit_preview(path, text, old, new, at)
            }
        }
    }

    pub fn apply(self) -> Result<String, String> {
        match self {
            Change::Write { path, content } => {
                let parent = Path::new(&path).parent();
                if let Some(parent) = parent {
                    if !parent.as_os_str().is_empty() && !parent.is_dir() {
                        return Err(format!(
                            "parent directory does not exist: {} (create it with bash first)",
                            parent.display()
                        ));
                    }
                }
                fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?;
                Ok(format!(
                    "wrote {} bytes ({} lines) to {path}",
                    content.len(),
                    content.lines().count()
                ))
            }
            Change::Edit {
                path,
                old,
                new,
                mut text,
            } => {
                let at = text
                    .find(old.as_str())
                    .ok_or_else(|| format!("{path}: text to replace disappeared"))?;
                let line = text[..at].matches('\n').count() + 1;
                text.replace_range(at..at + old.len(), &new);
                fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?;
                Ok(format!("edited {path}: 1 replacement at line {line}"))
            }
        }
    }
}

pub fn plan_write(args: &Value) -> Result<Change, String> {
    Ok(Change::Write {
        path: req(args, "path")?,
        content: req(args, "content")?,
    })
}

pub fn plan_edit(args: &Value) -> Result<Change, String> {
    let path = req(args, "path")?;
    let old = req(args, "old")?;
    let new = req(args, "new")?;
    if old.is_empty() {
        return Err("`old` must not be empty; use write to create a file".into());
    }
    let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
    let hits: Vec<usize> = text.match_indices(&old).map(|(i, _)| i).collect();
    match hits.len() {
        0 => Err(format!(
            "text to replace was not found in {path}. Read the file and copy the exact \
             text, including indentation."
        )),
        1 => Ok(Change::Edit {
            path,
            old,
            new,
            text,
        }),
        n => Err(format!(
            "text to replace appears {n} times in {path} (lines {}); include more \
             surrounding context so it is unique.",
            line_list(&text, &hits)
        )),
    }
}

pub fn read(args: &Value) -> Result<String, String> {
    let path = req(args, "path")?;
    let offset = args
        .get("offset")
        .and_then(|v| v.as_u64())
        .unwrap_or(1)
        .max(1) as usize;
    let limit = args
        .get("limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(MAX_READ_LINES as u64)
        .clamp(1, MAX_READ_LINES as u64) as usize;

    let meta = fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?;
    if meta.is_dir() {
        return Err(format!("{path} is a directory; use glob or grep"));
    }

    let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?;
    let mut reader = BufReader::with_capacity(64 * 1024, file);

    if let Ok(head) = reader.fill_buf() {
        if head.iter().take(8192).any(|&b| b == 0) {
            return Err(format!(
                "{path}: looks like a binary file and will not be shown"
            ));
        }
    }

    // Skip to the first requested line without buffering what is skipped, so a
    // 500 MB log with offset near the end costs a scan, not a 500 MB allocation.
    for _ in 1..offset {
        match skip_line(&mut reader).map_err(|e| format!("{path}: {e}"))? {
            true => {}
            false => return Ok(format!("{path} has fewer than {offset} lines")),
        }
    }

    let mut out = String::new();
    let mut produced = 0usize;
    let mut number = offset;

    while produced < limit {
        let (bytes, truncated) = match read_line_limited(&mut reader, MAX_LINE_BYTES)
            .map_err(|e| format!("{path}: {e}"))?
        {
            Some(line) => line,
            None => break,
        };
        let text = String::from_utf8_lossy(&bytes);
        let text = text.trim_end_matches('\n');
        let mut rendered = clip(text, MAX_LINE_CHARS);
        if truncated {
            rendered.push_str(" …(line truncated)");
        }
        out.push_str(&format!("{number:>6}\t{rendered}\n"));
        produced += 1;
        number += 1;
    }

    if produced == 0 {
        return Ok(if offset == 1 {
            format!("{path}: empty file")
        } else {
            format!("{path} has fewer than {offset} lines")
        });
    }

    if let Ok(head) = reader.fill_buf() {
        if !head.is_empty() {
            out.push_str(&format!("… more lines; continue with offset={number}\n"));
        }
    }

    Ok(out)
}

/// Consumes one line without keeping it. False at end of file.
fn skip_line<R: BufRead>(reader: &mut R) -> std::io::Result<bool> {
    let mut any = false;
    loop {
        let buf = reader.fill_buf()?;
        if buf.is_empty() {
            return Ok(any);
        }
        any = true;
        match buf.iter().position(|&b| b == b'\n') {
            Some(index) => {
                reader.consume(index + 1);
                return Ok(true);
            }
            None => {
                let len = buf.len();
                reader.consume(len);
            }
        }
    }
}

/// Reads one line, keeping at most `max` bytes but consuming the whole line.
/// Returns `(bytes, truncated)`; `None` at end of file.
fn read_line_limited<R: BufRead>(
    reader: &mut R,
    max: usize,
) -> std::io::Result<Option<(Vec<u8>, bool)>> {
    let mut kept: Vec<u8> = Vec::new();
    let mut any = false;
    let mut truncated = false;

    loop {
        let buf = reader.fill_buf()?;
        if buf.is_empty() {
            return Ok(if any { Some((kept, truncated)) } else { None });
        }
        any = true;

        let newline = buf.iter().position(|&b| b == b'\n');
        let take = match newline {
            Some(index) => index + 1,
            None => buf.len(),
        };

        if kept.len() < max {
            let room = max - kept.len();
            let slice = &buf[..take.min(room)];
            kept.extend_from_slice(slice);
            if take > slice.len() {
                truncated = true;
            }
        } else {
            truncated = true;
        }

        reader.consume(take);

        if newline.is_some() {
            return Ok(Some((kept, truncated)));
        }
    }
}

enum Matcher {
    Literal { needle: String, ignore_case: bool },
    Regex(regex::Regex),
}

impl Matcher {
    fn is_match(&self, line: &str) -> bool {
        match self {
            Matcher::Literal {
                needle,
                ignore_case,
            } => {
                if *ignore_case {
                    line.to_lowercase().contains(needle)
                } else {
                    line.contains(needle)
                }
            }
            Matcher::Regex(regex) => regex.is_match(line),
        }
    }
}

pub fn grep(args: &Value) -> Result<String, String> {
    let pattern = req(args, "pattern")?;
    if pattern.is_empty() {
        return Err("pattern must not be empty".into());
    }
    let base = args
        .get("path")
        .and_then(|v| v.as_str())
        .unwrap_or(".")
        .to_string();
    let ignore_case = args
        .get("ignore_case")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let fixed = args.get("fixed").and_then(|v| v.as_bool()).unwrap_or(false);

    let matcher = if fixed {
        Matcher::Literal {
            needle: if ignore_case {
                pattern.to_lowercase()
            } else {
                pattern.clone()
            },
            ignore_case,
        }
    } else {
        Matcher::Regex(
            regex::RegexBuilder::new(&pattern)
                .case_insensitive(ignore_case)
                .build()
                .map_err(|error| {
                    format!(
                        "invalid regex `{pattern}`: {error}\npass \"fixed\": true to match \
                         the text literally"
                    )
                })?,
        )
    };

    let root = Path::new(&base);
    let files = if root.is_file() {
        vec![root.to_path_buf()]
    } else {
        let mut files = Vec::new();
        walk(root, &mut files);
        files
    };

    let mut out = String::new();
    let mut matches = 0usize;
    for file in files {
        if matches >= MAX_MATCHES {
            break;
        }
        grep_file(&file, &matcher, &mut matches, &mut out);
    }

    if matches == 0 {
        return Ok(format!("no matches for `{pattern}` under {base}"));
    }
    if matches >= MAX_MATCHES {
        out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n"));
    }
    Ok(out)
}

pub fn glob(args: &Value) -> Result<String, String> {
    let pattern = req(args, "pattern")?;
    let base = args
        .get("path")
        .and_then(|v| v.as_str())
        .unwrap_or(".")
        .to_string();
    let root = Path::new(&base);
    if !root.is_dir() {
        return Err(format!("not a directory: {base}"));
    }

    let mut files = Vec::new();
    walk(root, &mut files);

    // A pattern without a slash is matched against the file name at any depth.
    let bare = !pattern.contains('/');
    let mut hits = Vec::new();
    for file in files {
        let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("");
        let hit = if bare {
            wildcard_match(pattern.as_bytes(), name.as_bytes())
        } else {
            let relative = file
                .strip_prefix(root)
                .unwrap_or(&file)
                .to_string_lossy()
                .to_string();
            glob_match(&pattern, &relative)
        };
        if hit {
            hits.push(file);
            if hits.len() >= MAX_MATCHES {
                break;
            }
        }
    }

    if hits.is_empty() {
        return Ok(format!("no files match `{pattern}` under {base}"));
    }

    let mut out = String::new();
    for hit in &hits {
        out.push_str(&hit.display().to_string());
        out.push('\n');
    }
    if hits.len() >= MAX_MATCHES {
        out.push_str(&format!("… stopped after {MAX_MATCHES} files\n"));
    }
    Ok(out)
}

fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) {
    let meta = match fs::metadata(path) {
        Ok(m) => m,
        Err(_) => return,
    };
    if meta.len() > MAX_SCAN_BYTES {
        return;
    }
    let bytes = match fs::read(path) {
        Ok(b) => b,
        Err(_) => return,
    };
    if bytes.iter().take(8192).any(|&b| b == 0) {
        return;
    }
    let text = String::from_utf8_lossy(&bytes);

    for (index, line) in text.lines().enumerate() {
        if *count >= MAX_MATCHES {
            return;
        }
        if matcher.is_match(line) {
            *count += 1;
            out.push_str(&format!(
                "{}:{}: {}\n",
                path.display(),
                index + 1,
                clip(line.trim_end(), 200)
            ));
        }
    }
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let file_type = match entry.file_type() {
            Ok(t) => t,
            Err(_) => continue,
        };
        let path = entry.path();
        if file_type.is_dir() {
            let name = entry.file_name();
            if SKIP_DIRS.iter().any(|skip| name == *skip) {
                continue;
            }
            walk(&path, out);
        } else if file_type.is_file() {
            out.push(path);
        }
    }
}

fn glob_match(pattern: &str, path: &str) -> bool {
    let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
    let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    match_segments(&p, &s)
}

fn match_segments(pattern: &[&str], path: &[&str]) -> bool {
    match pattern.split_first() {
        None => path.is_empty(),
        Some((&"**", rest)) => {
            if match_segments(rest, path) {
                return true;
            }
            for skip in 0..path.len() {
                if match_segments(rest, &path[skip + 1..]) {
                    return true;
                }
            }
            false
        }
        Some((segment, rest)) => match path.split_first() {
            None => false,
            Some((name, tail)) => {
                wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail)
            }
        },
    }
}

fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool {
    match pattern.split_first() {
        None => text.is_empty(),
        Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])),
        Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]),
        Some((byte, rest)) => match text.split_first() {
            Some((first, tail)) => first == byte && wildcard_match(rest, tail),
            None => false,
        },
    }
}

fn new_file_preview(path: &str, content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len());
    for line in lines.iter().take(PREVIEW_BUDGET) {
        out.push_str(&format!("+ {}\n", clip(line, 200)));
    }
    if lines.len() > PREVIEW_BUDGET {
        out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET));
    }
    out
}

fn diff_preview(old: &str, new: &str) -> String {
    let a: Vec<&str> = old.lines().collect();
    let b: Vec<&str> = new.lines().collect();

    let mut prefix = 0;
    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {
        prefix += 1;
    }
    let mut suffix = 0;
    while suffix < a.len().saturating_sub(prefix)
        && suffix < b.len().saturating_sub(prefix)
        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]
    {
        suffix += 1;
    }

    let start = prefix.saturating_sub(2);
    let a_end = a.len() - suffix;
    let b_end = b.len() - suffix;

    let mut out = format!(
        "@@ -{},{} +{},{} @@\n",
        start + 1,
        a_end.saturating_sub(start),
        start + 1,
        b_end.saturating_sub(start)
    );
    let mut budget = PREVIEW_BUDGET;

    for line in &a[start..prefix] {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("  {}\n", clip(line, 200)));
    }
    for line in &a[prefix..a_end] {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("- {}\n", clip(line, 200)));
    }
    for line in &b[prefix..b_end] {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("+ {}\n", clip(line, 200)));
    }
    for line in a[a_end..(a_end + 2).min(a.len())].iter() {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("  {}\n", clip(line, 200)));
    }
    if budget == 0 {
        out.push_str("… diff truncated\n");
    }
    out
}

fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    let line_no = text[..at].matches('\n').count() + 1;
    let old_lines = old.lines().count().max(1);

    let mut out = format!("@@ {path}:{line_no} @@\n");
    let mut budget = PREVIEW_BUDGET;

    let before_start = (line_no - 1).saturating_sub(2);
    for line in &lines[before_start..line_no.saturating_sub(1)] {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("  {}\n", clip(line, 200)));
    }
    for line in old.lines() {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("- {}\n", clip(line, 200)));
    }
    for line in new.lines() {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("+ {}\n", clip(line, 200)));
    }
    let after_start = (line_no - 1 + old_lines).min(lines.len());
    for line in &lines[after_start..(after_start + 2).min(lines.len())] {
        if budget == 0 {
            break;
        }
        budget -= 1;
        out.push_str(&format!("  {}\n", clip(line, 200)));
    }
    if budget == 0 {
        out.push_str("… diff truncated\n");
    }
    out
}

fn line_list(text: &str, offsets: &[usize]) -> String {
    let mut numbers: Vec<String> = offsets
        .iter()
        .take(10)
        .map(|&at| (text[..at].matches('\n').count() + 1).to_string())
        .collect();
    if offsets.len() > 10 {
        numbers.push("…".into());
    }
    numbers.join(", ")
}

fn req(args: &Value, key: &str) -> Result<String, String> {
    match args.get(key).and_then(|v| v.as_str()) {
        Some(value) => Ok(value.to_string()),
        None => Err(format!("missing required argument `{key}`")),
    }
}

fn clip(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let cut: String = s.chars().take(max).collect();
    format!("{cut}…")
}