bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
//! DET003: Unordered wildcard usage
//!
//! **Rule**: Detect wildcards without sorting for deterministic results
//!
//! **Why this matters**:
//! File glob results vary by filesystem and can change between runs,
//! breaking determinism.
//!
//! **Auto-fix**: Wrap command substitution with sort (only for $(ls ...) patterns)
//!
//! ## Examples
//!
//! ❌ **BAD** (non-deterministic):
//! ```bash
//! FILES=$(ls *.txt)
//! for f in *.c; do echo $f; done
//! ```
//!
//! ✅ **GOOD** (deterministic):
//! ```bash
//! FILES=$(ls *.txt | sort)
//! for f in $(printf '%s\n' *.c | sort); do echo "$f"; done
//! ```
//!
//! **Note**: For `for f in *.c`, no auto-fix is provided since the correct
//! transformation is complex. Users should manually review.

use crate::linter::{Diagnostic, Fix, LintResult, Severity, Span};

/// Check a `$(ls ...)` pattern for unordered wildcards and emit diagnostic with auto-fix
fn check_ls_wildcard(line: &str, line_num: usize, ls_start: usize, result: &mut LintResult) {
    let after_ls = &line[ls_start..];
    if let Some(close_paren) = find_matching_paren(after_ls) {
        let cmd_sub = &after_ls[..=close_paren];
        if cmd_sub.contains('*') {
            let span = Span::new(
                line_num + 1,
                ls_start + 1,
                line_num + 1,
                ls_start + close_paren + 2,
            );
            let inner = &cmd_sub[2..cmd_sub.len() - 1];
            let fixed = format!("$({} | sort)", inner);
            let diag = Diagnostic::new(
                "DET003",
                Severity::Warning,
                "Unordered wildcard in command substitution - results may vary",
                span,
            )
            .with_fix(Fix::new(fixed));
            result.add(diag);
        }
    }
}

/// Check a `for ... in *` pattern for unordered wildcards (no auto-fix)
fn check_for_loop_wildcard(line: &str, line_num: usize, result: &mut LintResult) {
    if line.contains("for ") && line.contains(" in ") {
        if let Some(col) = line.find('*') {
            let span = Span::new(line_num + 1, col + 1, line_num + 1, col + 2);
            let diag = Diagnostic::new(
                "DET003",
                Severity::Info,
                "Unordered wildcard in for-loop - consider sorting for determinism",
                span,
            );
            result.add(diag);
        }
    }
}

/// Commands where bare wildcard arguments produce non-deterministic ordering.
const WILDCARD_COMMANDS: &[&str] = &[
    "cat",
    "head",
    "tail",
    "wc",
    "grep",
    "sort",
    "diff",
    "echo",
    "ls",
    "md5sum",
    "sha256sum",
    "file",
    "du",
    "stat",
];

/// Check for bare wildcards in command arguments (e.g., `cat *.log`, `wc -l *.txt`).
/// These expand in filesystem order, which is non-deterministic.
fn check_command_wildcard(line: &str, line_num: usize, result: &mut LintResult) {
    let trimmed = line.trim();

    // Skip if wildcard is inside quotes
    if is_wildcard_quoted(trimmed) {
        return;
    }

    // Skip if wildcard is inside command substitution $(...) — handled by check_ls_wildcard
    if is_wildcard_in_cmd_sub(trimmed) {
        return;
    }

    // Check if a known command appears at line start or after a pipe
    let segments: Vec<&str> = trimmed.split('|').collect();
    for segment in &segments {
        let seg = segment.trim();
        for cmd in WILDCARD_COMMANDS {
            if seg.starts_with(cmd) && seg[cmd.len()..].starts_with([' ', '\t']) {
                if let Some(col) = line.find('*') {
                    let span = Span::new(line_num + 1, col + 1, line_num + 1, col + 2);
                    let diag = Diagnostic::new(
                        "DET003",
                        Severity::Info,
                        "Unordered wildcard in command arguments - glob expansion order is non-deterministic",
                        span,
                    );
                    result.add(diag);
                    return;
                }
            }
        }
    }
}

/// Check if the wildcard `*` is inside single or double quotes.
fn is_wildcard_quoted(line: &str) -> bool {
    let mut in_single = false;
    let mut in_double = false;
    for c in line.chars() {
        match c {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '*' if in_single || in_double => return true,
            _ => {}
        }
    }
    false
}

/// Check if the wildcard `*` appears only inside a `$(...)` command substitution.
fn is_wildcard_in_cmd_sub(line: &str) -> bool {
    let mut depth = 0i32;
    let bytes = line.as_bytes();
    for i in 0..bytes.len() {
        if i > 0 && bytes[i - 1] == b'$' && bytes[i] == b'(' {
            depth += 1;
        } else if bytes[i] == b')' && depth > 0 {
            depth -= 1;
        } else if bytes[i] == b'*' && depth == 0 {
            return false;
        }
    }
    // If we never saw a * outside cmd sub, and there IS a * somewhere, it's all inside
    line.contains('*')
}

/// Check for unordered wildcard usage
pub fn check(source: &str) -> LintResult {
    let mut result = LintResult::new();

    for (line_num, line) in source.lines().enumerate() {
        if line.contains('*') && !line.contains("| sort") {
            if let Some(ls_start) = line.find("$(ls ") {
                check_ls_wildcard(line, line_num, ls_start, &mut result);
            } else if line.contains("for ") && line.contains(" in ") {
                check_for_loop_wildcard(line, line_num, &mut result);
            } else {
                check_command_wildcard(line, line_num, &mut result);
            }
        }
    }

    result
}

/// Find the matching closing parenthesis for a command substitution
fn find_matching_paren(s: &str) -> Option<usize> {
    let mut depth = 0;
    for (i, c) in s.chars().enumerate() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_DET003_detects_ls_wildcard() {
        let script = "FILES=$(ls *.txt)";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.code, "DET003");
        assert_eq!(diag.severity, Severity::Warning);
    }

    #[test]
    fn test_DET003_detects_for_loop_wildcard() {
        let script = "for f in *.c; do echo $f; done";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        // For-loop wildcards get Info severity (no auto-fix)
        assert_eq!(result.diagnostics[0].severity, Severity::Info);
    }

    #[test]
    fn test_DET003_no_warning_with_sort() {
        let script = "FILES=$(ls *.txt | sort)";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_DET003_provides_correct_fix_for_ls() {
        let script = "FILES=$(ls *.txt)";
        let result = check(script);

        assert!(result.diagnostics[0].fix.is_some());
        let fix = result.diagnostics[0].fix.as_ref().unwrap();
        // Fix should wrap the entire command substitution correctly
        assert_eq!(fix.replacement, "$(ls *.txt | sort)");
    }

    #[test]
    fn test_DET003_no_fix_for_for_loop() {
        // For-loop wildcards are too complex to auto-fix safely
        let script = "for f in *.c; do echo $f; done";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        // Should NOT have a fix (user must manually review)
        assert!(result.diagnostics[0].fix.is_none());
    }

    #[test]
    fn test_DET003_fix_span_covers_full_command_sub() {
        let script = "FILES=$(ls *.txt)";
        let result = check(script);

        let diag = &result.diagnostics[0];
        // Span should cover $(ls *.txt) which is columns 7-17 (1-indexed)
        assert_eq!(diag.span.start_col, 7);
        assert_eq!(diag.span.end_col, 18); // Exclusive end
    }

    #[test]
    fn test_DET003_nested_parens() {
        // Test with nested parentheses inside command substitution
        let script = "FILES=$(ls $(echo *.txt))";
        let result = check(script);

        // Should still detect the pattern
        assert!(!result.diagnostics.is_empty());
    }

    #[test]
    fn test_DET003_detects_cat_wildcard() {
        let script = "cat /var/log/*.log";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
        assert_eq!(result.diagnostics[0].severity, Severity::Info);
    }

    #[test]
    fn test_DET003_detects_wc_wildcard() {
        let script = "wc -l /opt/data/*.txt";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
    }

    #[test]
    fn test_DET003_detects_head_wildcard() {
        let script = "head -n 5 /var/log/*.csv";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
    }

    #[test]
    fn test_DET003_no_warning_wildcard_in_quotes() {
        let script = "echo \"*.log\"";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_DET003_detects_wildcard_after_pipe() {
        let script = "find . -name foo | cat *.log";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_DET003_no_warning_sort_pipe() {
        let script = "cat *.log | sort";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_find_matching_paren() {
        assert_eq!(find_matching_paren("()"), Some(1));
        assert_eq!(find_matching_paren("(abc)"), Some(4));
        assert_eq!(find_matching_paren("((nested))"), Some(9));
        assert_eq!(find_matching_paren("(a(b)c)"), Some(6));
        assert_eq!(find_matching_paren("(unclosed"), None);
    }

    // ── check_command_wildcard coverage ──────────────────────────────────

    #[test]
    fn test_DET003_check_command_wildcard_tail() {
        let script = "tail -n 10 /var/log/*.log";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
        assert_eq!(result.diagnostics[0].severity, Severity::Info);
    }

    #[test]
    fn test_DET003_check_command_wildcard_grep() {
        let script = "grep -r pattern /etc/*.conf";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
    }

    #[test]
    fn test_DET003_check_command_wildcard_diff() {
        let script = "diff /backup/*.bak /current/*.conf";
        let result = check(script);
        assert!(!result.diagnostics.is_empty());
        assert_eq!(result.diagnostics[0].code, "DET003");
    }

    #[test]
    fn test_DET003_check_command_wildcard_md5sum() {
        let script = "md5sum /tmp/dist/*.tar.gz";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "DET003");
    }

    #[test]
    fn test_DET003_check_command_wildcard_sha256sum() {
        let script = "sha256sum /releases/*.zip";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_DET003_check_command_wildcard_du() {
        let script = "du -sh /var/log/*.log";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_DET003_check_command_wildcard_stat() {
        let script = "stat /etc/conf/*.d";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_DET003_check_command_wildcard_file() {
        let script = "file /tmp/uploads/*";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_DET003_check_command_wildcard_unknown_command_no_warn() {
        // Unknown command with wildcard should NOT warn
        let script = "mycommand /tmp/*.txt";
        let result = check(script);
        assert_eq!(
            result.diagnostics.len(),
            0,
            "unknown commands should not trigger DET003"
        );
    }

    // ── is_wildcard_quoted coverage ───────────────────────────────────────

    #[test]
    fn test_DET003_wildcard_in_single_quotes_no_warn() {
        let script = "echo '*.log'";
        let result = check(script);
        assert_eq!(
            result.diagnostics.len(),
            0,
            "wildcard in single quotes should not warn"
        );
    }

    #[test]
    fn test_DET003_wildcard_in_double_quotes_no_warn() {
        let script = "echo \"*.log\"";
        let result = check(script);
        assert_eq!(
            result.diagnostics.len(),
            0,
            "wildcard in double quotes should not warn"
        );
    }

    #[test]
    fn test_DET003_wildcard_after_closing_quote_warns() {
        // After the closing quote, the wildcard is unquoted
        let script = "cat 'prefix' *.log";
        let result = check(script);
        assert_eq!(
            result.diagnostics.len(),
            1,
            "unquoted wildcard after quoted string should warn"
        );
    }

    // ── is_wildcard_in_cmd_sub coverage ──────────────────────────────────

    #[test]
    fn test_DET003_wildcard_in_cmd_sub_no_extra_warn() {
        // $(ls *.txt) is handled by check_ls_wildcard, not check_command_wildcard
        let script = "FILES=$(ls *.txt)";
        let result = check(script);
        // Should have exactly 1 warning from check_ls_wildcard
        assert_eq!(
            result.diagnostics.len(),
            1,
            "only ls-wildcard warning expected"
        );
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
    }

    #[test]
    fn test_DET003_wildcard_in_non_ls_cmd_sub_no_warn() {
        // $(find . -name '*.txt') - wildcard inside cmd sub, not at top level
        let script = "FILES=$(find . -name '*.txt')";
        let result = check(script);
        // The wildcard is quoted inside the cmd sub - no DET003 warning expected
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_DET003_no_wildcard_no_warn() {
        let script = "cat /var/log/syslog";
        let result = check(script);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_DET003_empty_script_no_warn() {
        let result = check("");
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_DET003_multiline_multiple_detections() {
        let script = "cat *.log\nwc -l *.txt\nsort output";
        let result = check(script);
        // cat *.log and wc -l *.txt should both warn, but sort is already fine
        assert_eq!(result.diagnostics.len(), 2);
    }

    #[test]
    fn test_DET003_wildcard_commands_list_covers_all() {
        // Verify every command in WILDCARD_COMMANDS triggers detection
        let commands = [
            "cat", "head", "tail", "wc", "grep", "diff", "echo", "du", "stat",
        ];
        for cmd in &commands {
            let script = format!("{cmd} /tmp/*.txt");
            let result = check(&script);
            assert!(
                !result.diagnostics.is_empty(),
                "command '{cmd}' should trigger DET003"
            );
        }
    }
}