bashkit 0.1.19

Awesomely fast virtual sandbox with bash and file system
Documentation
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
//! diff builtin command - compare files line by line

use async_trait::async_trait;

use super::{Builtin, Context, read_text_file};
use crate::error::Result;
use crate::interpreter::ExecResult;

/// The diff builtin - compare files line by line.
///
/// Usage: diff [-u] [-q] FILE1 FILE2
///
/// Options:
///   -u         Output in unified format
///   -q         Report only whether files differ
///   --brief    Same as -q
///
/// Default output is normal (ed-style) format, matching `/usr/bin/diff`.
pub struct Diff;

struct DiffOptions {
    unified: bool,
    brief: bool,
}

fn parse_diff_args(args: &[String]) -> (DiffOptions, Vec<String>) {
    let mut opts = DiffOptions {
        unified: false,
        brief: false,
    };
    let mut files = Vec::new();

    for arg in args {
        match arg.as_str() {
            "-u" => opts.unified = true,
            "-q" | "--brief" => opts.brief = true,
            _ if !arg.starts_with('-') || arg == "-" => files.push(arg.clone()),
            _ => {} // ignore unknown options
        }
    }

    (opts, files)
}

/// Simple LCS-based diff algorithm
fn compute_diff<'a>(lines1: &'a [String], lines2: &'a [String]) -> Vec<DiffLine<'a>> {
    // Build LCS table
    let m = lines1.len();
    let n = lines2.len();

    // Cap at reasonable size to prevent DoS
    if m * n > 10_000_000 {
        // Fall back to simple diff for very large files
        return simple_diff(lines1, lines2);
    }

    let mut dp = vec![vec![0u32; n + 1]; m + 1];

    for i in 1..=m {
        for j in 1..=n {
            if lines1[i - 1] == lines2[j - 1] {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
            }
        }
    }

    // Backtrack to produce diff
    let mut result = Vec::new();
    let mut i = m;
    let mut j = n;

    while i > 0 || j > 0 {
        if i > 0 && j > 0 && lines1[i - 1] == lines2[j - 1] {
            result.push(DiffLine::Context(&lines1[i - 1]));
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j]) {
            result.push(DiffLine::Added(&lines2[j - 1]));
            j -= 1;
        } else if i > 0 {
            result.push(DiffLine::Removed(&lines1[i - 1]));
            i -= 1;
        }
    }

    result.reverse();
    result
}

/// Fallback for very large files
fn simple_diff<'a>(lines1: &'a [String], lines2: &'a [String]) -> Vec<DiffLine<'a>> {
    let mut result = Vec::new();
    for line in lines1 {
        result.push(DiffLine::Removed(line));
    }
    for line in lines2 {
        result.push(DiffLine::Added(line));
    }
    result
}

#[derive(Debug)]
enum DiffLine<'a> {
    Context(&'a str),
    Added(&'a str),
    Removed(&'a str),
}

/// Format diff output in normal (ed-style) format, the default for `/usr/bin/diff`.
///
/// Normal format uses commands like `1c1`, `2a3`, `3d2` followed by `< ` / `> ` lines.
fn format_normal(diff: &[DiffLine<'_>]) -> String {
    let mut output = String::new();

    let mut old_line: usize = 1;
    let mut new_line: usize = 1;
    let mut i = 0;

    while i < diff.len() {
        match diff[i] {
            DiffLine::Context(_) => {
                old_line += 1;
                new_line += 1;
                i += 1;
            }
            DiffLine::Removed(_) | DiffLine::Added(_) => {
                // Collect contiguous removed then added lines
                let old_start = old_line;
                let new_start = new_line;
                let mut removed = Vec::new();
                let mut added = Vec::new();

                // Collect removed lines first
                while i < diff.len() && matches!(diff[i], DiffLine::Removed(_)) {
                    if let DiffLine::Removed(line) = diff[i] {
                        removed.push(line);
                    }
                    old_line += 1;
                    i += 1;
                }
                // Then collect added lines
                while i < diff.len() && matches!(diff[i], DiffLine::Added(_)) {
                    if let DiffLine::Added(line) = diff[i] {
                        added.push(line);
                    }
                    new_line += 1;
                    i += 1;
                }

                // Determine command type
                let old_end = old_start + removed.len() - if removed.is_empty() { 0 } else { 1 };
                let new_end = new_start + added.len() - if added.is_empty() { 0 } else { 1 };

                if !removed.is_empty() && !added.is_empty() {
                    // Change
                    let old_range = if removed.len() == 1 {
                        format!("{}", old_start)
                    } else {
                        format!("{},{}", old_start, old_end)
                    };
                    let new_range = if added.len() == 1 {
                        format!("{}", new_start)
                    } else {
                        format!("{},{}", new_start, new_end)
                    };
                    output.push_str(&format!("{}c{}\n", old_range, new_range));
                    for line in &removed {
                        output.push_str(&format!("< {}\n", line));
                    }
                    output.push_str("---\n");
                    for line in &added {
                        output.push_str(&format!("> {}\n", line));
                    }
                } else if !removed.is_empty() {
                    // Delete
                    let old_range = if removed.len() == 1 {
                        format!("{}", old_start)
                    } else {
                        format!("{},{}", old_start, old_end)
                    };
                    output.push_str(&format!("{}d{}\n", old_range, new_start - 1));
                    for line in &removed {
                        output.push_str(&format!("< {}\n", line));
                    }
                } else if !added.is_empty() {
                    // Add
                    let new_range = if added.len() == 1 {
                        format!("{}", new_start)
                    } else {
                        format!("{},{}", new_start, new_end)
                    };
                    output.push_str(&format!("{}a{}\n", old_start - 1, new_range));
                    for line in &added {
                        output.push_str(&format!("> {}\n", line));
                    }
                }
            }
        }
    }

    output
}

fn format_unified(file1: &str, file2: &str, diff: &[DiffLine<'_>]) -> String {
    let mut output = String::new();

    // Check if there are any changes
    let has_changes = diff
        .iter()
        .any(|d| matches!(d, DiffLine::Added(_) | DiffLine::Removed(_)));
    if !has_changes {
        return output;
    }

    output.push_str(&format!("--- {}\n", file1));
    output.push_str(&format!("+++ {}\n", file2));

    // Generate hunks with context
    let context_lines = 3;
    let mut i = 0;

    while i < diff.len() {
        // Find next change
        let change_start = diff[i..]
            .iter()
            .position(|d| matches!(d, DiffLine::Added(_) | DiffLine::Removed(_)));

        let change_start = match change_start {
            Some(v) => i + v,
            None => break,
        };
        let hunk_start = change_start.saturating_sub(context_lines);

        // Find end of hunk (including context after changes)
        let mut hunk_end = change_start;
        let mut last_change = change_start;

        while hunk_end < diff.len() {
            if matches!(diff[hunk_end], DiffLine::Added(_) | DiffLine::Removed(_)) {
                last_change = hunk_end;
            }
            // If we're past the last change + context, stop
            if hunk_end > last_change + context_lines {
                break;
            }
            hunk_end += 1;
        }
        hunk_end = hunk_end.min(diff.len());

        // Count lines for hunk header
        let mut old_count = 0;
        let mut new_count = 0;
        let mut old_start = 1;
        let mut new_start = 1;
        let mut old_line = 1;
        let mut new_line = 1;

        for (idx, d) in diff.iter().enumerate().take(hunk_end) {
            if idx == hunk_start {
                old_start = old_line;
                new_start = new_line;
            }
            match d {
                DiffLine::Context(_) => {
                    if idx >= hunk_start {
                        old_count += 1;
                        new_count += 1;
                    }
                    old_line += 1;
                    new_line += 1;
                }
                DiffLine::Removed(_) => {
                    if idx >= hunk_start {
                        old_count += 1;
                    }
                    old_line += 1;
                }
                DiffLine::Added(_) => {
                    if idx >= hunk_start {
                        new_count += 1;
                    }
                    new_line += 1;
                }
            }
        }

        output.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            old_start, old_count, new_start, new_count
        ));

        for d in &diff[hunk_start..hunk_end] {
            match d {
                DiffLine::Context(line) => {
                    output.push(' ');
                    output.push_str(line);
                    output.push('\n');
                }
                DiffLine::Added(line) => {
                    output.push('+');
                    output.push_str(line);
                    output.push('\n');
                }
                DiffLine::Removed(line) => {
                    output.push('-');
                    output.push_str(line);
                    output.push('\n');
                }
            }
        }

        i = hunk_end;
    }

    output
}

#[async_trait]
impl Builtin for Diff {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: diff [OPTION]... FILE1 FILE2\nCompare files line by line.\n\n  -u\t\toutput in unified format\n  -q, --brief\treport only when files differ\n  --help\t\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("diff (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        let (opts, files) = parse_diff_args(ctx.args);

        if files.len() < 2 {
            return Ok(ExecResult::err("diff: missing operand\n".to_string(), 1));
        }

        // Read file1
        let lines1: Vec<String> = if files[0] == "-" {
            ctx.stdin
                .map(|s| s.lines().map(|l| l.to_string()).collect())
                .unwrap_or_default()
        } else {
            let path = if files[0].starts_with('/') {
                std::path::PathBuf::from(&files[0])
            } else {
                ctx.cwd.join(&files[0])
            };
            match read_text_file(&*ctx.fs, &path, "diff").await {
                Ok(text) => text.lines().map(|l| l.to_string()).collect(),
                Err(e) => return Ok(e),
            }
        };

        // Read file2
        let lines2: Vec<String> = if files[1] == "-" {
            ctx.stdin
                .map(|s| s.lines().map(|l| l.to_string()).collect())
                .unwrap_or_default()
        } else {
            let path = if files[1].starts_with('/') {
                std::path::PathBuf::from(&files[1])
            } else {
                ctx.cwd.join(&files[1])
            };
            match read_text_file(&*ctx.fs, &path, "diff").await {
                Ok(text) => text.lines().map(|l| l.to_string()).collect(),
                Err(e) => return Ok(e),
            }
        };

        if lines1 == lines2 {
            return Ok(ExecResult::ok(String::new()));
        }

        if opts.brief {
            return Ok(ExecResult::with_code(
                format!("Files {} and {} differ\n", files[0], files[1]),
                1,
            ));
        }

        let diff = compute_diff(&lines1, &lines2);

        let output = if opts.unified {
            format_unified(&files[0], &files[1], &diff)
        } else {
            format_normal(&diff)
        };

        // diff returns exit code 1 when files differ, output goes to stdout
        Ok(ExecResult::with_code(output, 1))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::fs::{FileSystem, InMemoryFs};

    async fn run_diff(args: &[&str], stdin: Option<&str>, files: &[(&str, &[u8])]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        for (path, content) in files {
            fs.write_file(std::path::Path::new(path), content)
                .await
                .unwrap();
        }
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Diff.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_diff_identical() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"hello\nworld\n"), ("/b.txt", b"hello\nworld\n")],
        )
        .await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "");
    }

    #[tokio::test]
    async fn test_diff_different() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"hello\nworld\n"), ("/b.txt", b"hello\nearth\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        // Default is normal format
        assert!(result.stdout.contains("2c2"));
        assert!(result.stdout.contains("< world"));
        assert!(result.stdout.contains("> earth"));
    }

    #[tokio::test]
    async fn test_diff_added_lines() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"a\nb\n"), ("/b.txt", b"a\nb\nc\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        // Normal format: add command
        assert!(result.stdout.contains("2a3"));
        assert!(result.stdout.contains("> c"));
    }

    #[tokio::test]
    async fn test_diff_removed_lines() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"a\nb\nc\n"), ("/b.txt", b"a\nb\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        // Normal format: delete command
        assert!(result.stdout.contains("3d2"));
        assert!(result.stdout.contains("< c"));
    }

    #[tokio::test]
    async fn test_diff_brief() {
        let result = run_diff(
            &["-q", "/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"hello\n"), ("/b.txt", b"world\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.contains("Files /a.txt and /b.txt differ"));
    }

    #[tokio::test]
    async fn test_diff_brief_identical() {
        let result = run_diff(
            &["-q", "/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"hello\n"), ("/b.txt", b"hello\n")],
        )
        .await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "");
    }

    #[tokio::test]
    async fn test_diff_empty_vs_content() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b""), ("/b.txt", b"hello\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.contains("> hello"));
    }

    #[tokio::test]
    async fn test_diff_missing_operand() {
        let result = run_diff(&["/a.txt"], None, &[("/a.txt", b"hello\n")]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("missing operand"));
    }

    #[tokio::test]
    async fn test_diff_file_not_found() {
        let result = run_diff(&["/a.txt", "/b.txt"], None, &[("/a.txt", b"hello\n")]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("diff:"));
    }

    #[tokio::test]
    async fn test_diff_unified_header() {
        let result = run_diff(
            &["-u", "/old.txt", "/new.txt"],
            None,
            &[("/old.txt", b"a\nb\nc\n"), ("/new.txt", b"a\nB\nc\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.contains("--- /old.txt"));
        assert!(result.stdout.contains("+++ /new.txt"));
        assert!(result.stdout.contains("@@"));
    }

    #[tokio::test]
    async fn test_diff_hunk_format() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[
                ("/a.txt", b"line1\nline2\nline3\n"),
                ("/b.txt", b"line1\nmodified\nline3\n"),
            ],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        // Normal format: change command
        assert!(result.stdout.contains("2c2"));
        assert!(result.stdout.contains("< line2"));
        assert!(result.stdout.contains("> modified"));
    }

    #[tokio::test]
    async fn test_diff_stdin() {
        let result = run_diff(&["-", "/b.txt"], Some("hello\n"), &[("/b.txt", b"world\n")]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.contains("< hello"));
        assert!(result.stdout.contains("> world"));
    }

    #[tokio::test]
    async fn test_diff_multiple_changes() {
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[
                ("/a.txt", b"a\nb\nc\nd\ne\n"),
                ("/b.txt", b"a\nB\nc\nD\ne\n"),
            ],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        // Normal format
        assert!(result.stdout.contains("< b"));
        assert!(result.stdout.contains("> B"));
        assert!(result.stdout.contains("< d"));
        assert!(result.stdout.contains("> D"));
    }

    #[tokio::test]
    async fn test_diff_normal_format_default() {
        // Default format should be normal (ed-style), not unified
        let result = run_diff(
            &["/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"a\n"), ("/b.txt", b"b\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.starts_with("1c1\n"));
        assert!(result.stdout.contains("< a"));
        assert!(result.stdout.contains("---\n"));
        assert!(result.stdout.contains("> b"));
        // Should NOT contain unified format markers
        assert!(!result.stdout.contains("---  "));
        assert!(!result.stdout.contains("+++"));
        assert!(!result.stdout.contains("@@"));
    }

    #[tokio::test]
    async fn test_diff_unified_with_flag() {
        // -u flag should produce unified format
        let result = run_diff(
            &["-u", "/a.txt", "/b.txt"],
            None,
            &[("/a.txt", b"a\n"), ("/b.txt", b"b\n")],
        )
        .await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.contains("--- /a.txt"));
        assert!(result.stdout.contains("+++ /b.txt"));
        assert!(result.stdout.contains("@@"));
    }
}