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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
|
/*
* This file is part of agent686
* Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
* SPDX-License-Identifier: GPL-3.0-or-later
* https://git.2137697.xyz/agent686
*/
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
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;
/// Edit rewrites the whole file, so it has to fit comfortably in the 32-bit
/// address space together with its own copy.
const MAX_EDIT_BYTES: u64 = 64 * 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. The file is re-read at apply time, so an edit made while the
/// approval prompt was open is not silently discarded.
pub enum Change {
Write {
path: String,
content: String,
},
Edit {
path: String,
old: String,
new: String,
},
}
impl Change {
pub fn path(&self) -> &str {
match self {
Change::Write { path, .. } | Change::Edit { path, .. } => path,
}
}
pub fn preview(&self) -> Result<String, String> {
match self {
Change::Write { path, content } => Ok(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 } => {
let text = fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
let span = locate(&text, old)?;
Ok(edit_preview(path, &text, &span, old, new))
}
}
}
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()
));
}
}
atomic_write(&path, &content)?;
Ok(format!(
"wrote {} bytes ({} lines) to {path}",
content.len(),
content.lines().count()
))
}
Change::Edit { path, old, new } => {
let mut text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
let span = locate(&text, &old)?;
let line = text[..span.start].matches('\n').count() + 1;
// Keep the file's line-ending style.
let replacement = if span.crlf {
new.replace("\r\n", "\n").replace('\n', "\r\n")
} else {
new.clone()
};
text.replace_range(span.start..span.end, &replacement);
atomic_write(&path, &text)?;
Ok(format!("edited {path}: 1 replacement at line {line}"))
}
}
}
}
/// Where the text to replace sits in the file, and whether the file uses CRLF.
struct Span {
start: usize,
end: usize,
crlf: bool,
}
fn locate(text: &str, old: &str) -> Result<Span, String> {
let exact: Vec<usize> = text.match_indices(old).map(|(index, _)| index).collect();
match exact.len() {
1 => {
return Ok(Span {
start: exact[0],
end: exact[0] + old.len(),
crlf: false,
})
}
0 => {}
many => {
return Err(format!(
"text to replace appears {many} times (lines {}); include more \
surrounding context so it is unique.",
line_list(text, &exact)
))
}
}
// A CRLF file shows up in `read` with a trailing carriage return the model
// cannot see. Retry with line endings normalised rather than reporting
// "not found" for text that is visibly there.
if text.contains("\r\n") {
let normalized = text.replace("\r\n", "\n");
let wanted = old.replace("\r\n", "\n");
let hits: Vec<usize> = normalized
.match_indices(&wanted)
.map(|(index, _)| index)
.collect();
match hits.len() {
1 => {
let start = original_offset(text, hits[0]);
if let Some(end) = original_range(text, start, &wanted) {
return Ok(Span {
start,
end,
crlf: true,
});
}
}
many if many > 1 => {
let lines: Vec<String> = hits
.iter()
.take(10)
.map(|hit| (normalized[..*hit].matches('\n').count() + 1).to_string())
.collect();
return Err(format!(
"text to replace appears {many} times in this CRLF file (lines {}); \
include more surrounding context so it is unique.",
lines.join(", ")
));
}
_ => {}
}
}
Err(
"text to replace was not found. Read the file and copy the exact text, \
including indentation."
.to_string(),
)
}
/// Byte offset in the original text for an offset in the CRLF-normalised text.
fn original_offset(text: &str, target: usize) -> usize {
let bytes = text.as_bytes();
let mut original = 0usize;
let mut normalized = 0usize;
while original < bytes.len() && normalized < target {
if bytes[original] == b'\r' && bytes.get(original + 1) == Some(&b'\n') {
original += 2;
} else {
original += 1;
}
normalized += 1;
}
original
}
/// End offset in the original text for a normalised match of `wanted`.
fn original_range(text: &str, start: usize, wanted: &str) -> Option<usize> {
let bytes = text.as_bytes();
let mut cursor = start;
for byte in wanted.bytes() {
if byte == b'\n' {
if bytes.get(cursor) == Some(&b'\r') && bytes.get(cursor + 1) == Some(&b'\n') {
cursor += 2;
} else if bytes.get(cursor) == Some(&b'\n') {
cursor += 1;
} else {
return None;
}
} else {
if bytes.get(cursor) != Some(&byte) {
return None;
}
cursor += 1;
}
}
Some(cursor)
}
/// Write via a temporary file and rename, so a crash or a full disk leaves the
/// original intact instead of a half-written file.
fn atomic_write(path: &str, content: &str) -> Result<(), String> {
let target = Path::new(path);
let parent = match target.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
_ => PathBuf::from("."),
};
let temp = parent.join(format!(
".agent686-{}-{}.tmp",
std::process::id(),
TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
));
fs::write(&temp, content).map_err(|e| format!("{}: {e}", temp.display()))?;
if let Ok(meta) = fs::metadata(target) {
let _ = fs::set_permissions(&temp, meta.permissions());
}
if let Err(error) = fs::rename(&temp, target) {
let _ = fs::remove_file(&temp);
return Err(format!("{path}: {error}"));
}
Ok(())
}
static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0);
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 bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?;
if bytes.len() as u64 > MAX_EDIT_BYTES {
return Err(format!(
"{path} is {} MiB, too large to edit safely; use bash (sed) instead",
bytes.len() / (1024 * 1024)
));
}
let text = String::from_utf8(bytes).map_err(|_| {
format!(
"{path} is not valid UTF-8, so edit cannot round-trip it without \
corrupting the file; use bash (sed, perl) instead"
)
})?;
// Fail before the approval prompt if the match is unusable.
locate(&text, &old)?;
Ok(Change::Edit { path, old, new })
}
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);
let offset = usize::try_from(offset)
.map_err(|_| format!("offset {offset} is too large for this build"))?;
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"));
}
if !meta.is_file() {
// A FIFO or a device would block forever, and this process is single
// threaded, so nothing could interrupt it.
return Err(format!("{path} is not a regular file"));
}
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);
if !root.exists() {
return Err(format!("{base}: no such file or directory"));
}
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;
let mut skipped = 0usize;
for file in files {
if matches >= MAX_MATCHES {
break;
}
grep_file(&file, &matcher, &mut matches, &mut skipped, &mut out);
}
if matches == 0 {
let mut message = format!("no matches for `{pattern}` under {base}");
if skipped > 0 {
message.push_str(&format!(
"\n({skipped} file(s) not searched: larger than 4 MiB or binary)"
));
}
return Ok(message);
}
if matches >= MAX_MATCHES {
out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n"));
}
if skipped > 0 {
out.push_str(&format!(
"({skipped} file(s) not searched: larger than {} or binary)\n",
"4 MiB"
));
}
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,
skipped: &mut usize,
out: &mut String,
) {
let meta = match fs::metadata(path) {
Ok(m) => m,
Err(_) => return,
};
if meta.len() > MAX_SCAN_BYTES {
*skipped += 1;
return;
}
let bytes = match fs::read(path) {
Ok(b) => b,
Err(_) => return,
};
if bytes.iter().take(8192).any(|&b| b == 0) {
*skipped += 1;
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);
} else if file_type.is_symlink()
&& fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false)
{
// Follow file symlinks; symlinked directories are skipped so a loop
// cannot walk forever.
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, span: &Span, old: &str, new: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let line_no = text[..span.start].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}…")
}
|