bashkit 0.20.1

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
//! Word count builtin - count lines, words, bytes, and characters

use async_trait::async_trait;

use super::{Builtin, Context, read_stream_file};
use crate::error::Result;
use crate::fs::vfs_join;
use crate::interpreter::ExecResult;

/// The wc builtin - print newline, word, and byte counts.
///
/// Usage: wc [-lwcmL] [FILE...]
///
/// Options:
///   -l, --lines   Print the newline count
///   -w, --words   Print the word count
///   -c, --bytes   Print the byte count
///   -m, --chars   Print the character count
///   -L, --max-line-length  Print the maximum line length
///
/// With no options, prints lines, words, and bytes.
pub struct Wc;

/// Parsed wc flags
struct WcFlags {
    lines: bool,
    words: bool,
    bytes: bool,
    chars: bool,
    max_line_length: bool,
}

impl WcFlags {
    #[allow(clippy::result_large_err)]
    fn parse(args: &[String]) -> std::result::Result<Self, ExecResult> {
        let mut lines = false;
        let mut words = false;
        let mut bytes = false;
        let mut chars = false;
        let mut max_line_length = false;

        for arg in args {
            if !arg.starts_with('-') {
                continue;
            }
            match arg.as_str() {
                // Operand-shaped: "-" is stdin, "--" ends options; neither is a flag.
                "-" | "--" => {}
                "--lines" => lines = true,
                "--words" => words = true,
                "--bytes" => bytes = true,
                "--chars" => chars = true,
                "--max-line-length" => max_line_length = true,
                // Unknown long option → reject (wc exits 1).
                _ if arg.starts_with("--") => {
                    return Err(super::invalid_option("wc", arg, 1));
                }
                _ => {
                    for ch in arg[1..].chars() {
                        match ch {
                            'l' => lines = true,
                            'w' => words = true,
                            'c' => bytes = true,
                            'm' => chars = true,
                            'L' => max_line_length = true,
                            _ => return Err(super::invalid_option("wc", &format!("-{ch}"), 1)),
                        }
                    }
                }
            }
        }

        // Default: show lines, words, bytes if no flags
        if !lines && !words && !bytes && !chars && !max_line_length {
            lines = true;
            words = true;
            bytes = true;
        }

        Ok(Self {
            lines,
            words,
            bytes,
            chars,
            max_line_length,
        })
    }

    /// Number of active count fields
    fn active_count(&self) -> usize {
        [
            self.lines,
            self.words,
            self.bytes,
            self.chars,
            self.max_line_length,
        ]
        .iter()
        .filter(|&&b| b)
        .count()
    }
}

#[async_trait]
impl Builtin for Wc {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: wc [OPTION]... [FILE]...\nPrint newline, word, and byte counts for each FILE.\n\n  -l, --lines\t\t\tprint the newline counts\n  -w, --words\t\t\tprint the word counts\n  -c, --bytes\t\t\tprint the byte counts\n  -m, --chars\t\t\tprint the character counts\n  -L, --max-line-length\t\tprint the maximum line length\n  --help\t\t\tdisplay this help and exit\n  --version\t\t\toutput version information and exit\n",
            Some("wc (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        let flags = match WcFlags::parse(ctx.args) {
            Ok(f) => f,
            Err(e) => return Ok(e),
        };

        let files: Vec<_> = ctx
            .args
            .iter()
            .filter(|a| !a.starts_with('-') || a.as_str() == "-")
            .collect();

        let mut output = String::new();
        let mut total_lines = 0usize;
        let mut total_words = 0usize;
        let mut total_bytes = 0usize;
        let mut total_chars = 0usize;
        let mut total_max_line = 0usize;

        if files.is_empty() {
            // Read from stdin
            if let Some(stdin) = ctx.stdin {
                let counts = count_data(stdin.as_bytes());
                // Real bash: no padding for single-value stdin, padded for multiple values
                let width = if flags.active_count() > 1 { 7 } else { 1 };
                output.push_str(&format_counts(&counts, &flags, None, width));
                output.push('\n');
            }
        } else {
            // Read every file first: the column width depends on all of them.
            let mut counted = Vec::with_capacity(files.len());
            for file in &files {
                let path = if file.starts_with('/') {
                    std::path::PathBuf::from(file)
                } else {
                    vfs_join(ctx.cwd, file)
                };
                let regular = ctx
                    .fs
                    .stat(&path)
                    .await
                    .is_ok_and(|m| m.file_type.is_file());
                match read_stream_file(&*ctx.fs, &path, "wc").await {
                    Ok(data) => {
                        counted.push((count_data(data.as_bytes()), regular && *file != "-"))
                    }
                    Err(e) => return Ok(e),
                }
            }
            let width = number_width(&counted, flags.active_count());
            for ((counts, _), file) in counted.iter().zip(&files) {
                total_lines += counts.lines;
                total_words += counts.words;
                total_bytes += counts.bytes;
                total_chars += counts.chars;
                if counts.max_line_length > total_max_line {
                    total_max_line = counts.max_line_length;
                }
                output.push_str(&format_counts(counts, &flags, Some(file), width));
                output.push('\n');
            }

            // Print total if multiple files
            if files.len() > 1 {
                let totals = TextCounts {
                    lines: total_lines,
                    words: total_words,
                    bytes: total_bytes,
                    chars: total_chars,
                    max_line_length: total_max_line,
                };
                output.push_str(&format_counts(
                    &totals,
                    &flags,
                    Some(&"total".to_string()),
                    width,
                ));
                output.push('\n');
            }
        }

        Ok(ExecResult::ok(output))
    }
}

struct TextCounts {
    lines: usize,
    words: usize,
    bytes: usize,
    chars: usize,
    max_line_length: usize,
}

/// Count stream data. Invalid UTF-8 is one character per byte, matching the
/// byte-oriented C locale instead of inventing Unicode replacement characters.
fn count_data(bytes: &[u8]) -> TextCounts {
    let text = String::from_utf8_lossy(bytes);
    // wc -l counts newline characters, not logical lines
    let lines = bytes.iter().filter(|&&byte| byte == b'\n').count();
    let words = text.split_whitespace().count();
    let byte_count = bytes.len();
    let chars = std::str::from_utf8(bytes)
        .map(|valid| valid.chars().count())
        .unwrap_or(byte_count);
    let max_line_length = text.lines().map(|l| l.chars().count()).max().unwrap_or(0);
    TextCounts {
        lines,
        words,
        bytes: byte_count,
        chars,
        max_line_length,
    }
}

/// GNU wc's `compute_number_width`: one file with one count is unpadded;
/// otherwise wide enough for the total size of the regular files, and at
/// least 7 when any input is not a regular file (its size is unknown).
fn number_width(counted: &[(TextCounts, bool)], active: usize) -> usize {
    if counted.len() == 1 && active == 1 {
        return 1;
    }
    let mut minimum = 1;
    let mut total = 0usize;
    for (counts, regular) in counted {
        if *regular {
            total = total.saturating_add(counts.bytes);
        } else {
            minimum = 7;
        }
    }
    total.to_string().len().max(minimum)
}

/// Format counts for output, each right-aligned in `width` columns.
fn format_counts(
    counts: &TextCounts,
    flags: &WcFlags,
    filename: Option<&String>,
    width: usize,
) -> String {
    let mut values: Vec<usize> = Vec::new();

    if flags.lines {
        values.push(counts.lines);
    }
    if flags.words {
        values.push(counts.words);
    }
    if flags.bytes {
        values.push(counts.bytes);
    }
    if flags.chars {
        values.push(counts.chars);
    }
    if flags.max_line_length {
        values.push(counts.max_line_length);
    }

    let parts: Vec<String> = values.iter().map(|v| format!("{v:>width$}")).collect();
    let result = parts.join(" ");

    if let Some(name) = filename {
        format!("{} {}", result, name)
    } else {
        result
    }
}

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

    use crate::fs::InMemoryFs;

    async fn run_wc(args: &[&str], stdin: Option<&str>) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        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: crate::builtins::test_stream_opt(stdin),
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

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

    // Issue #2425: a failed read reports the resolved VFS path, which must be
    // `/`-separated even where the host separator is `\`.
    #[tokio::test]
    async fn windows_containment_wc_error_path_is_slash_separated() {
        let fs = Arc::new(InMemoryFs::new());
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/d/proj");

        let args = vec!["src/missing.rs".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        let result = Wc.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
        assert!(
            result.stderr.starts_with("wc: /d/proj/src/missing.rs:"),
            "error path is not slash-separated:\n{}",
            result.stderr
        );
    }

    #[tokio::test]
    async fn test_wc_all() {
        let result = run_wc(&[], Some("one two three\nfour five\n")).await;
        assert_eq!(result.exit_code, 0);
        // 2 lines, 5 words, 25 bytes
        assert!(result.stdout.contains("2"));
        assert!(result.stdout.contains("5"));
    }

    #[tokio::test]
    async fn test_wc_lines_only() {
        let result = run_wc(&["-l"], Some("one\ntwo\nthree\n")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("3"));
    }

    #[tokio::test]
    async fn test_wc_words_only() {
        let result = run_wc(&["-w"], Some("one two three four five")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("5"));
    }

    #[tokio::test]
    async fn test_wc_bytes_only() {
        let result = run_wc(&["-c"], Some("hello")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("5"));
    }

    #[tokio::test]
    async fn test_wc_empty() {
        let result = run_wc(&[], Some("")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.contains("0"));
    }

    #[tokio::test]
    async fn test_wc_chars() {
        let result = run_wc(&["-m"], Some("hello")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("5"));
    }

    #[tokio::test]
    async fn test_wc_chars_unicode() {
        // héllo: 5 chars but 6 bytes (é is 2 bytes in UTF-8)
        let result = run_wc(&["-m"], Some("héllo")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("5"));
    }

    #[tokio::test]
    async fn test_wc_max_line_length() {
        let result = run_wc(&["-L"], Some("short\nlongerline\n")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("10"));
    }

    #[tokio::test]
    async fn test_wc_invalid_option() {
        let result = run_wc(&["-Q"], Some("hello")).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("invalid option -- 'Q'"));
    }

    #[tokio::test]
    async fn test_wc_long_flags() {
        let result = run_wc(&["--bytes"], Some("hello")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("5"));

        let result = run_wc(&["--lines"], Some("a\nb\n")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("2"));

        let result = run_wc(&["--words"], Some("one two three")).await;
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.trim().contains("3"));
    }
}